@@ -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
@@ -34,213 +35,357 @@ module Squeal.PostgreSQL.Expression
34 ( -- * Expression
35 ( -- * Expression
35 Expression (..)
36 Expression (..)
45 , Operator
38 , Operator
46− , OperatorDB
39+ , (:-->)
47− , unsafeBinaryOp
40+ , HasParameter (parameter)
48− , binaryOp
41+ , param
49− , FunctionVar
42+ -- ** Null
50− , unsafeFunctionVar
43+ , null_
51− , type (--->)
44+ , notNull
52− , FunctionNDB
45+ , coalesce
53− , unsafeFunctionN
46+ , fromNull
54− , functionN
47+ , isNull
55 , PGSubset (..)
57 , PGSubset (..)
56− , PGIntersect (..)
58+ -- ** Functions
62+ , unsafeVariadicFunction
90+ , notBetweenSymmetric
117+ -- *** Json and Jsonb operators
122+ -- *** Jsonb operators
147+ , jsonExtractPathAsText
148+ , jsonbExtractPathAsText
167+ , websearchToTSquery
175+ -- * Window Functions
176+ , WindowDefinition (..)
178+ , WindowFunction (..)
191+ , SortExpression (..)
194+ , TypeExpression (..)
220+ , timestampWithTimeZone
57 -- * Re-export
233 -- * Re-export
63import Control.Category
240import Control.Category
64import Control.DeepSeq
241import Control.DeepSeq
65import Data.ByteString (ByteString)
242import Data.ByteString (ByteString)
243+import Data.ByteString.Lazy (toStrict)
66import Data.Function ((&))
244import Data.Function ((&))
67import Data.Semigroup hiding (All)
245import Data.Semigroup hiding (All)
246+import qualified Data.Aeson as JSON
68import Data.String
247import Data.String
69import Generics.SOP hiding (All, from)
249import Generics.SOP hiding (All, from)
250+import GHC.Generics ((:*:) (..))
70import GHC.OverloadedLabels
251import GHC.OverloadedLabels
71import GHC.TypeLits
252import GHC.TypeLits
72import Numeric
253import Numeric
73import Prelude hiding (id, (.))
254import Prelude hiding (id, (.))
256+import qualified Data.ByteString as ByteString
75import qualified GHC.Generics as GHC
257import qualified GHC.Generics as GHC
258+import qualified Generics.SOP as SOP
77−import Squeal.PostgreSQL.Alias
78−import Squeal.PostgreSQL.List
79import Squeal.PostgreSQL.Render
260import Squeal.PostgreSQL.Render
80import Squeal.PostgreSQL.Schema
261import Squeal.PostgreSQL.Schema
83−-- >>> import Squeal.PostgreSQL
85{-----------------------------------------
263{-----------------------------------------
86column expressions
264column expressions
87-----------------------------------------}
265-----------------------------------------}
89{- | `Expression`s are used in a variety of contexts,
267{- | `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,
268+such as in the target list of the `Squeal.PostgreSQL.Query.select` command,
92as new column values in `Squeal.PostgreSQL.Manipulation.insertRow` or
269as new column values in `Squeal.PostgreSQL.Manipulation.insertRow` or
93`Squeal.PostgreSQL.Manipulation.update`,
270`Squeal.PostgreSQL.Manipulation.update`,
94−or in search `Squeal.PostgreSQL.Logic.Condition`s in a number of commands.
271+or in search `Condition`s in a number of commands.
96The expression syntax allows the calculation of
273The expression syntax allows the calculation of
97values from primitive expression using arithmetic, logical,
274values from primitive expression using arithmetic, logical,
98and other operations.
275and 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
277newtype Expression
115 (outer :: FromType)
278 (outer :: FromType)
116− (commons :: FromType)
117 (grp :: Grouping)
279 (grp :: Grouping)
280+ (commons :: FromType)
118 (schemas :: SchemasType)
281 (schemas :: SchemasType)
119 (params :: [NullityType])
282 (params :: [NullityType])
120 (from :: FromType)
283 (from :: FromType)
121 (ty :: NullityType)
284 (ty :: NullityType)
122 = UnsafeExpression { renderExpression :: ByteString }
285 = UnsafeExpression { renderExpression :: ByteString }
123 deriving (GHC.Generic,Show,Eq,Ord,NFData)
286 deriving (GHC.Generic,Show,Eq,Ord,NFData)
124−instance RenderSQL (Expression outer commons grp schemas params from ty) where
287+instance RenderSQL (Expression outer grp commons schemas params from ty) where
125 renderSQL = renderExpression
288 renderSQL = renderExpression
127−-- | An `Expr` is a closed `Expression`.
128−-- It is a F@RankNType@ but don't be scared.
129−-- Think of it as an expression which sees no
130−-- namespaces, so you can't use parameters
131−-- or alias references. It can be used as
132−-- a simple piece of more complex `Expression`s.
133type Expr x
290type Expr x
134− = forall outer commons grp schemas params from
291+ = forall outer grp commons schemas params from
135− . Expression outer commons grp schemas params from x
292+ . Expression outer grp commons schemas params from x
136− -- ^ cannot reference aliases
138−-- | A @RankNType@ for binary operators.
139type Operator x1 x2 y
294type Operator x1 x2 y
140− = forall outer commons grp schemas params from
295+ = forall outer grp commons schemas params from
141− . Expression outer commons grp schemas params from x1
296+ . Expression outer grp commons schemas params from x1
143− -> Expression outer commons grp schemas params from x2
297+ -> Expression outer grp commons schemas params from x2
145− -> Expression outer commons grp schemas params from y
298+ -> Expression outer grp commons schemas params from y
148−type OperatorDB schemas x1 x2 y
149− = forall outer commons grp params from
301+ = forall outer grp commons schemas params from
150− . Expression outer commons grp schemas params from x1
302+ . Expression outer grp commons schemas params from x
152− -> Expression outer commons grp schemas params from x2
303+ -> Expression outer grp commons schemas params from y
153− -- ^ right input
304+
305+type FunctionHet xs y
154− -> Expression outer commons grp schemas params from y
306+ = forall outer grp commons schemas params from
155− -- ^ output
307+ . NP (Expression outer grp commons schemas params from) xs
156−
308+ -> Expression outer grp commons schemas params from y
157−-- | A @RankNType@ for functions with a single argument.
309+
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`.
162−type (-->) x y
310+type FunctionHom x y
163− = forall outer commons grp schemas params from
311+ = forall outer grp commons schemas params from
164− . Expression outer commons grp schemas params from x
312+ . [Expression outer grp commons schemas params from x]
166− -> Expression outer commons grp schemas params from y
313+ -> Expression outer grp commons schemas params from x
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
314+ -> Expression outer grp commons schemas params from y
175−
316+unsafeFunctionHom :: ByteString -> FunctionHom x 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
200− = forall outer commons grp schemas params from
201− . [Expression outer commons grp schemas params from x0]
203− -> Expression outer commons grp schemas params from x1
204− -- ^ must have at least 1 input
205− -> Expression outer commons grp schemas params from y
208−{- | >>> printSQL (unsafeFunctionVar "greatest" [true, null_] false)
209−greatest(TRUE, NULL, FALSE)
211−unsafeFunctionVar :: ByteString -> FunctionVar x0 x1 y
212−unsafeFunctionVar fun xs x = UnsafeExpression $ fun <> parenthesized
317+unsafeFunctionHom fun xs x = UnsafeExpression $ fun <> parenthesized
213 (commaSeparated (renderSQL <$> xs) <> ", " <> renderSQL x)
318 (commaSeparated (renderSQL <$> xs) <> ", " <> renderSQL x)
320+{- | A `HasParameter` constraint is used to indicate a value that is
321+supplied externally to a SQL statement.
322+`Squeal.PostgreSQL.PQ.manipulateParams`,
323+`Squeal.PostgreSQL.PQ.queryParams` and
324+`Squeal.PostgreSQL.PQ.traversePrepared` support specifying data values
325+separately from the SQL command string, in which case `param`s are used to
326+refer to the out-of-line data values.
328+class KnownNat n => HasParameter
330+ (params :: [NullityType])
332+ | n params -> ty where
333+ -- | `parameter` takes a `Nat` using type application and a `TypeExpression`.
335+ -- >>> let expr = parameter @1 int4 :: Expression outer grp '[] schemas '[ 'Null 'PGint4] from ('Null 'PGint4)
336+ -- >>> printSQL expr
339+ :: TypeExpression schemas ty
340+ -> Expression outer grp commons schemas params from ty
341+ parameter ty = UnsafeExpression $ parenthesized $
342+ "$" <> renderNat @n <+> "::"
344+instance {-# OVERLAPPING #-} HasParameter 1 (ty1:tys) ty1
345+instance {-# OVERLAPPABLE #-} (KnownNat n, HasParameter (n-1) params ty)
346+ => HasParameter n (ty' : params) ty
348+-- | `param` takes a `Nat` using type application and for basic types,
349+-- infers a `TypeExpression`.
351+-- >>> let expr = param @1 :: Expression outer grp commons schemas '[ 'Null 'PGint4] from ('Null 'PGint4)
355+ :: forall n outer commons schemas params from grp ty
356+ . (PGTyped schemas ty, HasParameter n params ty)
357+ => Expression outer grp commons schemas params from ty -- ^ param
358+param = parameter @n (pgtype @schemas)
215instance (HasUnique tab (Join outer from) row, Has col row ty)
360instance (HasUnique tab (Join outer from) row, Has col row ty)
216− => IsLabel col (Expression outer commons 'Ungrouped schemas params from ty) where
361+ => IsLabel col (Expression outer 'Ungrouped commons schemas params from ty) where
217 fromLabel = UnsafeExpression $ renderSQL (Alias @col)
362 fromLabel = UnsafeExpression $ renderSQL (Alias @col)
218instance (HasUnique tab (Join outer from) row, Has col row ty, tys ~ '[ty])
363instance (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
364+ => IsLabel col (NP (Expression outer 'Ungrouped commons schemas params from) tys) where
220 fromLabel = fromLabel @col :* Nil
365 fromLabel = fromLabel @col :* Nil
221instance (HasUnique tab (Join outer from) row, Has col row ty, column ~ (col ::: ty))
366instance (HasUnique tab (Join outer from) row, Has col row ty, column ~ (col ::: ty))
222 => IsLabel col
367 => IsLabel col
223− (Aliased (Expression outer commons 'Ungrouped schemas params from) column) where
368+ (Aliased (Expression outer 'Ungrouped commons schemas params from) column) where
224 fromLabel = fromLabel @col `As` Alias
369 fromLabel = fromLabel @col `As` Alias
225instance (HasUnique tab (Join outer from) row, Has col row ty, columns ~ '[col ::: ty])
370instance (HasUnique tab (Join outer from) row, Has col row ty, columns ~ '[col ::: ty])
226 => IsLabel col
371 => IsLabel col
227− (NP (Aliased (Expression outer commons 'Ungrouped schemas params from)) columns) where
372+ (NP (Aliased (Expression outer 'Ungrouped commons schemas params from)) columns) where
228 fromLabel = fromLabel @col :* Nil
373 fromLabel = fromLabel @col :* Nil
230instance (Has tab (Join outer from) row, Has col row ty)
375instance (Has tab (Join outer from) row, Has col row ty)
231− => IsQualified tab col (Expression outer commons 'Ungrouped schemas params from ty) where
376+ => IsQualified tab col (Expression outer 'Ungrouped commons schemas params from ty) where
232 tab ! col = UnsafeExpression $
377 tab ! col = UnsafeExpression $
233 renderSQL tab <> "." <> renderSQL col
378 renderSQL tab <> "." <> renderSQL col
234instance (Has tab (Join outer from) row, Has col row ty, tys ~ '[ty])
379instance (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
380+ => IsQualified tab col (NP (Expression outer 'Ungrouped commons schemas params from) tys) where
236 tab ! col = tab ! col :* Nil
381 tab ! col = tab ! col :* Nil
237instance (Has tab (Join outer from) row, Has col row ty, column ~ (col ::: ty))
382instance (Has tab (Join outer from) row, Has col row ty, column ~ (col ::: ty))
238 => IsQualified tab col
383 => IsQualified tab col
239− (Aliased (Expression outer commons 'Ungrouped schemas params from) column) where
384+ (Aliased (Expression outer 'Ungrouped commons schemas params from) column) where
240 tab ! col = tab ! col `As` col
385 tab ! col = tab ! col `As` col
241instance (Has tab (Join outer from) row, Has col row ty, columns ~ '[col ::: ty])
386instance (Has tab (Join outer from) row, Has col row ty, columns ~ '[col ::: ty])
242 => IsQualified tab col
387 => IsQualified tab col
243− (NP (Aliased (Expression outer commons 'Ungrouped schemas params from)) columns) where
388+ (NP (Aliased (Expression outer 'Ungrouped commons schemas params from)) columns) where
244 tab ! col = tab ! col :* Nil
389 tab ! col = tab ! col :* Nil
@@ -248,7 +393,7 @@ instance
248 , Has col row ty
393 , Has col row ty
249 , GroupedBy tab col bys
394 , GroupedBy tab col bys
250 ) => IsLabel col
395 ) => IsLabel col
251− (Expression outer commons ('Grouped bys) schemas params from ty) where
396+ (Expression outer ('Grouped bys) commons schemas params from ty) where
252 fromLabel = UnsafeExpression $ renderSQL (Alias @col)
397 fromLabel = UnsafeExpression $ renderSQL (Alias @col)
254 ( HasUnique tab (Join outer from) row
399 ( HasUnique tab (Join outer from) row
@@ -256,7 +401,7 @@ instance
256 , GroupedBy tab col bys
401 , GroupedBy tab col bys
257 , tys ~ '[ty]
402 , tys ~ '[ty]
258 ) => IsLabel col
403 ) => IsLabel col
259− (NP (Expression outer commons ('Grouped bys) schemas params from) tys) where
404+ (NP (Expression outer ('Grouped bys) commons schemas params from) tys) where
260 fromLabel = fromLabel @col :* Nil
405 fromLabel = fromLabel @col :* Nil
262 ( HasUnique tab (Join outer from) row
407 ( HasUnique tab (Join outer from) row
@@ -264,7 +409,7 @@ instance
264 , GroupedBy tab col bys
409 , GroupedBy tab col bys
265 , column ~ (col ::: ty)
410 , column ~ (col ::: ty)
266 ) => IsLabel col
411 ) => IsLabel col
267− (Aliased (Expression outer commons ('Grouped bys) schemas params from) column) where
412+ (Aliased (Expression outer ('Grouped bys) commons schemas params from) column) where
268 fromLabel = fromLabel @col `As` Alias
413 fromLabel = fromLabel @col `As` Alias
270 ( HasUnique tab (Join outer from) row
415 ( HasUnique tab (Join outer from) row
@@ -272,7 +417,7 @@ instance
272 , GroupedBy tab col bys
417 , GroupedBy tab col bys
273 , columns ~ '[col ::: ty]
418 , columns ~ '[col ::: ty]
274 ) => IsLabel col
419 ) => IsLabel col
275− (NP (Aliased (Expression outer commons ('Grouped bys) schemas params from)) columns) where
420+ (NP (Aliased (Expression outer ('Grouped bys) commons schemas params from)) columns) where
276 fromLabel = fromLabel @col :* Nil
421 fromLabel = fromLabel @col :* Nil
@@ -280,7 +425,7 @@ instance
280 , Has col row ty
425 , Has col row ty
281 , GroupedBy tab col bys
426 , GroupedBy tab col bys
282 ) => IsQualified tab col
427 ) => IsQualified tab col
283− (Expression outer commons ('Grouped bys) schemas params from ty) where
428+ (Expression outer ('Grouped bys) commons schemas params from ty) where
284 tab ! col = UnsafeExpression $
429 tab ! col = UnsafeExpression $
285 renderSQL tab <> "." <> renderSQL col
430 renderSQL tab <> "." <> renderSQL col
@@ -289,7 +434,7 @@ instance
289 , GroupedBy tab col bys
434 , GroupedBy tab col bys
290 , tys ~ '[ty]
435 , tys ~ '[ty]
291 ) => IsQualified tab col
436 ) => IsQualified tab col
292− (NP (Expression outer commons ('Grouped bys) schemas params from) tys) where
437+ (NP (Expression outer ('Grouped bys) commons schemas params from) tys) where
293 tab ! col = tab ! col :* Nil
438 tab ! col = tab ! col :* Nil
295 ( Has tab (Join outer from) row
440 ( Has tab (Join outer from) row
@@ -297,7 +442,7 @@ instance
297 , GroupedBy tab col bys
442 , GroupedBy tab col bys
298 , column ~ (col ::: ty)
443 , column ~ (col ::: ty)
299 ) => IsQualified tab col
444 ) => IsQualified tab col
300− (Aliased (Expression outer commons ('Grouped bys) schemas params from) column) where
445+ (Aliased (Expression outer ('Grouped bys) commons schemas params from) column) where
301 tab ! col = tab ! col `As` col
446 tab ! col = tab ! col `As` col
303 ( Has tab (Join outer from) row
448 ( Has tab (Join outer from) row
@@ -305,78 +450,223 @@ instance
305 , GroupedBy tab col bys
450 , GroupedBy tab col bys
306 , columns ~ '[col ::: ty]
451 , columns ~ '[col ::: ty]
307 ) => IsQualified tab col
452 ) => IsQualified tab col
308− (NP (Aliased (Expression outer commons ('Grouped bys) schemas params from)) columns) where
453+ (NP (Aliased (Expression outer ('Grouped bys) commons schemas params from)) columns) where
309 tab ! col = tab ! col :* Nil
454 tab ! col = tab ! col :* Nil
456+-- | analagous to `Nothing`
458+-- >>> printSQL null_
460+null_ :: Expr ('Null ty)
461+null_ = UnsafeExpression "NULL"
463+-- | analagous to `Just`
465+-- >>> printSQL $ notNull true
467+notNull :: 'NotNull ty :--> 'Null ty
468+notNull = UnsafeExpression . renderSQL
470+-- | return the leftmost value which is not NULL
472+-- >>> printSQL $ coalesce [null_, true] false
473+-- COALESCE(NULL, TRUE, FALSE)
475+ :: [Expression outer grp commons schemas params from ('Null ty)]
476+ -- ^ @NULL@s may be present
477+ -> Expression outer grp commons schemas params from ('NotNull ty)
478+ -- ^ @NULL@ is absent
479+ -> Expression outer grp commons schemas params from ('NotNull ty)
480+coalesce nullxs notNullx = UnsafeExpression $
481+ "COALESCE" <> parenthesized (commaSeparated
482+ ((renderSQL <$> nullxs) <> [renderSQL notNullx]))
484+-- | analagous to `Data.Maybe.fromMaybe` using @COALESCE@
486+-- >>> printSQL $ fromNull true null_
487+-- COALESCE(NULL, TRUE)
489+ :: Expression outer grp commons schemas params from ('NotNull ty)
490+ -- ^ what to convert @NULL@ to
491+ -> Expression outer grp commons schemas params from ('Null ty)
492+ -> Expression outer grp commons schemas params from ('NotNull ty)
493+fromNull notNullx nullx = coalesce [nullx] notNullx
495+-- | >>> printSQL $ null_ & isNull
498+ :: Expression outer grp commons schemas params from ('Null ty)
499+ -- ^ possibly @NULL@
500+ -> Condition outer grp commons schemas params from
501+isNull x = UnsafeExpression $ renderSQL x <+> "IS NULL"
503+-- | >>> printSQL $ null_ & isNotNull
506+ :: Expression outer grp commons schemas params from ('Null ty)
507+ -- ^ possibly @NULL@
508+ -> Condition outer grp commons schemas params from
509+isNotNull x = UnsafeExpression $ renderSQL x <+> "IS NOT NULL"
511+-- | analagous to `maybe` using @IS NULL@
513+-- >>> printSQL $ matchNull true not_ null_
514+-- CASE WHEN NULL IS NULL THEN TRUE ELSE (NOT NULL) END
516+ :: Expression outer grp commons schemas params from (nullty)
517+ -- ^ what to convert @NULL@ to
518+ -> ( Expression outer grp commons schemas params from ('NotNull ty)
519+ -> Expression outer grp commons schemas params from (nullty) )
520+ -- ^ function to perform when @NULL@ is absent
521+ -> Expression outer grp commons schemas params from ('Null ty)
522+ -> Expression outer grp commons schemas params from (nullty)
523+matchNull y f x = ifThenElse (isNull x) y
524+ (f (UnsafeExpression (renderSQL x)))
526+{-| right inverse to `fromNull`, if its arguments are equal then
527+`nullIf` gives @NULL@.
529+>>> :set -XTypeApplications -XDataKinds
530+>>> let expr = nullIf false (param @1) :: Expression outer grp commons schemas '[ 'NotNull 'PGbool] from ('Null 'PGbool)
532+NULL IF (FALSE, ($1 :: bool))
535+ :: Expression outer grp commons schemas params from ('NotNull ty)
536+ -- ^ @NULL@ is absent
537+ -> Expression outer grp commons schemas params from ('NotNull ty)
538+ -- ^ @NULL@ is absent
539+ -> Expression outer grp commons schemas params from ('Null ty)
540+nullIf x y = UnsafeExpression $ "NULL IF" <+> parenthesized
541+ (renderSQL x <> ", " <> renderSQL y)
543+-- | >>> printSQL $ array [null_, false, true]
544+-- ARRAY[NULL, FALSE, TRUE]
546+ :: [Expression outer grp commons schemas params from ty]
548+ -> Expression outer grp commons schemas params from (null ('PGvararray ty))
549+array xs = UnsafeExpression $
550+ "ARRAY[" <> commaSeparated (renderSQL <$> xs) <> "]"
552+-- | >>> printSQL $ cardinality (array [null_, false, true])
553+-- cardinality(ARRAY[NULL, FALSE, TRUE])
554+cardinality :: null ('PGvararray ty) :--> null 'PGint8
555+cardinality = unsafeFunction "cardinality"
557+-- | >>> printSQL $ array [null_, false, true] & index 2
558+-- (ARRAY[NULL, FALSE, TRUE])[2]
560+ :: Word64 -- ^ index
561+ -> null ('PGvararray ty) :--> NullifyType ty
562+index n expr = UnsafeExpression $
563+ parenthesized (renderSQL expr) <> "[" <> fromString (show n) <> "]"
311instance (KnownSymbol label, label `In` labels) => IsPGlabel label
565instance (KnownSymbol label, label `In` labels) => IsPGlabel label
312− (Expression outer commons grp schemas params from (null ('PGenum labels))) where
566+ (Expression outer grp commons schemas params from (null ('PGenum labels))) where
313 label = UnsafeExpression $ renderSQL (PGlabel @label)
567 label = UnsafeExpression $ renderSQL (PGlabel @label)
569+-- | A row constructor is an expression that builds a row value
570+-- (also called a composite value) using values for its member fields.
573+-- type Complex = 'PGcomposite
574+-- '[ "real" ::: 'NotNull 'PGfloat8
575+-- , "imaginary" ::: 'NotNull 'PGfloat8 ]
578+-- >>> let i = row (0 `as` #real :* 1 `as` #imaginary) :: Expression outer grp commons schemas params from ('NotNull Complex)
583+ => NP (Aliased (Expression outer grp commons schemas params from)) row
584+ -- ^ zero or more expressions for the row field values
585+ -> Expression outer grp commons schemas params from (null ('PGcomposite row))
586+row exprs = UnsafeExpression $ "ROW" <> parenthesized
587+ (renderCommaSeparated (\ (expr `As` _) -> renderSQL expr) exprs)
590+-- type Complex = 'PGcomposite
591+-- '[ "real" ::: 'NotNull 'PGfloat8
592+-- , "imaginary" ::: 'NotNull 'PGfloat8 ]
593+-- type Schema = '["complex" ::: 'Typedef Complex]
596+-- >>> let i = row (0 `as` #real :* 1 `as` #imaginary) :: Expression outer grp '[] (Public Schema) from params ('NotNull Complex)
597+-- >>> printSQL $ i & field #complex #imaginary
598+-- (ROW(0, 1)::"complex")."imaginary"
600+ :: ( Has sch schemas schema
601+ , Has tydef schema ('Typedef ('PGcomposite row))
603+ => QualifiedAlias sch tydef -- ^ row type
604+ -> Alias field -- ^ field name
605+ -> Expression outer grp commons schemas params from ('NotNull ('PGcomposite row))
606+ -> Expression outer grp commons schemas params from ty
607+field td fld expr = UnsafeExpression $
608+ parenthesized (renderSQL expr <> "::" <> renderSQL td)
609+ <> "." <> renderSQL fld
612+ (Expression outer grp commons schemas params from (null ('PGvararray ty))) where
613+ (<>) = unsafeBinaryOp "||"
616+ (Expression outer grp commons schemas params from (null ('PGvararray ty))) where
620+-- | >>> let expr = greatest [param @1] currentTimestamp :: Expression outer grp commons schemas '[ 'NotNull 'PGtimestamptz] from ('NotNull 'PGtimestamptz)
622+-- GREATEST(($1 :: timestamp with time zone), CURRENT_TIMESTAMP)
623+greatest :: FunctionHom ty ty
624+greatest = unsafeFunctionHom "GREATEST"
626+-- | >>> printSQL $ least [null_] currentTimestamp
627+-- LEAST(NULL, CURRENT_TIMESTAMP)
628+least :: FunctionHom ty ty
629+least = unsafeFunctionHom "LEAST"
315-- | >>> printSQL $ unsafeBinaryOp "OR" true false
631-- | >>> printSQL $ unsafeBinaryOp "OR" true false
316-- (TRUE OR FALSE)
632-- (TRUE OR FALSE)
317−unsafeBinaryOp :: ByteString -> Operator ty0 ty1 ty2
633+unsafeBinaryOp :: ByteString {- ^ operator -} -> Operator ty0 ty1 ty2
318unsafeBinaryOp op x y = UnsafeExpression $ parenthesized $
634unsafeBinaryOp op x y = UnsafeExpression $ parenthesized $
319 renderSQL x <+> op <+> renderSQL y
635 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
637+-- | >>> printSQL $ unsafeUnaryOpL "NOT" true
329-- (NOT TRUE)
638-- (NOT TRUE)
330−unsafeLeftOp :: ByteString -> x --> y
639+unsafeUnaryOpL :: ByteString {- ^ operator -} -> x :--> y
331−unsafeLeftOp op x = UnsafeExpression $ parenthesized $ op <+> renderSQL x
640+unsafeUnaryOpL op x = UnsafeExpression $ parenthesized $ op <+> renderSQL x
333−leftOp
642+unsafeUnaryOpR :: ByteString {- ^ operator -} -> x :--> y
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
643+unsafeUnaryOpR op x = UnsafeExpression $ parenthesized $ renderSQL x <+> op
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
645-- | >>> printSQL $ unsafeFunction "f" true
353-- f(TRUE)
646-- f(TRUE)
354−unsafeFunction :: ByteString -> x --> y
647+unsafeFunction :: ByteString {- ^ function -} -> x :--> y
355unsafeFunction fun x = UnsafeExpression $
648unsafeFunction fun x = UnsafeExpression $
356 fun <> parenthesized (renderSQL x)
649 fun <> parenthesized (renderSQL x)
358−function
651+unsafeFunctionHet
359− :: (Has sch schemas schema, Has fun schema ('Function ('[x] :=> 'Returns y)))
652+ :: SListI xs
360− => QualifiedAlias sch fun
653+ => ByteString {- ^ function -}
361− -> FunctionDB schemas x y
654+ -> FunctionHet xs 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
367−unsafeFunctionN fun xs = UnsafeExpression $
655+unsafeFunctionHet fun xs = UnsafeExpression $
368 fun <> parenthesized (renderCommaSeparated renderSQL xs)
656 fun <> parenthesized (renderCommaSeparated renderSQL xs)
370−functionN
658+-- | Helper for defining variadic functions.
371− :: ( Has sch schemas schema
659+unsafeVariadicFunction
372− , Has fun schema ('Function (xs :=> 'Returns y))
373− , SListI xs )
660+ :: SListI elems
374− => QualifiedAlias sch fun
661+ => ByteString
375− -> FunctionNDB schemas xs y
662+ -- ^ function
376−functionN = unsafeFunctionN . renderSQL
663+ -> NP (Expression outer grp commons schemas params from) elems
664+ -> Expression outer grp commons schemas params from ret
665+unsafeVariadicFunction fun x = UnsafeExpression $
666+ fun <> parenthesized (commaSeparated (hcollapse (hmap (K . renderSQL) x)))
378instance ty `In` PGNum
668instance ty `In` PGNum
379− => Num (Expression outer commons grp schemas params from (null ty)) where
669+ => Num (Expression outer grp commons schemas params from (null ty)) where
380 (+) = unsafeBinaryOp "+"
670 (+) = unsafeBinaryOp "+"
381 (-) = unsafeBinaryOp "-"
671 (-) = unsafeBinaryOp "-"
382 (*) = unsafeBinaryOp "*"
672 (*) = unsafeBinaryOp "*"
@@ -388,7 +678,7 @@ instance ty `In` PGNum
390instance (ty `In` PGNum, ty `In` PGFloating) => Fractional
680instance (ty `In` PGNum, ty `In` PGFloating) => Fractional
391− (Expression outer commons grp schemas params from (null ty)) where
681+ (Expression outer grp commons schemas params from (null ty)) where
392 (/) = unsafeBinaryOp "/"
682 (/) = unsafeBinaryOp "/"
393 fromRational
683 fromRational
394 = UnsafeExpression
684 = UnsafeExpression
@@ -398,7 +688,7 @@ instance (ty `In` PGNum, ty `In` PGFloating) => Fractional
398 . fromRat @Double
688 . fromRat @Double
400instance (ty `In` PGNum, ty `In` PGFloating) => Floating
690instance (ty `In` PGNum, ty `In` PGFloating) => Floating
401− (Expression outer commons grp schemas params from (null ty)) where
691+ (Expression outer grp commons schemas params from (null ty)) where
402 pi = UnsafeExpression "pi()"
692 pi = UnsafeExpression "pi()"
403 exp = unsafeFunction "exp"
693 exp = unsafeFunction "exp"
404 log = unsafeFunction "ln"
694 log = unsafeFunction "ln"
@@ -419,54 +709,1764 @@ instance (ty `In` PGNum, ty `In` PGFloating) => Floating
419 acosh x = log (x + sqrt (x*x - 1))
709 acosh x = log (x + sqrt (x*x - 1))
420 atanh x = log ((1 + x) / (1 - x)) / 2
710 atanh x = log ((1 + x) / (1 - x)) / 2
422−-- | Contained by operators
712+-- | >>> :{
423−class PGSubset ty where
713+-- let
424− (@>) :: Operator (null0 ty) (null1 ty) ('Null 'PGbool)
714+-- expression :: Expr (null 'PGfloat4)
425− (@>) = unsafeBinaryOp "@>"
715+-- expression = atan2_ (pi *: 2)
426− (<@) :: Operator (null0 ty) (null1 ty) ('Null 'PGbool)
716+-- in printSQL expression
427− (<@) = unsafeBinaryOp "<@"
717+-- :}
428−instance PGSubset 'PGjsonb
718+-- atan2(pi(), 2)
429−instance PGSubset 'PGtsquery
719+atan2_
430−instance PGSubset ('PGvararray ty)
720+ :: float `In` PGFloating
431−instance PGSubset ('PGrange ty)
721+ => FunctionHet '[ null float, null float] (null float)
722+atan2_ = unsafeFunctionHet "atan2"
724+-- When a `cast` is applied to an `Expression` of a known type, it
725+-- represents a run-time type conversion. The cast will succeed only if a
726+-- suitable type conversion operation has been defined.
728+-- | >>> printSQL $ true & cast int4
731+ :: TypeExpression schemas ty1
732+ -- ^ type to cast as
733+ -> Expression outer grp commons schemas params from ty0
734+ -- ^ value to convert
735+ -> Expression outer grp commons schemas params from ty1
736+cast ty x = UnsafeExpression $ parenthesized $
737+ renderSQL x <+> "::" <+> renderSQL ty
739+-- | integer division, truncates the result
743+-- expression :: Expression outer grp commons schemas params from (null 'PGint2)
744+-- expression = 5 `quot_` 2
745+-- in printSQL expression
749+ :: int `In` PGIntegral
750+ => Operator (null int) (null int) (null int)
751+quot_ = unsafeBinaryOp "/"
753+-- | remainder upon integer division
757+-- expression :: Expression outer grp commons schemas params from (null 'PGint2)
758+-- expression = 5 `rem_` 2
759+-- in printSQL expression
763+ :: int `In` PGIntegral
764+ => Operator (null int) (null int) (null int)
765+rem_ = unsafeBinaryOp "%"
769+-- expression :: Expression outer grp commons schemas params from (null 'PGfloat4)
770+-- expression = trunc pi
771+-- in printSQL expression
774+trunc :: frac `In` PGFloating => null frac :--> null frac
775+trunc = unsafeFunction "trunc"
779+-- expression :: Expression outer grp commons schemas params from (null 'PGfloat4)
780+-- expression = round_ pi
781+-- in printSQL expression
784+round_ :: frac `In` PGFloating => null frac :--> null frac
785+round_ = unsafeFunction "round"
789+-- expression :: Expression outer grp commons schemas params from (null 'PGfloat4)
790+-- expression = ceiling_ pi
791+-- in printSQL expression
794+ceiling_ :: frac `In` PGFloating => null frac :--> null frac
795+ceiling_ = unsafeFunction "ceiling"
797+-- | A `Condition` is an `Expression`, which can evaluate
798+-- to `true`, `false` or `null_`. This is because SQL uses
799+-- a three valued logic.
800+type Condition outer grp commons schemas params from =
801+ Expression outer grp commons schemas params from ('Null 'PGbool)
803+-- | >>> printSQL true
805+true :: Expr (null 'PGbool)
806+true = UnsafeExpression "TRUE"
433−class PGIntersect ty where
808+-- | >>> printSQL false
810+false :: Expr (null 'PGbool)
811+false = UnsafeExpression "FALSE"
813+-- | >>> printSQL $ not_ true
815+not_ :: null 'PGbool :--> null 'PGbool
816+not_ = unsafeUnaryOpL "NOT"
818+-- | >>> printSQL $ true .&& false
434− (@&&) :: Operator (null0 ty) (null1 ty) ('Null 'PGbool)
820+(.&&) :: Operator (null 'PGbool) (null 'PGbool) (null 'PGbool)
435− (@&&) = unsafeBinaryOp "&&"
822+(.&&) = unsafeBinaryOp "AND"
436−instance PGIntersect ('PGvararray ty)
823+
437−instance PGIntersect ('PGrange ty)
824+-- | >>> printSQL $ true .|| false
826+(.||) :: Operator (null 'PGbool) (null 'PGbool) (null 'PGbool)
828+(.||) = unsafeBinaryOp "OR"
832+-- expression :: Expression outer grp commons schemas params from (null 'PGint2)
833+-- expression = caseWhenThenElse [(true, 1), (false, 2)] 3
834+-- in printSQL expression
836+-- CASE WHEN TRUE THEN 1 WHEN FALSE THEN 2 ELSE 3 END
838+ :: [ ( Condition outer grp commons schemas params from
839+ , Expression outer grp commons schemas params from ty
841+ -- ^ whens and thens
842+ -> Expression outer grp commons schemas params from ty
844+ -> Expression outer grp commons schemas params from ty
845+caseWhenThenElse whenThens else_ = UnsafeExpression $ mconcat
849+ [ " WHEN ", renderSQL when_
850+ , " THEN ", renderSQL then_
852+ | (when_,then_) <- whenThens
854+ , " ELSE ", renderSQL else_
860+-- expression :: Expression outer grp commons schemas params from (null 'PGint2)
861+-- expression = ifThenElse true 1 0
862+-- in printSQL expression
864+-- CASE WHEN TRUE THEN 1 ELSE 0 END
866+ :: Condition outer grp commons schemas params from
867+ -> Expression outer grp commons schemas params from ty -- ^ then
868+ -> Expression outer grp commons schemas params from ty -- ^ else
869+ -> Expression outer grp commons schemas params from ty
870+ifThenElse if_ then_ else_ = caseWhenThenElse [(if_,then_)] else_
872+-- | Comparison operations like `.==`, `./=`, `.>`, `.>=`, `.<` and `.<=`
873+-- will produce @NULL@s if one of their arguments is @NULL@.
875+-- >>> printSQL $ true .== null_
877+(.==) :: Operator (null0 ty) (null1 ty) ('Null 'PGbool)
878+(.==) = unsafeBinaryOp "="
881+-- | >>> printSQL $ true ./= null_
883+(./=) :: Operator (null0 ty) (null1 ty) ('Null 'PGbool)
884+(./=) = unsafeBinaryOp "<>"
887+-- | >>> printSQL $ true .>= null_
889+(.>=) :: Operator (null0 ty) (null1 ty) ('Null 'PGbool)
890+(.>=) = unsafeBinaryOp ">="
893+-- | >>> printSQL $ true .< null_
895+(.<) :: Operator (null0 ty) (null1 ty) ('Null 'PGbool)
896+(.<) = unsafeBinaryOp "<"
899+-- | >>> printSQL $ true .<= null_
901+(.<=) :: Operator (null0 ty) (null1 ty) ('Null 'PGbool)
902+(.<=) = unsafeBinaryOp "<="
905+-- | >>> printSQL $ true .> null_
907+(.>) :: Operator (null0 ty) (null1 ty) ('Null 'PGbool)
908+(.>) = unsafeBinaryOp ">"
912+>>> printSQL $ true `between` (null_, false)
913+TRUE BETWEEN NULL AND FALSE
916+ :: Expression outer grp commons schemas params from (null ty)
917+ -> ( Expression outer grp commons schemas params from (null ty)
918+ , Expression outer grp commons schemas params from (null ty) ) -- ^ bounds
919+ -> Condition outer grp commons schemas params from
920+between a (x,y) = UnsafeExpression $ renderSQL a <+> "BETWEEN"
921+ <+> renderSQL x <+> "AND" <+> renderSQL y
924+>>> printSQL $ true `notBetween` (null_, false)
925+TRUE NOT BETWEEN NULL AND FALSE
928+ :: Expression outer grp commons schemas params from (null ty)
929+ -> ( Expression outer grp commons schemas params from (null ty)
930+ , Expression outer grp commons schemas params from (null ty) ) -- ^ bounds
931+ -> Condition outer grp commons schemas params from
932+notBetween a (x,y) = UnsafeExpression $ renderSQL a <+> "NOT BETWEEN"
933+ <+> renderSQL x <+> "AND" <+> renderSQL y
935+{- | between, after sorting the comparison values
936+>>> printSQL $ true `betweenSymmetric` (null_, false)
937+TRUE BETWEEN SYMMETRIC NULL AND FALSE
940+ :: Expression outer grp commons schemas params from (null ty)
941+ -> ( Expression outer grp commons schemas params from (null ty)
942+ , Expression outer grp commons schemas params from (null ty) ) -- ^ bounds
943+ -> Condition outer grp commons schemas params from
944+betweenSymmetric a (x,y) = UnsafeExpression $ renderSQL a
945+ <+> "BETWEEN SYMMETRIC" <+> renderSQL x <+> "AND" <+> renderSQL y
947+{- | not between, after sorting the comparison values
948+>>> printSQL $ true `notBetweenSymmetric` (null_, false)
949+TRUE NOT BETWEEN SYMMETRIC NULL AND FALSE
952+ :: Expression outer grp commons schemas params from (null ty)
953+ -> ( Expression outer grp commons schemas params from (null ty)
954+ , Expression outer grp commons schemas params from (null ty) ) -- ^ bounds
955+ -> Condition outer grp commons schemas params from
956+notBetweenSymmetric a (x,y) = UnsafeExpression $ renderSQL a
957+ <+> "NOT BETWEEN SYMMETRIC" <+> renderSQL x <+> "AND" <+> renderSQL y
959+{- | not equal, treating null like an ordinary value
960+>>> printSQL $ true `isDistinctFrom` null_
961+(TRUE IS DISTINCT FROM NULL)
963+isDistinctFrom :: Operator (null0 ty) (null1 ty) ('Null 'PGbool)
964+isDistinctFrom = unsafeBinaryOp "IS DISTINCT FROM"
966+{- | equal, treating null like an ordinary value
967+>>> printSQL $ true `isNotDistinctFrom` null_
968+(TRUE IS NOT DISTINCT FROM NULL)
970+isNotDistinctFrom :: Operator (null0 ty) (null1 ty) ('NotNull 'PGbool)
971+isNotDistinctFrom = unsafeBinaryOp "IS NOT DISTINCT FROM"
974+>>> printSQL $ true & isTrue
977+isTrue :: null 'PGbool :--> 'NotNull 'PGbool
978+isTrue = unsafeUnaryOpR "IS TRUE"
980+{- | is false or unknown
981+>>> printSQL $ true & isNotTrue
984+isNotTrue :: null 'PGbool :--> 'NotNull 'PGbool
985+isNotTrue = unsafeUnaryOpR "IS NOT TRUE"
988+>>> printSQL $ true & isFalse
991+isFalse :: null 'PGbool :--> 'NotNull 'PGbool
992+isFalse = unsafeUnaryOpR "IS FALSE"
994+{- | is true or unknown
995+>>> printSQL $ true & isNotFalse
998+isNotFalse :: null 'PGbool :--> 'NotNull 'PGbool
999+isNotFalse = unsafeUnaryOpR "IS NOT FALSE"
1002+>>> printSQL $ true & isUnknown
1005+isUnknown :: null 'PGbool :--> 'NotNull 'PGbool
1006+isUnknown = unsafeUnaryOpR "IS UNKNOWN"
1008+{- | is true or false
1009+>>> printSQL $ true & isNotUnknown
1010+(TRUE IS NOT UNKNOWN)
1012+isNotUnknown :: null 'PGbool :--> 'NotNull 'PGbool
1013+isNotUnknown = unsafeUnaryOpR "IS NOT UNKNOWN"
1015+-- | >>> printSQL currentDate
1017+currentDate :: Expr (null 'PGdate)
1018+currentDate = UnsafeExpression "CURRENT_DATE"
1020+-- | >>> printSQL currentTime
1022+currentTime :: Expr (null 'PGtimetz)
1023+currentTime = UnsafeExpression "CURRENT_TIME"
1025+-- | >>> printSQL currentTimestamp
1026+-- CURRENT_TIMESTAMP
1027+currentTimestamp :: Expr (null 'PGtimestamptz)
1028+currentTimestamp = UnsafeExpression "CURRENT_TIMESTAMP"
1030+-- | >>> printSQL localTime
1032+localTime :: Expr (null 'PGtime)
1033+localTime = UnsafeExpression "LOCALTIME"
1035+-- | >>> printSQL localTimestamp
1037+localTimestamp :: Expr (null 'PGtimestamp)
1038+localTimestamp = UnsafeExpression "LOCALTIMESTAMP"
1040+{-----------------------------------------
1042+-----------------------------------------}
1044+escape :: Char -> String
439instance IsString
1056instance IsString
440− (Expression outer commons grp schemas params from (null 'PGtext)) where
1057+ (Expression outer grp commons schemas params from (null 'PGtext)) where
441 fromString str = UnsafeExpression $
1058 fromString str = UnsafeExpression $
442 "E\'" <> fromString (escape =<< str) <> "\'"
1059 "E\'" <> fromString (escape =<< str) <> "\'"
443instance IsString
1060instance IsString
444− (Expression outer commons grp schemas params from (null 'PGtsvector)) where
1061+ (Expression outer grp commons schemas params from (null 'PGtsvector)) where
445− fromString str = UnsafeExpression . parenthesized . (<> " :: tsvector") $
1062+ fromString str = cast tsvector . UnsafeExpression $
446 "E\'" <> fromString (escape =<< str) <> "\'"
1063 "E\'" <> fromString (escape =<< str) <> "\'"
447instance IsString
1064instance IsString
448− (Expression outer commons grp schemas params from (null 'PGtsquery)) where
1065+ (Expression outer grp commons schemas params from (null 'PGtsquery)) where
449− fromString str = UnsafeExpression . parenthesized . (<> " :: tsquery") $
1066+ fromString str = cast tsquery . UnsafeExpression $
450 "E\'" <> fromString (escape =<< str) <> "\'"
1067 "E\'" <> fromString (escape =<< str) <> "\'"
452instance Semigroup
1069instance Semigroup
453− (Expression outer commons grp schemas params from (null ('PGvararray ty))) where
1070+ (Expression outer grp commons schemas params from (null 'PGtext)) where
454 (<>) = unsafeBinaryOp "||"
1071 (<>) = unsafeBinaryOp "||"
455instance Semigroup
1072instance Semigroup
456− (Expression outer commons grp schemas params from (null 'PGjsonb)) where
457− (<>) = unsafeBinaryOp "||"
459− (Expression outer commons grp schemas params from (null 'PGtext)) where
460− (<>) = unsafeBinaryOp "||"
462− (Expression outer commons grp schemas params from (null 'PGtsvector)) where
1073+ (Expression outer grp commons schemas params from (null 'PGtsvector)) where
463 (<>) = unsafeBinaryOp "||"
1074 (<>) = unsafeBinaryOp "||"
465instance Monoid
1076instance Monoid
466− (Expression outer commons grp schemas params from (null 'PGtext)) where
1077+ (Expression outer grp commons schemas params from (null 'PGtext)) where
467 mempty = fromString ""
1078 mempty = fromString ""
468 mappend = (<>)
1079 mappend = (<>)
469instance Monoid
1080instance Monoid
470− (Expression outer commons grp schemas params from (null 'PGtsvector)) where
1081+ (Expression outer grp commons schemas params from (null 'PGtsvector)) where
471 mempty = fromString ""
1082 mempty = fromString ""
472 mappend = (<>)
1083 mappend = (<>)
1085+-- | >>> printSQL $ lower "ARRRGGG"
1086+-- lower(E'ARRRGGG')
1087+lower :: null 'PGtext :--> null 'PGtext
1088+lower = unsafeFunction "lower"
1090+-- | >>> printSQL $ upper "eeee"
1092+upper :: null 'PGtext :--> null 'PGtext
1093+upper = unsafeFunction "upper"
1095+-- | >>> printSQL $ charLength "four"
1096+-- char_length(E'four')
1097+charLength :: null 'PGtext :--> null 'PGint4
1098+charLength = unsafeFunction "char_length"
1100+-- | The `like` expression returns true if the @string@ matches
1101+-- the supplied @pattern@. If @pattern@ does not contain percent signs
1102+-- or underscores, then the pattern only represents the string itself;
1103+-- in that case `like` acts like the equals operator. An underscore (_)
1104+-- in pattern stands for (matches) any single character; a percent sign (%)
1105+-- matches any sequence of zero or more characters.
1107+-- >>> printSQL $ "abc" `like` "a%"
1108+-- (E'abc' LIKE E'a%')
1109+like :: Operator (null 'PGtext) (null 'PGtext) ('Null 'PGbool)
1110+like = unsafeBinaryOp "LIKE"
1112+-- | The key word ILIKE can be used instead of LIKE to make the
1113+-- match case-insensitive according to the active locale.
1115+-- >>> printSQL $ "abc" `ilike` "a%"
1116+-- (E'abc' ILIKE E'a%')
1117+ilike :: Operator (null 'PGtext) (null 'PGtext) ('Null 'PGbool)
1118+ilike = unsafeBinaryOp "ILIKE"
1120+{-----------------------------------------
1121+ -- json and jsonb support
1123+See https://www.postgresql.org/docs/10/static/functions-json.html -- most
1124+comments lifted directly from this page.
1126+Table 9.44: json and jsonb operators
1127+-----------------------------------------}
1129+-- | Get JSON value (object field or array element) at a key.
1131+ :: (json `In` PGJsonType, key `In` PGJsonKey)
1132+ => Operator (null json) (null key) ('Null json)
1134+(.->) = unsafeBinaryOp "->"
1136+-- | Get JSON value (object field or array element) at a key, as text.
1138+ :: (json `In` PGJsonType, key `In` PGJsonKey)
1139+ => Operator (null json) (null key) ('Null 'PGtext)
1141+(.->>) = unsafeBinaryOp "->>"
1143+-- | Get JSON value at a specified path.
1145+ :: (json `In` PGJsonType, PGTextArray "(.#>)" path)
1146+ => Operator (null json) (null path) ('Null json)
1148+(.#>) = unsafeBinaryOp "#>"
1150+-- | Get JSON value at a specified path as text.
1152+ :: (json `In` PGJsonType, PGTextArray "(.#>>)" path)
1153+ => Operator (null json) (null path) ('Null 'PGtext)
1155+(.#>>) = unsafeBinaryOp "#>>"
1157+-- Additional jsonb operators
1159+class PGSubset container where
1160+ (@>) :: Operator (null0 container) (null1 container) ('Null 'PGbool)
1161+ (@>) = unsafeBinaryOp "@>"
1162+ (<@) :: Operator (null0 container) (null1 container) ('Null 'PGbool)
1163+ (<@) = unsafeBinaryOp "<@"
1164+instance PGSubset 'PGjsonb
1165+instance PGSubset 'PGtsquery
1166+instance PGSubset ('PGvararray ty)
1168+-- | Does the string exist as a top-level key within the JSON value?
1169+(.?) :: Operator (null 'PGjsonb) (null 'PGtext) ('Null 'PGbool)
1171+(.?) = unsafeBinaryOp "?"
1173+-- | Do any of these array strings exist as top-level keys?
1176+ (null ('PGvararray ('NotNull 'PGtext)))
1179+(.?|) = unsafeBinaryOp "?|"
1181+-- | Do all of these array strings exist as top-level keys?
1184+ (null ('PGvararray ('NotNull 'PGtext)))
1187+(.?&) = unsafeBinaryOp "?&"
1189+-- | Concatenate two jsonb values into a new jsonb value.
1191+ (Expression outer grp commons schemas params from (null 'PGjsonb)) where
1192+ (<>) = unsafeBinaryOp "||"
1194+-- | Delete a key or keys from a JSON object, or remove an array element.
1196+-- If the right operand is..
1198+-- @ text @: Delete key/value pair or string element from left operand. Key/value pairs
1199+-- are matched based on their key value.
1201+-- @ text[] @: Delete multiple key/value pairs or string elements
1202+-- from left operand. Key/value pairs are matched based on their key value.
1204+-- @ integer @: Delete the array element with specified index (Negative integers
1205+-- count from the end). Throws an error if top level container is not an array.
1207+ :: (key `In` '[ 'PGtext, 'PGvararray ('NotNull 'PGtext), 'PGint4, 'PGint2 ]) -- hlint error without parens here
1208+ => Operator (null 'PGjsonb) (null key) (null 'PGjsonb)
1210+(.-.) = unsafeBinaryOp "-"
1212+-- | Delete the field or element with specified path (for JSON arrays, negative
1213+-- integers count from the end)
1215+ :: PGTextArray "(#-.)" arrayty
1216+ => Operator (null 'PGjsonb) (null arrayty)(null 'PGjsonb)
1218+(#-.) = unsafeBinaryOp "#-"
1220+{-----------------------------------------
1221+Table 9.45: JSON creation functions
1222+-----------------------------------------}
1224+-- | Literal binary JSON
1225+jsonbLit :: JSON.ToJSON x => x -> Expr (null 'PGjsonb)
1226+jsonbLit = cast jsonb . UnsafeExpression
1227+ . singleQuotedUtf8 . toStrict . JSON.encode
1230+jsonLit :: JSON.ToJSON x => x -> Expr (null 'PGjson)
1231+jsonLit = cast json . UnsafeExpression
1232+ . singleQuotedUtf8 . toStrict . JSON.encode
1234+-- | Returns the value as json. Arrays and composites are converted
1235+-- (recursively) to arrays and objects; otherwise, if there is a cast from the
1236+-- type to json, the cast function will be used to perform the conversion;
1237+-- otherwise, a scalar value is produced. For any scalar type other than a
1238+-- number, a Boolean, or a null value, the text representation will be used, in
1239+-- such a fashion that it is a valid json value.
1240+toJson :: null ty :--> null 'PGjson
1241+toJson = unsafeFunction "to_json"
1243+-- | Returns the value as jsonb. Arrays and composites are converted
1244+-- (recursively) to arrays and objects; otherwise, if there is a cast from the
1245+-- type to json, the cast function will be used to perform the conversion;
1246+-- otherwise, a scalar value is produced. For any scalar type other than a
1247+-- number, a Boolean, or a null value, the text representation will be used, in
1248+-- such a fashion that it is a valid jsonb value.
1249+toJsonb :: null ty :--> null 'PGjsonb
1250+toJsonb = unsafeFunction "to_jsonb"
1252+-- | Returns the array as a JSON array. A PostgreSQL multidimensional array
1253+-- becomes a JSON array of arrays.
1255+ :: PGArray "arrayToJson" arr
1256+ => null arr :--> null 'PGjson
1257+arrayToJson = unsafeFunction "array_to_json"
1259+-- | Returns the row as a JSON object.
1260+rowToJson :: null ('PGcomposite ty) :--> null 'PGjson
1261+rowToJson = unsafeFunction "row_to_json"
1263+-- | Builds a possibly-heterogeneously-typed JSON array out of a variadic
1267+ => NP (Expression outer grp commons schemas params from) elems
1268+ -> Expression outer grp commons schemas params from (null 'PGjson)
1269+jsonBuildArray = unsafeVariadicFunction "json_build_array"
1271+-- | Builds a possibly-heterogeneously-typed (binary) JSON array out of a
1272+-- variadic argument list.
1275+ => NP (Expression outer grp commons schemas params from) elems
1276+ -> Expression outer grp commons schemas params from (null 'PGjsonb)
1277+jsonbBuildArray = unsafeVariadicFunction "jsonb_build_array"
1280+ :: SOP.SListI elems
1281+ => NP (Aliased (Expression outer grp commons schemas params from)) elems
1284+ (`appEndo` []) . hcfoldMap (Proxy :: SOP.Proxy SOP.Top)
1285+ (\(col `As` name) -> Endo $ \xs ->
1286+ renderAliasString name : renderSQL col : xs)
1288+ renderAliasString :: KnownSymbol alias => Alias alias -> ByteString
1289+ renderAliasString = singleQuotedText . fromString . symbolVal
1291+-- | Builds a possibly-heterogeneously-typed JSON object out of a variadic
1292+-- argument list. The elements of the argument list must alternate between text
1295+ :: SOP.SListI elems
1296+ => NP (Aliased (Expression outer grp commons schemas params from)) elems
1297+ -> Expression outer grp commons schemas params from (null 'PGjson)
1299+ = unsafeFunction "json_build_object"
1302+ . unsafeRowFunction
1304+-- | Builds a possibly-heterogeneously-typed (binary) JSON object out of a
1305+-- variadic argument list. The elements of the argument list must alternate
1306+-- between text and values.
1308+ :: SOP.SListI elems
1309+ => NP (Aliased (Expression outer grp commons schemas params from)) elems
1310+ -> Expression outer grp commons schemas params from (null 'PGjsonb)
1312+ = unsafeFunction "jsonb_build_object"
1315+ . unsafeRowFunction
1317+-- | Builds a JSON object out of a text array. The array must have either
1318+-- exactly one dimension with an even number of members, in which case they are
1319+-- taken as alternating key/value pairs, or two dimensions such that each inner
1320+-- array has exactly two elements, which are taken as a key/value pair.
1322+ :: PGArrayOf "jsonObject" arr ('NotNull 'PGtext)
1323+ => null arr :--> null 'PGjson
1324+jsonObject = unsafeFunction "json_object"
1326+-- | Builds a binary JSON object out of a text array. The array must have either
1327+-- exactly one dimension with an even number of members, in which case they are
1328+-- taken as alternating key/value pairs, or two dimensions such that each inner
1329+-- array has exactly two elements, which are taken as a key/value pair.
1331+ :: PGArrayOf "jsonbObject" arr ('NotNull 'PGtext)
1332+ => null arr :--> null 'PGjsonb
1333+jsonbObject = unsafeFunction "jsonb_object"
1335+-- | This is an alternate form of 'jsonObject' that takes two arrays; one for
1336+-- keys and one for values, that are zipped pairwise to create a JSON object.
1338+ :: ( PGArrayOf "jsonZipObject" keysArray ('NotNull 'PGtext)
1339+ , PGArrayOf "jsonZipObject" valuesArray ('NotNull 'PGtext))
1340+ => Expression outer grp commons schemas params from (null keysArray)
1341+ -> Expression outer grp commons schemas params from (null valuesArray)
1342+ -> Expression outer grp commons schemas params from (null 'PGjson)
1343+jsonZipObject ks vs =
1344+ unsafeVariadicFunction "json_object" (ks :* vs :* Nil)
1346+-- | This is an alternate form of 'jsonObject' that takes two arrays; one for
1347+-- keys and one for values, that are zipped pairwise to create a binary JSON
1350+ :: ( PGArrayOf "jsonbZipObject" keysArray ('NotNull 'PGtext)
1351+ , PGArrayOf "jsonbZipObject" valuesArray ('NotNull 'PGtext))
1352+ => Expression outer grp commons schemas params from (null keysArray)
1353+ -> Expression outer grp commons schemas params from (null valuesArray)
1354+ -> Expression outer grp commons schemas params from (null 'PGjsonb)
1355+jsonbZipObject ks vs =
1356+ unsafeVariadicFunction "jsonb_object" (ks :* vs :* Nil)
1358+{-----------------------------------------
1359+Table 9.46: JSON processing functions
1360+-----------------------------------------}
1362+-- | Returns the number of elements in the outermost JSON array.
1363+jsonArrayLength :: null 'PGjson :--> null 'PGint4
1364+jsonArrayLength = unsafeFunction "json_array_length"
1366+-- | Returns the number of elements in the outermost binary JSON array.
1367+jsonbArrayLength :: null 'PGjsonb :--> null 'PGint4
1368+jsonbArrayLength = unsafeFunction "jsonb_array_length"
1370+-- | Returns JSON value pointed to by the given path (equivalent to #>
1374+ => Expression outer grp commons schemas params from (null 'PGjson)
1375+ -> NP (Expression outer grp commons schemas params from) elems
1376+ -> Expression outer grp commons schemas params from (null 'PGjsonb)
1377+jsonExtractPath x xs =
1378+ unsafeVariadicFunction "json_extract_path" (x :* xs)
1380+-- | Returns JSON value pointed to by the given path (equivalent to #>
1384+ => Expression outer grp commons schemas params from (null 'PGjsonb)
1385+ -> NP (Expression outer grp commons schemas params from) elems
1386+ -> Expression outer grp commons schemas params from (null 'PGjsonb)
1387+jsonbExtractPath x xs =
1388+ unsafeVariadicFunction "jsonb_extract_path" (x :* xs)
1390+-- | Returns JSON value pointed to by the given path (equivalent to #>
1391+-- operator), as text.
1392+jsonExtractPathAsText
1394+ => Expression outer grp commons schemas params from (null 'PGjson)
1395+ -> NP (Expression outer grp commons schemas params from) elems
1396+ -> Expression outer grp commons schemas params from (null 'PGjson)
1397+jsonExtractPathAsText x xs =
1398+ unsafeVariadicFunction "json_extract_path_text" (x :* xs)
1400+-- | Returns JSON value pointed to by the given path (equivalent to #>
1401+-- operator), as text.
1402+jsonbExtractPathAsText
1404+ => Expression outer grp commons schemas params from (null 'PGjsonb)
1405+ -> NP (Expression outer grp commons schemas params from) elems
1406+ -> Expression outer grp commons schemas params from (null 'PGjsonb)
1407+jsonbExtractPathAsText x xs =
1408+ unsafeVariadicFunction "jsonb_extract_path_text" (x :* xs)
1410+-- | Returns the type of the outermost JSON value as a text string. Possible
1411+-- types are object, array, string, number, boolean, and null.
1412+jsonTypeof :: null 'PGjson :--> null 'PGtext
1413+jsonTypeof = unsafeFunction "json_typeof"
1415+-- | Returns the type of the outermost binary JSON value as a text string.
1416+-- Possible types are object, array, string, number, boolean, and null.
1417+jsonbTypeof :: null 'PGjsonb :--> null 'PGtext
1418+jsonbTypeof = unsafeFunction "jsonb_typeof"
1420+-- | Returns its argument with all object fields that have null values omitted.
1421+-- Other null values are untouched.
1422+jsonStripNulls :: null 'PGjson :--> null 'PGjson
1423+jsonStripNulls = unsafeFunction "json_strip_nulls"
1425+-- | Returns its argument with all object fields that have null values omitted.
1426+-- Other null values are untouched.
1427+jsonbStripNulls :: null 'PGjsonb :--> null 'PGjsonb
1428+jsonbStripNulls = unsafeFunction "jsonb_strip_nulls"
1430+-- | @ jsonbSet target path new_value create_missing @
1432+-- Returns target with the section designated by path replaced by new_value,
1433+-- or with new_value added if create_missing is true ( default is true) and the
1434+-- item designated by path does not exist. As with the path orientated
1435+-- operators, negative integers that appear in path count from the end of JSON
1438+ :: PGTextArray "jsonbSet" arr
1439+ => Expression outer grp commons schemas params from (null 'PGjsonb)
1440+ -> Expression outer grp commons schemas params from (null arr)
1441+ -> Expression outer grp commons schemas params from (null 'PGjsonb)
1442+ -> Maybe (Expression outer grp commons schemas params from (null 'PGbool))
1443+ -> Expression outer grp commons schemas params from (null 'PGjsonb)
1444+jsonbSet tgt path val createMissing = case createMissing of
1445+ Just m -> unsafeVariadicFunction "jsonb_set" (tgt :* path :* val :* m :* Nil)
1446+ Nothing -> unsafeVariadicFunction "jsonb_set" (tgt :* path :* val :* Nil)
1448+-- | @ jsonbInsert target path new_value insert_after @
1450+-- Returns target with new_value inserted. If target section designated by
1451+-- path is in a JSONB array, new_value will be inserted before target or after
1452+-- if insert_after is true (default is false). If target section designated by
1453+-- path is in JSONB object, new_value will be inserted only if target does not
1454+-- exist. As with the path orientated operators, negative integers that appear
1455+-- in path count from the end of JSON arrays.
1457+ :: PGTextArray "jsonbInsert" arr
1458+ => Expression outer grp commons schemas params from (null 'PGjsonb)
1459+ -> Expression outer grp commons schemas params from (null arr)
1460+ -> Expression outer grp commons schemas params from (null 'PGjsonb)
1461+ -> Maybe (Expression outer grp commons schemas params from (null 'PGbool))
1462+ -> Expression outer grp commons schemas params from (null 'PGjsonb)
1463+jsonbInsert tgt path val insertAfter = case insertAfter of
1464+ Just i -> unsafeVariadicFunction "jsonb_insert" (tgt :* path :* val :* i :* Nil)
1465+ Nothing -> unsafeVariadicFunction "jsonb_insert" (tgt :* path :* val :* Nil)
1467+-- | Returns its argument as indented JSON text.
1468+jsonbPretty :: null 'PGjsonb :--> null 'PGtext
1469+jsonbPretty = unsafeFunction "jsonb_pretty"
1471+(@@) :: Operator (null 'PGtsvector) (null 'PGtsquery) ('Null 'PGbool)
1472+(@@) = unsafeBinaryOp "@@"
1474+(.&) :: Operator (null 'PGtsquery) (null 'PGtsquery) (null 'PGtsquery)
1475+(.&) = unsafeBinaryOp "&&"
1477+(.|) :: Operator (null 'PGtsquery) (null 'PGtsquery) (null 'PGtsquery)
1478+(.|) = unsafeBinaryOp "||"
1480+(.!) :: null 'PGtsquery :--> null 'PGtsquery
1481+(.!) = unsafeUnaryOpL "!!"
1483+(<->) :: Operator (null 'PGtsquery) (null 'PGtsquery) (null 'PGtsquery)
1484+(<->) = unsafeBinaryOp "<->"
1487+ :: null ('PGvararray ('NotNull 'PGtext))
1488+ :--> null 'PGtsvector
1489+arrayToTSvector = unsafeFunction "array_to_tsvector"
1491+tsvectorLength :: null 'PGtsvector :--> null 'PGint4
1492+tsvectorLength = unsafeFunction "length"
1494+numnode :: null 'PGtsquery :--> null 'PGint4
1495+numnode = unsafeFunction "numnode"
1498+ :: FunctionHet '[null 'PGtext, null 'PGtext] (null 'PGtsquery)
1499+plainToTSquery = unsafeFunctionHet "plainto_tsquery"
1502+ :: FunctionHet '[null 'PGtext, null 'PGtext] (null 'PGtsquery)
1503+phraseToTSquery = unsafeFunctionHet "phraseto_tsquery"
1506+ :: FunctionHet '[null 'PGtext, null 'PGtext] (null 'PGtsquery)
1507+websearchToTSquery = unsafeFunctionHet "websearch_to_tsquery"
1509+queryTree :: null 'PGtsquery :--> null 'PGtext
1510+queryTree = unsafeFunction "query_tree"
1513+ :: FunctionHet '[null 'PGtext, null 'PGtext] (null 'PGtsquery)
1514+toTSquery = unsafeFunctionHet "to_tsquery"
1517+ :: ty `In` '[ 'PGtext, 'PGjson, 'PGjsonb]
1518+ => FunctionHet '[null 'PGtext, null ty] (null 'PGtsquery)
1519+toTSvector = unsafeFunctionHet "to_tsvector"
1521+{-----------------------------------------
1523+-----------------------------------------}
1526+`Aggregate` functions compute a single result from a set of input values.
1527+`Aggregate` functions can be used as `GroupedBy` `Expression`s as well
1528+as `WindowFunction`s.
1530+class Aggregate expr1 expr2 aggr
1531+ | aggr -> expr1, aggr -> expr2 where
1533+ -- | A special aggregation that does not require an input
1537+ -- expression :: Expression '[] ('Grouped bys) commons schemas params from ('NotNull 'PGint8)
1538+ -- expression = countStar
1539+ -- in printSQL expression
1542+ countStar :: aggr ('NotNull 'PGint8)
1546+ -- expression :: Expression '[] ('Grouped bys) commons schemas params '[tab ::: '["col" ::: null ty]] ('NotNull 'PGint8)
1547+ -- expression = count (All #col)
1548+ -- in printSQL expression
1550+ -- count(ALL "col")
1554+ -> aggr ('NotNull 'PGint8)
1558+ -- expression :: Expression '[] ('Grouped bys) commons schemas params '[tab ::: '["col" ::: 'Null 'PGnumeric]] ('NotNull 'PGnumeric)
1559+ -- expression = sum_ (Distinct #col)
1560+ -- in printSQL expression
1562+ -- sum(DISTINCT "col")
1566+ -> aggr ('NotNull ty)
1568+ -- | input values, including nulls, concatenated into an array
1571+ -> aggr ('Null ('PGvararray ty))
1573+ -- | aggregates values as a JSON array
1576+ -> aggr ('Null 'PGjson)
1578+ -- | aggregates values as a JSON array
1581+ -> aggr ('Null 'PGjsonb)
1584+ the bitwise AND of all non-null input values, or null if none
1587+ expression :: Expression '[] ('Grouped bys) commons schemas params '[tab ::: '["col" ::: null 'PGint4]] ('Null 'PGint4)
1588+ expression = bitAnd (Distinct #col)
1589+ in printSQL expression
1591+ bit_and(DISTINCT "col")
1594+ :: int `In` PGIntegral
1595+ => expr1 (null int)
1596+ -- ^ what to aggregate
1597+ -> aggr ('Null int)
1600+ the bitwise OR of all non-null input values, or null if none
1604+ expression :: Expression '[] ('Grouped bys) commons schemas params '[tab ::: '["col" ::: null 'PGint4]] ('Null 'PGint4)
1605+ expression = bitOr (All #col)
1606+ in printSQL expression
1611+ :: int `In` PGIntegral
1612+ => expr1 (null int)
1613+ -- ^ what to aggregate
1614+ -> aggr ('Null int)
1617+ true if all input values are true, otherwise false
1621+ winFun :: WindowFunction '[] 'Ungrouped commons schemas params '[tab ::: '["col" ::: null 'PGbool]] ('Null 'PGbool)
1622+ winFun = boolAnd #col
1628+ :: expr1 (null 'PGbool)
1629+ -- ^ what to aggregate
1630+ -> aggr ('Null 'PGbool)
1633+ true if at least one input value is true, otherwise false
1637+ expression :: Expression '[] ('Grouped bys) commons schemas params '[tab ::: '["col" ::: null 'PGbool]] ('Null 'PGbool)
1638+ expression = boolOr (All #col)
1639+ in printSQL expression
1644+ :: expr1(null 'PGbool)
1645+ -- ^ what to aggregate
1646+ -> aggr ('Null 'PGbool)
1649+ equivalent to `boolAnd`
1653+ expression :: Expression '[] ('Grouped bys) commons schemas params '[tab ::: '["col" ::: null 'PGbool]] ('Null 'PGbool)
1654+ expression = every (Distinct #col)
1655+ in printSQL expression
1657+ every(DISTINCT "col")
1660+ :: expr1 (null 'PGbool)
1661+ -- ^ what to aggregate
1662+ -> aggr ('Null 'PGbool)
1664+ {- |maximum value of expression across all input values-}
1667+ -- ^ what to maximize
1670+ -- | minimum value of expression across all input values
1673+ -- ^ what to minimize
1676+ -- | the average (arithmetic mean) of all input values
1679+ -- ^ what to average
1680+ -> aggr ('Null (PGAvg ty))
1682+ {- | correlation coefficient
1685+ expression :: Expression '[] ('Grouped g) c s p '[t ::: '["x" ::: 'NotNull 'PGfloat8, "y" ::: 'NotNull 'PGfloat8]] ('Null 'PGfloat8)
1686+ expression = corr (All (#y :*: #x))
1687+ in printSQL expression
1692+ :: expr2 (null 'PGfloat8)
1693+ -> aggr ('Null 'PGfloat8)
1695+ {- | population covariance
1698+ expression :: Expression '[] ('Grouped g) c s p '[t ::: '["x" ::: 'NotNull 'PGfloat8, "y" ::: 'NotNull 'PGfloat8]] ('Null 'PGfloat8)
1699+ expression = covarPop (All (#y :*: #x))
1700+ in printSQL expression
1702+ covar_pop(ALL "y", "x")
1705+ :: expr2 (null 'PGfloat8)
1706+ -> aggr ('Null 'PGfloat8)
1708+ {- | sample covariance
1711+ winFun :: WindowFunction '[] 'Ungrouped c s p '[t ::: '["x" ::: 'NotNull 'PGfloat8, "y" ::: 'NotNull 'PGfloat8]] ('Null 'PGfloat8)
1712+ winFun = covarSamp (#y :*: #x)
1715+ covar_samp("y", "x")
1718+ :: expr2 (null 'PGfloat8)
1719+ -> aggr ('Null 'PGfloat8)
1721+ {- | average of the independent variable (sum(X)/N)
1724+ expression :: Expression '[] ('Grouped g) c s p '[t ::: '["x" ::: 'NotNull 'PGfloat8, "y" ::: 'NotNull 'PGfloat8]] ('Null 'PGfloat8)
1725+ expression = regrAvgX (All (#y :*: #x))
1726+ in printSQL expression
1728+ regr_avgx(ALL "y", "x")
1731+ :: expr2 (null 'PGfloat8)
1732+ -> aggr ('Null 'PGfloat8)
1734+ {- | average of the dependent variable (sum(Y)/N)
1737+ winFun :: WindowFunction '[] 'Ungrouped c s p '[t ::: '["x" ::: 'NotNull 'PGfloat8, "y" ::: 'NotNull 'PGfloat8]] ('Null 'PGfloat8)
1738+ winFun = regrAvgY (#y :*: #x)
1741+ regr_avgy("y", "x")
1744+ :: expr2 (null 'PGfloat8)
1745+ -> aggr ('Null 'PGfloat8)
1747+ {- | number of input rows in which both expressions are nonnull
1750+ winFun :: WindowFunction '[] 'Ungrouped c s p '[t ::: '["x" ::: 'NotNull 'PGfloat8, "y" ::: 'NotNull 'PGfloat8]] ('Null 'PGint8)
1751+ winFun = regrCount (#y :*: #x)
1754+ regr_count("y", "x")
1757+ :: expr2 (null 'PGfloat8)
1758+ -> aggr ('Null 'PGint8)
1760+ {- | y-intercept of the least-squares-fit linear equation determined by the (X, Y) pairs
1763+ expression :: Expression '[] ('Grouped g) c s p '[t ::: '["x" ::: 'NotNull 'PGfloat8, "y" ::: 'NotNull 'PGfloat8]] ('Null 'PGfloat8)
1764+ expression = regrIntercept (All (#y :*: #x))
1765+ in printSQL expression
1767+ regr_intercept(ALL "y", "x")
1770+ :: expr2 (null 'PGfloat8)
1771+ -> aggr ('Null 'PGfloat8)
1773+ -- | @regr_r2(Y, X)@, square of the correlation coefficient
1775+ :: expr2 (null 'PGfloat8)
1776+ -> aggr ('Null 'PGfloat8)
1778+ -- | @regr_slope(Y, X)@, slope of the least-squares-fit linear equation
1779+ -- determined by the (X, Y) pairs
1781+ :: expr2 (null 'PGfloat8)
1782+ -> aggr ('Null 'PGfloat8)
1784+ -- | @regr_sxx(Y, X)@, sum(X^2) - sum(X)^2/N
1785+ -- (“sum of squares” of the independent variable)
1787+ :: expr2 (null 'PGfloat8)
1788+ -> aggr ('Null 'PGfloat8)
1790+ -- | @regr_sxy(Y, X)@, sum(X*Y) - sum(X) * sum(Y)/N
1791+ -- (“sum of products” of independent times dependent variable)
1793+ :: expr2 (null 'PGfloat8)
1794+ -> aggr ('Null 'PGfloat8)
1796+ -- | @regr_syy(Y, X)@, sum(Y^2) - sum(Y)^2/N
1797+ -- (“sum of squares” of the dependent variable)
1799+ :: expr2 (null 'PGfloat8)
1800+ -> aggr ('Null 'PGfloat8)
1802+ -- | historical alias for `stddevSamp`
1805+ -> aggr ('Null (PGAvg ty))
1807+ -- | population standard deviation of the input values
1810+ -> aggr ('Null (PGAvg ty))
1812+ -- | sample standard deviation of the input values
1815+ -> aggr ('Null (PGAvg ty))
1817+ -- | historical alias for `varSamp`
1820+ -> aggr ('Null (PGAvg ty))
1822+ -- | population variance of the input values
1823+ -- (square of the population standard deviation)
1826+ -> aggr ('Null (PGAvg ty))
1828+ -- | sample variance of the input values
1829+ -- (square of the sample standard deviation)
1832+ -> aggr ('Null (PGAvg ty))
1835+`Distinction`s are used for the input of `Aggregate` `Expression`s.
1836+`All` invokes the aggregate once for each input row.
1837+`Distinct` invokes the aggregate once for each distinct value of the expression
1838+(or distinct set of values, for multiple expressions) found in the input
1840+data Distinction expr ty
1842+ | Distinct (expr ty)
1843+ deriving (GHC.Generic,Show,Eq,Ord)
1844+instance NFData (Distinction (Expression outer grp commons schemas params from) ty)
1845+instance RenderSQL (Distinction (Expression outer grp commons schemas params from) ty) where
1847+ All x -> "ALL" <+> renderSQL x
1848+ Distinct x -> "DISTINCT" <+> renderSQL x
1851+ ( Expression outer grp commons schemas params from
1853+ Expression outer grp commons schemas params from) xty ) where
1856+ "ALL" <+> renderSQL x <> ", " <> renderSQL x'
1857+ Distinct (x :*: x') ->
1858+ "DISTINCT" <+> renderSQL x <> ", " <> renderSQL x'
1861+ (Distinction (Expression outer 'Ungrouped commons schemas params from))
1862+ (Distinction (Expression outer 'Ungrouped commons schemas params from :*: Expression outer 'Ungrouped commons schemas params from))
1863+ (Expression outer ('Grouped bys) commons schemas params from) where
1864+ countStar = UnsafeExpression "count(*)"
1865+ count = unsafeAggregate1 "count"
1866+ sum_ = unsafeAggregate1 "sum"
1867+ arrayAgg = unsafeAggregate1 "array_agg"
1868+ jsonAgg = unsafeAggregate1 "json_agg"
1869+ jsonbAgg = unsafeAggregate1 "jsonb_agg"
1870+ bitAnd = unsafeAggregate1 "bit_and"
1871+ bitOr = unsafeAggregate1 "bit_or"
1872+ boolAnd = unsafeAggregate1 "bool_and"
1873+ boolOr = unsafeAggregate1 "bool_or"
1874+ every = unsafeAggregate1 "every"
1875+ max_ = unsafeAggregate1 "max"
1876+ min_ = unsafeAggregate1 "min"
1877+ avg = unsafeAggregate1 "avg"
1878+ corr = unsafeAggregate2 "corr"
1879+ covarPop = unsafeAggregate2 "covar_pop"
1880+ covarSamp = unsafeAggregate2 "covar_samp"
1881+ regrAvgX = unsafeAggregate2 "regr_avgx"
1882+ regrAvgY = unsafeAggregate2 "regr_avgy"
1883+ regrCount = unsafeAggregate2 "regr_count"
1884+ regrIntercept = unsafeAggregate2 "regr_intercept"
1885+ regrR2 = unsafeAggregate2 "regr_r2"
1886+ regrSlope = unsafeAggregate2 "regr_slope"
1887+ regrSxx = unsafeAggregate2 "regr_sxx"
1888+ regrSxy = unsafeAggregate2 "regr_sxy"
1889+ regrSyy = unsafeAggregate2 "regr_syy"
1890+ stddev = unsafeAggregate1 "stddev"
1891+ stddevPop = unsafeAggregate1 "stddev_pop"
1892+ stddevSamp = unsafeAggregate1 "stddev_samp"
1893+ variance = unsafeAggregate1 "variance"
1894+ varPop = unsafeAggregate1 "var_pop"
1895+ varSamp = unsafeAggregate1 "var_samp"
1897+ (Expression outer grp commons schemas params from)
1898+ (Expression outer grp commons schemas params from :*: Expression outer grp commons schemas params from)
1899+ (WindowFunction outer grp commons schemas params from) where
1900+ countStar = UnsafeWindowFunction "count(*)"
1901+ count = unsafeWindowFunction1 "count"
1902+ sum_ = unsafeWindowFunction1 "sum"
1903+ arrayAgg = unsafeWindowFunction1 "array_agg"
1904+ jsonAgg = unsafeWindowFunction1 "json_agg"
1905+ jsonbAgg = unsafeWindowFunction1 "jsonb_agg"
1906+ bitAnd = unsafeWindowFunction1 "bit_and"
1907+ bitOr = unsafeWindowFunction1 "bit_or"
1908+ boolAnd = unsafeWindowFunction1 "bool_and"
1909+ boolOr = unsafeWindowFunction1 "bool_or"
1910+ every = unsafeWindowFunction1 "every"
1911+ max_ = unsafeWindowFunction1 "max"
1912+ min_ = unsafeWindowFunction1 "min"
1913+ avg = unsafeWindowFunction1 "avg"
1914+ corr = unsafeWindowFunction2 "corr"
1915+ covarPop = unsafeWindowFunction2 "covar_pop"
1916+ covarSamp = unsafeWindowFunction2 "covar_samp"
1917+ regrAvgX = unsafeWindowFunction2 "regr_avgx"
1918+ regrAvgY = unsafeWindowFunction2 "regr_avgy"
1919+ regrCount = unsafeWindowFunction2 "regr_count"
1920+ regrIntercept = unsafeWindowFunction2 "regr_intercept"
1921+ regrR2 = unsafeWindowFunction2 "regr_r2"
1922+ regrSlope = unsafeWindowFunction2 "regr_slope"
1923+ regrSxx = unsafeWindowFunction2 "regr_sxx"
1924+ regrSxy = unsafeWindowFunction2 "regr_sxy"
1925+ regrSyy = unsafeWindowFunction2 "regr_syy"
1926+ stddev = unsafeWindowFunction1 "stddev"
1927+ stddevPop = unsafeWindowFunction1 "stddev_pop"
1928+ stddevSamp = unsafeWindowFunction1 "stddev_samp"
1929+ variance = unsafeWindowFunction1 "variance"
1930+ varPop = unsafeWindowFunction1 "var_pop"
1931+ varSamp = unsafeWindowFunction1 "var_samp"
1933+-- | escape hatch to define aggregate functions
1935+ :: ByteString -- ^ aggregate function
1936+ -> Distinction (Expression outer 'Ungrouped commons schemas params from) xty
1937+ -> Expression outer ('Grouped bys) commons schemas params from yty
1938+unsafeAggregate1 fun x = UnsafeExpression $ mconcat
1939+ [fun, "(", renderSQL x, ")"]
1941+-- | escape hatch to define aggregate binary functions
1943+ :: ByteString -- ^ aggregate function
1944+ -> Distinction (Expression outer 'Ungrouped commons schemas params from :*: Expression outer 'Ungrouped commons schemas params from) xty
1945+ -> Expression outer ('Grouped bys) commons schemas params from yty
1946+unsafeAggregate2 fun xx = UnsafeExpression $ mconcat
1947+ [fun, "(", renderSQL xx, ")"]
1949+-- | A type family that calculates `PGAvg` type of a `PGType`.
1950+type family PGAvg ty where
1951+ PGAvg 'PGint2 = 'PGnumeric
1952+ PGAvg 'PGint4 = 'PGnumeric
1953+ PGAvg 'PGint8 = 'PGnumeric
1954+ PGAvg 'PGnumeric = 'PGnumeric
1955+ PGAvg 'PGfloat4 = 'PGfloat8
1956+ PGAvg 'PGfloat8 = 'PGfloat8
1957+ PGAvg 'PGinterval = 'PGinterval
1958+ PGAvg pg = TypeError
1959+ ('Text "Squeal type error: No average for " ':<>: 'ShowType pg)
1961+{-----------------------------------------
1963+-----------------------------------------}
1965+-- | `TypeExpression`s are used in `cast`s and
1966+-- `Squeal.PostgreSQL.Definition.createTable` commands.
1967+newtype TypeExpression (schemas :: SchemasType) (ty :: NullityType)
1968+ = UnsafeTypeExpression { renderTypeExpression :: ByteString }
1969+ deriving (GHC.Generic,Show,Eq,Ord,NFData)
1970+instance RenderSQL (TypeExpression schemas ty) where
1971+ renderSQL = renderTypeExpression
1973+-- | The enum or composite type in a `Typedef` can be expressed by its alias.
1975+ :: (Has sch schemas schema, Has td schema ('Typedef ty))
1976+ => QualifiedAlias sch td
1977+ -> TypeExpression schemas (null ty)
1978+typedef = UnsafeTypeExpression . renderSQL
1980+-- | The composite type corresponding to a `Table` definition can be expressed
1983+ :: (Has sch schemas schema, Has tab schema ('Table table))
1984+ => QualifiedAlias sch tab
1985+ -> TypeExpression schemas (null ('PGcomposite (TableToRow table)))
1986+typetable = UnsafeTypeExpression . renderSQL
1988+-- | The composite type corresponding to a `View` definition can be expressed
1991+ :: (Has sch schemas schema, Has vw schema ('View view))
1992+ => QualifiedAlias sch vw
1993+ -> TypeExpression schemas (null ('PGcomposite view))
1994+typeview = UnsafeTypeExpression . renderSQL
1996+-- | logical Boolean (true/false)
1997+bool :: TypeExpression schemas (null 'PGbool)
1998+bool = UnsafeTypeExpression "bool"
1999+-- | signed two-byte integer
2000+int2, smallint :: TypeExpression schemas (null 'PGint2)
2001+int2 = UnsafeTypeExpression "int2"
2002+smallint = UnsafeTypeExpression "smallint"
2003+-- | signed four-byte integer
2004+int4, int, integer :: TypeExpression schemas (null 'PGint4)
2005+int4 = UnsafeTypeExpression "int4"
2006+int = UnsafeTypeExpression "int"
2007+integer = UnsafeTypeExpression "integer"
2008+-- | signed eight-byte integer
2009+int8, bigint :: TypeExpression schemas (null 'PGint8)
2010+int8 = UnsafeTypeExpression "int8"
2011+bigint = UnsafeTypeExpression "bigint"
2012+-- | arbitrary precision numeric type
2013+numeric :: TypeExpression schemas (null 'PGnumeric)
2014+numeric = UnsafeTypeExpression "numeric"
2015+-- | single precision floating-point number (4 bytes)
2016+float4, real :: TypeExpression schemas (null 'PGfloat4)
2017+float4 = UnsafeTypeExpression "float4"
2018+real = UnsafeTypeExpression "real"
2019+-- | double precision floating-point number (8 bytes)
2020+float8, doublePrecision :: TypeExpression schemas (null 'PGfloat8)
2021+float8 = UnsafeTypeExpression "float8"
2022+doublePrecision = UnsafeTypeExpression "double precision"
2023+-- | currency amount
2024+money :: TypeExpression schema (null 'PGmoney)
2025+money = UnsafeTypeExpression "money"
2026+-- | variable-length character string
2027+text :: TypeExpression schemas (null 'PGtext)
2028+text = UnsafeTypeExpression "text"
2029+-- | fixed-length character string
2031+ :: forall n schemas null. (KnownNat n, 1 <= n)
2032+ => TypeExpression schemas (null ('PGchar n))
2033+char = UnsafeTypeExpression $ "char(" <> renderNat @n <> ")"
2034+character = UnsafeTypeExpression $ "character(" <> renderNat @n <> ")"
2035+-- | variable-length character string
2036+varchar, characterVarying
2037+ :: forall n schemas null. (KnownNat n, 1 <= n)
2038+ => TypeExpression schemas (null ('PGvarchar n))
2039+varchar = UnsafeTypeExpression $ "varchar(" <> renderNat @n <> ")"
2040+characterVarying = UnsafeTypeExpression $
2041+ "character varying(" <> renderNat @n <> ")"
2042+-- | binary data ("byte array")
2043+bytea :: TypeExpression schemas (null 'PGbytea)
2044+bytea = UnsafeTypeExpression "bytea"
2045+-- | date and time (no time zone)
2046+timestamp :: TypeExpression schemas (null 'PGtimestamp)
2047+timestamp = UnsafeTypeExpression "timestamp"
2048+-- | date and time, including time zone
2049+timestampWithTimeZone :: TypeExpression schemas (null 'PGtimestamptz)
2050+timestampWithTimeZone = UnsafeTypeExpression "timestamp with time zone"
2051+-- | calendar date (year, month, day)
2052+date :: TypeExpression schemas (null 'PGdate)
2053+date = UnsafeTypeExpression "date"
2054+-- | time of day (no time zone)
2055+time :: TypeExpression schemas (null 'PGtime)
2056+time = UnsafeTypeExpression "time"
2057+-- | time of day, including time zone
2058+timeWithTimeZone :: TypeExpression schemas (null 'PGtimetz)
2059+timeWithTimeZone = UnsafeTypeExpression "time with time zone"
2061+interval :: TypeExpression schemas (null 'PGinterval)
2062+interval = UnsafeTypeExpression "interval"
2063+-- | universally unique identifier
2064+uuid :: TypeExpression schemas (null 'PGuuid)
2065+uuid = UnsafeTypeExpression "uuid"
2066+-- | IPv4 or IPv6 host address
2067+inet :: TypeExpression schemas (null 'PGinet)
2068+inet = UnsafeTypeExpression "inet"
2069+-- | textual JSON data
2070+json :: TypeExpression schemas (null 'PGjson)
2071+json = UnsafeTypeExpression "json"
2072+-- | binary JSON data, decomposed
2073+jsonb :: TypeExpression schemas (null 'PGjsonb)
2074+jsonb = UnsafeTypeExpression "jsonb"
2075+-- | variable length array
2077+ :: TypeExpression schemas pg
2078+ -> TypeExpression schemas (null ('PGvararray pg))
2079+vararray ty = UnsafeTypeExpression $ renderSQL ty <> "[]"
2080+-- | fixed length array
2082+-- >>> renderSQL (fixarray @'[2] json)
2085+ :: forall dims schemas null pg. SOP.All KnownNat dims
2086+ => TypeExpression schemas pg
2087+ -> TypeExpression schemas (null ('PGfixarray dims pg))
2088+fixarray ty = UnsafeTypeExpression $
2089+ renderSQL ty <> renderDims @dims
2091+ renderDims :: forall ns. SOP.All KnownNat ns => ByteString
2095+ . ByteString.intercalate "]["
2097+ $ hcmap (SOP.Proxy @KnownNat)
2098+ (K . fromString . show . natVal)
2099+ (hpure SOP.Proxy :: NP SOP.Proxy ns)
2100+tsvector :: TypeExpression schemas (null 'PGtsvector)
2101+tsvector = UnsafeTypeExpression "tsvector"
2102+tsquery :: TypeExpression schemas (null 'PGtsquery)
2103+tsquery = UnsafeTypeExpression "tsquery"
2105+-- | `pgtype` is a demoted version of a `PGType`
2106+class PGTyped schemas (ty :: NullityType) where
2107+ pgtype :: TypeExpression schemas ty
2108+instance PGTyped schemas (null 'PGbool) where pgtype = bool
2109+instance PGTyped schemas (null 'PGint2) where pgtype = int2
2110+instance PGTyped schemas (null 'PGint4) where pgtype = int4
2111+instance PGTyped schemas (null 'PGint8) where pgtype = int8
2112+instance PGTyped schemas (null 'PGnumeric) where pgtype = numeric
2113+instance PGTyped schemas (null 'PGfloat4) where pgtype = float4
2114+instance PGTyped schemas (null 'PGfloat8) where pgtype = float8
2115+instance PGTyped schemas (null 'PGmoney) where pgtype = money
2116+instance PGTyped schemas (null 'PGtext) where pgtype = text
2117+instance (KnownNat n, 1 <= n)
2118+ => PGTyped schemas (null ('PGchar n)) where pgtype = char @n
2119+instance (KnownNat n, 1 <= n)
2120+ => PGTyped schemas (null ('PGvarchar n)) where pgtype = varchar @n
2121+instance PGTyped schemas (null 'PGbytea) where pgtype = bytea
2122+instance PGTyped schemas (null 'PGtimestamp) where pgtype = timestamp
2123+instance PGTyped schemas (null 'PGtimestamptz) where pgtype = timestampWithTimeZone
2124+instance PGTyped schemas (null 'PGdate) where pgtype = date
2125+instance PGTyped schemas (null 'PGtime) where pgtype = time
2126+instance PGTyped schemas (null 'PGtimetz) where pgtype = timeWithTimeZone
2127+instance PGTyped schemas (null 'PGinterval) where pgtype = interval
2128+instance PGTyped schemas (null 'PGuuid) where pgtype = uuid
2129+instance PGTyped schemas (null 'PGjson) where pgtype = json
2130+instance PGTyped schemas (null 'PGjsonb) where pgtype = jsonb
2131+instance PGTyped schemas ty
2132+ => PGTyped schemas (null ('PGvararray ty)) where
2133+ pgtype = vararray (pgtype @schemas @ty)
2134+instance (SOP.All KnownNat dims, PGTyped schemas ty)
2135+ => PGTyped schemas (null ('PGfixarray dims ty)) where
2136+ pgtype = fixarray @dims (pgtype @schemas @ty)
2137+instance PGTyped schemas (null 'PGtsvector) where pgtype = tsvector
2138+instance PGTyped schemas (null 'PGtsquery) where pgtype = tsquery
2140+{-----------------------------------------
2142+-----------------------------------------}
2144+-- | `SortExpression`s are used by `orderBy` to optionally sort the results
2145+-- of a `Squeal.PostgreSQL.Query.Query`. `Asc` or `Desc`
2146+-- set the sort direction of a `NotNull` result
2147+-- column to ascending or descending. Ascending order puts smaller values
2148+-- first, where "smaller" is defined in terms of the `.<` operator. Similarly,
2149+-- descending order is determined with the `.>` operator. `AscNullsFirst`,
2150+-- `AscNullsLast`, `DescNullsFirst` and `DescNullsLast` options are used to
2151+-- determine whether nulls appear before or after non-null values in the sort
2152+-- ordering of a `Null` result column.
2153+data SortExpression outer grp commons schemas params from where
2155+ :: Expression outer grp commons schemas params from ('NotNull ty)
2156+ -> SortExpression outer grp commons schemas params from
2158+ :: Expression outer grp commons schemas params from ('NotNull ty)
2159+ -> SortExpression outer grp commons schemas params from
2161+ :: Expression outer grp commons schemas params from ('Null ty)
2162+ -> SortExpression outer grp commons schemas params from
2164+ :: Expression outer grp commons schemas params from ('Null ty)
2165+ -> SortExpression outer grp commons schemas params from
2167+ :: Expression outer grp commons schemas params from ('Null ty)
2168+ -> SortExpression outer grp commons schemas params from
2170+ :: Expression outer grp commons schemas params from ('Null ty)
2171+ -> SortExpression outer grp commons schemas params from
2172+deriving instance Show (SortExpression outer grp commons schemas params from)
2175+The `orderBy` clause causes the result rows of a `Squeal.PostgreSQL.Query.TableExpression`
2176+to be sorted according to the specified `SortExpression`(s).
2177+If two rows are equal according to the leftmost expression,
2178+they are compared according to the next expression and so on.
2179+If they are equal according to all specified expressions,
2180+they are returned in an implementation-dependent order.
2182+You can also control the order in which rows are processed by window functions
2183+using `orderBy` within `Squeal.PostgreSQL.Query.Over`.
2185+class OrderBy expr where
2187+ :: [SortExpression outer grp commons schemas params from]
2188+ -> expr outer grp commons schemas params from
2189+ -> expr outer grp commons schemas params from
2191+-- | Render a `SortExpression`.
2192+instance RenderSQL (SortExpression outer grp commons schemas params from) where
2194+ Asc expression -> renderSQL expression <+> "ASC"
2195+ Desc expression -> renderSQL expression <+> "DESC"
2196+ AscNullsFirst expression -> renderSQL expression
2197+ <+> "ASC NULLS FIRST"
2198+ DescNullsFirst expression -> renderSQL expression
2199+ <+> "DESC NULLS FIRST"
2200+ AscNullsLast expression -> renderSQL expression <+> "ASC NULLS LAST"
2201+ DescNullsLast expression -> renderSQL expression <+> "DESC NULLS LAST"
2203+-- | A `WindowDefinition` is a set of table rows that are somehow related
2204+-- to the current row
2205+data WindowDefinition outer grp commons schemas params from where
2208+ => NP (Expression outer grp commons schemas params from) bys
2209+ -> [SortExpression outer grp commons schemas params from]
2210+ -> WindowDefinition outer grp commons schemas params from
2212+instance OrderBy WindowDefinition where
2213+ orderBy sortsR (WindowDefinition parts sortsL)
2214+ = WindowDefinition parts (sortsL ++ sortsR)
2216+instance RenderSQL (WindowDefinition outer commons schemas from grp params) where
2217+ renderSQL (WindowDefinition part ord) =
2218+ renderPartitionByClause part <> renderOrderByClause ord
2220+ renderPartitionByClause = \case
2222+ parts -> "PARTITION" <+> "BY" <+> renderCommaSeparated renderExpression parts
2223+ renderOrderByClause = \case
2225+ srts -> " ORDER" <+> "BY"
2226+ <+> commaSeparated (renderSQL <$> srts)
2229+The `partitionBy` clause within `Squeal.PostgreSQL.Query.Over` divides the rows into groups,
2230+or partitions, that share the same values of the `partitionBy` `Expression`(s).
2231+For each row, the window function is computed across the rows that fall into
2232+the same partition as the current row.
2236+ => NP (Expression outer grp commons schemas params from) bys
2237+ -> WindowDefinition outer grp commons schemas params from
2238+partitionBy bys = WindowDefinition bys []
2241+A window function performs a calculation across a set of table rows
2242+that are somehow related to the current row. This is comparable to the type
2243+of calculation that can be done with an aggregate function.
2244+However, window functions do not cause rows to become grouped into a single
2245+output row like non-window aggregate calls would.
2246+Instead, the rows retain their separate identities.
2247+Behind the scenes, the window function is able to access more than
2248+just the current row of the query result.
2250+newtype WindowFunction
2251+ (outer :: FromType)
2253+ (commons :: FromType)
2254+ (schemas :: SchemasType)
2255+ (params :: [NullityType])
2257+ (ty :: NullityType)
2258+ = UnsafeWindowFunction { renderWindowFunction :: ByteString }
2259+ deriving (GHC.Generic,Show,Eq,Ord,NFData)
2261+instance RenderSQL (WindowFunction outer grp commons schemas params from ty) where
2262+ renderSQL = renderWindowFunction
2264+unsafeWindowFunction1
2266+ -> Expression outer grp commons schemas params from ty0
2267+ -> WindowFunction outer grp commons schemas params from ty1
2268+unsafeWindowFunction1 fun x
2269+ = UnsafeWindowFunction $ fun <> parenthesized (renderSQL x)
2271+unsafeWindowFunction2
2273+ -> (Expression outer grp commons schemas params from :*: Expression outer grp commons schemas params from) ty0
2274+ -> WindowFunction outer grp commons schemas params from ty1
2275+unsafeWindowFunction2 fun (x :*: x')
2276+ = UnsafeWindowFunction $ fun <> parenthesized (renderSQL x <> ", " <> renderSQL x')
2278+{- | rank of the current row with gaps; same as `rowNumber` of its first peer
2282+rank :: WindowFunction outer grp commons schemas params from ('NotNull 'PGint8)
2283+rank = UnsafeWindowFunction "rank()"
2285+{- | number of the current row within its partition, counting from 1
2286+>>> printSQL rowNumber
2289+rowNumber :: WindowFunction outer grp commons schemas params from ('NotNull 'PGint8)
2290+rowNumber = UnsafeWindowFunction "row_number()"
2292+{- | rank of the current row without gaps; this function counts peer groups
2293+>>> printSQL denseRank
2296+denseRank :: WindowFunction outer grp commons schemas params from ('NotNull 'PGint8)
2297+denseRank = UnsafeWindowFunction "dense_rank()"
2299+{- | relative rank of the current row: (rank - 1) / (total partition rows - 1)
2300+>>> printSQL percentRank
2303+percentRank :: WindowFunction outer grp commons schemas params from ('NotNull 'PGfloat8)
2304+percentRank = UnsafeWindowFunction "percent_rank()"
2306+{- | cumulative distribution: (number of partition rows
2307+preceding or peer with current row) / total partition rows
2308+>>> printSQL cumeDist
2311+cumeDist :: WindowFunction outer grp commons schemas params from ('NotNull 'PGfloat8)
2312+cumeDist = UnsafeWindowFunction "cume_dist()"
2314+{- | integer ranging from 1 to the argument value,
2315+dividing the partition as equally as possible
2318+ :: Expression outer grp commons schemas params from ('NotNull 'PGint4)
2320+ -> WindowFunction outer grp commons schemas params from ('NotNull 'PGint4)
2321+ntile = unsafeWindowFunction1 "ntile"
2323+{- | returns value evaluated at the row that is offset rows before the current
2324+row within the partition; if there is no such row, instead return default
2325+(which must be of the same type as value). Both offset and default are
2326+evaluated with respect to the current row.
2329+ :: Expression outer grp commons schemas params from ty
2331+ -> Expression outer grp commons schemas params from ('NotNull 'PGint4)
2333+ -> Expression outer grp commons schemas params from ty
2335+ -> WindowFunction outer grp commons schemas params from ty
2336+lag value offset def = UnsafeWindowFunction $ "lag"
2338+ (commaSeparated ([renderSQL value, renderSQL offset, renderSQL def]))
2340+{- | returns value evaluated at the row that is offset rows after the current
2341+row within the partition; if there is no such row, instead return default
2342+(which must be of the same type as value). Both offset and default are
2343+evaluated with respect to the current row.
2346+ :: Expression outer grp commons schemas params from ty
2348+ -> Expression outer grp commons schemas params from ('NotNull 'PGint4)
2350+ -> Expression outer grp commons schemas params from ty
2352+ -> WindowFunction outer grp commons schemas params from ty
2353+lead value offset def = UnsafeWindowFunction $ "lag"
2355+ (commaSeparated ([renderSQL value, renderSQL offset, renderSQL def]))
2357+{- | returns value evaluated at the row that is the
2358+first row of the window frame
2361+ :: Expression outer grp commons schemas params from ty
2363+ -> WindowFunction outer grp commons schemas params from ty
2364+firstValue = unsafeWindowFunction1 "first_value"
2366+{- | returns value evaluated at the row that is the
2367+last row of the window frame
2370+ :: Expression outer grp commons schemas params from ty
2372+ -> WindowFunction outer grp commons schemas params from ty
2373+lastValue = unsafeWindowFunction1 "last_value"
2375+{- | returns value evaluated at the row that is the nth
2376+row of the window frame (counting from 1); null if no such row
2379+ :: Expression outer grp commons schemas params from (null ty)
2381+ -> Expression outer grp commons schemas params from ('NotNull 'PGint4)
2383+ -> WindowFunction outer grp commons schemas params from ('Null ty)
2384+nthValue value nth = UnsafeWindowFunction $ "nth_value"
2385+ <> parenthesized (commaSeparated [renderSQL value, renderSQL nth])
2388+Create date from year, month and day fields
2390+>>> printSQL (makeDate (1984 :* 7 *: 3))
2391+make_date(1984, 7, 3)
2393+makeDate :: FunctionHet
2394+ '[ null 'PGint4, null 'PGint4, null 'PGint4 ]
2396+makeDate = unsafeFunctionHet "make_date"
2399+Create time from hour, minute and seconds fields
2401+>>> printSQL (makeTime (8 :* 15 *: 23.5))
2402+make_time(8, 15, 23.5)
2404+makeTime :: FunctionHet
2405+ '[ null 'PGint4, null 'PGint4, null 'PGfloat8 ]
2407+makeTime = unsafeFunctionHet "make_time"
2410+Create timestamp from year, month, day, hour, minute and seconds fields
2412+>>> printSQL (makeTimestamp (2013 :* 7 :* 15 :* 8 :* 15 *: 23.5))
2413+make_timestamp(2013, 7, 15, 8, 15, 23.5)
2415+makeTimestamp :: FunctionHet
2416+ '[ null 'PGint4, null 'PGint4, null 'PGint4
2417+ , null 'PGint4, null 'PGint4, null 'PGfloat8 ]
2418+ ( null 'PGtimestamp )
2419+makeTimestamp = unsafeFunctionHet "make_timestamp"
2422+Create timestamp with time zone from
2423+year, month, day, hour, minute and seconds fields;
2424+the current time zone is used
2426+>>> printSQL (makeTimestamptz (2013 :* 7 :* 15 :* 8 :* 15 *: 23.5))
2427+make_timestamptz(2013, 7, 15, 8, 15, 23.5)
2429+makeTimestamptz :: FunctionHet
2430+ '[ null 'PGint4, null 'PGint4, null 'PGint4
2431+ , null 'PGint4, null 'PGint4, null 'PGfloat8 ]
2432+ ( null 'PGtimestamptz )
2433+makeTimestamptz = unsafeFunctionHet "make_timestamptz"
2436+Affine space operations on time types.
2438+class TimeOp time diff | time -> diff where
2440+ >>> printSQL (makeDate (1984 :* 7 *: 3) !+ 365)
2441+ (make_date(1984, 7, 3) + 365)
2443+ (!+) :: Operator (null time) (null diff) (null time)
2444+ (!+) = unsafeBinaryOp "+"
2446+ >>> printSQL (365 +! makeDate (1984 :* 7 *: 3))
2447+ (365 + make_date(1984, 7, 3))
2449+ (+!) :: Operator (null diff) (null time) (null time)
2450+ (+!) = unsafeBinaryOp "+"
2452+ >>> printSQL (makeDate (1984 :* 7 *: 3) !- 365)
2453+ (make_date(1984, 7, 3) - 365)
2455+ (!-) :: Operator (null time) (null diff) (null time)
2456+ (!-) = unsafeBinaryOp "-"
2458+ >>> printSQL (makeDate (1984 :* 7 *: 3) !-! currentDate)
2459+ (make_date(1984, 7, 3) - CURRENT_DATE)
2461+ (!-!) :: Operator (null time) (null time) (null diff)
2462+ (!-!) = unsafeBinaryOp "-"
2463+instance TimeOp 'PGtimestamp 'PGinterval
2464+instance TimeOp 'PGtimestamptz 'PGinterval
2465+instance TimeOp 'PGtime 'PGinterval
2466+instance TimeOp 'PGtimetz 'PGinterval
2467+instance TimeOp 'PGinterval 'PGinterval
2468+instance TimeOp 'PGdate 'PGint4