@@ -1,13 +1,14 @@
2−Module: Squeal.PostgreSQL.Expression
2+Module: Squeal.PostgreSQL.Query
3Description: Squeal expressions
3Description: Squeal expressions
4−Copyright: (c) Eitan Chatav, 2019
4+Copyright: (c) Eitan Chatav, 2017
5Maintainer: eitan@morphism.tech
5Maintainer: eitan@morphism.tech
6Stability: experimental
6Stability: experimental
8Squeal expressions are the atoms used to build statements.
8Squeal expressions are the atoms used to build statements.
11+{-# OPTIONS_GHC -fno-warn-redundant-constraints #-}
11{-# LANGUAGE
12{-# LANGUAGE
12 AllowAmbiguousTypes
13 AllowAmbiguousTypes
13 , ConstraintKinds
14 , ConstraintKinds
@@ -33,350 +34,559 @@ Squeal expressions are the atoms used to build statements.
33module Squeal.PostgreSQL.Expression
34module Squeal.PostgreSQL.Expression
34 ( -- * Expression
35 ( -- * Expression
35 Expression (..)
36 Expression (..)
36− , Expr
37+ , HasParameter (parameter)
37− , type (-->)
38+ , param
38− , FunctionDB
39+ -- ** Null
39− , unsafeFunction
40+ , null_
40− , function
41+ , notNull
41− , unsafeLeftOp
42+ , coalesce
42− , leftOp
43+ , fromNull
43− , unsafeRightOp
44+ , isNull
44− , rightOp
45+ , isNotNull
45− , Operator
46+ , matchNull
46− , OperatorDB
47+ , nullIf
47 , unsafeBinaryOp
54 , unsafeBinaryOp
48− , binaryOp
55+ , unsafeUnaryOp
49− , FunctionVar
56+ , unsafeFunction
50− , unsafeFunctionVar
57+ , unsafeVariadicFunction
51− , type (--->)
58+ , atan2_
52− , FunctionNDB
59+ , cast
53− , unsafeFunctionN
60+ , quot_
54− , functionN
61+ , rem_
55− , PGSubset (..)
62+ , trunc
56− , PGIntersect (..)
63+ , round_
95+ -- *** Json and Jsonb operators
100+ -- *** Jsonb operators
127+ , jsonExtractPathAsText
128+ , jsonbExtractPathAsText
140+ -- * Window Functions
141+ , WindowDefinition (..)
143+ , WindowFunction (..)
156+ , SortExpression (..)
159+ , TypeExpression (..)
184+ , timestampWithTimeZone
57 -- * Re-export
195 -- * Re-export
59− , K (..)
197+ , NP ((:*), Nil)
63import Control.Category
200import Control.Category
64import Control.DeepSeq
201import Control.DeepSeq
65import Data.ByteString (ByteString)
202import Data.ByteString (ByteString)
203+import Data.ByteString.Lazy (toStrict)
66import Data.Function ((&))
204import Data.Function ((&))
67import Data.Semigroup hiding (All)
205import Data.Semigroup hiding (All)
206+import qualified Data.Aeson as JSON
68import Data.String
208import Data.String
69−import Generics.SOP hiding (All, from)
210+import Generics.SOP hiding (from)
70import GHC.OverloadedLabels
211import GHC.OverloadedLabels
71import GHC.TypeLits
212import GHC.TypeLits
73import Prelude hiding (id, (.))
213import Prelude hiding (id, (.))
215+import qualified Data.ByteString as ByteString
75import qualified GHC.Generics as GHC
216import qualified GHC.Generics as GHC
77−import Squeal.PostgreSQL.Alias
78−import Squeal.PostgreSQL.List
79import Squeal.PostgreSQL.Render
218import Squeal.PostgreSQL.Render
80import Squeal.PostgreSQL.Schema
219import Squeal.PostgreSQL.Schema
83−-- >>> import Squeal.PostgreSQL
85{-----------------------------------------
221{-----------------------------------------
86column expressions
222column expressions
87-----------------------------------------}
223-----------------------------------------}
89{- | `Expression`s are used in a variety of contexts,
225{- | `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,
226+such as in the target list of the `Squeal.PostgreSQL.Query.select` command,
92as new column values in `Squeal.PostgreSQL.Manipulation.insertRow` or
227as new column values in `Squeal.PostgreSQL.Manipulation.insertRow` or
93`Squeal.PostgreSQL.Manipulation.update`,
228`Squeal.PostgreSQL.Manipulation.update`,
94−or in search `Squeal.PostgreSQL.Logic.Condition`s in a number of commands.
229+or in search `Condition`s in a number of commands.
96The expression syntax allows the calculation of
231The expression syntax allows the calculation of
97values from primitive expression using arithmetic, logical,
232values from primitive expression using arithmetic, logical,
98and other operations.
233and 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
235newtype Expression
116− (commons :: FromType)
117 (grp :: Grouping)
236 (grp :: Grouping)
237+ (commons :: FromType)
118 (schemas :: SchemasType)
238 (schemas :: SchemasType)
119 (params :: [NullityType])
239 (params :: [NullityType])
120 (from :: FromType)
240 (from :: FromType)
121 (ty :: NullityType)
241 (ty :: NullityType)
122 = UnsafeExpression { renderExpression :: ByteString }
242 = UnsafeExpression { renderExpression :: ByteString }
123 deriving (GHC.Generic,Show,Eq,Ord,NFData)
243 deriving (GHC.Generic,Show,Eq,Ord,NFData)
124−instance RenderSQL (Expression outer commons grp schemas params from ty) where
245+instance RenderSQL (Expression grp commons schemas params from ty) where
125 renderSQL = renderExpression
246 renderSQL = renderExpression
127−-- | An `Expr` is a closed `Expression`.
248+{- | A `HasParameter` constraint is used to indicate a value that is
128−-- It is a F@RankNType@ but don't be scared.
249+supplied externally to a SQL statement.
129−-- Think of it as an expression which sees no
250+`Squeal.PostgreSQL.PQ.manipulateParams`,
130−-- namespaces, so you can't use parameters
251+`Squeal.PostgreSQL.PQ.queryParams` and
131−-- or alias references. It can be used as
252+`Squeal.PostgreSQL.PQ.traversePrepared` support specifying data values
132−-- a simple piece of more complex `Expression`s.
253+separately from the SQL command string, in which case `param`s are used to
133−type Expr x
254+refer to the out-of-line data values.
134− = forall outer commons grp schemas params from
135− . Expression outer commons grp schemas params from x
136− -- ^ cannot reference aliases
138−-- | A @RankNType@ for binary operators.
139−type Operator x1 x2 y
140− = forall outer commons grp schemas params from
141− . Expression outer commons grp schemas params from x1
143− -> Expression outer commons grp schemas params from x2
145− -> Expression outer commons grp schemas params from y
148−type OperatorDB schemas x1 x2 y
149− = forall outer commons grp params from
150− . Expression outer commons grp schemas params from x1
152− -> Expression outer commons grp schemas params from x2
154− -> Expression outer commons grp schemas params from y
157−-- | A @RankNType@ for functions with a single argument.
158−-- These could be either function calls or unary operators.
159−-- This is a subtype of the usual Haskell function type `Prelude.->`,
160−-- indeed a subcategory as it is closed under the usual
161−-- `Prelude..` and `Prelude.id`.
163− = forall outer commons grp schemas params from
164− . Expression outer commons grp schemas params from x
166− -> Expression outer commons grp schemas params from y
169−type FunctionDB schemas x y
170− = forall outer commons grp params from
171− . Expression outer commons grp schemas params from x
173− -> Expression outer commons grp schemas params from y
176−{- | A @RankNType@ for functions with a fixed-length list of heterogeneous arguments.
177−Use the `*:` operator to end your argument lists, like so.
179−>>> printSQL (unsafeFunctionN "fun" (true :* false :* localTime *: true))
180−fun(TRUE, FALSE, LOCALTIME, TRUE)
183− = forall outer commons grp schemas params from
184− . NP (Expression outer commons grp schemas params from) xs
186− -> Expression outer commons grp schemas params from y
189−type FunctionNDB schemas xs y
190− = forall outer commons grp params from
191− . NP (Expression outer commons grp schemas params from) xs
193− -> Expression outer commons grp schemas params from y
196−{- | A @RankNType@ for functions with a variable-length list of
197−homogeneous arguments and at least 1 more argument.
199−type FunctionVar x0 x1 y
256+class KnownNat n => HasParameter
200− = forall outer commons grp schemas params from
257+ (n :: Nat)
201− . [Expression outer commons grp schemas params from x0]
258+ (params :: [NullityType])
202− -- ^ inputs
259+ (ty :: NullityType)
203− -> Expression outer commons grp schemas params from x1
260+ | n params -> ty where
204− -- ^ must have at least 1 input
261+ -- | `parameter` takes a `Nat` using type application and a `TypeExpression`.
205− -> Expression outer commons grp schemas params from y
262+ --
206− -- ^ output
263+ -- >>> let expr = parameter @1 int4 :: Expression grp '[] schemas '[ 'Null 'PGint4] from ('Null 'PGint4)
207−
264+ -- >>> printSQL expr
208−{- | >>> printSQL (unsafeFunctionVar "greatest" [true, null_] false)
265+ -- ($1 :: int4)
209−greatest(TRUE, NULL, FALSE)
266+ parameter
210−-}
267+ :: TypeExpression schemas ty
211−unsafeFunctionVar :: ByteString -> FunctionVar x0 x1 y
268+ -> Expression grp commons schemas params from ty
212−unsafeFunctionVar fun xs x = UnsafeExpression $ fun <> parenthesized
269+ parameter ty = UnsafeExpression $ parenthesized $
213− (commaSeparated (renderSQL <$> xs) <> ", " <> renderSQL x)
270+ "$" <> renderNat @n <+> "::"
272+instance {-# OVERLAPPING #-} HasParameter 1 (ty1:tys) ty1
273+instance {-# OVERLAPPABLE #-} (KnownNat n, HasParameter (n-1) params ty)
274+ => HasParameter n (ty' : params) ty
276+-- | `param` takes a `Nat` using type application and for basic types,
277+-- infers a `TypeExpression`.
279+-- >>> let expr = param @1 :: Expression grp commons schemas '[ 'Null 'PGint4] from ('Null 'PGint4)
283+ :: forall n commons schemas params from grp ty
284+ . (PGTyped schemas ty, HasParameter n params ty)
285+ => Expression grp commons schemas params from ty -- ^ param
286+param = parameter @n (pgtype @schemas)
215−instance (HasUnique tab (Join outer from) row, Has col row ty)
288+instance (HasUnique tab from row, Has col row ty)
216− => IsLabel col (Expression outer commons 'Ungrouped schemas params from ty) where
289+ => IsLabel col (Expression 'Ungrouped commons schemas params from ty) where
217 fromLabel = UnsafeExpression $ renderSQL (Alias @col)
290 fromLabel = UnsafeExpression $ renderSQL (Alias @col)
218−instance (HasUnique tab (Join outer from) row, Has col row ty, tys ~ '[ty])
291+instance (HasUnique tab from row, Has col row ty, column ~ (col ::: ty))
219− => IsLabel col (NP (Expression outer commons 'Ungrouped schemas params from) tys) where
220− fromLabel = fromLabel @col :* Nil
221−instance (HasUnique tab (Join outer from) row, Has col row ty, column ~ (col ::: ty))
222 => IsLabel col
292 => IsLabel col
223− (Aliased (Expression outer commons 'Ungrouped schemas params from) column) where
293+ (Aliased (Expression 'Ungrouped commons schemas params from) column) where
224 fromLabel = fromLabel @col `As` Alias
294 fromLabel = fromLabel @col `As` Alias
225−instance (HasUnique tab (Join outer from) row, Has col row ty, columns ~ '[col ::: ty])
295+instance (HasUnique tab from row, Has col row ty, columns ~ '[col ::: ty])
226 => IsLabel col
296 => IsLabel col
227− (NP (Aliased (Expression outer commons 'Ungrouped schemas params from)) columns) where
297+ (NP (Aliased (Expression 'Ungrouped commons schemas params from)) columns) where
228 fromLabel = fromLabel @col :* Nil
298 fromLabel = fromLabel @col :* Nil
230−instance (Has tab (Join outer from) row, Has col row ty)
300+instance (Has tab from row, Has col row ty)
231− => IsQualified tab col (Expression outer commons 'Ungrouped schemas params from ty) where
301+ => IsQualified tab col (Expression 'Ungrouped commons schemas params from ty) where
232 tab ! col = UnsafeExpression $
302 tab ! col = UnsafeExpression $
233 renderSQL tab <> "." <> renderSQL col
303 renderSQL tab <> "." <> renderSQL col
234−instance (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
236− tab ! col = tab ! col :* Nil
237−instance (Has tab (Join outer from) row, Has col row ty, column ~ (col ::: ty))
304+instance (Has tab from row, Has col row ty, column ~ (col ::: ty))
238 => IsQualified tab col
305 => IsQualified tab col
239− (Aliased (Expression outer commons 'Ungrouped schemas params from) column) where
306+ (Aliased (Expression 'Ungrouped commons schemas params from) column) where
240 tab ! col = tab ! col `As` col
307 tab ! col = tab ! col `As` col
241−instance (Has tab (Join outer from) row, Has col row ty, columns ~ '[col ::: ty])
308+instance (Has tab from row, Has col row ty, columns ~ '[col ::: ty])
242 => IsQualified tab col
309 => IsQualified tab col
243− (NP (Aliased (Expression outer commons 'Ungrouped schemas params from)) columns) where
310+ (NP (Aliased (Expression 'Ungrouped commons schemas params from)) columns) where
244 tab ! col = tab ! col :* Nil
311 tab ! col = tab ! col :* Nil
247− ( HasUnique tab (Join outer from) row
314+ ( HasUnique tab from row
248 , Has col row ty
315 , Has col row ty
249 , GroupedBy tab col bys
316 , GroupedBy tab col bys
250 ) => IsLabel col
317 ) => IsLabel col
251− (Expression outer commons ('Grouped bys) schemas params from ty) where
318+ (Expression ('Grouped bys) commons schemas params from ty) where
252 fromLabel = UnsafeExpression $ renderSQL (Alias @col)
319 fromLabel = UnsafeExpression $ renderSQL (Alias @col)
254− ( HasUnique tab (Join outer from) row
321+ ( HasUnique tab from row
256− , GroupedBy tab col bys
259− (NP (Expression outer commons ('Grouped bys) schemas params from) tys) where
260− fromLabel = fromLabel @col :* Nil
262− ( HasUnique tab (Join outer from) row
263 , Has col row ty
322 , Has col row ty
264 , GroupedBy tab col bys
323 , GroupedBy tab col bys
265 , column ~ (col ::: ty)
324 , column ~ (col ::: ty)
266 ) => IsLabel col
325 ) => IsLabel col
267− (Aliased (Expression outer commons ('Grouped bys) schemas params from) column) where
326+ (Aliased (Expression ('Grouped bys) commons schemas params from) column) where
268 fromLabel = fromLabel @col `As` Alias
327 fromLabel = fromLabel @col `As` Alias
270− ( HasUnique tab (Join outer from) row
329+ ( HasUnique tab from row
271 , Has col row ty
330 , Has col row ty
272 , GroupedBy tab col bys
331 , GroupedBy tab col bys
273 , columns ~ '[col ::: ty]
332 , columns ~ '[col ::: ty]
274 ) => IsLabel col
333 ) => IsLabel col
275− (NP (Aliased (Expression outer commons ('Grouped bys) schemas params from)) columns) where
334+ (NP (Aliased (Expression ('Grouped bys) commons schemas params from)) columns) where
276 fromLabel = fromLabel @col :* Nil
335 fromLabel = fromLabel @col :* Nil
279− ( Has tab (Join outer from) row
338+ ( Has tab from row
280 , Has col row ty
339 , Has col row ty
281 , GroupedBy tab col bys
340 , GroupedBy tab col bys
282 ) => IsQualified tab col
341 ) => IsQualified tab col
283− (Expression outer commons ('Grouped bys) schemas params from ty) where
342+ (Expression ('Grouped bys) commons schemas params from ty) where
284 tab ! col = UnsafeExpression $
343 tab ! col = UnsafeExpression $
285 renderSQL tab <> "." <> renderSQL col
344 renderSQL tab <> "." <> renderSQL col
287− ( Has tab (Join outer from) row
346+ ( Has tab from row
289− , GroupedBy tab col bys
291− ) => IsQualified tab col
292− (NP (Expression outer commons ('Grouped bys) schemas params from) tys) where
293− tab ! col = tab ! col :* Nil
295− ( Has tab (Join outer from) row
296 , Has col row ty
347 , Has col row ty
297 , GroupedBy tab col bys
348 , GroupedBy tab col bys
298 , column ~ (col ::: ty)
349 , column ~ (col ::: ty)
299 ) => IsQualified tab col
350 ) => IsQualified tab col
300− (Aliased (Expression outer commons ('Grouped bys) schemas params from) column) where
351+ (Aliased (Expression ('Grouped bys) commons schemas params from) column) where
301 tab ! col = tab ! col `As` col
352 tab ! col = tab ! col `As` col
303− ( Has tab (Join outer from) row
354+ ( Has tab from row
304 , Has col row ty
355 , Has col row ty
305 , GroupedBy tab col bys
356 , GroupedBy tab col bys
306 , columns ~ '[col ::: ty]
357 , columns ~ '[col ::: ty]
307 ) => IsQualified tab col
358 ) => IsQualified tab col
308− (NP (Aliased (Expression outer commons ('Grouped bys) schemas params from)) columns) where
359+ (NP (Aliased (Expression ('Grouped bys) commons schemas params from)) columns) where
309 tab ! col = tab ! col :* Nil
360 tab ! col = tab ! col :* Nil
362+-- | analagous to `Nothing`
364+-- >>> printSQL null_
366+null_ :: Expression commons schemas rels grouping params ('Null ty)
367+null_ = UnsafeExpression "NULL"
369+-- | analagous to `Just`
371+-- >>> printSQL $ notNull true
374+ :: Expression commons schemas rels grouping params ('NotNull ty)
375+ -> Expression commons schemas rels grouping params ('Null ty)
376+notNull = UnsafeExpression . renderSQL
378+-- | return the leftmost value which is not NULL
380+-- >>> printSQL $ coalesce [null_, true] false
381+-- COALESCE(NULL, TRUE, FALSE)
383+ :: [Expression grp commons schemas params from ('Null ty)]
384+ -- ^ @NULL@s may be present
385+ -> Expression grp commons schemas params from ('NotNull ty)
386+ -- ^ @NULL@ is absent
387+ -> Expression grp commons schemas params from ('NotNull ty)
388+coalesce nullxs notNullx = UnsafeExpression $
389+ "COALESCE" <> parenthesized (commaSeparated
390+ ((renderSQL <$> nullxs) <> [renderSQL notNullx]))
392+-- | analagous to `Data.Maybe.fromMaybe` using @COALESCE@
394+-- >>> printSQL $ fromNull true null_
395+-- COALESCE(NULL, TRUE)
397+ :: Expression grp commons schemas params from ('NotNull ty)
398+ -- ^ what to convert @NULL@ to
399+ -> Expression grp commons schemas params from ('Null ty)
400+ -> Expression grp commons schemas params from ('NotNull ty)
401+fromNull notNullx nullx = coalesce [nullx] notNullx
403+-- | >>> printSQL $ null_ & isNull
406+ :: Expression grp commons schemas params from ('Null ty)
407+ -- ^ possibly @NULL@
408+ -> Condition grp commons schemas params from
409+isNull x = UnsafeExpression $ renderSQL x <+> "IS NULL"
411+-- | >>> printSQL $ null_ & isNotNull
414+ :: Expression grp commons schemas params from ('Null ty)
415+ -- ^ possibly @NULL@
416+ -> Condition grp commons schemas params from
417+isNotNull x = UnsafeExpression $ renderSQL x <+> "IS NOT NULL"
419+-- | analagous to `maybe` using @IS NULL@
421+-- >>> printSQL $ matchNull true not_ null_
422+-- CASE WHEN NULL IS NULL THEN TRUE ELSE (NOT NULL) END
424+ :: Expression grp commons schemas params from (nullty)
425+ -- ^ what to convert @NULL@ to
426+ -> ( Expression grp commons schemas params from ('NotNull ty)
427+ -> Expression grp commons schemas params from (nullty) )
428+ -- ^ function to perform when @NULL@ is absent
429+ -> Expression grp commons schemas params from ('Null ty)
430+ -> Expression grp commons schemas params from (nullty)
431+matchNull y f x = ifThenElse (isNull x) y
432+ (f (UnsafeExpression (renderSQL x)))
434+{-| right inverse to `fromNull`, if its arguments are equal then
435+`nullIf` gives @NULL@.
437+>>> :set -XTypeApplications -XDataKinds
438+>>> let expr = nullIf false (param @1) :: Expression grp commons schemas '[ 'NotNull 'PGbool] from ('Null 'PGbool)
440+NULL IF (FALSE, ($1 :: bool))
443+ :: Expression grp commons schemas params from ('NotNull ty)
444+ -- ^ @NULL@ is absent
445+ -> Expression grp commons schemas params from ('NotNull ty)
446+ -- ^ @NULL@ is absent
447+ -> Expression grp commons schemas params from ('Null ty)
448+nullIf x y = UnsafeExpression $ "NULL IF" <+> parenthesized
449+ (renderSQL x <> ", " <> renderSQL y)
451+-- | >>> printSQL $ array [null_, false, true]
452+-- ARRAY[NULL, FALSE, TRUE]
454+ :: [Expression grp commons schemas params from ty]
456+ -> Expression grp commons schemas params from (nullity ('PGvararray ty))
457+array xs = UnsafeExpression $
458+ "ARRAY[" <> commaSeparated (renderSQL <$> xs) <> "]"
460+-- | >>> printSQL $ array [null_, false, true] & index 2
461+-- (ARRAY[NULL, FALSE, TRUE])[2]
463+ :: Word64 -- ^ index
464+ -> Expression grp commons schemas params from (nullity ('PGvararray ty)) -- ^ array
465+ -> Expression grp commons schemas params from (NullifyType ty)
466+index n expr = UnsafeExpression $
467+ parenthesized (renderSQL expr) <> "[" <> fromString (show n) <> "]"
311instance (KnownSymbol label, label `In` labels) => IsPGlabel label
469instance (KnownSymbol label, label `In` labels) => IsPGlabel label
312− (Expression outer commons grp schemas params from (null ('PGenum labels))) where
470+ (Expression grp commons schemas params from (nullity ('PGenum labels))) where
313 label = UnsafeExpression $ renderSQL (PGlabel @label)
471 label = UnsafeExpression $ renderSQL (PGlabel @label)
473+-- | A row constructor is an expression that builds a row value
474+-- (also called a composite value) using values for its member fields.
477+-- type Complex = 'PGcomposite
478+-- '[ "real" ::: 'NotNull 'PGfloat8
479+-- , "imaginary" ::: 'NotNull 'PGfloat8 ]
482+-- >>> let i = row (0 `as` #real :* 1 `as` #imaginary) :: Expression grp commons schemas params from ('NotNull Complex)
487+ => NP (Aliased (Expression grp commons schemas params from)) row
488+ -- ^ zero or more expressions for the row field values
489+ -> Expression grp commons schemas params from (nullity ('PGcomposite row))
490+row exprs = UnsafeExpression $ "ROW" <> parenthesized
491+ (renderCommaSeparated (\ (expr `As` _) -> renderSQL expr) exprs)
494+-- type Complex = 'PGcomposite
495+-- '[ "real" ::: 'NotNull 'PGfloat8
496+-- , "imaginary" ::: 'NotNull 'PGfloat8 ]
497+-- type Schema = '["complex" ::: 'Typedef Complex]
500+-- >>> let i = row (0 `as` #real :* 1 `as` #imaginary) :: Expression grp '[] (Public Schema) from params ('NotNull Complex)
501+-- >>> printSQL $ i & field #complex #imaginary
502+-- (ROW(0, 1)::"complex")."imaginary"
504+ :: ( Has sch schemas schema
505+ , Has tydef schema ('Typedef ('PGcomposite row))
507+ => QualifiedAlias sch tydef -- ^ row type
508+ -> Alias field -- ^ field name
509+ -> Expression grp commons schemas params from ('NotNull ('PGcomposite row))
510+ -> Expression grp commons schemas params from ty
511+field td fld expr = UnsafeExpression $
512+ parenthesized (renderSQL expr <> "::" <> renderSQL td)
513+ <> "." <> renderSQL fld
516+ (Expression grp commons schemas params from (nullity ('PGvararray ty))) where
517+ (<>) = unsafeBinaryOp "||"
520+ (Expression grp commons schemas params from (nullity ('PGvararray ty))) where
524+-- | >>> let expr = greatest currentTimestamp [param @1] :: Expression grp commons schemas '[ 'NotNull 'PGtimestamptz] from ('NotNull 'PGtimestamptz)
526+-- GREATEST(CURRENT_TIMESTAMP, ($1 :: timestamp with time zone))
528+ :: Expression grp commons schemas params from (nullty)
529+ -- ^ needs at least 1 argument
530+ -> [Expression grp commons schemas params from (nullty)]
532+ -> Expression grp commons schemas params from (nullty)
533+greatest x xs = UnsafeExpression $ "GREATEST("
534+ <> commaSeparated (renderSQL <$> (x:xs)) <> ")"
536+-- | >>> printSQL $ least currentTimestamp [null_]
537+-- LEAST(CURRENT_TIMESTAMP, NULL)
539+ :: Expression grp commons schemas params from (nullty)
540+ -- ^ needs at least 1 argument
541+ -> [Expression grp commons schemas params from (nullty)]
543+ -> Expression grp commons schemas params from (nullty)
544+least x xs = UnsafeExpression $ "LEAST("
545+ <> commaSeparated (renderSQL <$> (x:xs)) <> ")"
315-- | >>> printSQL $ unsafeBinaryOp "OR" true false
547-- | >>> printSQL $ unsafeBinaryOp "OR" true false
316-- (TRUE OR FALSE)
548-- (TRUE OR FALSE)
317−unsafeBinaryOp :: ByteString -> Operator ty0 ty1 ty2
549+unsafeBinaryOp
552+ -> Expression grp commons schemas params from (ty0)
553+ -> Expression grp commons schemas params from (ty1)
554+ -> Expression grp commons schemas params from (ty2)
318unsafeBinaryOp op x y = UnsafeExpression $ parenthesized $
555unsafeBinaryOp op x y = UnsafeExpression $ parenthesized $
319 renderSQL x <+> op <+> renderSQL y
556 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
558+-- | >>> printSQL $ unsafeUnaryOp "NOT" true
329-- (NOT TRUE)
559-- (NOT TRUE)
330−unsafeLeftOp :: ByteString -> x --> y
561+ :: ByteString
331−unsafeLeftOp op x = UnsafeExpression $ parenthesized $ op <+> renderSQL x
562+ -- ^ operator
332−
563+ -> Expression grp commons schemas params from (ty0)
333−leftOp
564+ -> Expression grp commons schemas params from (ty1)
334− :: forall op sch schemas schema x y.
335− ( Has sch schemas schema
336− , Has op schema ('Operator ('LeftOp x y)) )
337− => FunctionDB schemas x y
338−leftOp = unsafeLeftOp $ renderSymbol @op
340−-- | >>> printSQL $ true & unsafeRightOp "IS NOT TRUE"
341−-- (TRUE IS NOT TRUE)
342−unsafeRightOp :: ByteString -> x --> y
343−unsafeRightOp op x = UnsafeExpression $ parenthesized $ renderSQL x <+> op
565+unsafeUnaryOp op x = UnsafeExpression $ parenthesized $
344−
566+ op <+> renderSQL x
346− :: forall op sch schemas schema x y.
347− ( Has sch schemas schema
348− , Has op schema ('Operator ('RightOp x y)) )
349− => FunctionDB schemas x y
350−rightOp = unsafeRightOp $ renderSymbol @op
352-- | >>> printSQL $ unsafeFunction "f" true
568-- | >>> printSQL $ unsafeFunction "f" true
353-- f(TRUE)
569-- f(TRUE)
354−unsafeFunction :: ByteString -> x --> y
570+unsafeFunction
573+ -> Expression grp commons schemas params from (xty)
574+ -> Expression grp commons schemas params from (yty)
355unsafeFunction fun x = UnsafeExpression $
575unsafeFunction fun x = UnsafeExpression $
356 fun <> parenthesized (renderSQL x)
576 fun <> parenthesized (renderSQL x)
358−function
578+-- | Helper for defining variadic functions.
359− :: (Has sch schemas schema, Has fun schema ('Function ('[x] :=> 'Returns y)))
579+unsafeVariadicFunction
360− => QualifiedAlias sch fun
580+ :: SListI elems
361− -> FunctionDB schemas x y
362−function = unsafeFunction . renderSQL
364−-- | >>> printSQL $ unsafeFunctionN "f" (currentTime :* localTimestamp :* false *: literal 'a')
365−-- f(CURRENT_TIME, LOCALTIMESTAMP, FALSE, E'a')
366−unsafeFunctionN :: SListI xs => ByteString -> xs ---> y
581+ => ByteString
583+ -> NP (Expression grp commons schemas params from) elems
584+ -> Expression grp commons schemas params from ret
367−unsafeFunctionN fun xs = UnsafeExpression $
585+unsafeVariadicFunction fun x = UnsafeExpression $
368− fun <> parenthesized (renderCommaSeparated renderSQL xs)
586+ fun <> parenthesized (commaSeparated (hcollapse (hmap (K . renderSQL) x)))
371− :: ( Has sch schemas schema
372− , Has fun schema ('Function (xs :=> 'Returns y))
374− => QualifiedAlias sch fun
375− -> FunctionNDB schemas xs y
376−functionN = unsafeFunctionN . renderSQL
378instance ty `In` PGNum
588instance ty `In` PGNum
379− => Num (Expression outer commons grp schemas params from (null ty)) where
589+ => Num (Expression grp commons schemas params from (nullity ty)) where
380 (+) = unsafeBinaryOp "+"
590 (+) = unsafeBinaryOp "+"
381 (-) = unsafeBinaryOp "-"
591 (-) = unsafeBinaryOp "-"
382 (*) = unsafeBinaryOp "*"
592 (*) = unsafeBinaryOp "*"
@@ -388,17 +598,12 @@ instance ty `In` PGNum
390instance (ty `In` PGNum, ty `In` PGFloating) => Fractional
600instance (ty `In` PGNum, ty `In` PGFloating) => Fractional
391− (Expression outer commons grp schemas params from (null ty)) where
601+ (Expression grp commons schemas params from (nullity ty)) where
392 (/) = unsafeBinaryOp "/"
602 (/) = unsafeBinaryOp "/"
393− fromRational
603+ fromRational x = fromInteger (numerator x) / fromInteger (denominator x)
397− . showFFloat Nothing
400instance (ty `In` PGNum, ty `In` PGFloating) => Floating
605instance (ty `In` PGNum, ty `In` PGFloating) => Floating
401− (Expression outer commons grp schemas params from (null ty)) where
606+ (Expression grp commons schemas params from (nullity ty)) where
402 pi = UnsafeExpression "pi()"
607 pi = UnsafeExpression "pi()"
403 exp = unsafeFunction "exp"
608 exp = unsafeFunction "exp"
404 log = unsafeFunction "ln"
609 log = unsafeFunction "ln"
@@ -419,54 +624,1497 @@ instance (ty `In` PGNum, ty `In` PGFloating) => Floating
419 acosh x = log (x + sqrt (x*x - 1))
624 acosh x = log (x + sqrt (x*x - 1))
420 atanh x = log ((1 + x) / (1 - x)) / 2
625 atanh x = log ((1 + x) / (1 - x)) / 2
422−-- | Contained by operators
627+-- | >>> :{
423−class PGSubset ty where
628+-- let
424− (@>) :: Operator (null0 ty) (null1 ty) ('Null 'PGbool)
629+-- expression :: Expression grp commons schemas params from (nullity 'PGfloat4)
425− (@>) = unsafeBinaryOp "@>"
630+-- expression = atan2_ pi 2
426− (<@) :: Operator (null0 ty) (null1 ty) ('Null 'PGbool)
631+-- in printSQL expression
427− (<@) = unsafeBinaryOp "<@"
632+-- :}
428−instance PGSubset 'PGjsonb
633+-- atan2(pi(), 2)
429−instance PGSubset 'PGtsquery
634+atan2_
430−instance PGSubset ('PGvararray ty)
635+ :: float `In` PGFloating
431−instance PGSubset ('PGrange ty)
636+ => Expression grp commons schemas params from (nullity float)
433−class PGIntersect ty where
638+ -> Expression grp commons schemas params from (nullity float)
434− (@&&) :: Operator (null0 ty) (null1 ty) ('Null 'PGbool)
639+ -- ^ denominator
435− (@&&) = unsafeBinaryOp "&&"
640+ -> Expression grp commons schemas params from (nullity float)
436−instance PGIntersect ('PGvararray ty)
641+atan2_ y x = UnsafeExpression $
437−instance PGIntersect ('PGrange ty)
642+ "atan2(" <> renderSQL y <> ", " <> renderSQL x <> ")"
644+-- When a `cast` is applied to an `Expression` of a known type, it
645+-- represents a run-time type conversion. The cast will succeed only if a
646+-- suitable type conversion operation has been defined.
648+-- | >>> printSQL $ true & cast int4
651+ :: TypeExpression schemas ty1
652+ -- ^ type to cast as
653+ -> Expression grp commons schemas params from ty0
654+ -- ^ value to convert
655+ -> Expression grp commons schemas params from ty1
656+cast ty x = UnsafeExpression $ parenthesized $
657+ renderSQL x <+> "::" <+> renderSQL ty
659+-- | integer division, truncates the result
663+-- expression :: Expression grp commons schemas params from (nullity 'PGint2)
664+-- expression = 5 `quot_` 2
665+-- in printSQL expression
669+ :: int `In` PGIntegral
670+ => Expression grp commons schemas params from (nullity int)
672+ -> Expression grp commons schemas params from (nullity int)
674+ -> Expression grp commons schemas params from (nullity int)
675+quot_ = unsafeBinaryOp "/"
677+-- | remainder upon integer division
681+-- expression :: Expression grp commons schemas params from (nullity 'PGint2)
682+-- expression = 5 `rem_` 2
683+-- in printSQL expression
687+ :: int `In` PGIntegral
688+ => Expression grp commons schemas params from (nullity int)
690+ -> Expression grp commons schemas params from (nullity int)
692+ -> Expression grp commons schemas params from (nullity int)
693+rem_ = unsafeBinaryOp "%"
697+-- expression :: Expression grp commons schemas params from (nullity 'PGfloat4)
698+-- expression = trunc pi
699+-- in printSQL expression
703+ :: frac `In` PGFloating
704+ => Expression grp commons schemas params from (nullity frac)
705+ -- ^ fractional number
706+ -> Expression grp commons schemas params from (nullity frac)
707+trunc = unsafeFunction "trunc"
711+-- expression :: Expression grp commons schemas params from (nullity 'PGfloat4)
712+-- expression = round_ pi
713+-- in printSQL expression
717+ :: frac `In` PGFloating
718+ => Expression grp commons schemas params from (nullity frac)
719+ -- ^ fractional number
720+ -> Expression grp commons schemas params from (nullity frac)
721+round_ = unsafeFunction "round"
725+-- expression :: Expression grp commons schemas params from (nullity 'PGfloat4)
726+-- expression = ceiling_ pi
727+-- in printSQL expression
731+ :: frac `In` PGFloating
732+ => Expression grp commons schemas params from (nullity frac)
733+ -- ^ fractional number
734+ -> Expression grp commons schemas params from (nullity frac)
735+ceiling_ = unsafeFunction "ceiling"
737+-- | A `Condition` is an `Expression`, which can evaluate
738+-- to `true`, `false` or `null_`. This is because SQL uses
739+-- a three valued logic.
740+type Condition grp commons schemas params from =
741+ Expression grp commons schemas params from ('Null 'PGbool)
743+-- | >>> printSQL true
745+true :: Expression grp commons schemas params from (nullity 'PGbool)
746+true = UnsafeExpression "TRUE"
748+-- | >>> printSQL false
750+false :: Expression grp commons schemas params from (nullity 'PGbool)
751+false = UnsafeExpression "FALSE"
753+-- | >>> printSQL $ not_ true
756+ :: Expression grp commons schemas params from (nullity 'PGbool)
757+ -> Expression grp commons schemas params from (nullity 'PGbool)
758+not_ = unsafeUnaryOp "NOT"
760+-- | >>> printSQL $ true .&& false
763+ :: Expression grp commons schemas params from (nullity 'PGbool)
764+ -> Expression grp commons schemas params from (nullity 'PGbool)
765+ -> Expression grp commons schemas params from (nullity 'PGbool)
767+(.&&) = unsafeBinaryOp "AND"
769+-- | >>> printSQL $ true .|| false
772+ :: Expression grp commons schemas params from (nullity 'PGbool)
773+ -> Expression grp commons schemas params from (nullity 'PGbool)
774+ -> Expression grp commons schemas params from (nullity 'PGbool)
776+(.||) = unsafeBinaryOp "OR"
780+-- expression :: Expression grp commons schemas params from (nullity 'PGint2)
781+-- expression = caseWhenThenElse [(true, 1), (false, 2)] 3
782+-- in printSQL expression
784+-- CASE WHEN TRUE THEN 1 WHEN FALSE THEN 2 ELSE 3 END
786+ :: [ ( Condition grp commons schemas params from
787+ , Expression grp commons schemas params from ty
789+ -- ^ whens and thens
790+ -> Expression grp commons schemas params from ty
792+ -> Expression grp commons schemas params from ty
793+caseWhenThenElse whenThens else_ = UnsafeExpression $ mconcat
797+ [ " WHEN ", renderSQL when_
798+ , " THEN ", renderSQL then_
800+ | (when_,then_) <- whenThens
802+ , " ELSE ", renderSQL else_
808+-- expression :: Expression grp commons schemas params from (nullity 'PGint2)
809+-- expression = ifThenElse true 1 0
810+-- in printSQL expression
812+-- CASE WHEN TRUE THEN 1 ELSE 0 END
814+ :: Condition grp commons schemas params from
815+ -> Expression grp commons schemas params from ty -- ^ then
816+ -> Expression grp commons schemas params from ty -- ^ else
817+ -> Expression grp commons schemas params from ty
818+ifThenElse if_ then_ else_ = caseWhenThenElse [(if_,then_)] else_
820+-- | Comparison operations like `.==`, `./=`, `.>`, `.>=`, `.<` and `.<=`
821+-- will produce @NULL@s if one of their arguments is @NULL@.
823+-- >>> printSQL $ true .== null_
826+ :: Expression grp commons schemas params from (nullity0 ty) -- ^ lhs
827+ -> Expression grp commons schemas params from (nullity1 ty) -- ^ rhs
828+ -> Condition grp commons schemas params from
829+(.==) = unsafeBinaryOp "="
832+-- | >>> printSQL $ true ./= null_
835+ :: Expression grp commons schemas params from (nullity0 ty) -- ^ lhs
836+ -> Expression grp commons schemas params from (nullity1 ty) -- ^ rhs
837+ -> Condition grp commons schemas params from
838+(./=) = unsafeBinaryOp "<>"
841+-- | >>> printSQL $ true .>= null_
844+ :: Expression grp commons schemas params from (nullity0 ty) -- ^ lhs
845+ -> Expression grp commons schemas params from (nullity1 ty) -- ^ rhs
846+ -> Condition grp commons schemas params from
847+(.>=) = unsafeBinaryOp ">="
850+-- | >>> printSQL $ true .< null_
853+ :: Expression grp commons schemas params from (nullity0 ty) -- ^ lhs
854+ -> Expression grp commons schemas params from (nullity1 ty) -- ^ rhs
855+ -> Condition grp commons schemas params from
856+(.<) = unsafeBinaryOp "<"
859+-- | >>> printSQL $ true .<= null_
862+ :: Expression grp commons schemas params from (nullity0 ty) -- ^ lhs
863+ -> Expression grp commons schemas params from (nullity1 ty) -- ^ rhs
864+ -> Condition grp commons schemas params from
865+(.<=) = unsafeBinaryOp "<="
868+-- | >>> printSQL $ true .> null_
871+ :: Expression grp commons schemas params from (nullity0 ty) -- ^ lhs
872+ -> Expression grp commons schemas params from (nullity1 ty) -- ^ rhs
873+ -> Condition grp commons schemas params from
874+(.>) = unsafeBinaryOp ">"
877+-- | >>> printSQL currentDate
880+ :: Expression grp commons schemas params from (nullity 'PGdate)
881+currentDate = UnsafeExpression "CURRENT_DATE"
883+-- | >>> printSQL currentTime
886+ :: Expression grp commons schemas params from (nullity 'PGtimetz)
887+currentTime = UnsafeExpression "CURRENT_TIME"
889+-- | >>> printSQL currentTimestamp
892+ :: Expression grp commons schemas params from (nullity 'PGtimestamptz)
893+currentTimestamp = UnsafeExpression "CURRENT_TIMESTAMP"
895+-- | >>> printSQL localTime
898+ :: Expression grp commons schemas params from (nullity 'PGtime)
899+localTime = UnsafeExpression "LOCALTIME"
901+-- | >>> printSQL localTimestamp
904+ :: Expression grp commons schemas params from (nullity 'PGtimestamp)
905+localTimestamp = UnsafeExpression "LOCALTIMESTAMP"
907+{-----------------------------------------
909+-----------------------------------------}
439instance IsString
911instance IsString
440− (Expression outer commons grp schemas params from (null 'PGtext)) where
912+ (Expression grp commons schemas params from (nullity 'PGtext)) where
441 fromString str = UnsafeExpression $
913 fromString str = UnsafeExpression $
442 "E\'" <> fromString (escape =<< str) <> "\'"
914 "E\'" <> fromString (escape =<< str) <> "\'"
443−instance IsString
915+ where
444− (Expression outer commons grp schemas params from (null 'PGtsvector)) where
916+ escape = \case
445− fromString str = UnsafeExpression . parenthesized . (<> " :: tsvector") $
917+ '\NUL' -> "\\0"
446− "E\'" <> fromString (escape =<< str) <> "\'"
918+ '\'' -> "''"
447−instance IsString
919+ '"' -> "\\\""
448− (Expression outer commons grp schemas params from (null 'PGtsquery)) where
920+ '\b' -> "\\b"
449− fromString str = UnsafeExpression . parenthesized . (<> " :: tsquery") $
921+ '\n' -> "\\n"
450− "E\'" <> fromString (escape =<< str) <> "\'"
922+ '\r' -> "\\r"
452instance Semigroup
927instance Semigroup
453− (Expression outer commons grp schemas params from (null ('PGvararray ty))) where
454− (<>) = unsafeBinaryOp "||"
456− (Expression outer commons grp schemas params from (null 'PGjsonb)) where
457− (<>) = unsafeBinaryOp "||"
459− (Expression outer commons grp schemas params from (null 'PGtext)) where
928+ (Expression grp commons schemas params from (nullity 'PGtext)) where
460− (<>) = unsafeBinaryOp "||"
462− (Expression outer commons grp schemas params from (null 'PGtsvector)) where
463 (<>) = unsafeBinaryOp "||"
929 (<>) = unsafeBinaryOp "||"
465instance Monoid
931instance Monoid
466− (Expression outer commons grp schemas params from (null 'PGtext)) where
932+ (Expression grp commons schemas params from (nullity 'PGtext)) where
467− mempty = fromString ""
470− (Expression outer commons grp schemas params from (null 'PGtsvector)) where
471 mempty = fromString ""
933 mempty = fromString ""
472 mappend = (<>)
934 mappend = (<>)
936+-- | >>> printSQL $ lower "ARRRGGG"
939+ :: Expression grp commons schemas params from (nullity 'PGtext)
940+ -- ^ string to lower case
941+ -> Expression grp commons schemas params from (nullity 'PGtext)
942+lower = unsafeFunction "lower"
944+-- | >>> printSQL $ upper "eeee"
947+ :: Expression grp commons schemas params from (nullity 'PGtext)
948+ -- ^ string to upper case
949+ -> Expression grp commons schemas params from (nullity 'PGtext)
950+upper = unsafeFunction "upper"
952+-- | >>> printSQL $ charLength "four"
953+-- char_length(E'four')
955+ :: Expression grp commons schemas params from (nullity 'PGtext)
956+ -- ^ string to measure
957+ -> Expression grp commons schemas params from (nullity 'PGint4)
958+charLength = unsafeFunction "char_length"
960+-- | The `like` expression returns true if the @string@ matches
961+-- the supplied @pattern@. If @pattern@ does not contain percent signs
962+-- or underscores, then the pattern only represents the string itself;
963+-- in that case `like` acts like the equals operator. An underscore (_)
964+-- in pattern stands for (matches) any single character; a percent sign (%)
965+-- matches any sequence of zero or more characters.
967+-- >>> printSQL $ "abc" `like` "a%"
968+-- (E'abc' LIKE E'a%')
970+ :: Expression grp commons schemas params from (nullity 'PGtext)
972+ -> Expression grp commons schemas params from (nullity 'PGtext)
974+ -> Expression grp commons schemas params from (nullity 'PGbool)
975+like = unsafeBinaryOp "LIKE"
977+-- | The key word ILIKE can be used instead of LIKE to make the
978+-- match case-insensitive according to the active locale.
980+-- >>> printSQL $ "abc" `ilike` "a%"
981+-- (E'abc' ILIKE E'a%')
983+ :: Expression grp commons schemas params from (nullity 'PGtext)
985+ -> Expression grp commons schemas params from (nullity 'PGtext)
987+ -> Expression grp commons schemas params from (nullity 'PGbool)
988+ilike = unsafeBinaryOp "ILIKE"
990+{-----------------------------------------
991+ -- json and jsonb support
993+See https://www.postgresql.org/docs/10/static/functions-json.html -- most
994+comments lifted directly from this page.
996+Table 9.44: json and jsonb operators
997+-----------------------------------------}
999+-- | Get JSON value (object field or array element) at a key.
1001+ :: (json `In` PGJsonType, key `In` PGJsonKey)
1002+ => Expression grp commons schemas params from (nullity json)
1003+ -> Expression grp commons schemas params from (nullity key)
1004+ -> Expression grp commons schemas params from ('Null json)
1006+(.->) = unsafeBinaryOp "->"
1008+-- | Get JSON value (object field or array element) at a key, as text.
1010+ :: (json `In` PGJsonType, key `In` PGJsonKey)
1011+ => Expression grp commons schemas params from (nullity json)
1012+ -> Expression grp commons schemas params from (nullity key)
1013+ -> Expression grp commons schemas params from ('Null 'PGtext)
1015+(.->>) = unsafeBinaryOp "->>"
1017+-- | Get JSON value at a specified path.
1019+ :: (json `In` PGJsonType, PGTextArray "(.#>)" path)
1020+ => Expression grp commons schemas params from (nullity json)
1021+ -> Expression grp commons schemas params from (nullity path)
1022+ -> Expression grp commons schemas params from ('Null json)
1024+(.#>) = unsafeBinaryOp "#>"
1026+-- | Get JSON value at a specified path as text.
1028+ :: (json `In` PGJsonType, PGTextArray "(.#>>)" path)
1029+ => Expression grp commons schemas params from (nullity json)
1030+ -> Expression grp commons schemas params from (nullity path)
1031+ -> Expression grp commons schemas params from ('Null 'PGtext)
1033+(.#>>) = unsafeBinaryOp "#>>"
1035+-- Additional jsonb operators
1037+-- | Does the left JSON value contain the right JSON path/value entries at the
1040+ :: Expression grp commons schemas params from (nullity 'PGjsonb)
1041+ -> Expression grp commons schemas params from (nullity 'PGjsonb)
1042+ -> Condition grp commons schemas params from
1044+(.@>) = unsafeBinaryOp "@>"
1046+-- | Are the left JSON path/value entries contained at the top level within the
1047+-- right JSON value?
1049+ :: Expression grp commons schemas params from (nullity 'PGjsonb)
1050+ -> Expression grp commons schemas params from (nullity 'PGjsonb)
1051+ -> Condition grp commons schemas params from
1053+(.<@) = unsafeBinaryOp "<@"
1055+-- | Does the string exist as a top-level key within the JSON value?
1057+ :: Expression grp commons schemas params from (nullity 'PGjsonb)
1058+ -> Expression grp commons schemas params from (nullity 'PGtext)
1059+ -> Condition grp commons schemas params from
1061+(.?) = unsafeBinaryOp "?"
1063+-- | Do any of these array strings exist as top-level keys?
1065+ :: Expression grp commons schemas params from (nullity 'PGjsonb)
1066+ -> Expression grp commons schemas params from (nullity ('PGvararray ('NotNull 'PGtext)))
1067+ -> Condition grp commons schemas params from
1069+(.?|) = unsafeBinaryOp "?|"
1071+-- | Do all of these array strings exist as top-level keys?
1073+ :: Expression grp commons schemas params from (nullity 'PGjsonb)
1074+ -> Expression grp commons schemas params from (nullity ('PGvararray ('NotNull 'PGtext)))
1075+ -> Condition grp commons schemas params from
1077+(.?&) = unsafeBinaryOp "?&"
1079+-- | Concatenate two jsonb values into a new jsonb value.
1081+ Semigroup (Expression commons schemas from grouping param (nullity 'PGjsonb)) where
1082+ (<>) = unsafeBinaryOp "||"
1084+-- | Delete a key or keys from a JSON object, or remove an array element.
1086+-- If the right operand is..
1088+-- @ text @: Delete key/value pair or string element from left operand. Key/value pairs
1089+-- are matched based on their key value.
1091+-- @ text[] @: Delete multiple key/value pairs or string elements
1092+-- from left operand. Key/value pairs are matched based on their key value.
1094+-- @ integer @: Delete the array element with specified index (Negative integers
1095+-- count from the end). Throws an error if top level container is not an array.
1097+ :: (key `In` '[ 'PGtext, 'PGvararray ('NotNull 'PGtext), 'PGint4, 'PGint2 ]) -- hlint error without parens here
1098+ => Expression grp commons schemas params from (nullity 'PGjsonb)
1099+ -> Expression grp commons schemas params from (nullity key)
1100+ -> Expression grp commons schemas params from (nullity 'PGjsonb)
1102+(.-.) = unsafeBinaryOp "-"
1104+-- | Delete the field or element with specified path (for JSON arrays, negative
1105+-- integers count from the end)
1107+ :: PGTextArray "(#-.)" arrayty
1108+ => Expression grp commons schemas params from (nullity 'PGjsonb)
1109+ -> Expression grp commons schemas params from (nullity arrayty)
1110+ -> Expression grp commons schemas params from (nullity 'PGjsonb)
1112+(#-.) = unsafeBinaryOp "#-"
1114+{-----------------------------------------
1115+Table 9.45: JSON creation functions
1116+-----------------------------------------}
1118+-- | Literal binary JSON
1121+ => x -> Expression grp commons schemas params from (nullity 'PGjsonb)
1122+jsonbLit = cast jsonb . UnsafeExpression
1123+ . singleQuotedUtf8 . toStrict . JSON.encode
1128+ => x -> Expression grp commons schemas params from (nullity 'PGjson)
1129+jsonLit = cast json . UnsafeExpression
1130+ . singleQuotedUtf8 . toStrict . JSON.encode
1132+-- | Returns the value as json. Arrays and composites are converted
1133+-- (recursively) to arrays and objects; otherwise, if there is a cast from the
1134+-- type to json, the cast function will be used to perform the conversion;
1135+-- otherwise, a scalar value is produced. For any scalar type other than a
1136+-- number, a Boolean, or a null value, the text representation will be used, in
1137+-- such a fashion that it is a valid json value.
1139+ :: Expression grp commons schemas params from (nullity ty)
1140+ -> Expression grp commons schemas params from (nullity 'PGjson)
1141+toJson = unsafeFunction "to_json"
1143+-- | Returns the value as jsonb. Arrays and composites are converted
1144+-- (recursively) to arrays and objects; otherwise, if there is a cast from the
1145+-- type to json, the cast function will be used to perform the conversion;
1146+-- otherwise, a scalar value is produced. For any scalar type other than a
1147+-- number, a Boolean, or a null value, the text representation will be used, in
1148+-- such a fashion that it is a valid jsonb value.
1150+ :: Expression grp commons schemas params from (nullity ty)
1151+ -> Expression grp commons schemas params from (nullity 'PGjsonb)
1152+toJsonb = unsafeFunction "to_jsonb"
1154+-- | Returns the array as a JSON array. A PostgreSQL multidimensional array
1155+-- becomes a JSON array of arrays.
1157+ :: PGArray "arrayToJson" arr
1158+ => Expression grp commons schemas params from (nullity arr)
1159+ -> Expression grp commons schemas params from (nullity 'PGjson)
1160+arrayToJson = unsafeFunction "array_to_json"
1162+-- | Returns the row as a JSON object.
1164+ :: Expression grp commons schemas params from (nullity ('PGcomposite ty))
1165+ -> Expression grp commons schemas params from (nullity 'PGjson)
1166+rowToJson = unsafeFunction "row_to_json"
1168+-- | Builds a possibly-heterogeneously-typed JSON array out of a variadic
1172+ => NP (Expression grp commons schemas params from) elems
1173+ -> Expression grp commons schemas params from (nullity 'PGjson)
1174+jsonBuildArray = unsafeVariadicFunction "json_build_array"
1176+-- | Builds a possibly-heterogeneously-typed (binary) JSON array out of a
1177+-- variadic argument list.
1180+ => NP (Expression grp commons schemas params from) elems
1181+ -> Expression grp commons schemas params from (nullity 'PGjsonb)
1182+jsonbBuildArray = unsafeVariadicFunction "jsonb_build_array"
1186+ => NP (Aliased (Expression grp commons schemas params from)) elems
1189+ (`appEndo` []) . hcfoldMap (Proxy :: Proxy Top)
1190+ (\(col `As` name) -> Endo $ \xs ->
1191+ renderAliasString name : renderSQL col : xs)
1193+ renderAliasString :: KnownSymbol alias => Alias alias -> ByteString
1194+ renderAliasString = singleQuotedText . fromString . symbolVal
1196+-- | Builds a possibly-heterogeneously-typed JSON object out of a variadic
1197+-- argument list. The elements of the argument list must alternate between text
1201+ => NP (Aliased (Expression grp commons schemas params from)) elems
1202+ -> Expression grp commons schemas params from (nullity 'PGjson)
1204+ = unsafeFunction "json_build_object"
1207+ . unsafeRowFunction
1209+-- | Builds a possibly-heterogeneously-typed (binary) JSON object out of a
1210+-- variadic argument list. The elements of the argument list must alternate
1211+-- between text and values.
1214+ => NP (Aliased (Expression grp commons schemas params from)) elems
1215+ -> Expression grp commons schemas params from (nullity 'PGjsonb)
1217+ = unsafeFunction "jsonb_build_object"
1220+ . unsafeRowFunction
1222+-- | Builds a JSON object out of a text array. The array must have either
1223+-- exactly one dimension with an even number of members, in which case they are
1224+-- taken as alternating key/value pairs, or two dimensions such that each inner
1225+-- array has exactly two elements, which are taken as a key/value pair.
1227+ :: PGArrayOf "jsonObject" arr ('NotNull 'PGtext)
1228+ => Expression grp commons schemas params from (nullity arr)
1229+ -> Expression grp commons schemas params from (nullity 'PGjson)
1230+jsonObject = unsafeFunction "json_object"
1232+-- | Builds a binary JSON object out of a text array. The array must have either
1233+-- exactly one dimension with an even number of members, in which case they are
1234+-- taken as alternating key/value pairs, or two dimensions such that each inner
1235+-- array has exactly two elements, which are taken as a key/value pair.
1237+ :: PGArrayOf "jsonbObject" arr ('NotNull 'PGtext)
1238+ => Expression grp commons schemas params from (nullity arr)
1239+ -> Expression grp commons schemas params from (nullity 'PGjsonb)
1240+jsonbObject = unsafeFunction "jsonb_object"
1242+-- | This is an alternate form of 'jsonObject' that takes two arrays; one for
1243+-- keys and one for values, that are zipped pairwise to create a JSON object.
1245+ :: ( PGArrayOf "jsonZipObject" keysArray ('NotNull 'PGtext)
1246+ , PGArrayOf "jsonZipObject" valuesArray ('NotNull 'PGtext))
1247+ => Expression grp commons schemas params from (nullity keysArray)
1248+ -> Expression grp commons schemas params from (nullity valuesArray)
1249+ -> Expression grp commons schemas params from (nullity 'PGjson)
1250+jsonZipObject ks vs =
1251+ unsafeVariadicFunction "json_object" (ks :* vs :* Nil)
1253+-- | This is an alternate form of 'jsonObject' that takes two arrays; one for
1254+-- keys and one for values, that are zipped pairwise to create a binary JSON
1257+ :: ( PGArrayOf "jsonbZipObject" keysArray ('NotNull 'PGtext)
1258+ , PGArrayOf "jsonbZipObject" valuesArray ('NotNull 'PGtext))
1259+ => Expression grp commons schemas params from (nullity keysArray)
1260+ -> Expression grp commons schemas params from (nullity valuesArray)
1261+ -> Expression grp commons schemas params from (nullity 'PGjsonb)
1262+jsonbZipObject ks vs =
1263+ unsafeVariadicFunction "jsonb_object" (ks :* vs :* Nil)
1265+{-----------------------------------------
1266+Table 9.46: JSON processing functions
1267+-----------------------------------------}
1269+-- | Returns the number of elements in the outermost JSON array.
1271+ :: Expression grp commons schemas params from (nullity 'PGjson)
1272+ -> Expression grp commons schemas params from (nullity 'PGint4)
1273+jsonArrayLength = unsafeFunction "json_array_length"
1275+-- | Returns the number of elements in the outermost binary JSON array.
1277+ :: Expression grp commons schemas params from (nullity 'PGjsonb)
1278+ -> Expression grp commons schemas params from (nullity 'PGint4)
1279+jsonbArrayLength = unsafeFunction "jsonb_array_length"
1281+-- | Returns JSON value pointed to by the given path (equivalent to #>
1285+ => Expression grp commons schemas params from (nullity 'PGjson)
1286+ -> NP (Expression grp commons schemas params from) elems
1287+ -> Expression grp commons schemas params from (nullity 'PGjsonb)
1288+jsonExtractPath x xs =
1289+ unsafeVariadicFunction "json_extract_path" (x :* xs)
1291+-- | Returns JSON value pointed to by the given path (equivalent to #>
1295+ => Expression grp commons schemas params from (nullity 'PGjsonb)
1296+ -> NP (Expression grp commons schemas params from) elems
1297+ -> Expression grp commons schemas params from (nullity 'PGjsonb)
1298+jsonbExtractPath x xs =
1299+ unsafeVariadicFunction "jsonb_extract_path" (x :* xs)
1301+-- | Returns JSON value pointed to by the given path (equivalent to #>
1302+-- operator), as text.
1303+jsonExtractPathAsText
1305+ => Expression grp commons schemas params from (nullity 'PGjson)
1306+ -> NP (Expression grp commons schemas params from) elems
1307+ -> Expression grp commons schemas params from (nullity 'PGjson)
1308+jsonExtractPathAsText x xs =
1309+ unsafeVariadicFunction "json_extract_path_text" (x :* xs)
1311+-- | Returns JSON value pointed to by the given path (equivalent to #>
1312+-- operator), as text.
1313+jsonbExtractPathAsText
1315+ => Expression grp commons schemas params from (nullity 'PGjsonb)
1316+ -> NP (Expression grp commons schemas params from) elems
1317+ -> Expression grp commons schemas params from (nullity 'PGjsonb)
1318+jsonbExtractPathAsText x xs =
1319+ unsafeVariadicFunction "jsonb_extract_path_text" (x :* xs)
1321+-- | Returns the type of the outermost JSON value as a text string. Possible
1322+-- types are object, array, string, number, boolean, and null.
1324+ :: Expression grp commons schemas params from (nullity 'PGjson)
1325+ -> Expression grp commons schemas params from (nullity 'PGtext)
1326+jsonTypeof = unsafeFunction "json_typeof"
1328+-- | Returns the type of the outermost binary JSON value as a text string.
1329+-- Possible types are object, array, string, number, boolean, and null.
1331+ :: Expression grp commons schemas params from (nullity 'PGjsonb)
1332+ -> Expression grp commons schemas params from (nullity 'PGtext)
1333+jsonbTypeof = unsafeFunction "jsonb_typeof"
1335+-- | Returns its argument with all object fields that have null values omitted.
1336+-- Other null values are untouched.
1338+ :: Expression grp commons schemas params from (nullity 'PGjson)
1339+ -> Expression grp commons schemas params from (nullity 'PGjson)
1340+jsonStripNulls = unsafeFunction "json_strip_nulls"
1342+-- | Returns its argument with all object fields that have null values omitted.
1343+-- Other null values are untouched.
1345+ :: Expression grp commons schemas params from (nullity 'PGjsonb)
1346+ -> Expression grp commons schemas params from (nullity 'PGjsonb)
1347+jsonbStripNulls = unsafeFunction "jsonb_strip_nulls"
1349+-- | @ jsonbSet target path new_value create_missing @
1351+-- Returns target with the section designated by path replaced by new_value,
1352+-- or with new_value added if create_missing is true ( default is true) and the
1353+-- item designated by path does not exist. As with the path orientated
1354+-- operators, negative integers that appear in path count from the end of JSON
1357+ :: PGTextArray "jsonbSet" arr
1358+ => Expression grp commons schemas params from (nullity 'PGjsonb)
1359+ -> Expression grp commons schemas params from (nullity arr)
1360+ -> Expression grp commons schemas params from (nullity 'PGjsonb)
1361+ -> Maybe (Expression grp commons schemas params from (nullity 'PGbool))
1362+ -> Expression grp commons schemas params from (nullity 'PGjsonb)
1363+jsonbSet tgt path val createMissing = case createMissing of
1364+ Just m -> unsafeVariadicFunction "jsonb_set" (tgt :* path :* val :* m :* Nil)
1365+ Nothing -> unsafeVariadicFunction "jsonb_set" (tgt :* path :* val :* Nil)
1367+-- | @ jsonbInsert target path new_value insert_after @
1369+-- Returns target with new_value inserted. If target section designated by
1370+-- path is in a JSONB array, new_value will be inserted before target or after
1371+-- if insert_after is true (default is false). If target section designated by
1372+-- path is in JSONB object, new_value will be inserted only if target does not
1373+-- exist. As with the path orientated operators, negative integers that appear
1374+-- in path count from the end of JSON arrays.
1376+ :: PGTextArray "jsonbInsert" arr
1377+ => Expression grp commons schemas params from (nullity 'PGjsonb)
1378+ -> Expression grp commons schemas params from (nullity arr)
1379+ -> Expression grp commons schemas params from (nullity 'PGjsonb)
1380+ -> Maybe (Expression grp commons schemas params from (nullity 'PGbool))
1381+ -> Expression grp commons schemas params from (nullity 'PGjsonb)
1382+jsonbInsert tgt path val insertAfter = case insertAfter of
1383+ Just i -> unsafeVariadicFunction "jsonb_insert" (tgt :* path :* val :* i :* Nil)
1384+ Nothing -> unsafeVariadicFunction "jsonb_insert" (tgt :* path :* val :* Nil)
1386+-- | Returns its argument as indented JSON text.
1388+ :: Expression grp commons schemas params from (nullity 'PGjsonb)
1389+ -> Expression grp commons schemas params from (nullity 'PGtext)
1390+jsonbPretty = unsafeFunction "jsonb_pretty"
1392+{-----------------------------------------
1394+-----------------------------------------}
1396+class Aggregate expr1 expr2 aggr
1397+ | aggr -> expr1, aggr -> expr2 where
1399+ -- | A special aggregation that does not require an input
1403+ -- expression :: Expression (Grouped bys) commons schemas params from ('NotNull 'PGint8)
1404+ -- expression = countStar
1405+ -- in printSQL expression
1408+ countStar :: aggr ('NotNull 'PGint8)
1412+ -- expression :: Expression (Grouped bys) commons schemas params '[tab ::: '["col" ::: nullity ty]] ('NotNull 'PGint8)
1413+ -- expression = count (All #col)
1414+ -- in printSQL expression
1416+ -- count(ALL "col")
1420+ -> aggr ('NotNull 'PGint8)
1424+ -- expression :: Expression ('Grouped bys) commons schemas params '[tab ::: '["col" ::: 'Null 'PGnumeric]] ('Null 'PGnumeric)
1425+ -- expression = sum_ (Distinct #col)
1426+ -- in printSQL expression
1428+ -- sum(DISTINCT "col")
1431+ => expr1 (nullity ty)
1432+ -> aggr (nullity ty)
1436+ -- expression :: Expression ('Grouped bys) commons schemas params '[tab ::: '["col" ::: nullity 'PGint4]] (nullity 'PGint4)
1437+ -- expression = bitAnd (Distinct #col)
1438+ -- in printSQL expression
1440+ -- bit_and(DISTINCT "col")
1442+ :: int `In` PGIntegral
1443+ => expr1 (nullity int)
1444+ -- ^ what to aggregate
1445+ -> aggr (nullity int)
1449+ -- expression :: Expression ('Grouped bys) commons schemas params '[tab ::: '["col" ::: nullity 'PGint4]] (nullity 'PGint4)
1450+ -- expression = bitOr (All #col)
1451+ -- in printSQL expression
1453+ -- bit_or(ALL "col")
1455+ :: int `In` PGIntegral
1456+ => expr1 (nullity int)
1457+ -- ^ what to aggregate
1458+ -> aggr (nullity int)
1462+ -- expression :: Expression (Grouped bys) commons schemas params '[tab ::: '["col" ::: nullity 'PGbool]] (nullity 'PGbool)
1463+ -- expression = boolAnd (All #col)
1464+ -- in printSQL expression
1466+ -- bool_and(ALL "col")
1468+ :: expr1 (nullity 'PGbool)
1469+ -- ^ what to aggregate
1470+ -> aggr (nullity 'PGbool)
1474+ -- expression :: Expression (Grouped bys) commons schemas params '[tab ::: '["col" ::: nullity 'PGbool]] (nullity 'PGbool)
1475+ -- expression = boolOr (All #col)
1476+ -- in printSQL expression
1478+ -- bool_or(ALL "col")
1480+ :: expr1(nullity 'PGbool)
1481+ -- ^ what to aggregate
1482+ -> aggr (nullity 'PGbool)
1484+ -- | synonym for `boolAnd`
1488+ -- expression :: Expression (Grouped bys) commons schemas params '[tab ::: '["col" ::: nullity 'PGbool]] (nullity 'PGbool)
1489+ -- expression = every (Distinct #col)
1490+ -- in printSQL expression
1492+ -- every(DISTINCT "col")
1494+ :: expr1 (nullity 'PGbool)
1495+ -- ^ what to aggregate
1496+ -> aggr (nullity 'PGbool)
1498+ -- | maximum value of expression across all input values
1500+ :: expr1 (nullity ty)
1501+ -- ^ what to maximize
1502+ -> aggr (nullity ty)
1504+ -- | minimum value of expression across all input values
1506+ :: expr1 (nullity ty)
1507+ -- ^ what to minimize
1508+ -> aggr (nullity ty)
1510+ -- | average aggregation
1512+ :: expr1 (nullity ty)
1513+ -- ^ what to average
1514+ -> aggr (nullity (PGAvg ty))
1516+ -- | @corr (y :*: x)@, correlation coefficient
1518+ :: expr2 (nullity 'PGfloat8)
1519+ -> aggr (nullity 'PGfloat8)
1521+ -- | @covarPop (y :*: x)@, population covariance
1523+ :: expr2 (nullity 'PGfloat8)
1524+ -> aggr (nullity 'PGfloat8)
1526+ -- | @covarPop (y :*: x)@, sample covariance
1528+ :: expr2 (nullity 'PGfloat8)
1529+ -> aggr (nullity 'PGfloat8)
1531+ -- | @regrAvgX (y :*: x)@, average of the independent variable (sum(X)/N)
1533+ :: expr2 (nullity 'PGfloat8)
1534+ -> aggr (nullity 'PGfloat8)
1536+ -- | @regrAvgY (y :*: x)@, average of the dependent variable (sum(Y)/N)
1538+ :: expr2 (nullity 'PGfloat8)
1539+ -> aggr (nullity 'PGfloat8)
1541+ -- | @regrCount (y :*: x)@, number of input rows in which both expressions are nonnull
1543+ :: expr2 (nullity 'PGfloat8)
1544+ -> aggr (nullity 'PGint8)
1546+ -- | @regrIntercept (y :*: x)@, y-intercept of the least-squares-fit linear
1547+ -- equation determined by the (X, Y) pairs
1549+ :: expr2 (nullity 'PGfloat8)
1550+ -> aggr (nullity 'PGfloat8)
1552+ -- | @regrR2 (y :*: x)@, square of the correlation coefficient
1554+ :: expr2 (nullity 'PGfloat8)
1555+ -> aggr (nullity 'PGfloat8)
1557+ -- | @regrSlope (y :*: x)@, slope of the least-squares-fit linear equation
1558+ -- determined by the (X, Y) pairs
1560+ :: expr2 (nullity 'PGfloat8)
1561+ -> aggr (nullity 'PGfloat8)
1563+ -- | @regrSxx (y :*: x)@, sum(X^2) - sum(X)^2/N
1564+ -- (“sum of squares” of the independent variable)
1566+ :: expr2 (nullity 'PGfloat8)
1567+ -> aggr (nullity 'PGfloat8)
1569+ -- | @regrSxy (y :*: x)@, sum(X*Y) - sum(X) * sum(Y)/N
1570+ -- (“sum of products” of independent times dependent variable)
1572+ :: expr2 (nullity 'PGfloat8)
1573+ -> aggr (nullity 'PGfloat8)
1575+ -- | @regrSyy (y :*: x)@, sum(Y^2) - sum(Y)^2/N
1576+ -- (“sum of squares” of the dependent variable)
1578+ :: expr2 (nullity 'PGfloat8)
1579+ -> aggr (nullity 'PGfloat8)
1581+ -- | historical alias for `stddevSamp`
1583+ :: expr1 (nullity ty)
1584+ -> aggr (nullity (PGAvg ty))
1586+ -- | population standard deviation of the input values
1588+ :: expr1 (nullity ty)
1589+ -> aggr (nullity (PGAvg ty))
1591+ -- | sample standard deviation of the input values
1593+ :: expr1 (nullity ty)
1594+ -> aggr (nullity (PGAvg ty))
1596+ -- | historical alias for `varSamp`
1598+ :: expr1 (nullity ty)
1599+ -> aggr (nullity (PGAvg ty))
1601+ -- | population variance of the input values
1602+ -- (square of the population standard deviation)
1604+ :: expr1 (nullity ty)
1605+ -> aggr (nullity (PGAvg ty))
1607+ -- | sample variance of the input values
1608+ -- (square of the sample standard deviation)
1610+ :: expr1 (nullity ty)
1611+ -> aggr (nullity (PGAvg ty))
1613+data Distinction expr ty
1615+ | Distinct (expr ty)
1616+ deriving (GHC.Generic,Show,Eq,Ord)
1617+instance NFData (Distinction (Expression grp commons schemas params from) ty)
1618+instance RenderSQL (Distinction (Expression grp commons schemas params from) ty) where
1620+ All x -> "ALL" <+> renderSQL x
1621+ Distinct x -> "DISTINCT" <+> renderSQL x
1624+ ( Expression grp commons schemas params from
1626+ Expression grp commons schemas params from) xty ) where
1628+ All (x GHC.:*: x') ->
1629+ "ALL" <+> renderSQL x <> ", " <> renderSQL x'
1630+ Distinct (x GHC.:*: x') ->
1631+ "DISTINCT" <+> renderSQL x <> ", " <> renderSQL x'
1634+ (Distinction (Expression 'Ungrouped commons schemas params from))
1635+ (Distinction (Expression 'Ungrouped commons schemas params from GHC.:*: Expression 'Ungrouped commons schemas params from))
1636+ (Expression ('Grouped bys) commons schemas params from) where
1637+ countStar = UnsafeExpression "count(*)"
1638+ count = unsafeAggregate1 "count"
1639+ sum_ = unsafeAggregate1 "sum"
1640+ bitAnd = unsafeAggregate1 "bit_and"
1641+ bitOr = unsafeAggregate1 "bit_or"
1642+ boolAnd = unsafeAggregate1 "bool_and"
1643+ boolOr = unsafeAggregate1 "bool_or"
1644+ every = unsafeAggregate1 "every"
1645+ max_ = unsafeAggregate1 "max"
1646+ min_ = unsafeAggregate1 "min"
1647+ avg = unsafeAggregate1 "avg"
1648+ corr = unsafeAggregate2 "corr"
1649+ covarPop = unsafeAggregate2 "covar_pop"
1650+ covarSamp = unsafeAggregate2 "covar_samp"
1651+ regrAvgX = unsafeAggregate2 "regr_avgx"
1652+ regrAvgY = unsafeAggregate2 "regr_avgy"
1653+ regrCount = unsafeAggregate2 "regr_count"
1654+ regrIntercept = unsafeAggregate2 "regr_intercept"
1655+ regrR2 = unsafeAggregate2 "regr_r2"
1656+ regrSlope = unsafeAggregate2 "regr_slope"
1657+ regrSxx = unsafeAggregate2 "regr_sxx"
1658+ regrSxy = unsafeAggregate2 "regr_sxy"
1659+ regrSyy = unsafeAggregate2 "regr_syy"
1660+ stddev = unsafeAggregate1 "stddev"
1661+ stddevPop = unsafeAggregate1 "stddev_pop"
1662+ stddevSamp = unsafeAggregate1 "stddev_samp"
1663+ variance = unsafeAggregate1 "variance"
1664+ varPop = unsafeAggregate1 "var_pop"
1665+ varSamp = unsafeAggregate1 "var_samp"
1667+ (Expression grp commons schemas params from)
1668+ (Expression grp commons schemas params from GHC.:*: Expression grp commons schemas params from)
1669+ (WindowFunction grp commons schemas params from) where
1670+ countStar = UnsafeWindowFunction "count(*)"
1671+ count = unsafeWindowFunction1 "count"
1672+ sum_ = unsafeWindowFunction1 "sum"
1673+ bitAnd = unsafeWindowFunction1 "bit_and"
1674+ bitOr = unsafeWindowFunction1 "bit_or"
1675+ boolAnd = unsafeWindowFunction1 "bool_and"
1676+ boolOr = unsafeWindowFunction1 "bool_or"
1677+ every = unsafeWindowFunction1 "every"
1678+ max_ = unsafeWindowFunction1 "max"
1679+ min_ = unsafeWindowFunction1 "min"
1680+ avg = unsafeWindowFunction1 "avg"
1681+ corr = unsafeWindowFunction2 "corr"
1682+ covarPop = unsafeWindowFunction2 "covar_pop"
1683+ covarSamp = unsafeWindowFunction2 "covar_samp"
1684+ regrAvgX = unsafeWindowFunction2 "regr_avgx"
1685+ regrAvgY = unsafeWindowFunction2 "regr_avgy"
1686+ regrCount = unsafeWindowFunction2 "regr_count"
1687+ regrIntercept = unsafeWindowFunction2 "regr_intercept"
1688+ regrR2 = unsafeWindowFunction2 "regr_r2"
1689+ regrSlope = unsafeWindowFunction2 "regr_slope"
1690+ regrSxx = unsafeWindowFunction2 "regr_sxx"
1691+ regrSxy = unsafeWindowFunction2 "regr_sxy"
1692+ regrSyy = unsafeWindowFunction2 "regr_syy"
1693+ stddev = unsafeWindowFunction1 "stddev"
1694+ stddevPop = unsafeWindowFunction1 "stddev_pop"
1695+ stddevSamp = unsafeWindowFunction1 "stddev_samp"
1696+ variance = unsafeWindowFunction1 "variance"
1697+ varPop = unsafeWindowFunction1 "var_pop"
1698+ varSamp = unsafeWindowFunction1 "var_samp"
1700+-- | escape hatch to define aggregate functions
1702+ :: ByteString -- ^ aggregate function
1703+ -> Distinction (Expression 'Ungrouped commons schemas params from) xty
1704+ -> Expression ('Grouped bys) commons schemas params from yty
1705+unsafeAggregate1 fun x = UnsafeExpression $ mconcat
1706+ [fun, "(", renderSQL x, ")"]
1708+-- | escape hatch to define aggregate binary functions
1710+ :: ByteString -- ^ aggregate function
1711+ -> Distinction (Expression 'Ungrouped commons schemas params from GHC.:*: Expression 'Ungrouped commons schemas params from) xty
1712+ -> Expression ('Grouped bys) commons schemas params from yty
1713+unsafeAggregate2 fun xx = UnsafeExpression $ mconcat
1714+ [fun, "(", renderSQL xx, ")"]
1716+-- | A type family that calculates `PGAvg` type of a `PGType`.
1717+type family PGAvg ty where
1718+ PGAvg 'PGint2 = 'PGnumeric
1719+ PGAvg 'PGint4 = 'PGnumeric
1720+ PGAvg 'PGint8 = 'PGnumeric
1721+ PGAvg 'PGnumeric = 'PGnumeric
1722+ PGAvg 'PGfloat4 = 'PGfloat8
1723+ PGAvg 'PGfloat8 = 'PGfloat8
1724+ PGAvg 'PGinterval = 'PGinterval
1725+ -- PGAvg pg = TypeError
1727+{-----------------------------------------
1729+-----------------------------------------}
1731+-- | `TypeExpression`s are used in `cast`s and `createTable` commands.
1732+newtype TypeExpression (schemas :: SchemasType) (ty :: NullityType)
1733+ = UnsafeTypeExpression { renderTypeExpression :: ByteString }
1734+ deriving (GHC.Generic,Show,Eq,Ord,NFData)
1735+instance RenderSQL (TypeExpression schemas ty) where
1736+ renderSQL = renderTypeExpression
1738+-- | The enum or composite type in a `Typedef` can be expressed by its alias.
1740+ :: (Has sch schemas schema, Has td schema ('Typedef ty))
1741+ => QualifiedAlias sch td
1742+ -> TypeExpression schemas (nullity ty)
1743+typedef = UnsafeTypeExpression . renderSQL
1745+-- | The composite type corresponding to a `Table` definition can be expressed
1748+ :: (Has sch schemas schema, Has tab schema ('Table table))
1749+ => QualifiedAlias sch tab
1750+ -> TypeExpression schemas (nullity ('PGcomposite (TableToRow table)))
1751+typetable = UnsafeTypeExpression . renderSQL
1753+-- | The composite type corresponding to a `View` definition can be expressed
1756+ :: (Has sch schemas schema, Has vw schema ('View view))
1757+ => QualifiedAlias sch vw
1758+ -> TypeExpression schemas (nullity ('PGcomposite view))
1759+typeview = UnsafeTypeExpression . renderSQL
1761+-- | logical Boolean (true/false)
1762+bool :: TypeExpression schemas (nullity 'PGbool)
1763+bool = UnsafeTypeExpression "bool"
1764+-- | signed two-byte integer
1765+int2, smallint :: TypeExpression schemas (nullity 'PGint2)
1766+int2 = UnsafeTypeExpression "int2"
1767+smallint = UnsafeTypeExpression "smallint"
1768+-- | signed four-byte integer
1769+int4, int, integer :: TypeExpression schemas (nullity 'PGint4)
1770+int4 = UnsafeTypeExpression "int4"
1771+int = UnsafeTypeExpression "int"
1772+integer = UnsafeTypeExpression "integer"
1773+-- | signed eight-byte integer
1774+int8, bigint :: TypeExpression schemas (nullity 'PGint8)
1775+int8 = UnsafeTypeExpression "int8"
1776+bigint = UnsafeTypeExpression "bigint"
1777+-- | arbitrary precision numeric type
1778+numeric :: TypeExpression schemas (nullity 'PGnumeric)
1779+numeric = UnsafeTypeExpression "numeric"
1780+-- | single precision floating-point number (4 bytes)
1781+float4, real :: TypeExpression schemas (nullity 'PGfloat4)
1782+float4 = UnsafeTypeExpression "float4"
1783+real = UnsafeTypeExpression "real"
1784+-- | double precision floating-point number (8 bytes)
1785+float8, doublePrecision :: TypeExpression schemas (nullity 'PGfloat8)
1786+float8 = UnsafeTypeExpression "float8"
1787+doublePrecision = UnsafeTypeExpression "double precision"
1788+-- | variable-length character string
1789+text :: TypeExpression schemas (nullity 'PGtext)
1790+text = UnsafeTypeExpression "text"
1791+-- | fixed-length character string
1793+ :: forall n schemas nullity. (KnownNat n, 1 <= n)
1794+ => TypeExpression schemas (nullity ('PGchar n))
1795+char = UnsafeTypeExpression $ "char(" <> renderNat @n <> ")"
1796+character = UnsafeTypeExpression $ "character(" <> renderNat @n <> ")"
1797+-- | variable-length character string
1798+varchar, characterVarying
1799+ :: forall n schemas nullity. (KnownNat n, 1 <= n)
1800+ => TypeExpression schemas (nullity ('PGvarchar n))
1801+varchar = UnsafeTypeExpression $ "varchar(" <> renderNat @n <> ")"
1802+characterVarying = UnsafeTypeExpression $
1803+ "character varying(" <> renderNat @n <> ")"
1804+-- | binary data ("byte array")
1805+bytea :: TypeExpression schemas (nullity 'PGbytea)
1806+bytea = UnsafeTypeExpression "bytea"
1807+-- | date and time (no time zone)
1808+timestamp :: TypeExpression schemas (nullity 'PGtimestamp)
1809+timestamp = UnsafeTypeExpression "timestamp"
1810+-- | date and time, including time zone
1811+timestampWithTimeZone :: TypeExpression schemas (nullity 'PGtimestamptz)
1812+timestampWithTimeZone = UnsafeTypeExpression "timestamp with time zone"
1813+-- | calendar date (year, month, day)
1814+date :: TypeExpression schemas (nullity 'PGdate)
1815+date = UnsafeTypeExpression "date"
1816+-- | time of day (no time zone)
1817+time :: TypeExpression schemas (nullity 'PGtime)
1818+time = UnsafeTypeExpression "time"
1819+-- | time of day, including time zone
1820+timeWithTimeZone :: TypeExpression schemas (nullity 'PGtimetz)
1821+timeWithTimeZone = UnsafeTypeExpression "time with time zone"
1823+interval :: TypeExpression schemas (nullity 'PGinterval)
1824+interval = UnsafeTypeExpression "interval"
1825+-- | universally unique identifier
1826+uuid :: TypeExpression schemas (nullity 'PGuuid)
1827+uuid = UnsafeTypeExpression "uuid"
1828+-- | IPv4 or IPv6 host address
1829+inet :: TypeExpression schemas (nullity 'PGinet)
1830+inet = UnsafeTypeExpression "inet"
1831+-- | textual JSON data
1832+json :: TypeExpression schemas (nullity 'PGjson)
1833+json = UnsafeTypeExpression "json"
1834+-- | binary JSON data, decomposed
1835+jsonb :: TypeExpression schemas (nullity 'PGjsonb)
1836+jsonb = UnsafeTypeExpression "jsonb"
1837+-- | variable length array
1839+ :: TypeExpression schemas pg
1840+ -> TypeExpression schemas (nullity ('PGvararray pg))
1841+vararray ty = UnsafeTypeExpression $ renderSQL ty <> "[]"
1842+-- | fixed length array
1844+-- >>> renderSQL (fixarray @'[2] json)
1847+ :: forall dims schemas nullity pg. All KnownNat dims
1848+ => TypeExpression schemas pg
1849+ -> TypeExpression schemas (nullity ('PGfixarray dims pg))
1850+fixarray ty = UnsafeTypeExpression $
1851+ renderSQL ty <> renderDims @dims
1853+ renderDims :: forall ns. All KnownNat ns => ByteString
1857+ . ByteString.intercalate "]["
1859+ $ hcmap (Proxy @KnownNat)
1860+ (K . fromString . show . natVal)
1861+ (hpure Proxy :: NP Proxy ns)
1863+-- | `pgtype` is a demoted version of a `PGType`
1864+class PGTyped schemas (ty :: NullityType) where
1865+ pgtype :: TypeExpression schemas ty
1866+instance PGTyped schemas (nullity 'PGbool) where pgtype = bool
1867+instance PGTyped schemas (nullity 'PGint2) where pgtype = int2
1868+instance PGTyped schemas (nullity 'PGint4) where pgtype = int4
1869+instance PGTyped schemas (nullity 'PGint8) where pgtype = int8
1870+instance PGTyped schemas (nullity 'PGnumeric) where pgtype = numeric
1871+instance PGTyped schemas (nullity 'PGfloat4) where pgtype = float4
1872+instance PGTyped schemas (nullity 'PGfloat8) where pgtype = float8
1873+instance PGTyped schemas (nullity 'PGtext) where pgtype = text
1874+instance (KnownNat n, 1 <= n)
1875+ => PGTyped schemas (nullity ('PGchar n)) where pgtype = char @n
1876+instance (KnownNat n, 1 <= n)
1877+ => PGTyped schemas (nullity ('PGvarchar n)) where pgtype = varchar @n
1878+instance PGTyped schemas (nullity 'PGbytea) where pgtype = bytea
1879+instance PGTyped schemas (nullity 'PGtimestamp) where pgtype = timestamp
1880+instance PGTyped schemas (nullity 'PGtimestamptz) where pgtype = timestampWithTimeZone
1881+instance PGTyped schemas (nullity 'PGdate) where pgtype = date
1882+instance PGTyped schemas (nullity 'PGtime) where pgtype = time
1883+instance PGTyped schemas (nullity 'PGtimetz) where pgtype = timeWithTimeZone
1884+instance PGTyped schemas (nullity 'PGinterval) where pgtype = interval
1885+instance PGTyped schemas (nullity 'PGuuid) where pgtype = uuid
1886+instance PGTyped schemas (nullity 'PGjson) where pgtype = json
1887+instance PGTyped schemas (nullity 'PGjsonb) where pgtype = jsonb
1888+instance PGTyped schemas ty
1889+ => PGTyped schemas (nullity ('PGvararray ty)) where
1890+ pgtype = vararray (pgtype @schemas @ty)
1891+instance (All KnownNat dims, PGTyped schemas ty)
1892+ => PGTyped schemas (nullity ('PGfixarray dims ty)) where
1893+ pgtype = fixarray @dims (pgtype @schemas @ty)
1895+{-----------------------------------------
1897+-----------------------------------------}
1899+-- | `SortExpression`s are used by `sortBy` to optionally sort the results
1900+-- of a `Query`. `Asc` or `Desc` set the sort direction of a `NotNull` result
1901+-- column to ascending or descending. Ascending order puts smaller values
1902+-- first, where "smaller" is defined in terms of the `.<` operator. Similarly,
1903+-- descending order is determined with the `.>` operator. `AscNullsFirst`,
1904+-- `AscNullsLast`, `DescNullsFirst` and `DescNullsLast` options are used to
1905+-- determine whether nulls appear before or after non-null values in the sort
1906+-- ordering of a `Null` result column.
1907+data SortExpression grp commons schemas params from where
1909+ :: Expression grp commons schemas params from ('NotNull ty)
1910+ -> SortExpression grp commons schemas params from
1912+ :: Expression grp commons schemas params from ('NotNull ty)
1913+ -> SortExpression grp commons schemas params from
1915+ :: Expression grp commons schemas params from ('Null ty)
1916+ -> SortExpression grp commons schemas params from
1918+ :: Expression grp commons schemas params from ('Null ty)
1919+ -> SortExpression grp commons schemas params from
1921+ :: Expression grp commons schemas params from ('Null ty)
1922+ -> SortExpression grp commons schemas params from
1924+ :: Expression grp commons schemas params from ('Null ty)
1925+ -> SortExpression grp commons schemas params from
1926+deriving instance Show (SortExpression grp commons schemas params from)
1928+class OrderBy expr where
1930+ :: [SortExpression grp commons schemas params from]
1931+ -> expr grp commons schemas params from
1932+ -> expr grp commons schemas params from
1934+-- | Render a `SortExpression`.
1935+instance RenderSQL (SortExpression grp commons schemas params from) where
1937+ Asc expression -> renderSQL expression <+> "ASC"
1938+ Desc expression -> renderSQL expression <+> "DESC"
1939+ AscNullsFirst expression -> renderSQL expression
1940+ <+> "ASC NULLS FIRST"
1941+ DescNullsFirst expression -> renderSQL expression
1942+ <+> "DESC NULLS FIRST"
1943+ AscNullsLast expression -> renderSQL expression <+> "ASC NULLS LAST"
1944+ DescNullsLast expression -> renderSQL expression <+> "DESC NULLS LAST"
1946+data WindowDefinition grp commons schemas params from where
1949+ => NP (Expression grp commons schemas params from) bys
1950+ -> [SortExpression grp commons schemas params from]
1951+ -> WindowDefinition grp commons schemas params from
1953+instance OrderBy WindowDefinition where
1954+ orderBy sortsR (WindowDefinition parts sortsL)
1955+ = WindowDefinition parts (sortsL ++ sortsR)
1957+instance RenderSQL (WindowDefinition commons schemas from grp params) where
1958+ renderSQL (WindowDefinition part ord) =
1959+ renderPartitionByClause part <> renderOrderByClause ord
1961+ renderPartitionByClause = \case
1963+ parts -> "PARTITION" <+> "BY" <+> renderCommaSeparated renderExpression parts
1964+ renderOrderByClause = \case
1966+ srts -> " ORDER" <+> "BY"
1967+ <+> commaSeparated (renderSQL <$> srts)
1971+ => NP (Expression grp commons schemas params from) bys
1972+ -> WindowDefinition grp commons schemas params from
1973+partitionBy bys = WindowDefinition bys []
1975+newtype WindowFunction
1977+ (commons :: FromType)
1978+ (schemas :: SchemasType)
1979+ (params :: [NullityType])
1981+ (ty :: NullityType)
1982+ = UnsafeWindowFunction { renderWindowFunction :: ByteString }
1983+ deriving (GHC.Generic,Show,Eq,Ord,NFData)
1985+instance RenderSQL (WindowFunction grp commons schemas params from ty) where
1986+ renderSQL = renderWindowFunction
1988+unsafeWindowFunction1
1990+ -> Expression grp commons schemas params from ty0
1991+ -> WindowFunction grp commons schemas params from ty1
1992+unsafeWindowFunction1 fun x
1993+ = UnsafeWindowFunction $ fun <> parenthesized (renderSQL x)
1995+unsafeWindowFunction2
1997+ -> (Expression grp commons schemas params from GHC.:*: Expression grp commons schemas params from) ty0
1998+ -> WindowFunction grp commons schemas params from ty1
1999+unsafeWindowFunction2 fun (x GHC.:*: x')
2000+ = UnsafeWindowFunction $ fun <> parenthesized (renderSQL x <> ", " <> renderSQL x')
2002+-- | escape hatch to define aggregate binary functions
2004+-- :: ByteString -- ^ aggregate function
2005+-- -> Distinction (Expression 'Ungrouped commons schemas params from GHC.:*: Expression 'Ungrouped commons schemas params from) xty
2006+-- -> Expression ('Grouped bys) commons schemas params from yty
2007+-- unsafeAggregate2 fun xx = UnsafeExpression $ mconcat
2008+-- [fun, "(", renderSQL xx, ")"]
2010+{- | rank of the current row with gaps; same as `rowNumber` of its first peer
2014+rank :: WindowFunction grp commons schemas params from ('NotNull 'PGint8)
2015+rank = UnsafeWindowFunction "rank()"
2017+{- | number of the current row within its partition, counting from 1
2018+>>> printSQL rowNumber
2021+rowNumber :: WindowFunction grp commons schemas params from ('NotNull 'PGint8)
2022+rowNumber = UnsafeWindowFunction "row_number()"
2024+{- | rank of the current row without gaps; this function counts peer groups
2025+>>> printSQL denseRank
2028+denseRank :: WindowFunction grp commons schemas params from ('NotNull 'PGint8)
2029+denseRank = UnsafeWindowFunction "dense_rank()"
2031+{- | relative rank of the current row: (rank - 1) / (total partition rows - 1)
2032+>>> printSQL percentRank
2035+percentRank :: WindowFunction grp commons schemas params from ('NotNull 'PGfloat8)
2036+percentRank = UnsafeWindowFunction "percent_rank()"
2038+{- | cumulative distribution: (number of partition rows
2039+preceding or peer with current row) / total partition rows
2040+>>> printSQL cumeDist
2043+cumeDist :: WindowFunction grp commons schemas params from ('NotNull 'PGfloat8)
2044+cumeDist = UnsafeWindowFunction "cume_dist()"
2046+{- | integer ranging from 1 to the argument value,
2047+dividing the partition as equally as possible
2050+ :: Expression grp commons schemas params from ('NotNull 'PGint4)
2052+ -> WindowFunction grp commons schemas params from ('NotNull 'PGint4)
2053+ntile numBuckets = UnsafeWindowFunction $ "ntile"
2054+ <> parenthesized (renderSQL numBuckets)
2056+{- | returns value evaluated at the row that is offset rows before the current
2057+row within the partition; if there is no such row, instead return default
2058+(which must be of the same type as value). Both offset and default are
2059+evaluated with respect to the current row.
2062+ :: Expression grp commons schemas params from ty
2064+ -> Expression grp commons schemas params from ('NotNull 'PGint4)
2066+ -> Expression grp commons schemas params from ty
2068+ -> WindowFunction grp commons schemas params from ty
2069+lag value offset def = UnsafeWindowFunction $ "lag"
2071+ (commaSeparated ([renderSQL value, renderSQL offset, renderSQL def]))
2073+{- | returns value evaluated at the row that is offset rows after the current
2074+row within the partition; if there is no such row, instead return default
2075+(which must be of the same type as value). Both offset and default are
2076+evaluated with respect to the current row.
2079+ :: Expression grp commons schemas params from ty
2081+ -> Expression grp commons schemas params from ('NotNull 'PGint4)
2083+ -> Expression grp commons schemas params from ty
2085+ -> WindowFunction grp commons schemas params from ty
2086+lead value offset def = UnsafeWindowFunction $ "lag"
2088+ (commaSeparated ([renderSQL value, renderSQL offset, renderSQL def]))
2090+{- | returns value evaluated at the row that is the
2091+first row of the window frame
2094+ :: Expression grp commons schemas params from ty
2096+ -> WindowFunction grp commons schemas params from ty
2097+firstValue value = UnsafeWindowFunction $ "first_value"
2098+ <> parenthesized (renderSQL value)
2100+{- | returns value evaluated at the row that is the
2101+last row of the window frame
2104+ :: Expression grp commons schemas params from ty
2106+ -> WindowFunction grp commons schemas params from ty
2107+lastValue value = UnsafeWindowFunction $ "last_value"
2108+ <> parenthesized (renderSQL value)
2110+{- | returns value evaluated at the row that is the nth
2111+row of the window frame (counting from 1); null if no such row
2114+ :: Expression grp commons schemas params from (nullity ty)
2116+ -> Expression grp commons schemas params from ('NotNull 'PGint4)
2118+ -> WindowFunction grp commons schemas params from ('Null ty)
2119+nthValue value nth = UnsafeWindowFunction $ "nth_value"
2120+ <> parenthesized (commaSeparated [renderSQL value, renderSQL nth])