@@ -1,14 +1,13 @@
2Module: Squeal.PostgreSQL.Expression
2Module: Squeal.PostgreSQL.Expression
3Description: Squeal expressions
3Description: Squeal expressions
4−Copyright: (c) Eitan Chatav, 2017
4+Copyright: (c) Eitan Chatav, 2019
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 #-}
12{-# LANGUAGE
11{-# LANGUAGE
13 AllowAmbiguousTypes
12 AllowAmbiguousTypes
14 , ConstraintKinds
13 , ConstraintKinds
@@ -34,343 +33,214 @@ Squeal expressions are the atoms used to build statements.
34module Squeal.PostgreSQL.Expression
33module Squeal.PostgreSQL.Expression
35 ( -- * Expression
34 ( -- * Expression
36 Expression (..)
35 Expression (..)
37− , ClosedExpression
36+ , Expr
38 , Operator
45 , Operator
39− , ComparisonOperator
46+ , OperatorDB
40− , HasParameter (parameter)
58 , unsafeBinaryOp
47 , unsafeBinaryOp
59− , unsafeUnaryOp
48+ , binaryOp
60− , unsafeFunction
49+ , FunctionVar
61− , unsafeFunction2
50+ , unsafeFunctionVar
62− , unsafeVariadicFunction
51+ , type (--->)
63− , atan2_
52+ , FunctionNDB
64− , cast
53+ , unsafeFunctionN
65− , quot_
54+ , functionN
66− , rem_
55+ , PGSubset (..)
67− , trunc
56+ , PGIntersect (..)
90− , notBetweenSymmetric
117− -- *** Json and Jsonb operators
122− -- *** Jsonb operators
149− , jsonExtractPathAsText
150− , jsonbExtractPathAsText
168− -- * Window Functions
169− , WindowDefinition (..)
171− , WindowFunction (..)
184− , SortExpression (..)
187− , TypeExpression (..)
213− , timestampWithTimeZone
231− , websearchToTSquery
235 -- * Re-export
57 -- * Re-export
242import Control.Category
63import Control.Category
243import Control.DeepSeq
64import Control.DeepSeq
244import Data.ByteString (ByteString)
65import Data.ByteString (ByteString)
245−import Data.ByteString.Lazy (toStrict)
246import Data.Function ((&))
66import Data.Function ((&))
247import Data.Semigroup hiding (All)
67import Data.Semigroup hiding (All)
248−import qualified Data.Aeson as JSON
249import Data.String
68import Data.String
251import Generics.SOP hiding (All, from)
69import Generics.SOP hiding (All, from)
252−import GHC.Generics ((:*:) (..))
253import GHC.OverloadedLabels
70import GHC.OverloadedLabels
254import GHC.TypeLits
71import GHC.TypeLits
255import Numeric
72import Numeric
256import Prelude hiding (id, (.))
73import Prelude hiding (id, (.))
258−import qualified Data.ByteString as ByteString
259import qualified GHC.Generics as GHC
75import qualified GHC.Generics as GHC
260−import qualified Generics.SOP as SOP
77+import Squeal.PostgreSQL.Alias
78+import Squeal.PostgreSQL.List
262import Squeal.PostgreSQL.Render
79import Squeal.PostgreSQL.Render
263import Squeal.PostgreSQL.Schema
80import Squeal.PostgreSQL.Schema
83+-- >>> import Squeal.PostgreSQL
265{-----------------------------------------
85{-----------------------------------------
266column expressions
86column expressions
267-----------------------------------------}
87-----------------------------------------}
269{- | `Expression`s are used in a variety of contexts,
89{- | `Expression`s are used in a variety of contexts,
90+such as in the target `Squeal.PostgreSQL.Query.List` of the
270−such as in the target list of the `Squeal.PostgreSQL.Query.select` command,
91+`Squeal.PostgreSQL.Query.select` command,
271as new column values in `Squeal.PostgreSQL.Manipulation.insertRow` or
92as new column values in `Squeal.PostgreSQL.Manipulation.insertRow` or
272`Squeal.PostgreSQL.Manipulation.update`,
93`Squeal.PostgreSQL.Manipulation.update`,
273−or in search `Condition`s in a number of commands.
94+or in search `Squeal.PostgreSQL.Logic.Condition`s in a number of commands.
275The expression syntax allows the calculation of
96The expression syntax allows the calculation of
276values from primitive expression using arithmetic, logical,
97values from primitive expression using arithmetic, logical,
277and other operations.
98and 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`.
279newtype Expression
114newtype Expression
280 (outer :: FromType)
115 (outer :: FromType)
282 (commons :: FromType)
116 (commons :: FromType)
283 (schemas :: SchemasType)
118 (schemas :: SchemasType)
284 (params :: [NullityType])
119 (params :: [NullityType])
285 (from :: FromType)
120 (from :: FromType)
286 (ty :: NullityType)
121 (ty :: NullityType)
287 = UnsafeExpression { renderExpression :: ByteString }
122 = UnsafeExpression { renderExpression :: ByteString }
288 deriving (GHC.Generic,Show,Eq,Ord,NFData)
123 deriving (GHC.Generic,Show,Eq,Ord,NFData)
289−instance RenderSQL (Expression outer grp commons schemas params from ty) where
124+instance RenderSQL (Expression outer commons grp schemas params from ty) where
290 renderSQL = renderExpression
125 renderSQL = renderExpression
292−type ClosedExpression ty
127+-- | An `Expr` is a closed `Expression`.
293− = forall outer grp commons schemas params from
128+-- It is a F@RankNType@ but don't be scared.
294− . Expression outer grp commons schemas params from ty
129+-- Think of it as an expression which sees no
295−
130+-- namespaces, so you can't use parameters
296−type Operator ty1 ty2 ty3
131+-- or alias references. It can be used as
297− = forall outer grp commons schemas params from
132+-- a simple piece of more complex `Expression`s.
298− . Expression outer grp commons schemas params from ty1
133+type Expr x
299− -> Expression outer grp commons schemas params from ty2
134+ = forall outer commons grp schemas params from
300− -> Expression outer grp commons schemas params from ty3
135+ . Expression outer commons grp schemas params from x
301−
136+ -- ^ cannot reference aliases
302−type ComparisonOperator ty1 ty2
137+
303− = Operator ty1 ty2 ('Null 'PGbool)
138+-- | A @RankNType@ for binary operators.
304−
139+type Operator x1 x2 y
305−{- | A `HasParameter` constraint is used to indicate a value that is
140+ = forall outer commons grp schemas params from
306−supplied externally to a SQL statement.
141+ . Expression outer commons grp schemas params from x1
307−`Squeal.PostgreSQL.PQ.manipulateParams`,
142+ -- ^ left input
308−`Squeal.PostgreSQL.PQ.queryParams` and
143+ -> Expression outer commons grp schemas params from x2
309−`Squeal.PostgreSQL.PQ.traversePrepared` support specifying data values
144+ -- ^ right input
310−separately from the SQL command string, in which case `param`s are used to
145+ -> Expression outer commons grp schemas params from y
311−refer to the out-of-line data values.
146+ -- ^ output
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.
313−class KnownNat n => HasParameter
199+type FunctionVar x0 x1 y
314− (n :: Nat)
200+ = forall outer commons grp schemas params from
315− (params :: [NullityType])
201+ . [Expression outer commons grp schemas params from x0]
316− (ty :: NullityType)
202+ -- ^ inputs
317− | n params -> ty where
203+ -> Expression outer commons grp schemas params from x1
318− -- | `parameter` takes a `Nat` using type application and a `TypeExpression`.
204+ -- ^ must have at least 1 input
320− -- >>> let expr = parameter @1 int4 :: Expression outer grp '[] schemas '[ 'Null 'PGint4] from ('Null 'PGint4)
205+ -> Expression outer commons grp schemas params from y
321− -- >>> printSQL expr
206+ -- ^ output
323− parameter
208+{- | >>> printSQL (unsafeFunctionVar "greatest" [true, null_] false)
324− :: TypeExpression schemas ty
209+greatest(TRUE, NULL, FALSE)
325− -> Expression outer grp commons schemas params from ty
210+-}
211+unsafeFunctionVar :: ByteString -> FunctionVar x0 x1 y
326− parameter ty = UnsafeExpression $ parenthesized $
212+unsafeFunctionVar fun xs x = UnsafeExpression $ fun <> parenthesized
327− "$" <> renderNat @n <+> "::"
213+ (commaSeparated (renderSQL <$> xs) <> ", " <> renderSQL x)
329−instance {-# OVERLAPPING #-} HasParameter 1 (ty1:tys) ty1
330−instance {-# OVERLAPPABLE #-} (KnownNat n, HasParameter (n-1) params ty)
331− => HasParameter n (ty' : params) ty
333−-- | `param` takes a `Nat` using type application and for basic types,
334−-- infers a `TypeExpression`.
336−-- >>> let expr = param @1 :: Expression outer grp commons schemas '[ 'Null 'PGint4] from ('Null 'PGint4)
340− :: forall n outer commons schemas params from grp ty
341− . (PGTyped schemas ty, HasParameter n params ty)
342− => Expression outer grp commons schemas params from ty -- ^ param
343−param = parameter @n (pgtype @schemas)
345instance (HasUnique tab (Join outer from) row, Has col row ty)
215instance (HasUnique tab (Join outer from) row, Has col row ty)
346− => IsLabel col (Expression outer 'Ungrouped commons schemas params from ty) where
216+ => IsLabel col (Expression outer commons 'Ungrouped schemas params from ty) where
347 fromLabel = UnsafeExpression $ renderSQL (Alias @col)
217 fromLabel = UnsafeExpression $ renderSQL (Alias @col)
348instance (HasUnique tab (Join outer from) row, Has col row ty, tys ~ '[ty])
218instance (HasUnique tab (Join outer from) row, Has col row ty, tys ~ '[ty])
349− => IsLabel col (NP (Expression outer 'Ungrouped commons schemas params from) tys) where
219+ => IsLabel col (NP (Expression outer commons 'Ungrouped schemas params from) tys) where
350 fromLabel = fromLabel @col :* Nil
220 fromLabel = fromLabel @col :* Nil
351instance (HasUnique tab (Join outer from) row, Has col row ty, column ~ (col ::: ty))
221instance (HasUnique tab (Join outer from) row, Has col row ty, column ~ (col ::: ty))
352 => IsLabel col
222 => IsLabel col
353− (Aliased (Expression outer 'Ungrouped commons schemas params from) column) where
223+ (Aliased (Expression outer commons 'Ungrouped schemas params from) column) where
354 fromLabel = fromLabel @col `As` Alias
224 fromLabel = fromLabel @col `As` Alias
355instance (HasUnique tab (Join outer from) row, Has col row ty, columns ~ '[col ::: ty])
225instance (HasUnique tab (Join outer from) row, Has col row ty, columns ~ '[col ::: ty])
356 => IsLabel col
226 => IsLabel col
357− (NP (Aliased (Expression outer 'Ungrouped commons schemas params from)) columns) where
227+ (NP (Aliased (Expression outer commons 'Ungrouped schemas params from)) columns) where
358 fromLabel = fromLabel @col :* Nil
228 fromLabel = fromLabel @col :* Nil
360instance (Has tab (Join outer from) row, Has col row ty)
230instance (Has tab (Join outer from) row, Has col row ty)
361− => IsQualified tab col (Expression outer 'Ungrouped commons schemas params from ty) where
231+ => IsQualified tab col (Expression outer commons 'Ungrouped schemas params from ty) where
362 tab ! col = UnsafeExpression $
232 tab ! col = UnsafeExpression $
363 renderSQL tab <> "." <> renderSQL col
233 renderSQL tab <> "." <> renderSQL col
364instance (Has tab (Join outer from) row, Has col row ty, tys ~ '[ty])
234instance (Has tab (Join outer from) row, Has col row ty, tys ~ '[ty])
365− => IsQualified tab col (NP (Expression outer 'Ungrouped commons schemas params from) tys) where
235+ => IsQualified tab col (NP (Expression outer commons 'Ungrouped schemas params from) tys) where
366 tab ! col = tab ! col :* Nil
236 tab ! col = tab ! col :* Nil
367instance (Has tab (Join outer from) row, Has col row ty, column ~ (col ::: ty))
237instance (Has tab (Join outer from) row, Has col row ty, column ~ (col ::: ty))
368 => IsQualified tab col
238 => IsQualified tab col
369− (Aliased (Expression outer 'Ungrouped commons schemas params from) column) where
239+ (Aliased (Expression outer commons 'Ungrouped schemas params from) column) where
370 tab ! col = tab ! col `As` col
240 tab ! col = tab ! col `As` col
371instance (Has tab (Join outer from) row, Has col row ty, columns ~ '[col ::: ty])
241instance (Has tab (Join outer from) row, Has col row ty, columns ~ '[col ::: ty])
372 => IsQualified tab col
242 => IsQualified tab col
373− (NP (Aliased (Expression outer 'Ungrouped commons schemas params from)) columns) where
243+ (NP (Aliased (Expression outer commons 'Ungrouped schemas params from)) columns) where
374 tab ! col = tab ! col :* Nil
244 tab ! col = tab ! col :* Nil
@@ -378,7 +248,7 @@ instance
378 , Has col row ty
248 , Has col row ty
379 , GroupedBy tab col bys
249 , GroupedBy tab col bys
380 ) => IsLabel col
250 ) => IsLabel col
381− (Expression outer ('Grouped bys) commons schemas params from ty) where
251+ (Expression outer commons ('Grouped bys) schemas params from ty) where
382 fromLabel = UnsafeExpression $ renderSQL (Alias @col)
252 fromLabel = UnsafeExpression $ renderSQL (Alias @col)
384 ( HasUnique tab (Join outer from) row
254 ( HasUnique tab (Join outer from) row
@@ -386,7 +256,7 @@ instance
386 , GroupedBy tab col bys
256 , GroupedBy tab col bys
387 , tys ~ '[ty]
257 , tys ~ '[ty]
388 ) => IsLabel col
258 ) => IsLabel col
389− (NP (Expression outer ('Grouped bys) commons schemas params from) tys) where
259+ (NP (Expression outer commons ('Grouped bys) schemas params from) tys) where
390 fromLabel = fromLabel @col :* Nil
260 fromLabel = fromLabel @col :* Nil
392 ( HasUnique tab (Join outer from) row
262 ( HasUnique tab (Join outer from) row
@@ -394,7 +264,7 @@ instance
394 , GroupedBy tab col bys
264 , GroupedBy tab col bys
395 , column ~ (col ::: ty)
265 , column ~ (col ::: ty)
396 ) => IsLabel col
266 ) => IsLabel col
397− (Aliased (Expression outer ('Grouped bys) commons schemas params from) column) where
267+ (Aliased (Expression outer commons ('Grouped bys) schemas params from) column) where
398 fromLabel = fromLabel @col `As` Alias
268 fromLabel = fromLabel @col `As` Alias
400 ( HasUnique tab (Join outer from) row
270 ( HasUnique tab (Join outer from) row
@@ -402,7 +272,7 @@ instance
402 , GroupedBy tab col bys
272 , GroupedBy tab col bys
403 , columns ~ '[col ::: ty]
273 , columns ~ '[col ::: ty]
404 ) => IsLabel col
274 ) => IsLabel col
405− (NP (Aliased (Expression outer ('Grouped bys) commons schemas params from)) columns) where
275+ (NP (Aliased (Expression outer commons ('Grouped bys) schemas params from)) columns) where
406 fromLabel = fromLabel @col :* Nil
276 fromLabel = fromLabel @col :* Nil
@@ -410,7 +280,7 @@ instance
410 , Has col row ty
280 , Has col row ty
411 , GroupedBy tab col bys
281 , GroupedBy tab col bys
412 ) => IsQualified tab col
282 ) => IsQualified tab col
413− (Expression outer ('Grouped bys) commons schemas params from ty) where
283+ (Expression outer commons ('Grouped bys) schemas params from ty) where
414 tab ! col = UnsafeExpression $
284 tab ! col = UnsafeExpression $
415 renderSQL tab <> "." <> renderSQL col
285 renderSQL tab <> "." <> renderSQL col
@@ -419,7 +289,7 @@ instance
419 , GroupedBy tab col bys
289 , GroupedBy tab col bys
420 , tys ~ '[ty]
290 , tys ~ '[ty]
421 ) => IsQualified tab col
291 ) => IsQualified tab col
422− (NP (Expression outer ('Grouped bys) commons schemas params from) tys) where
292+ (NP (Expression outer commons ('Grouped bys) schemas params from) tys) where
423 tab ! col = tab ! col :* Nil
293 tab ! col = tab ! col :* Nil
425 ( Has tab (Join outer from) row
295 ( Has tab (Join outer from) row
@@ -427,7 +297,7 @@ instance
427 , GroupedBy tab col bys
297 , GroupedBy tab col bys
428 , column ~ (col ::: ty)
298 , column ~ (col ::: ty)
429 ) => IsQualified tab col
299 ) => IsQualified tab col
430− (Aliased (Expression outer ('Grouped bys) commons schemas params from) column) where
300+ (Aliased (Expression outer commons ('Grouped bys) schemas params from) column) where
431 tab ! col = tab ! col `As` col
301 tab ! col = tab ! col `As` col
433 ( Has tab (Join outer from) row
303 ( Has tab (Join outer from) row
@@ -435,253 +305,78 @@ instance
435 , GroupedBy tab col bys
305 , GroupedBy tab col bys
436 , columns ~ '[col ::: ty]
306 , columns ~ '[col ::: ty]
437 ) => IsQualified tab col
307 ) => IsQualified tab col
438− (NP (Aliased (Expression outer ('Grouped bys) commons schemas params from)) columns) where
308+ (NP (Aliased (Expression outer commons ('Grouped bys) schemas params from)) columns) where
439 tab ! col = tab ! col :* Nil
309 tab ! col = tab ! col :* Nil
441−-- | analagous to `Nothing`
443−-- >>> printSQL null_
445−null_ :: Expression outer grp commons schemas params from ('Null ty)
446−null_ = UnsafeExpression "NULL"
448−-- | analagous to `Just`
450−-- >>> printSQL $ notNull true
453− :: Expression outer grp commons schemas params from ('NotNull ty)
454− -> Expression outer grp commons schemas params from ('Null ty)
455−notNull = UnsafeExpression . renderSQL
457−-- | return the leftmost value which is not NULL
459−-- >>> printSQL $ coalesce [null_, true] false
460−-- COALESCE(NULL, TRUE, FALSE)
462− :: [Expression outer grp commons schemas params from ('Null ty)]
463− -- ^ @NULL@s may be present
464− -> Expression outer grp commons schemas params from ('NotNull ty)
465− -- ^ @NULL@ is absent
466− -> Expression outer grp commons schemas params from ('NotNull ty)
467−coalesce nullxs notNullx = UnsafeExpression $
468− "COALESCE" <> parenthesized (commaSeparated
469− ((renderSQL <$> nullxs) <> [renderSQL notNullx]))
471−-- | analagous to `Data.Maybe.fromMaybe` using @COALESCE@
473−-- >>> printSQL $ fromNull true null_
474−-- COALESCE(NULL, TRUE)
476− :: Expression outer grp commons schemas params from ('NotNull ty)
477− -- ^ what to convert @NULL@ to
478− -> Expression outer grp commons schemas params from ('Null ty)
479− -> Expression outer grp commons schemas params from ('NotNull ty)
480−fromNull notNullx nullx = coalesce [nullx] notNullx
482−-- | >>> printSQL $ null_ & isNull
485− :: Expression outer grp commons schemas params from ('Null ty)
486− -- ^ possibly @NULL@
487− -> Condition outer grp commons schemas params from
488−isNull x = UnsafeExpression $ renderSQL x <+> "IS NULL"
490−-- | >>> printSQL $ null_ & isNotNull
493− :: Expression outer grp commons schemas params from ('Null ty)
494− -- ^ possibly @NULL@
495− -> Condition outer grp commons schemas params from
496−isNotNull x = UnsafeExpression $ renderSQL x <+> "IS NOT NULL"
498−-- | analagous to `maybe` using @IS NULL@
500−-- >>> printSQL $ matchNull true not_ null_
501−-- CASE WHEN NULL IS NULL THEN TRUE ELSE (NOT NULL) END
503− :: Expression outer grp commons schemas params from (nullty)
504− -- ^ what to convert @NULL@ to
505− -> ( Expression outer grp commons schemas params from ('NotNull ty)
506− -> Expression outer grp commons schemas params from (nullty) )
507− -- ^ function to perform when @NULL@ is absent
508− -> Expression outer grp commons schemas params from ('Null ty)
509− -> Expression outer grp commons schemas params from (nullty)
510−matchNull y f x = ifThenElse (isNull x) y
511− (f (UnsafeExpression (renderSQL x)))
513−{-| right inverse to `fromNull`, if its arguments are equal then
514−`nullIf` gives @NULL@.
516−>>> :set -XTypeApplications -XDataKinds
517−>>> let expr = nullIf false (param @1) :: Expression outer grp commons schemas '[ 'NotNull 'PGbool] from ('Null 'PGbool)
519−NULL IF (FALSE, ($1 :: bool))
522− :: Expression outer grp commons schemas params from ('NotNull ty)
523− -- ^ @NULL@ is absent
524− -> Expression outer grp commons schemas params from ('NotNull ty)
525− -- ^ @NULL@ is absent
526− -> Expression outer grp commons schemas params from ('Null ty)
527−nullIf x y = UnsafeExpression $ "NULL IF" <+> parenthesized
528− (renderSQL x <> ", " <> renderSQL y)
530−-- | >>> printSQL $ array [null_, false, true]
531−-- ARRAY[NULL, FALSE, TRUE]
533− :: [Expression outer grp commons schemas params from ty]
535− -> Expression outer grp commons schemas params from (nullity ('PGvararray ty))
536−array xs = UnsafeExpression $
537− "ARRAY[" <> commaSeparated (renderSQL <$> xs) <> "]"
539−-- | >>> printSQL $ cardinality (array [null_, false, true])
540−-- cardinality(ARRAY[NULL, FALSE, TRUE])
542− :: Expression outer grp commons schemas params from (nullity ('PGvararray ty))
543− -> Expression outer grp commons schemas params from (nullity 'PGint8)
544−cardinality = unsafeFunction "cardinality"
546−-- | >>> printSQL $ array [null_, false, true] & index 2
547−-- (ARRAY[NULL, FALSE, TRUE])[2]
549− :: Word64 -- ^ index
550− -> Expression outer grp commons schemas params from (nullity ('PGvararray ty)) -- ^ array
551− -> Expression outer grp commons schemas params from (NullifyType ty)
552−index n expr = UnsafeExpression $
553− parenthesized (renderSQL expr) <> "[" <> fromString (show n) <> "]"
555instance (KnownSymbol label, label `In` labels) => IsPGlabel label
311instance (KnownSymbol label, label `In` labels) => IsPGlabel label
556− (Expression outer grp commons schemas params from (nullity ('PGenum labels))) where
312+ (Expression outer commons grp schemas params from (null ('PGenum labels))) where
557 label = UnsafeExpression $ renderSQL (PGlabel @label)
313 label = UnsafeExpression $ renderSQL (PGlabel @label)
559−-- | A row constructor is an expression that builds a row value
560−-- (also called a composite value) using values for its member fields.
563−-- type Complex = 'PGcomposite
564−-- '[ "real" ::: 'NotNull 'PGfloat8
565−-- , "imaginary" ::: 'NotNull 'PGfloat8 ]
568−-- >>> let i = row (0 `as` #real :* 1 `as` #imaginary) :: Expression outer grp commons schemas params from ('NotNull Complex)
573− => NP (Aliased (Expression outer grp commons schemas params from)) row
574− -- ^ zero or more expressions for the row field values
575− -> Expression outer grp commons schemas params from (nullity ('PGcomposite row))
576−row exprs = UnsafeExpression $ "ROW" <> parenthesized
577− (renderCommaSeparated (\ (expr `As` _) -> renderSQL expr) exprs)
580−-- type Complex = 'PGcomposite
581−-- '[ "real" ::: 'NotNull 'PGfloat8
582−-- , "imaginary" ::: 'NotNull 'PGfloat8 ]
583−-- type Schema = '["complex" ::: 'Typedef Complex]
586−-- >>> let i = row (0 `as` #real :* 1 `as` #imaginary) :: Expression outer grp '[] (Public Schema) from params ('NotNull Complex)
587−-- >>> printSQL $ i & field #complex #imaginary
588−-- (ROW(0, 1)::"complex")."imaginary"
590− :: ( Has sch schemas schema
591− , Has tydef schema ('Typedef ('PGcomposite row))
593− => QualifiedAlias sch tydef -- ^ row type
594− -> Alias field -- ^ field name
595− -> Expression outer grp commons schemas params from ('NotNull ('PGcomposite row))
596− -> Expression outer grp commons schemas params from ty
597−field td fld expr = UnsafeExpression $
598− parenthesized (renderSQL expr <> "::" <> renderSQL td)
599− <> "." <> renderSQL fld
602− (Expression outer grp commons schemas params from (nullity ('PGvararray ty))) where
603− (<>) = unsafeBinaryOp "||"
606− (Expression outer grp commons schemas params from (nullity ('PGvararray ty))) where
610−-- | >>> let expr = greatest currentTimestamp [param @1] :: Expression outer grp commons schemas '[ 'NotNull 'PGtimestamptz] from ('NotNull 'PGtimestamptz)
612−-- GREATEST(CURRENT_TIMESTAMP, ($1 :: timestamp with time zone))
614− :: Expression outer grp commons schemas params from (nullty)
615− -- ^ needs at least 1 argument
616− -> [Expression outer grp commons schemas params from (nullty)]
618− -> Expression outer grp commons schemas params from (nullty)
619−greatest x xs = UnsafeExpression $ "GREATEST("
620− <> commaSeparated (renderSQL <$> (x:xs)) <> ")"
622−-- | >>> printSQL $ least currentTimestamp [null_]
623−-- LEAST(CURRENT_TIMESTAMP, NULL)
625− :: Expression outer grp commons schemas params from (nullty)
626− -- ^ needs at least 1 argument
627− -> [Expression outer grp commons schemas params from (nullty)]
629− -> Expression outer grp commons schemas params from (nullty)
630−least x xs = UnsafeExpression $ "LEAST("
631− <> commaSeparated (renderSQL <$> (x:xs)) <> ")"
633-- | >>> printSQL $ unsafeBinaryOp "OR" true false
315-- | >>> printSQL $ unsafeBinaryOp "OR" true false
634-- (TRUE OR FALSE)
316-- (TRUE OR FALSE)
635−unsafeBinaryOp
317+unsafeBinaryOp :: ByteString -> Operator ty0 ty1 ty2
638− -> Expression outer grp commons schemas params from (ty0)
639− -> Expression outer grp commons schemas params from (ty1)
640− -> Expression outer grp commons schemas params from (ty2)
641unsafeBinaryOp op x y = UnsafeExpression $ parenthesized $
318unsafeBinaryOp op x y = UnsafeExpression $ parenthesized $
642 renderSQL x <+> op <+> renderSQL y
319 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
644−-- | >>> printSQL $ unsafeUnaryOp "NOT" true
328+-- | >>> printSQL $ unsafeLeftOp "NOT" true
645-- (NOT TRUE)
329-- (NOT TRUE)
647− :: ByteString
330+unsafeLeftOp :: ByteString -> x --> y
648− -- ^ operator
331+unsafeLeftOp op x = UnsafeExpression $ parenthesized $ op <+> renderSQL x
649− -> Expression outer grp commons schemas params from (ty0)
332+
650− -> Expression outer grp commons schemas params from (ty1)
333+leftOp
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
651−unsafeUnaryOp op x = UnsafeExpression $ parenthesized $
343+unsafeRightOp op x = UnsafeExpression $ parenthesized $ renderSQL x <+> op
652− op <+> renderSQL x
344+
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
654-- | >>> printSQL $ unsafeFunction "f" true
352-- | >>> printSQL $ unsafeFunction "f" true
655-- f(TRUE)
353-- f(TRUE)
656−unsafeFunction
354+unsafeFunction :: ByteString -> x --> y
659− -> Expression outer grp commons schemas params from xty
660− -> Expression outer grp commons schemas params from yty
661unsafeFunction fun x = UnsafeExpression $
355unsafeFunction fun x = UnsafeExpression $
662 fun <> parenthesized (renderSQL x)
356 fun <> parenthesized (renderSQL x)
664−unsafeFunction2
358+function
665− :: ByteString
359+ :: (Has sch schemas schema, Has fun schema ('Function ('[x] :=> 'Returns y)))
666− -- ^ function
360+ => QualifiedAlias sch fun
667− -> Expression outer grp commons schemas params from ty1
361+ -> FunctionDB schemas x y
668− -> Expression outer grp commons schemas params from ty2
362+function = unsafeFunction . renderSQL
669− -> Expression outer grp commons schemas params from ty
670−unsafeFunction2 fun x1 x2 = UnsafeExpression $
671− fun <> parenthesized (commaSeparated [renderSQL x1, renderSQL x2])
673−-- | Helper for defining variadic functions.
364+-- | >>> printSQL $ unsafeFunctionN "f" (currentTime :* localTimestamp :* false *: literal 'a')
674−unsafeVariadicFunction
365+-- f(CURRENT_TIME, LOCALTIMESTAMP, FALSE, E'a')
676− => ByteString
366+unsafeFunctionN :: SListI xs => ByteString -> xs ---> y
678− -> NP (Expression outer grp commons schemas params from) elems
679− -> Expression outer grp commons schemas params from ret
680−unsafeVariadicFunction fun x = UnsafeExpression $
367+unsafeFunctionN fun xs = UnsafeExpression $
681− fun <> parenthesized (commaSeparated (hcollapse (hmap (K . renderSQL) x)))
368+ fun <> parenthesized (renderCommaSeparated renderSQL xs)
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
683instance ty `In` PGNum
378instance ty `In` PGNum
684− => Num (Expression outer grp commons schemas params from (nullity ty)) where
379+ => Num (Expression outer commons grp schemas params from (null ty)) where
685 (+) = unsafeBinaryOp "+"
380 (+) = unsafeBinaryOp "+"
686 (-) = unsafeBinaryOp "-"
381 (-) = unsafeBinaryOp "-"
687 (*) = unsafeBinaryOp "*"
382 (*) = unsafeBinaryOp "*"
@@ -693,7 +388,7 @@ instance ty `In` PGNum
695instance (ty `In` PGNum, ty `In` PGFloating) => Fractional
390instance (ty `In` PGNum, ty `In` PGFloating) => Fractional
696− (Expression outer grp commons schemas params from (nullity ty)) where
391+ (Expression outer commons grp schemas params from (null ty)) where
697 (/) = unsafeBinaryOp "/"
392 (/) = unsafeBinaryOp "/"
698 fromRational
393 fromRational
699 = UnsafeExpression
394 = UnsafeExpression
@@ -703,7 +398,7 @@ instance (ty `In` PGNum, ty `In` PGFloating) => Fractional
703 . fromRat @Double
398 . fromRat @Double
705instance (ty `In` PGNum, ty `In` PGFloating) => Floating
400instance (ty `In` PGNum, ty `In` PGFloating) => Floating
706− (Expression outer grp commons schemas params from (nullity ty)) where
401+ (Expression outer commons grp schemas params from (null ty)) where
707 pi = UnsafeExpression "pi()"
402 pi = UnsafeExpression "pi()"
708 exp = unsafeFunction "exp"
403 exp = unsafeFunction "exp"
709 log = unsafeFunction "ln"
404 log = unsafeFunction "ln"
@@ -724,1974 +419,54 @@ instance (ty `In` PGNum, ty `In` PGFloating) => Floating
724 acosh x = log (x + sqrt (x*x - 1))
419 acosh x = log (x + sqrt (x*x - 1))
725 atanh x = log ((1 + x) / (1 - x)) / 2
420 atanh x = log ((1 + x) / (1 - x)) / 2
727−-- | >>> :{
422+-- | Contained by operators
728−-- let
423+class PGSubset ty where
729−-- expression :: Expression outer grp commons schemas params from (nullity 'PGfloat4)
424+ (@>) :: Operator (null0 ty) (null1 ty) ('Null 'PGbool)
730−-- expression = atan2_ pi 2
425+ (@>) = unsafeBinaryOp "@>"
731−-- in printSQL expression
426+ (<@) :: Operator (null0 ty) (null1 ty) ('Null 'PGbool)
732−-- :}
427+ (<@) = unsafeBinaryOp "<@"
733−-- atan2(pi(), 2)
428+instance PGSubset 'PGjsonb
734−atan2_
429+instance PGSubset 'PGtsquery
735− :: float `In` PGFloating
430+instance PGSubset ('PGvararray ty)
736− => Expression outer grp commons schemas params from (nullity float)
431+instance PGSubset ('PGrange ty)
738− -> Expression outer grp commons schemas params from (nullity float)
433+class PGIntersect ty where
739− -- ^ denominator
434+ (@&&) :: Operator (null0 ty) (null1 ty) ('Null 'PGbool)
740− -> Expression outer grp commons schemas params from (nullity float)
435+ (@&&) = unsafeBinaryOp "&&"
741−atan2_ y x = UnsafeExpression $
436+instance PGIntersect ('PGvararray ty)
742− "atan2(" <> renderSQL y <> ", " <> renderSQL x <> ")"
437+instance PGIntersect ('PGrange ty)
744−-- When a `cast` is applied to an `Expression` of a known type, it
745−-- represents a run-time type conversion. The cast will succeed only if a
746−-- suitable type conversion operation has been defined.
748−-- | >>> printSQL $ true & cast int4
751− :: TypeExpression schemas ty1
752− -- ^ type to cast as
753− -> Expression outer grp commons schemas params from ty0
754− -- ^ value to convert
755− -> Expression outer grp commons schemas params from ty1
756−cast ty x = UnsafeExpression $ parenthesized $
757− renderSQL x <+> "::" <+> renderSQL ty
759−-- | integer division, truncates the result
763−-- expression :: Expression outer grp commons schemas params from (nullity 'PGint2)
764−-- expression = 5 `quot_` 2
765−-- in printSQL expression
769− :: int `In` PGIntegral
770− => Expression outer grp commons schemas params from (nullity int)
772− -> Expression outer grp commons schemas params from (nullity int)
774− -> Expression outer grp commons schemas params from (nullity int)
775−quot_ = unsafeBinaryOp "/"
777−-- | remainder upon integer division
781−-- expression :: Expression outer grp commons schemas params from (nullity 'PGint2)
782−-- expression = 5 `rem_` 2
783−-- in printSQL expression
787− :: int `In` PGIntegral
788− => Expression outer grp commons schemas params from (nullity int)
790− -> Expression outer grp commons schemas params from (nullity int)
792− -> Expression outer grp commons schemas params from (nullity int)
793−rem_ = unsafeBinaryOp "%"
797−-- expression :: Expression outer grp commons schemas params from (nullity 'PGfloat4)
798−-- expression = trunc pi
799−-- in printSQL expression
803− :: frac `In` PGFloating
804− => Expression outer grp commons schemas params from (nullity frac)
805− -- ^ fractional number
806− -> Expression outer grp commons schemas params from (nullity frac)
807−trunc = unsafeFunction "trunc"
811−-- expression :: Expression outer grp commons schemas params from (nullity 'PGfloat4)
812−-- expression = round_ pi
813−-- in printSQL expression
817− :: frac `In` PGFloating
818− => Expression outer grp commons schemas params from (nullity frac)
819− -- ^ fractional number
820− -> Expression outer grp commons schemas params from (nullity frac)
821−round_ = unsafeFunction "round"
825−-- expression :: Expression outer grp commons schemas params from (nullity 'PGfloat4)
826−-- expression = ceiling_ pi
827−-- in printSQL expression
831− :: frac `In` PGFloating
832− => Expression outer grp commons schemas params from (nullity frac)
833− -- ^ fractional number
834− -> Expression outer grp commons schemas params from (nullity frac)
835−ceiling_ = unsafeFunction "ceiling"
837−-- | A `Condition` is an `Expression`, which can evaluate
838−-- to `true`, `false` or `null_`. This is because SQL uses
839−-- a three valued logic.
840−type Condition outer grp commons schemas params from =
841− Expression outer grp commons schemas params from ('Null 'PGbool)
843−-- | >>> printSQL true
845−true :: Expression outer grp commons schemas params from (nullity 'PGbool)
846−true = UnsafeExpression "TRUE"
848−-- | >>> printSQL false
850−false :: Expression outer grp commons schemas params from (nullity 'PGbool)
851−false = UnsafeExpression "FALSE"
853−-- | >>> printSQL $ not_ true
856− :: Expression outer grp commons schemas params from (nullity 'PGbool)
857− -> Expression outer grp commons schemas params from (nullity 'PGbool)
858−not_ = unsafeUnaryOp "NOT"
860−-- | >>> printSQL $ true .&& false
863− :: Expression outer grp commons schemas params from (nullity 'PGbool)
864− -> Expression outer grp commons schemas params from (nullity 'PGbool)
865− -> Expression outer grp commons schemas params from (nullity 'PGbool)
867−(.&&) = unsafeBinaryOp "AND"
869−-- | >>> printSQL $ true .|| false
872− :: Expression outer grp commons schemas params from (nullity 'PGbool)
873− -> Expression outer grp commons schemas params from (nullity 'PGbool)
874− -> Expression outer grp commons schemas params from (nullity 'PGbool)
876−(.||) = unsafeBinaryOp "OR"
880−-- expression :: Expression outer grp commons schemas params from (nullity 'PGint2)
881−-- expression = caseWhenThenElse [(true, 1), (false, 2)] 3
882−-- in printSQL expression
884−-- CASE WHEN TRUE THEN 1 WHEN FALSE THEN 2 ELSE 3 END
886− :: [ ( Condition outer grp commons schemas params from
887− , Expression outer grp commons schemas params from ty
889− -- ^ whens and thens
890− -> Expression outer grp commons schemas params from ty
892− -> Expression outer grp commons schemas params from ty
893−caseWhenThenElse whenThens else_ = UnsafeExpression $ mconcat
897− [ " WHEN ", renderSQL when_
898− , " THEN ", renderSQL then_
900− | (when_,then_) <- whenThens
902− , " ELSE ", renderSQL else_
908−-- expression :: Expression outer grp commons schemas params from (nullity 'PGint2)
909−-- expression = ifThenElse true 1 0
910−-- in printSQL expression
912−-- CASE WHEN TRUE THEN 1 ELSE 0 END
914− :: Condition outer grp commons schemas params from
915− -> Expression outer grp commons schemas params from ty -- ^ then
916− -> Expression outer grp commons schemas params from ty -- ^ else
917− -> Expression outer grp commons schemas params from ty
918−ifThenElse if_ then_ else_ = caseWhenThenElse [(if_,then_)] else_
920−-- | Comparison operations like `.==`, `./=`, `.>`, `.>=`, `.<` and `.<=`
921−-- will produce @NULL@s if one of their arguments is @NULL@.
923−-- >>> printSQL $ true .== null_
926− :: Expression outer grp commons schemas params from (nullity0 ty) -- ^ lhs
927− -> Expression outer grp commons schemas params from (nullity1 ty) -- ^ rhs
928− -> Condition outer grp commons schemas params from
929−(.==) = unsafeBinaryOp "="
932−-- | >>> printSQL $ true ./= null_
935− :: Expression outer grp commons schemas params from (nullity0 ty) -- ^ lhs
936− -> Expression outer grp commons schemas params from (nullity1 ty) -- ^ rhs
937− -> Condition outer grp commons schemas params from
938−(./=) = unsafeBinaryOp "<>"
941−-- | >>> printSQL $ true .>= null_
944− :: Expression outer grp commons schemas params from (nullity0 ty) -- ^ lhs
945− -> Expression outer grp commons schemas params from (nullity1 ty) -- ^ rhs
946− -> Condition outer grp commons schemas params from
947−(.>=) = unsafeBinaryOp ">="
950−-- | >>> printSQL $ true .< null_
953− :: Expression outer grp commons schemas params from (nullity0 ty) -- ^ lhs
954− -> Expression outer grp commons schemas params from (nullity1 ty) -- ^ rhs
955− -> Condition outer grp commons schemas params from
956−(.<) = unsafeBinaryOp "<"
959−-- | >>> printSQL $ true .<= null_
962− :: Expression outer grp commons schemas params from (nullity0 ty) -- ^ lhs
963− -> Expression outer grp commons schemas params from (nullity1 ty) -- ^ rhs
964− -> Condition outer grp commons schemas params from
965−(.<=) = unsafeBinaryOp "<="
968−-- | >>> printSQL $ true .> null_
971− :: Expression outer grp commons schemas params from (nullity0 ty) -- ^ lhs
972− -> Expression outer grp commons schemas params from (nullity1 ty) -- ^ rhs
973− -> Condition outer grp commons schemas params from
974−(.>) = unsafeBinaryOp ">"
978−>>> printSQL $ true `between` (null_, false)
979−TRUE BETWEEN NULL AND FALSE
982− :: Expression outer grp commons schemas params from (nullity ty)
983− -> ( Expression outer grp commons schemas params from (nullity ty)
984− , Expression outer grp commons schemas params from (nullity ty) ) -- ^ bounds
985− -> Condition outer grp commons schemas params from
986−between a (x,y) = UnsafeExpression $ renderSQL a <+> "BETWEEN"
987− <+> renderSQL x <+> "AND" <+> renderSQL y
990−>>> printSQL $ true `notBetween` (null_, false)
991−TRUE NOT BETWEEN NULL AND FALSE
994− :: Expression outer grp commons schemas params from (nullity ty)
995− -> ( Expression outer grp commons schemas params from (nullity ty)
996− , Expression outer grp commons schemas params from (nullity ty) ) -- ^ bounds
997− -> Condition outer grp commons schemas params from
998−notBetween a (x,y) = UnsafeExpression $ renderSQL a <+> "NOT BETWEEN"
999− <+> renderSQL x <+> "AND" <+> renderSQL y
1001−{- | between, after sorting the comparison values
1002−>>> printSQL $ true `betweenSymmetric` (null_, false)
1003−TRUE BETWEEN SYMMETRIC NULL AND FALSE
1006− :: Expression outer grp commons schemas params from (nullity ty)
1007− -> ( Expression outer grp commons schemas params from (nullity ty)
1008− , Expression outer grp commons schemas params from (nullity ty) ) -- ^ bounds
1009− -> Condition outer grp commons schemas params from
1010−betweenSymmetric a (x,y) = UnsafeExpression $ renderSQL a
1011− <+> "BETWEEN SYMMETRIC" <+> renderSQL x <+> "AND" <+> renderSQL y
1013−{- | not between, after sorting the comparison values
1014−>>> printSQL $ true `notBetweenSymmetric` (null_, false)
1015−TRUE NOT BETWEEN SYMMETRIC NULL AND FALSE
1018− :: Expression outer grp commons schemas params from (nullity ty)
1019− -> ( Expression outer grp commons schemas params from (nullity ty)
1020− , Expression outer grp commons schemas params from (nullity ty) ) -- ^ bounds
1021− -> Condition outer grp commons schemas params from
1022−notBetweenSymmetric a (x,y) = UnsafeExpression $ renderSQL a
1023− <+> "NOT BETWEEN SYMMETRIC" <+> renderSQL x <+> "AND" <+> renderSQL y
1025−{- | not equal, treating null like an ordinary value
1026−>>> printSQL $ true `isDistinctFrom` null_
1027−(TRUE IS DISTINCT FROM NULL)
1030− :: Expression outer grp commons schemas params from (nullity ty)
1031− -> Expression outer grp commons schemas params from (nullity ty)
1032− -> Condition outer grp commons schemas params from
1033−isDistinctFrom = unsafeBinaryOp "IS DISTINCT FROM"
1035−{- | equal, treating null like an ordinary value
1036−>>> printSQL $ true `isNotDistinctFrom` null_
1037−(TRUE IS NOT DISTINCT FROM NULL)
1040− :: Expression outer grp commons schemas params from (nullity ty)
1041− -> Expression outer grp commons schemas params from (nullity ty)
1042− -> Condition outer grp commons schemas params from
1043−isNotDistinctFrom = unsafeBinaryOp "IS NOT DISTINCT FROM"
1046−>>> printSQL $ true & isTrue
1050− :: Expression outer grp commons schemas params from (nullity 'PGbool)
1051− -> Condition outer grp commons schemas params from
1052−isTrue b = UnsafeExpression $ renderSQL b <+> "IS TRUE"
1054−{- | is false or unknown
1055−>>> printSQL $ true & isNotTrue
1059− :: Expression outer grp commons schemas params from (nullity 'PGbool)
1060− -> Condition outer grp commons schemas params from
1061−isNotTrue b = UnsafeExpression $ renderSQL b <+> "IS NOT TRUE"
1064−>>> printSQL $ true & isFalse
1068− :: Expression outer grp commons schemas params from (nullity 'PGbool)
1069− -> Condition outer grp commons schemas params from
1070−isFalse b = UnsafeExpression $ renderSQL b <+> "IS FALSE"
1072−{- | is true or unknown
1073−>>> printSQL $ true & isNotFalse
1077− :: Expression outer grp commons schemas params from (nullity 'PGbool)
1078− -> Condition outer grp commons schemas params from
1079−isNotFalse b = UnsafeExpression $ renderSQL b <+> "IS NOT FALSE"
1082−>>> printSQL $ true & isUnknown
1086− :: Expression outer grp commons schemas params from (nullity 'PGbool)
1087− -> Condition outer grp commons schemas params from
1088−isUnknown b = UnsafeExpression $ renderSQL b <+> "IS UNKNOWN"
1090−{- | is true or false
1091−>>> printSQL $ true & isNotUnknown
1095− :: Expression outer grp commons schemas params from (nullity 'PGbool)
1096− -> Condition outer grp commons schemas params from
1097−isNotUnknown b = UnsafeExpression $ renderSQL b <+> "IS NOT UNKNOWN"
1099−-- | >>> printSQL currentDate
1102− :: Expression outer grp commons schemas params from (nullity 'PGdate)
1103−currentDate = UnsafeExpression "CURRENT_DATE"
1105−-- | >>> printSQL currentTime
1108− :: Expression outer grp commons schemas params from (nullity 'PGtimetz)
1109−currentTime = UnsafeExpression "CURRENT_TIME"
1111−-- | >>> printSQL currentTimestamp
1112−-- CURRENT_TIMESTAMP
1114− :: Expression outer grp commons schemas params from (nullity 'PGtimestamptz)
1115−currentTimestamp = UnsafeExpression "CURRENT_TIMESTAMP"
1117−-- | >>> printSQL localTime
1120− :: Expression outer grp commons schemas params from (nullity 'PGtime)
1121−localTime = UnsafeExpression "LOCALTIME"
1123−-- | >>> printSQL localTimestamp
1126− :: Expression outer grp commons schemas params from (nullity 'PGtimestamp)
1127−localTimestamp = UnsafeExpression "LOCALTIMESTAMP"
1129−{-----------------------------------------
1131−-----------------------------------------}
1133−escape :: Char -> String
1145instance IsString
439instance IsString
1146− (Expression outer grp commons schemas params from (nullity 'PGtext)) where
440+ (Expression outer commons grp schemas params from (null 'PGtext)) where
1147 fromString str = UnsafeExpression $
441 fromString str = UnsafeExpression $
1148 "E\'" <> fromString (escape =<< str) <> "\'"
442 "E\'" <> fromString (escape =<< str) <> "\'"
1149instance IsString
443instance IsString
1150− (Expression outer grp commons schemas params from (nullity 'PGtsvector)) where
444+ (Expression outer commons grp schemas params from (null 'PGtsvector)) where
1151− fromString str = cast tsvector . UnsafeExpression $
445+ fromString str = UnsafeExpression . parenthesized . (<> " :: tsvector") $
1152 "E\'" <> fromString (escape =<< str) <> "\'"
446 "E\'" <> fromString (escape =<< str) <> "\'"
1153instance IsString
447instance IsString
1154− (Expression outer grp commons schemas params from (nullity 'PGtsquery)) where
448+ (Expression outer commons grp schemas params from (null 'PGtsquery)) where
1155− fromString str = cast tsquery . UnsafeExpression $
449+ fromString str = UnsafeExpression . parenthesized . (<> " :: tsquery") $
1156 "E\'" <> fromString (escape =<< str) <> "\'"
450 "E\'" <> fromString (escape =<< str) <> "\'"
1158instance Semigroup
452instance Semigroup
453+ (Expression outer commons grp schemas params from (null ('PGvararray ty))) where
454+ (<>) = unsafeBinaryOp "||"
1159− (Expression outer grp commons schemas params from (nullity 'PGtext)) where
456+ (Expression outer commons grp schemas params from (null 'PGjsonb)) where
1160 (<>) = unsafeBinaryOp "||"
457 (<>) = unsafeBinaryOp "||"
1161instance Semigroup
458instance Semigroup
459+ (Expression outer commons grp schemas params from (null 'PGtext)) where
460+ (<>) = unsafeBinaryOp "||"
1162− (Expression outer grp commons schemas params from (nullity 'PGtsvector)) where
462+ (Expression outer commons grp schemas params from (null 'PGtsvector)) where
1163 (<>) = unsafeBinaryOp "||"
463 (<>) = unsafeBinaryOp "||"
1165instance Monoid
465instance Monoid
1166− (Expression outer grp commons schemas params from (nullity 'PGtext)) where
466+ (Expression outer commons grp schemas params from (null 'PGtext)) where
1167 mempty = fromString ""
467 mempty = fromString ""
1168 mappend = (<>)
468 mappend = (<>)
1169instance Monoid
469instance Monoid
1170− (Expression outer grp commons schemas params from (nullity 'PGtsvector)) where
470+ (Expression outer commons grp schemas params from (null 'PGtsvector)) where
1171 mempty = fromString ""
471 mempty = fromString ""
1172 mappend = (<>)
472 mappend = (<>)
1174−-- | >>> printSQL $ lower "ARRRGGG"
1175−-- lower(E'ARRRGGG')
1177− :: Expression outer grp commons schemas params from (nullity 'PGtext)
1178− -- ^ string to lower case
1179− -> Expression outer grp commons schemas params from (nullity 'PGtext)
1180−lower = unsafeFunction "lower"
1182−-- | >>> printSQL $ upper "eeee"
1185− :: Expression outer grp commons schemas params from (nullity 'PGtext)
1186− -- ^ string to upper case
1187− -> Expression outer grp commons schemas params from (nullity 'PGtext)
1188−upper = unsafeFunction "upper"
1190−-- | >>> printSQL $ charLength "four"
1191−-- char_length(E'four')
1193− :: Expression outer grp commons schemas params from (nullity 'PGtext)
1194− -- ^ string to measure
1195− -> Expression outer grp commons schemas params from (nullity 'PGint4)
1196−charLength = unsafeFunction "char_length"
1198−-- | The `like` expression returns true if the @string@ matches
1199−-- the supplied @pattern@. If @pattern@ does not contain percent signs
1200−-- or underscores, then the pattern only represents the string itself;
1201−-- in that case `like` acts like the equals operator. An underscore (_)
1202−-- in pattern stands for (matches) any single character; a percent sign (%)
1203−-- matches any sequence of zero or more characters.
1205−-- >>> printSQL $ "abc" `like` "a%"
1206−-- (E'abc' LIKE E'a%')
1208− :: Expression outer grp commons schemas params from (nullity 'PGtext)
1210− -> Expression outer grp commons schemas params from (nullity 'PGtext)
1212− -> Expression outer grp commons schemas params from (nullity 'PGbool)
1213−like = unsafeBinaryOp "LIKE"
1215−-- | The key word ILIKE can be used instead of LIKE to make the
1216−-- match case-insensitive according to the active locale.
1218−-- >>> printSQL $ "abc" `ilike` "a%"
1219−-- (E'abc' ILIKE E'a%')
1221− :: Expression outer grp commons schemas params from (nullity 'PGtext)
1223− -> Expression outer grp commons schemas params from (nullity 'PGtext)
1225− -> Expression outer grp commons schemas params from (nullity 'PGbool)
1226−ilike = unsafeBinaryOp "ILIKE"
1228−{-----------------------------------------
1229− -- json and jsonb support
1231−See https://www.postgresql.org/docs/10/static/functions-json.html -- most
1232−comments lifted directly from this page.
1234−Table 9.44: json and jsonb operators
1235−-----------------------------------------}
1237−-- | Get JSON value (object field or array element) at a key.
1239− :: (json `In` PGJsonType, key `In` PGJsonKey)
1240− => Expression outer grp commons schemas params from (nullity json)
1241− -> Expression outer grp commons schemas params from (nullity key)
1242− -> Expression outer grp commons schemas params from ('Null json)
1244−(.->) = unsafeBinaryOp "->"
1246−-- | Get JSON value (object field or array element) at a key, as text.
1248− :: (json `In` PGJsonType, key `In` PGJsonKey)
1249− => Expression outer grp commons schemas params from (nullity json)
1250− -> Expression outer grp commons schemas params from (nullity key)
1251− -> Expression outer grp commons schemas params from ('Null 'PGtext)
1253−(.->>) = unsafeBinaryOp "->>"
1255−-- | Get JSON value at a specified path.
1257− :: (json `In` PGJsonType, PGTextArray "(.#>)" path)
1258− => Expression outer grp commons schemas params from (nullity json)
1259− -> Expression outer grp commons schemas params from (nullity path)
1260− -> Expression outer grp commons schemas params from ('Null json)
1262−(.#>) = unsafeBinaryOp "#>"
1264−-- | Get JSON value at a specified path as text.
1266− :: (json `In` PGJsonType, PGTextArray "(.#>>)" path)
1267− => Expression outer grp commons schemas params from (nullity json)
1268− -> Expression outer grp commons schemas params from (nullity path)
1269− -> Expression outer grp commons schemas params from ('Null 'PGtext)
1271−(.#>>) = unsafeBinaryOp "#>>"
1273−-- Additional jsonb operators
1275−-- | Does the left JSON value contain the right JSON path/value entries at the
1278− :: Expression outer grp commons schemas params from (nullity 'PGjsonb)
1279− -> Expression outer grp commons schemas params from (nullity 'PGjsonb)
1280− -> Condition outer grp commons schemas params from
1282−(.@>) = unsafeBinaryOp "@>"
1284−-- | Are the left JSON path/value entries contained at the top level within the
1285−-- right JSON value?
1287− :: Expression outer grp commons schemas params from (nullity 'PGjsonb)
1288− -> Expression outer grp commons schemas params from (nullity 'PGjsonb)
1289− -> Condition outer grp commons schemas params from
1291−(.<@) = unsafeBinaryOp "<@"
1293−-- | Does the string exist as a top-level key within the JSON value?
1295− :: Expression outer grp commons schemas params from (nullity 'PGjsonb)
1296− -> Expression outer grp commons schemas params from (nullity 'PGtext)
1297− -> Condition outer grp commons schemas params from
1299−(.?) = unsafeBinaryOp "?"
1301−-- | Do any of these array strings exist as top-level keys?
1303− :: Expression outer grp commons schemas params from (nullity 'PGjsonb)
1304− -> Expression outer grp commons schemas params from (nullity ('PGvararray ('NotNull 'PGtext)))
1305− -> Condition outer grp commons schemas params from
1307−(.?|) = unsafeBinaryOp "?|"
1309−-- | Do all of these array strings exist as top-level keys?
1311− :: Expression outer grp commons schemas params from (nullity 'PGjsonb)
1312− -> Expression outer grp commons schemas params from (nullity ('PGvararray ('NotNull 'PGtext)))
1313− -> Condition outer grp commons schemas params from
1315−(.?&) = unsafeBinaryOp "?&"
1317−-- | Concatenate two jsonb values into a new jsonb value.
1319− (Expression outer grp commons schemas params from (nullity 'PGjsonb)) where
1320− (<>) = unsafeBinaryOp "||"
1322−-- | Delete a key or keys from a JSON object, or remove an array element.
1324−-- If the right operand is..
1326−-- @ text @: Delete key/value pair or string element from left operand. Key/value pairs
1327−-- are matched based on their key value.
1329−-- @ text[] @: Delete multiple key/value pairs or string elements
1330−-- from left operand. Key/value pairs are matched based on their key value.
1332−-- @ integer @: Delete the array element with specified index (Negative integers
1333−-- count from the end). Throws an error if top level container is not an array.
1335− :: (key `In` '[ 'PGtext, 'PGvararray ('NotNull 'PGtext), 'PGint4, 'PGint2 ]) -- hlint error without parens here
1336− => Expression outer grp commons schemas params from (nullity 'PGjsonb)
1337− -> Expression outer grp commons schemas params from (nullity key)
1338− -> Expression outer grp commons schemas params from (nullity 'PGjsonb)
1340−(.-.) = unsafeBinaryOp "-"
1342−-- | Delete the field or element with specified path (for JSON arrays, negative
1343−-- integers count from the end)
1345− :: PGTextArray "(#-.)" arrayty
1346− => Expression outer grp commons schemas params from (nullity 'PGjsonb)
1347− -> Expression outer grp commons schemas params from (nullity arrayty)
1348− -> Expression outer grp commons schemas params from (nullity 'PGjsonb)
1350−(#-.) = unsafeBinaryOp "#-"
1352−{-----------------------------------------
1353−Table 9.45: JSON creation functions
1354−-----------------------------------------}
1356−-- | Literal binary JSON
1359− => x -> Expression outer grp commons schemas params from (nullity 'PGjsonb)
1360−jsonbLit = cast jsonb . UnsafeExpression
1361− . singleQuotedUtf8 . toStrict . JSON.encode
1366− => x -> Expression outer grp commons schemas params from (nullity 'PGjson)
1367−jsonLit = cast json . UnsafeExpression
1368− . singleQuotedUtf8 . toStrict . JSON.encode
1370−-- | Returns the value as json. Arrays and composites are converted
1371−-- (recursively) to arrays and objects; otherwise, if there is a cast from the
1372−-- type to json, the cast function will be used to perform the conversion;
1373−-- otherwise, a scalar value is produced. For any scalar type other than a
1374−-- number, a Boolean, or a null value, the text representation will be used, in
1375−-- such a fashion that it is a valid json value.
1377− :: Expression outer grp commons schemas params from (nullity ty)
1378− -> Expression outer grp commons schemas params from (nullity 'PGjson)
1379−toJson = unsafeFunction "to_json"
1381−-- | Returns the value as jsonb. Arrays and composites are converted
1382−-- (recursively) to arrays and objects; otherwise, if there is a cast from the
1383−-- type to json, the cast function will be used to perform the conversion;
1384−-- otherwise, a scalar value is produced. For any scalar type other than a
1385−-- number, a Boolean, or a null value, the text representation will be used, in
1386−-- such a fashion that it is a valid jsonb value.
1388− :: Expression outer grp commons schemas params from (nullity ty)
1389− -> Expression outer grp commons schemas params from (nullity 'PGjsonb)
1390−toJsonb = unsafeFunction "to_jsonb"
1392−-- | Returns the array as a JSON array. A PostgreSQL multidimensional array
1393−-- becomes a JSON array of arrays.
1395− :: PGArray "arrayToJson" arr
1396− => Expression outer grp commons schemas params from (nullity arr)
1397− -> Expression outer grp commons schemas params from (nullity 'PGjson)
1398−arrayToJson = unsafeFunction "array_to_json"
1400−-- | Returns the row as a JSON object.
1402− :: Expression outer grp commons schemas params from (nullity ('PGcomposite ty))
1403− -> Expression outer grp commons schemas params from (nullity 'PGjson)
1404−rowToJson = unsafeFunction "row_to_json"
1406−-- | Builds a possibly-heterogeneously-typed JSON array out of a variadic
1410− => NP (Expression outer grp commons schemas params from) elems
1411− -> Expression outer grp commons schemas params from (nullity 'PGjson)
1412−jsonBuildArray = unsafeVariadicFunction "json_build_array"
1414−-- | Builds a possibly-heterogeneously-typed (binary) JSON array out of a
1415−-- variadic argument list.
1418− => NP (Expression outer grp commons schemas params from) elems
1419− -> Expression outer grp commons schemas params from (nullity 'PGjsonb)
1420−jsonbBuildArray = unsafeVariadicFunction "jsonb_build_array"
1423− :: SOP.SListI elems
1424− => NP (Aliased (Expression outer grp commons schemas params from)) elems
1427− (`appEndo` []) . hcfoldMap (Proxy :: SOP.Proxy SOP.Top)
1428− (\(col `As` name) -> Endo $ \xs ->
1429− renderAliasString name : renderSQL col : xs)
1431− renderAliasString :: KnownSymbol alias => Alias alias -> ByteString
1432− renderAliasString = singleQuotedText . fromString . symbolVal
1434−-- | Builds a possibly-heterogeneously-typed JSON object out of a variadic
1435−-- argument list. The elements of the argument list must alternate between text
1438− :: SOP.SListI elems
1439− => NP (Aliased (Expression outer grp commons schemas params from)) elems
1440− -> Expression outer grp commons schemas params from (nullity 'PGjson)
1442− = unsafeFunction "json_build_object"
1445− . unsafeRowFunction
1447−-- | Builds a possibly-heterogeneously-typed (binary) JSON object out of a
1448−-- variadic argument list. The elements of the argument list must alternate
1449−-- between text and values.
1451− :: SOP.SListI elems
1452− => NP (Aliased (Expression outer grp commons schemas params from)) elems
1453− -> Expression outer grp commons schemas params from (nullity 'PGjsonb)
1455− = unsafeFunction "jsonb_build_object"
1458− . unsafeRowFunction
1460−-- | Builds a JSON object out of a text array. The array must have either
1461−-- exactly one dimension with an even number of members, in which case they are
1462−-- taken as alternating key/value pairs, or two dimensions such that each inner
1463−-- array has exactly two elements, which are taken as a key/value pair.
1465− :: PGArrayOf "jsonObject" arr ('NotNull 'PGtext)
1466− => Expression outer grp commons schemas params from (nullity arr)
1467− -> Expression outer grp commons schemas params from (nullity 'PGjson)
1468−jsonObject = unsafeFunction "json_object"
1470−-- | Builds a binary JSON object out of a text array. The array must have either
1471−-- exactly one dimension with an even number of members, in which case they are
1472−-- taken as alternating key/value pairs, or two dimensions such that each inner
1473−-- array has exactly two elements, which are taken as a key/value pair.
1475− :: PGArrayOf "jsonbObject" arr ('NotNull 'PGtext)
1476− => Expression outer grp commons schemas params from (nullity arr)
1477− -> Expression outer grp commons schemas params from (nullity 'PGjsonb)
1478−jsonbObject = unsafeFunction "jsonb_object"
1480−-- | This is an alternate form of 'jsonObject' that takes two arrays; one for
1481−-- keys and one for values, that are zipped pairwise to create a JSON object.
1483− :: ( PGArrayOf "jsonZipObject" keysArray ('NotNull 'PGtext)
1484− , PGArrayOf "jsonZipObject" valuesArray ('NotNull 'PGtext))
1485− => Expression outer grp commons schemas params from (nullity keysArray)
1486− -> Expression outer grp commons schemas params from (nullity valuesArray)
1487− -> Expression outer grp commons schemas params from (nullity 'PGjson)
1488−jsonZipObject ks vs =
1489− unsafeVariadicFunction "json_object" (ks :* vs :* Nil)
1491−-- | This is an alternate form of 'jsonObject' that takes two arrays; one for
1492−-- keys and one for values, that are zipped pairwise to create a binary JSON
1495− :: ( PGArrayOf "jsonbZipObject" keysArray ('NotNull 'PGtext)
1496− , PGArrayOf "jsonbZipObject" valuesArray ('NotNull 'PGtext))
1497− => Expression outer grp commons schemas params from (nullity keysArray)
1498− -> Expression outer grp commons schemas params from (nullity valuesArray)
1499− -> Expression outer grp commons schemas params from (nullity 'PGjsonb)
1500−jsonbZipObject ks vs =
1501− unsafeVariadicFunction "jsonb_object" (ks :* vs :* Nil)
1503−{-----------------------------------------
1504−Table 9.46: JSON processing functions
1505−-----------------------------------------}
1507−-- | Returns the number of elements in the outermost JSON array.
1509− :: Expression outer grp commons schemas params from (nullity 'PGjson)
1510− -> Expression outer grp commons schemas params from (nullity 'PGint4)
1511−jsonArrayLength = unsafeFunction "json_array_length"
1513−-- | Returns the number of elements in the outermost binary JSON array.
1515− :: Expression outer grp commons schemas params from (nullity 'PGjsonb)
1516− -> Expression outer grp commons schemas params from (nullity 'PGint4)
1517−jsonbArrayLength = unsafeFunction "jsonb_array_length"
1519−-- | Returns JSON value pointed to by the given path (equivalent to #>
1523− => Expression outer grp commons schemas params from (nullity 'PGjson)
1524− -> NP (Expression outer grp commons schemas params from) elems
1525− -> Expression outer grp commons schemas params from (nullity 'PGjsonb)
1526−jsonExtractPath x xs =
1527− unsafeVariadicFunction "json_extract_path" (x :* xs)
1529−-- | Returns JSON value pointed to by the given path (equivalent to #>
1533− => Expression outer grp commons schemas params from (nullity 'PGjsonb)
1534− -> NP (Expression outer grp commons schemas params from) elems
1535− -> Expression outer grp commons schemas params from (nullity 'PGjsonb)
1536−jsonbExtractPath x xs =
1537− unsafeVariadicFunction "jsonb_extract_path" (x :* xs)
1539−-- | Returns JSON value pointed to by the given path (equivalent to #>
1540−-- operator), as text.
1541−jsonExtractPathAsText
1543− => Expression outer grp commons schemas params from (nullity 'PGjson)
1544− -> NP (Expression outer grp commons schemas params from) elems
1545− -> Expression outer grp commons schemas params from (nullity 'PGjson)
1546−jsonExtractPathAsText x xs =
1547− unsafeVariadicFunction "json_extract_path_text" (x :* xs)
1549−-- | Returns JSON value pointed to by the given path (equivalent to #>
1550−-- operator), as text.
1551−jsonbExtractPathAsText
1553− => Expression outer grp commons schemas params from (nullity 'PGjsonb)
1554− -> NP (Expression outer grp commons schemas params from) elems
1555− -> Expression outer grp commons schemas params from (nullity 'PGjsonb)
1556−jsonbExtractPathAsText x xs =
1557− unsafeVariadicFunction "jsonb_extract_path_text" (x :* xs)
1559−-- | Returns the type of the outermost JSON value as a text string. Possible
1560−-- types are object, array, string, number, boolean, and null.
1562− :: Expression outer grp commons schemas params from (nullity 'PGjson)
1563− -> Expression outer grp commons schemas params from (nullity 'PGtext)
1564−jsonTypeof = unsafeFunction "json_typeof"
1566−-- | Returns the type of the outermost binary JSON value as a text string.
1567−-- Possible types are object, array, string, number, boolean, and null.
1569− :: Expression outer grp commons schemas params from (nullity 'PGjsonb)
1570− -> Expression outer grp commons schemas params from (nullity 'PGtext)
1571−jsonbTypeof = unsafeFunction "jsonb_typeof"
1573−-- | Returns its argument with all object fields that have null values omitted.
1574−-- Other null values are untouched.
1576− :: Expression outer grp commons schemas params from (nullity 'PGjson)
1577− -> Expression outer grp commons schemas params from (nullity 'PGjson)
1578−jsonStripNulls = unsafeFunction "json_strip_nulls"
1580−-- | Returns its argument with all object fields that have null values omitted.
1581−-- Other null values are untouched.
1583− :: Expression outer grp commons schemas params from (nullity 'PGjsonb)
1584− -> Expression outer grp commons schemas params from (nullity 'PGjsonb)
1585−jsonbStripNulls = unsafeFunction "jsonb_strip_nulls"
1587−-- | @ jsonbSet target path new_value create_missing @
1589−-- Returns target with the section designated by path replaced by new_value,
1590−-- or with new_value added if create_missing is true ( default is true) and the
1591−-- item designated by path does not exist. As with the path orientated
1592−-- operators, negative integers that appear in path count from the end of JSON
1595− :: PGTextArray "jsonbSet" arr
1596− => Expression outer grp commons schemas params from (nullity 'PGjsonb)
1597− -> Expression outer grp commons schemas params from (nullity arr)
1598− -> Expression outer grp commons schemas params from (nullity 'PGjsonb)
1599− -> Maybe (Expression outer grp commons schemas params from (nullity 'PGbool))
1600− -> Expression outer grp commons schemas params from (nullity 'PGjsonb)
1601−jsonbSet tgt path val createMissing = case createMissing of
1602− Just m -> unsafeVariadicFunction "jsonb_set" (tgt :* path :* val :* m :* Nil)
1603− Nothing -> unsafeVariadicFunction "jsonb_set" (tgt :* path :* val :* Nil)
1605−-- | @ jsonbInsert target path new_value insert_after @
1607−-- Returns target with new_value inserted. If target section designated by
1608−-- path is in a JSONB array, new_value will be inserted before target or after
1609−-- if insert_after is true (default is false). If target section designated by
1610−-- path is in JSONB object, new_value will be inserted only if target does not
1611−-- exist. As with the path orientated operators, negative integers that appear
1612−-- in path count from the end of JSON arrays.
1614− :: PGTextArray "jsonbInsert" arr
1615− => Expression outer grp commons schemas params from (nullity 'PGjsonb)
1616− -> Expression outer grp commons schemas params from (nullity arr)
1617− -> Expression outer grp commons schemas params from (nullity 'PGjsonb)
1618− -> Maybe (Expression outer grp commons schemas params from (nullity 'PGbool))
1619− -> Expression outer grp commons schemas params from (nullity 'PGjsonb)
1620−jsonbInsert tgt path val insertAfter = case insertAfter of
1621− Just i -> unsafeVariadicFunction "jsonb_insert" (tgt :* path :* val :* i :* Nil)
1622− Nothing -> unsafeVariadicFunction "jsonb_insert" (tgt :* path :* val :* Nil)
1624−-- | Returns its argument as indented JSON text.
1626− :: Expression outer grp commons schemas params from (nullity 'PGjsonb)
1627− -> Expression outer grp commons schemas params from (nullity 'PGtext)
1628−jsonbPretty = unsafeFunction "jsonb_pretty"
1630−(@@) :: ComparisonOperator (nullity 'PGtsvector) (nullity 'PGtsquery)
1631−(@@) = unsafeBinaryOp "@@"
1633−(.&) :: Operator (nullity 'PGtsquery) (nullity 'PGtsquery) (nullity 'PGtsquery)
1634−(.&) = unsafeBinaryOp "&&"
1636−(.|) :: Operator (nullity 'PGtsquery) (nullity 'PGtsquery) (nullity 'PGtsquery)
1637−(.|) = unsafeBinaryOp "||"
1640− :: Expression outer grp commons schemas params from (nullity 'PGtsquery)
1641− -> Expression outer grp commons schemas params from (nullity 'PGtsquery)
1642−(.!) = unsafeUnaryOp "!!"
1644−(<->) :: Operator (nullity 'PGtsquery) (nullity 'PGtsquery) (nullity 'PGtsquery)
1645−(<->) = unsafeBinaryOp "<->"
1648− :: Expression outer grp commons schemas params from (nullity ('PGvararray ('NotNull 'PGtext)))
1649− -> Expression outer grp commons schemas params from (nullity 'PGtsvector)
1650−arrayToTSvector = unsafeFunction "array_to_tsvector"
1653− :: Expression outer grp commons schemas params from (nullity 'PGtsvector)
1654− -> Expression outer grp commons schemas params from (nullity 'PGint4)
1655−tsvectorLength = unsafeFunction "length"
1658− :: Expression outer grp commons schemas params from (nullity 'PGtsquery)
1659− -> Expression outer grp commons schemas params from (nullity 'PGint4)
1660−numnode = unsafeFunction "numnode"
1663− :: Expression outer grp commons schemas params from (nullity 'PGtext)
1664− -> Expression outer grp commons schemas params from (nullity 'PGtext)
1665− -> Expression outer grp commons schemas params from (nullity 'PGtsquery)
1666−plainToTSquery = unsafeFunction2 "plainto_tsquery"
1669− :: Expression outer grp commons schemas params from (nullity 'PGtext)
1670− -> Expression outer grp commons schemas params from (nullity 'PGtext)
1671− -> Expression outer grp commons schemas params from (nullity 'PGtsquery)
1672−phraseToTSquery = unsafeFunction2 "phraseto_tsquery"
1675− :: Expression outer grp commons schemas params from (nullity 'PGtext)
1676− -> Expression outer grp commons schemas params from (nullity 'PGtext)
1677− -> Expression outer grp commons schemas params from (nullity 'PGtsquery)
1678−websearchToTSquery = unsafeFunction2 "websearch_to_tsquery"
1681− :: Expression outer grp commons schemas params from (nullity 'PGtsquery)
1682− -> Expression outer grp commons schemas params from (nullity 'PGtext)
1683−queryTree = unsafeFunction "query_tree"
1686− :: Expression outer grp commons schemas params from (nullity 'PGtext)
1687− -> Expression outer grp commons schemas params from (nullity 'PGtext)
1688− -> Expression outer grp commons schemas params from (nullity 'PGtsquery)
1689−toTSquery = unsafeFunction2 "to_tsquery"
1692− :: ty `In` '[ 'PGtext, 'PGjson, 'PGjsonb]
1693− => Expression outer grp commons schemas params from (nullity 'PGtext)
1694− -> Expression outer grp commons schemas params from (nullity ty)
1695− -> Expression outer grp commons schemas params from (nullity 'PGtsquery)
1696−toTSvector = unsafeFunction2 "to_tsvector"
1698−{-----------------------------------------
1700−-----------------------------------------}
1703−`Aggregate` functions compute a single result from a set of input values.
1704−`Aggregate` functions can be used as `GroupedBy` `Expression`s as well
1705−as `WindowFunction`s.
1707−class Aggregate expr1 expr2 aggr
1708− | aggr -> expr1, aggr -> expr2 where
1710− -- | A special aggregation that does not require an input
1714− -- expression :: Expression '[] ('Grouped bys) commons schemas params from ('NotNull 'PGint8)
1715− -- expression = countStar
1716− -- in printSQL expression
1719− countStar :: aggr ('NotNull 'PGint8)
1723− -- expression :: Expression '[] ('Grouped bys) commons schemas params '[tab ::: '["col" ::: nullity ty]] ('NotNull 'PGint8)
1724− -- expression = count (All #col)
1725− -- in printSQL expression
1727− -- count(ALL "col")
1731− -> aggr ('NotNull 'PGint8)
1735− -- expression :: Expression '[] ('Grouped bys) commons schemas params '[tab ::: '["col" ::: 'Null 'PGnumeric]] ('NotNull 'PGnumeric)
1736− -- expression = sum_ (Distinct #col)
1737− -- in printSQL expression
1739− -- sum(DISTINCT "col")
1742− => expr1 (nullity ty)
1743− -> aggr ('NotNull ty)
1745− -- | input values, including nulls, concatenated into an array
1748− -> aggr ('Null ('PGvararray ty))
1750− -- | aggregates values as a JSON array
1753− -> aggr ('Null 'PGjson)
1755− -- | aggregates values as a JSON array
1758− -> aggr ('Null 'PGjsonb)
1761− the bitwise AND of all non-null input values, or null if none
1764− expression :: Expression '[] ('Grouped bys) commons schemas params '[tab ::: '["col" ::: nullity 'PGint4]] ('Null 'PGint4)
1765− expression = bitAnd (Distinct #col)
1766− in printSQL expression
1768− bit_and(DISTINCT "col")
1771− :: int `In` PGIntegral
1772− => expr1 (nullity int)
1773− -- ^ what to aggregate
1774− -> aggr ('Null int)
1777− the bitwise OR of all non-null input values, or null if none
1781− expression :: Expression '[] ('Grouped bys) commons schemas params '[tab ::: '["col" ::: nullity 'PGint4]] ('Null 'PGint4)
1782− expression = bitOr (All #col)
1783− in printSQL expression
1788− :: int `In` PGIntegral
1789− => expr1 (nullity int)
1790− -- ^ what to aggregate
1791− -> aggr ('Null int)
1794− true if all input values are true, otherwise false
1798− winFun :: WindowFunction '[] 'Ungrouped commons schemas params '[tab ::: '["col" ::: nullity 'PGbool]] ('Null 'PGbool)
1799− winFun = boolAnd #col
1805− :: expr1 (nullity 'PGbool)
1806− -- ^ what to aggregate
1807− -> aggr ('Null 'PGbool)
1810− true if at least one input value is true, otherwise false
1814− expression :: Expression '[] ('Grouped bys) commons schemas params '[tab ::: '["col" ::: nullity 'PGbool]] ('Null 'PGbool)
1815− expression = boolOr (All #col)
1816− in printSQL expression
1821− :: expr1(nullity 'PGbool)
1822− -- ^ what to aggregate
1823− -> aggr ('Null 'PGbool)
1826− equivalent to `boolAnd`
1830− expression :: Expression '[] ('Grouped bys) commons schemas params '[tab ::: '["col" ::: nullity 'PGbool]] ('Null 'PGbool)
1831− expression = every (Distinct #col)
1832− in printSQL expression
1834− every(DISTINCT "col")
1837− :: expr1 (nullity 'PGbool)
1838− -- ^ what to aggregate
1839− -> aggr ('Null 'PGbool)
1841− {- |maximum value of expression across all input values-}
1843− :: expr1 (nullity ty)
1844− -- ^ what to maximize
1847− -- | minimum value of expression across all input values
1849− :: expr1 (nullity ty)
1850− -- ^ what to minimize
1853− -- | the average (arithmetic mean) of all input values
1855− :: expr1 (nullity ty)
1856− -- ^ what to average
1857− -> aggr ('Null (PGAvg ty))
1859− {- | correlation coefficient
1862− expression :: Expression '[] ('Grouped g) c s p '[t ::: '["x" ::: 'NotNull 'PGfloat8, "y" ::: 'NotNull 'PGfloat8]] ('Null 'PGfloat8)
1863− expression = corr (All (#y :*: #x))
1864− in printSQL expression
1869− :: expr2 (nullity 'PGfloat8)
1870− -> aggr ('Null 'PGfloat8)
1872− {- | population covariance
1875− expression :: Expression '[] ('Grouped g) c s p '[t ::: '["x" ::: 'NotNull 'PGfloat8, "y" ::: 'NotNull 'PGfloat8]] ('Null 'PGfloat8)
1876− expression = covarPop (All (#y :*: #x))
1877− in printSQL expression
1879− covar_pop(ALL "y", "x")
1882− :: expr2 (nullity 'PGfloat8)
1883− -> aggr ('Null 'PGfloat8)
1885− {- | sample covariance
1888− winFun :: WindowFunction '[] 'Ungrouped c s p '[t ::: '["x" ::: 'NotNull 'PGfloat8, "y" ::: 'NotNull 'PGfloat8]] ('Null 'PGfloat8)
1889− winFun = covarSamp (#y :*: #x)
1892− covar_samp("y", "x")
1895− :: expr2 (nullity 'PGfloat8)
1896− -> aggr ('Null 'PGfloat8)
1898− {- | average of the independent variable (sum(X)/N)
1901− expression :: Expression '[] ('Grouped g) c s p '[t ::: '["x" ::: 'NotNull 'PGfloat8, "y" ::: 'NotNull 'PGfloat8]] ('Null 'PGfloat8)
1902− expression = regrAvgX (All (#y :*: #x))
1903− in printSQL expression
1905− regr_avgx(ALL "y", "x")
1908− :: expr2 (nullity 'PGfloat8)
1909− -> aggr ('Null 'PGfloat8)
1911− {- | average of the dependent variable (sum(Y)/N)
1914− winFun :: WindowFunction '[] 'Ungrouped c s p '[t ::: '["x" ::: 'NotNull 'PGfloat8, "y" ::: 'NotNull 'PGfloat8]] ('Null 'PGfloat8)
1915− winFun = regrAvgY (#y :*: #x)
1918− regr_avgy("y", "x")
1921− :: expr2 (nullity 'PGfloat8)
1922− -> aggr ('Null 'PGfloat8)
1924− {- | number of input rows in which both expressions are nonnull
1927− winFun :: WindowFunction '[] 'Ungrouped c s p '[t ::: '["x" ::: 'NotNull 'PGfloat8, "y" ::: 'NotNull 'PGfloat8]] ('Null 'PGint8)
1928− winFun = regrCount (#y :*: #x)
1931− regr_count("y", "x")
1934− :: expr2 (nullity 'PGfloat8)
1935− -> aggr ('Null 'PGint8)
1937− {- | y-intercept of the least-squares-fit linear equation determined by the (X, Y) pairs
1940− expression :: Expression '[] ('Grouped g) c s p '[t ::: '["x" ::: 'NotNull 'PGfloat8, "y" ::: 'NotNull 'PGfloat8]] ('Null 'PGfloat8)
1941− expression = regrIntercept (All (#y :*: #x))
1942− in printSQL expression
1944− regr_intercept(ALL "y", "x")
1947− :: expr2 (nullity 'PGfloat8)
1948− -> aggr ('Null 'PGfloat8)
1950− -- | @regr_r2(Y, X)@, square of the correlation coefficient
1952− :: expr2 (nullity 'PGfloat8)
1953− -> aggr ('Null 'PGfloat8)
1955− -- | @regr_slope(Y, X)@, slope of the least-squares-fit linear equation
1956− -- determined by the (X, Y) pairs
1958− :: expr2 (nullity 'PGfloat8)
1959− -> aggr ('Null 'PGfloat8)
1961− -- | @regr_sxx(Y, X)@, sum(X^2) - sum(X)^2/N
1962− -- (“sum of squares” of the independent variable)
1964− :: expr2 (nullity 'PGfloat8)
1965− -> aggr ('Null 'PGfloat8)
1967− -- | @regr_sxy(Y, X)@, sum(X*Y) - sum(X) * sum(Y)/N
1968− -- (“sum of products” of independent times dependent variable)
1970− :: expr2 (nullity 'PGfloat8)
1971− -> aggr ('Null 'PGfloat8)
1973− -- | @regr_syy(Y, X)@, sum(Y^2) - sum(Y)^2/N
1974− -- (“sum of squares” of the dependent variable)
1976− :: expr2 (nullity 'PGfloat8)
1977− -> aggr ('Null 'PGfloat8)
1979− -- | historical alias for `stddevSamp`
1981− :: expr1 (nullity ty)
1982− -> aggr ('Null (PGAvg ty))
1984− -- | population standard deviation of the input values
1986− :: expr1 (nullity ty)
1987− -> aggr ('Null (PGAvg ty))
1989− -- | sample standard deviation of the input values
1991− :: expr1 (nullity ty)
1992− -> aggr ('Null (PGAvg ty))
1994− -- | historical alias for `varSamp`
1996− :: expr1 (nullity ty)
1997− -> aggr ('Null (PGAvg ty))
1999− -- | population variance of the input values
2000− -- (square of the population standard deviation)
2002− :: expr1 (nullity ty)
2003− -> aggr ('Null (PGAvg ty))
2005− -- | sample variance of the input values
2006− -- (square of the sample standard deviation)
2008− :: expr1 (nullity ty)
2009− -> aggr ('Null (PGAvg ty))
2012−`Distinction`s are used for the input of `Aggregate` `Expression`s.
2013−`All` invokes the aggregate once for each input row.
2014−`Distinct` invokes the aggregate once for each distinct value of the expression
2015−(or distinct set of values, for multiple expressions) found in the input
2017−data Distinction expr ty
2019− | Distinct (expr ty)
2020− deriving (GHC.Generic,Show,Eq,Ord)
2021−instance NFData (Distinction (Expression outer grp commons schemas params from) ty)
2022−instance RenderSQL (Distinction (Expression outer grp commons schemas params from) ty) where
2024− All x -> "ALL" <+> renderSQL x
2025− Distinct x -> "DISTINCT" <+> renderSQL x
2028− ( Expression outer grp commons schemas params from
2030− Expression outer grp commons schemas params from) xty ) where
2033− "ALL" <+> renderSQL x <> ", " <> renderSQL x'
2034− Distinct (x :*: x') ->
2035− "DISTINCT" <+> renderSQL x <> ", " <> renderSQL x'
2038− (Distinction (Expression outer 'Ungrouped commons schemas params from))
2039− (Distinction (Expression outer 'Ungrouped commons schemas params from :*: Expression outer 'Ungrouped commons schemas params from))
2040− (Expression outer ('Grouped bys) commons schemas params from) where
2041− countStar = UnsafeExpression "count(*)"
2042− count = unsafeAggregate1 "count"
2043− sum_ = unsafeAggregate1 "sum"
2044− arrayAgg = unsafeAggregate1 "array_agg"
2045− jsonAgg = unsafeAggregate1 "json_agg"
2046− jsonbAgg = unsafeAggregate1 "jsonb_agg"
2047− bitAnd = unsafeAggregate1 "bit_and"
2048− bitOr = unsafeAggregate1 "bit_or"
2049− boolAnd = unsafeAggregate1 "bool_and"
2050− boolOr = unsafeAggregate1 "bool_or"
2051− every = unsafeAggregate1 "every"
2052− max_ = unsafeAggregate1 "max"
2053− min_ = unsafeAggregate1 "min"
2054− avg = unsafeAggregate1 "avg"
2055− corr = unsafeAggregate2 "corr"
2056− covarPop = unsafeAggregate2 "covar_pop"
2057− covarSamp = unsafeAggregate2 "covar_samp"
2058− regrAvgX = unsafeAggregate2 "regr_avgx"
2059− regrAvgY = unsafeAggregate2 "regr_avgy"
2060− regrCount = unsafeAggregate2 "regr_count"
2061− regrIntercept = unsafeAggregate2 "regr_intercept"
2062− regrR2 = unsafeAggregate2 "regr_r2"
2063− regrSlope = unsafeAggregate2 "regr_slope"
2064− regrSxx = unsafeAggregate2 "regr_sxx"
2065− regrSxy = unsafeAggregate2 "regr_sxy"
2066− regrSyy = unsafeAggregate2 "regr_syy"
2067− stddev = unsafeAggregate1 "stddev"
2068− stddevPop = unsafeAggregate1 "stddev_pop"
2069− stddevSamp = unsafeAggregate1 "stddev_samp"
2070− variance = unsafeAggregate1 "variance"
2071− varPop = unsafeAggregate1 "var_pop"
2072− varSamp = unsafeAggregate1 "var_samp"
2074− (Expression outer grp commons schemas params from)
2075− (Expression outer grp commons schemas params from :*: Expression outer grp commons schemas params from)
2076− (WindowFunction outer grp commons schemas params from) where
2077− countStar = UnsafeWindowFunction "count(*)"
2078− count = unsafeWindowFunction1 "count"
2079− sum_ = unsafeWindowFunction1 "sum"
2080− arrayAgg = unsafeWindowFunction1 "array_agg"
2081− jsonAgg = unsafeWindowFunction1 "json_agg"
2082− jsonbAgg = unsafeWindowFunction1 "jsonb_agg"
2083− bitAnd = unsafeWindowFunction1 "bit_and"
2084− bitOr = unsafeWindowFunction1 "bit_or"
2085− boolAnd = unsafeWindowFunction1 "bool_and"
2086− boolOr = unsafeWindowFunction1 "bool_or"
2087− every = unsafeWindowFunction1 "every"
2088− max_ = unsafeWindowFunction1 "max"
2089− min_ = unsafeWindowFunction1 "min"
2090− avg = unsafeWindowFunction1 "avg"
2091− corr = unsafeWindowFunction2 "corr"
2092− covarPop = unsafeWindowFunction2 "covar_pop"
2093− covarSamp = unsafeWindowFunction2 "covar_samp"
2094− regrAvgX = unsafeWindowFunction2 "regr_avgx"
2095− regrAvgY = unsafeWindowFunction2 "regr_avgy"
2096− regrCount = unsafeWindowFunction2 "regr_count"
2097− regrIntercept = unsafeWindowFunction2 "regr_intercept"
2098− regrR2 = unsafeWindowFunction2 "regr_r2"
2099− regrSlope = unsafeWindowFunction2 "regr_slope"
2100− regrSxx = unsafeWindowFunction2 "regr_sxx"
2101− regrSxy = unsafeWindowFunction2 "regr_sxy"
2102− regrSyy = unsafeWindowFunction2 "regr_syy"
2103− stddev = unsafeWindowFunction1 "stddev"
2104− stddevPop = unsafeWindowFunction1 "stddev_pop"
2105− stddevSamp = unsafeWindowFunction1 "stddev_samp"
2106− variance = unsafeWindowFunction1 "variance"
2107− varPop = unsafeWindowFunction1 "var_pop"
2108− varSamp = unsafeWindowFunction1 "var_samp"
2110−-- | escape hatch to define aggregate functions
2112− :: ByteString -- ^ aggregate function
2113− -> Distinction (Expression outer 'Ungrouped commons schemas params from) xty
2114− -> Expression outer ('Grouped bys) commons schemas params from yty
2115−unsafeAggregate1 fun x = UnsafeExpression $ mconcat
2116− [fun, "(", renderSQL x, ")"]
2118−-- | escape hatch to define aggregate binary functions
2120− :: ByteString -- ^ aggregate function
2121− -> Distinction (Expression outer 'Ungrouped commons schemas params from :*: Expression outer 'Ungrouped commons schemas params from) xty
2122− -> Expression outer ('Grouped bys) commons schemas params from yty
2123−unsafeAggregate2 fun xx = UnsafeExpression $ mconcat
2124− [fun, "(", renderSQL xx, ")"]
2126−-- | A type family that calculates `PGAvg` type of a `PGType`.
2127−type family PGAvg ty where
2128− PGAvg 'PGint2 = 'PGnumeric
2129− PGAvg 'PGint4 = 'PGnumeric
2130− PGAvg 'PGint8 = 'PGnumeric
2131− PGAvg 'PGnumeric = 'PGnumeric
2132− PGAvg 'PGfloat4 = 'PGfloat8
2133− PGAvg 'PGfloat8 = 'PGfloat8
2134− PGAvg 'PGinterval = 'PGinterval
2135− PGAvg pg = TypeError
2136− ('Text "Squeal type error: No average for " ':<>: 'ShowType pg)
2138−{-----------------------------------------
2140−-----------------------------------------}
2142−-- | `TypeExpression`s are used in `cast`s and
2143−-- `Squeal.PostgreSQL.Definition.createTable` commands.
2144−newtype TypeExpression (schemas :: SchemasType) (ty :: NullityType)
2145− = UnsafeTypeExpression { renderTypeExpression :: ByteString }
2146− deriving (GHC.Generic,Show,Eq,Ord,NFData)
2147−instance RenderSQL (TypeExpression schemas ty) where
2148− renderSQL = renderTypeExpression
2150−-- | The enum or composite type in a `Typedef` can be expressed by its alias.
2152− :: (Has sch schemas schema, Has td schema ('Typedef ty))
2153− => QualifiedAlias sch td
2154− -> TypeExpression schemas (nullity ty)
2155−typedef = UnsafeTypeExpression . renderSQL
2157−-- | The composite type corresponding to a `Table` definition can be expressed
2160− :: (Has sch schemas schema, Has tab schema ('Table table))
2161− => QualifiedAlias sch tab
2162− -> TypeExpression schemas (nullity ('PGcomposite (TableToRow table)))
2163−typetable = UnsafeTypeExpression . renderSQL
2165−-- | The composite type corresponding to a `View` definition can be expressed
2168− :: (Has sch schemas schema, Has vw schema ('View view))
2169− => QualifiedAlias sch vw
2170− -> TypeExpression schemas (nullity ('PGcomposite view))
2171−typeview = UnsafeTypeExpression . renderSQL
2173−-- | logical Boolean (true/false)
2174−bool :: TypeExpression schemas (nullity 'PGbool)
2175−bool = UnsafeTypeExpression "bool"
2176−-- | signed two-byte integer
2177−int2, smallint :: TypeExpression schemas (nullity 'PGint2)
2178−int2 = UnsafeTypeExpression "int2"
2179−smallint = UnsafeTypeExpression "smallint"
2180−-- | signed four-byte integer
2181−int4, int, integer :: TypeExpression schemas (nullity 'PGint4)
2182−int4 = UnsafeTypeExpression "int4"
2183−int = UnsafeTypeExpression "int"
2184−integer = UnsafeTypeExpression "integer"
2185−-- | signed eight-byte integer
2186−int8, bigint :: TypeExpression schemas (nullity 'PGint8)
2187−int8 = UnsafeTypeExpression "int8"
2188−bigint = UnsafeTypeExpression "bigint"
2189−-- | arbitrary precision numeric type
2190−numeric :: TypeExpression schemas (nullity 'PGnumeric)
2191−numeric = UnsafeTypeExpression "numeric"
2192−-- | single precision floating-point number (4 bytes)
2193−float4, real :: TypeExpression schemas (nullity 'PGfloat4)
2194−float4 = UnsafeTypeExpression "float4"
2195−real = UnsafeTypeExpression "real"
2196−-- | double precision floating-point number (8 bytes)
2197−float8, doublePrecision :: TypeExpression schemas (nullity 'PGfloat8)
2198−float8 = UnsafeTypeExpression "float8"
2199−doublePrecision = UnsafeTypeExpression "double precision"
2200−-- | currency amount
2201−money :: TypeExpression schema (nullity 'PGmoney)
2202−money = UnsafeTypeExpression "money"
2203−-- | variable-length character string
2204−text :: TypeExpression schemas (nullity 'PGtext)
2205−text = UnsafeTypeExpression "text"
2206−-- | fixed-length character string
2208− :: forall n schemas nullity. (KnownNat n, 1 <= n)
2209− => TypeExpression schemas (nullity ('PGchar n))
2210−char = UnsafeTypeExpression $ "char(" <> renderNat @n <> ")"
2211−character = UnsafeTypeExpression $ "character(" <> renderNat @n <> ")"
2212−-- | variable-length character string
2213−varchar, characterVarying
2214− :: forall n schemas nullity. (KnownNat n, 1 <= n)
2215− => TypeExpression schemas (nullity ('PGvarchar n))
2216−varchar = UnsafeTypeExpression $ "varchar(" <> renderNat @n <> ")"
2217−characterVarying = UnsafeTypeExpression $
2218− "character varying(" <> renderNat @n <> ")"
2219−-- | binary data ("byte array")
2220−bytea :: TypeExpression schemas (nullity 'PGbytea)
2221−bytea = UnsafeTypeExpression "bytea"
2222−-- | date and time (no time zone)
2223−timestamp :: TypeExpression schemas (nullity 'PGtimestamp)
2224−timestamp = UnsafeTypeExpression "timestamp"
2225−-- | date and time, including time zone
2226−timestampWithTimeZone :: TypeExpression schemas (nullity 'PGtimestamptz)
2227−timestampWithTimeZone = UnsafeTypeExpression "timestamp with time zone"
2228−-- | calendar date (year, month, day)
2229−date :: TypeExpression schemas (nullity 'PGdate)
2230−date = UnsafeTypeExpression "date"
2231−-- | time of day (no time zone)
2232−time :: TypeExpression schemas (nullity 'PGtime)
2233−time = UnsafeTypeExpression "time"
2234−-- | time of day, including time zone
2235−timeWithTimeZone :: TypeExpression schemas (nullity 'PGtimetz)
2236−timeWithTimeZone = UnsafeTypeExpression "time with time zone"
2238−interval :: TypeExpression schemas (nullity 'PGinterval)
2239−interval = UnsafeTypeExpression "interval"
2240−-- | universally unique identifier
2241−uuid :: TypeExpression schemas (nullity 'PGuuid)
2242−uuid = UnsafeTypeExpression "uuid"
2243−-- | IPv4 or IPv6 host address
2244−inet :: TypeExpression schemas (nullity 'PGinet)
2245−inet = UnsafeTypeExpression "inet"
2246−-- | textual JSON data
2247−json :: TypeExpression schemas (nullity 'PGjson)
2248−json = UnsafeTypeExpression "json"
2249−-- | binary JSON data, decomposed
2250−jsonb :: TypeExpression schemas (nullity 'PGjsonb)
2251−jsonb = UnsafeTypeExpression "jsonb"
2252−-- | variable length array
2254− :: TypeExpression schemas pg
2255− -> TypeExpression schemas (nullity ('PGvararray pg))
2256−vararray ty = UnsafeTypeExpression $ renderSQL ty <> "[]"
2257−-- | fixed length array
2259−-- >>> renderSQL (fixarray @'[2] json)
2262− :: forall dims schemas nullity pg. SOP.All KnownNat dims
2263− => TypeExpression schemas pg
2264− -> TypeExpression schemas (nullity ('PGfixarray dims pg))
2265−fixarray ty = UnsafeTypeExpression $
2266− renderSQL ty <> renderDims @dims
2268− renderDims :: forall ns. SOP.All KnownNat ns => ByteString
2272− . ByteString.intercalate "]["
2274− $ hcmap (SOP.Proxy @KnownNat)
2275− (K . fromString . show . natVal)
2276− (hpure SOP.Proxy :: NP SOP.Proxy ns)
2277−tsvector :: TypeExpression schemas (nullity 'PGtsvector)
2278−tsvector = UnsafeTypeExpression "tsvector"
2279−tsquery :: TypeExpression schemas (nullity 'PGtsquery)
2280−tsquery = UnsafeTypeExpression "tsquery"
2282−-- | `pgtype` is a demoted version of a `PGType`
2283−class PGTyped schemas (ty :: NullityType) where
2284− pgtype :: TypeExpression schemas ty
2285−instance PGTyped schemas (nullity 'PGbool) where pgtype = bool
2286−instance PGTyped schemas (nullity 'PGint2) where pgtype = int2
2287−instance PGTyped schemas (nullity 'PGint4) where pgtype = int4
2288−instance PGTyped schemas (nullity 'PGint8) where pgtype = int8
2289−instance PGTyped schemas (nullity 'PGnumeric) where pgtype = numeric
2290−instance PGTyped schemas (nullity 'PGfloat4) where pgtype = float4
2291−instance PGTyped schemas (nullity 'PGfloat8) where pgtype = float8
2292−instance PGTyped schemas (nullity 'PGmoney) where pgtype = money
2293−instance PGTyped schemas (nullity 'PGtext) where pgtype = text
2294−instance (KnownNat n, 1 <= n)
2295− => PGTyped schemas (nullity ('PGchar n)) where pgtype = char @n
2296−instance (KnownNat n, 1 <= n)
2297− => PGTyped schemas (nullity ('PGvarchar n)) where pgtype = varchar @n
2298−instance PGTyped schemas (nullity 'PGbytea) where pgtype = bytea
2299−instance PGTyped schemas (nullity 'PGtimestamp) where pgtype = timestamp
2300−instance PGTyped schemas (nullity 'PGtimestamptz) where pgtype = timestampWithTimeZone
2301−instance PGTyped schemas (nullity 'PGdate) where pgtype = date
2302−instance PGTyped schemas (nullity 'PGtime) where pgtype = time
2303−instance PGTyped schemas (nullity 'PGtimetz) where pgtype = timeWithTimeZone
2304−instance PGTyped schemas (nullity 'PGinterval) where pgtype = interval
2305−instance PGTyped schemas (nullity 'PGuuid) where pgtype = uuid
2306−instance PGTyped schemas (nullity 'PGjson) where pgtype = json
2307−instance PGTyped schemas (nullity 'PGjsonb) where pgtype = jsonb
2308−instance PGTyped schemas ty
2309− => PGTyped schemas (nullity ('PGvararray ty)) where
2310− pgtype = vararray (pgtype @schemas @ty)
2311−instance (SOP.All KnownNat dims, PGTyped schemas ty)
2312− => PGTyped schemas (nullity ('PGfixarray dims ty)) where
2313− pgtype = fixarray @dims (pgtype @schemas @ty)
2314−instance PGTyped schemas (nullity 'PGtsvector) where pgtype = tsvector
2315−instance PGTyped schemas (nullity 'PGtsquery) where pgtype = tsquery
2317−{-----------------------------------------
2319−-----------------------------------------}
2321−-- | `SortExpression`s are used by `orderBy` to optionally sort the results
2322−-- of a `Squeal.PostgreSQL.Query.Query`. `Asc` or `Desc`
2323−-- set the sort direction of a `NotNull` result
2324−-- column to ascending or descending. Ascending order puts smaller values
2325−-- first, where "smaller" is defined in terms of the `.<` operator. Similarly,
2326−-- descending order is determined with the `.>` operator. `AscNullsFirst`,
2327−-- `AscNullsLast`, `DescNullsFirst` and `DescNullsLast` options are used to
2328−-- determine whether nulls appear before or after non-null values in the sort
2329−-- ordering of a `Null` result column.
2330−data SortExpression outer grp commons schemas params from where
2332− :: Expression outer grp commons schemas params from ('NotNull ty)
2333− -> SortExpression outer grp commons schemas params from
2335− :: Expression outer grp commons schemas params from ('NotNull ty)
2336− -> SortExpression outer grp commons schemas params from
2338− :: Expression outer grp commons schemas params from ('Null ty)
2339− -> SortExpression outer grp commons schemas params from
2341− :: Expression outer grp commons schemas params from ('Null ty)
2342− -> SortExpression outer grp commons schemas params from
2344− :: Expression outer grp commons schemas params from ('Null ty)
2345− -> SortExpression outer grp commons schemas params from
2347− :: Expression outer grp commons schemas params from ('Null ty)
2348− -> SortExpression outer grp commons schemas params from
2349−deriving instance Show (SortExpression outer grp commons schemas params from)
2352−The `orderBy` clause causes the result rows of a `Squeal.PostgreSQL.Query.TableExpression`
2353−to be sorted according to the specified `SortExpression`(s).
2354−If two rows are equal according to the leftmost expression,
2355−they are compared according to the next expression and so on.
2356−If they are equal according to all specified expressions,
2357−they are returned in an implementation-dependent order.
2359−You can also control the order in which rows are processed by window functions
2360−using `orderBy` within `Squeal.PostgreSQL.Query.Over`.
2362−class OrderBy expr where
2364− :: [SortExpression outer grp commons schemas params from]
2365− -> expr outer grp commons schemas params from
2366− -> expr outer grp commons schemas params from
2368−-- | Render a `SortExpression`.
2369−instance RenderSQL (SortExpression outer grp commons schemas params from) where
2371− Asc expression -> renderSQL expression <+> "ASC"
2372− Desc expression -> renderSQL expression <+> "DESC"
2373− AscNullsFirst expression -> renderSQL expression
2374− <+> "ASC NULLS FIRST"
2375− DescNullsFirst expression -> renderSQL expression
2376− <+> "DESC NULLS FIRST"
2377− AscNullsLast expression -> renderSQL expression <+> "ASC NULLS LAST"
2378− DescNullsLast expression -> renderSQL expression <+> "DESC NULLS LAST"
2380−-- | A `WindowDefinition` is a set of table rows that are somehow related
2381−-- to the current row
2382−data WindowDefinition outer grp commons schemas params from where
2385− => NP (Expression outer grp commons schemas params from) bys
2386− -> [SortExpression outer grp commons schemas params from]
2387− -> WindowDefinition outer grp commons schemas params from
2389−instance OrderBy WindowDefinition where
2390− orderBy sortsR (WindowDefinition parts sortsL)
2391− = WindowDefinition parts (sortsL ++ sortsR)
2393−instance RenderSQL (WindowDefinition outer commons schemas from grp params) where
2394− renderSQL (WindowDefinition part ord) =
2395− renderPartitionByClause part <> renderOrderByClause ord
2397− renderPartitionByClause = \case
2399− parts -> "PARTITION" <+> "BY" <+> renderCommaSeparated renderExpression parts
2400− renderOrderByClause = \case
2402− srts -> " ORDER" <+> "BY"
2403− <+> commaSeparated (renderSQL <$> srts)
2406−The `partitionBy` clause within `Squeal.PostgreSQL.Query.Over` divides the rows into groups,
2407−or partitions, that share the same values of the `partitionBy` `Expression`(s).
2408−For each row, the window function is computed across the rows that fall into
2409−the same partition as the current row.
2413− => NP (Expression outer grp commons schemas params from) bys
2414− -> WindowDefinition outer grp commons schemas params from
2415−partitionBy bys = WindowDefinition bys []
2418−A window function performs a calculation across a set of table rows
2419−that are somehow related to the current row. This is comparable to the type
2420−of calculation that can be done with an aggregate function.
2421−However, window functions do not cause rows to become grouped into a single
2422−output row like non-window aggregate calls would.
2423−Instead, the rows retain their separate identities.
2424−Behind the scenes, the window function is able to access more than
2425−just the current row of the query result.
2427−newtype WindowFunction
2428− (outer :: FromType)
2430− (commons :: FromType)
2431− (schemas :: SchemasType)
2432− (params :: [NullityType])
2434− (ty :: NullityType)
2435− = UnsafeWindowFunction { renderWindowFunction :: ByteString }
2436− deriving (GHC.Generic,Show,Eq,Ord,NFData)
2438−instance RenderSQL (WindowFunction outer grp commons schemas params from ty) where
2439− renderSQL = renderWindowFunction
2441−unsafeWindowFunction1
2443− -> Expression outer grp commons schemas params from ty0
2444− -> WindowFunction outer grp commons schemas params from ty1
2445−unsafeWindowFunction1 fun x
2446− = UnsafeWindowFunction $ fun <> parenthesized (renderSQL x)
2448−unsafeWindowFunction2
2450− -> (Expression outer grp commons schemas params from :*: Expression outer grp commons schemas params from) ty0
2451− -> WindowFunction outer grp commons schemas params from ty1
2452−unsafeWindowFunction2 fun (x :*: x')
2453− = UnsafeWindowFunction $ fun <> parenthesized (renderSQL x <> ", " <> renderSQL x')
2455−{- | rank of the current row with gaps; same as `rowNumber` of its first peer
2459−rank :: WindowFunction outer grp commons schemas params from ('NotNull 'PGint8)
2460−rank = UnsafeWindowFunction "rank()"
2462−{- | number of the current row within its partition, counting from 1
2463−>>> printSQL rowNumber
2466−rowNumber :: WindowFunction outer grp commons schemas params from ('NotNull 'PGint8)
2467−rowNumber = UnsafeWindowFunction "row_number()"
2469−{- | rank of the current row without gaps; this function counts peer groups
2470−>>> printSQL denseRank
2473−denseRank :: WindowFunction outer grp commons schemas params from ('NotNull 'PGint8)
2474−denseRank = UnsafeWindowFunction "dense_rank()"
2476−{- | relative rank of the current row: (rank - 1) / (total partition rows - 1)
2477−>>> printSQL percentRank
2480−percentRank :: WindowFunction outer grp commons schemas params from ('NotNull 'PGfloat8)
2481−percentRank = UnsafeWindowFunction "percent_rank()"
2483−{- | cumulative distribution: (number of partition rows
2484−preceding or peer with current row) / total partition rows
2485−>>> printSQL cumeDist
2488−cumeDist :: WindowFunction outer grp commons schemas params from ('NotNull 'PGfloat8)
2489−cumeDist = UnsafeWindowFunction "cume_dist()"
2491−{- | integer ranging from 1 to the argument value,
2492−dividing the partition as equally as possible
2495− :: Expression outer grp commons schemas params from ('NotNull 'PGint4)
2497− -> WindowFunction outer grp commons schemas params from ('NotNull 'PGint4)
2498−ntile = unsafeWindowFunction1 "ntile"
2500−{- | returns value evaluated at the row that is offset rows before the current
2501−row within the partition; if there is no such row, instead return default
2502−(which must be of the same type as value). Both offset and default are
2503−evaluated with respect to the current row.
2506− :: Expression outer grp commons schemas params from ty
2508− -> Expression outer grp commons schemas params from ('NotNull 'PGint4)
2510− -> Expression outer grp commons schemas params from ty
2512− -> WindowFunction outer grp commons schemas params from ty
2513−lag value offset def = UnsafeWindowFunction $ "lag"
2515− (commaSeparated ([renderSQL value, renderSQL offset, renderSQL def]))
2517−{- | returns value evaluated at the row that is offset rows after the current
2518−row within the partition; if there is no such row, instead return default
2519−(which must be of the same type as value). Both offset and default are
2520−evaluated with respect to the current row.
2523− :: Expression outer grp commons schemas params from ty
2525− -> Expression outer grp commons schemas params from ('NotNull 'PGint4)
2527− -> Expression outer grp commons schemas params from ty
2529− -> WindowFunction outer grp commons schemas params from ty
2530−lead value offset def = UnsafeWindowFunction $ "lag"
2532− (commaSeparated ([renderSQL value, renderSQL offset, renderSQL def]))
2534−{- | returns value evaluated at the row that is the
2535−first row of the window frame
2538− :: Expression outer grp commons schemas params from ty
2540− -> WindowFunction outer grp commons schemas params from ty
2541−firstValue = unsafeWindowFunction1 "first_value"
2543−{- | returns value evaluated at the row that is the
2544−last row of the window frame
2547− :: Expression outer grp commons schemas params from ty
2549− -> WindowFunction outer grp commons schemas params from ty
2550−lastValue = unsafeWindowFunction1 "last_value"
2552−{- | returns value evaluated at the row that is the nth
2553−row of the window frame (counting from 1); null if no such row
2556− :: Expression outer grp commons schemas params from (nullity ty)
2558− -> Expression outer grp commons schemas params from ('NotNull 'PGint4)
2560− -> WindowFunction outer grp commons schemas params from ('Null ty)
2561−nthValue value nth = UnsafeWindowFunction $ "nth_value"
2562− <> parenthesized (commaSeparated [renderSQL value, renderSQL nth])
2565−Create date from year, month and day fields
2567−>>> printSQL (makeDate 1984 7 3)
2568−make_date(1984, 7, 3)
2571− :: Expression outer grp commons schemas params from (nullity 'PGint4)
2573− -> Expression outer grp commons schemas params from (nullity 'PGint4)
2575− -> Expression outer grp commons schemas params from (nullity 'PGint4)
2577− -> Expression outer grp commons schemas params from (nullity 'PGdate)
2578−makeDate y m d = UnsafeExpression $ "make_date" <>
2579− parenthesized (renderCommaSeparated renderSQL (y :* m :* d :* Nil))
2582−Create time from hour, minute and seconds fields
2584−>>> printSQL (makeTime 8 15 23.5)
2585−make_time(8, 15, 23.5)
2588− :: Expression outer grp commons schemas params from (nullity 'PGint4)
2590− -> Expression outer grp commons schemas params from (nullity 'PGint4)
2592− -> Expression outer grp commons schemas params from (nullity 'PGfloat8)
2594− -> Expression outer grp commons schemas params from (nullity 'PGtime)
2595−makeTime h m s = UnsafeExpression $ "make_time" <>
2596− parenthesized (renderCommaSeparated renderSQL (h :* m :* s :* Nil))
2599−Create timestamp from year, month, day, hour, minute and seconds fields
2601−>>> printSQL (makeTimestamp 2013 7 15 8 15 23.5)
2602−make_timestamp(2013, 7, 15, 8, 15, 23.5)
2605− :: Expression outer grp commons schemas params from (nullity 'PGint4)
2607− -> Expression outer grp commons schemas params from (nullity 'PGint4)
2609− -> Expression outer grp commons schemas params from (nullity 'PGint4)
2611− -> Expression outer grp commons schemas params from (nullity 'PGint4)
2613− -> Expression outer grp commons schemas params from (nullity 'PGint4)
2615− -> Expression outer grp commons schemas params from (nullity 'PGfloat8)
2617− -> Expression outer grp commons schemas params from (nullity 'PGtimestamp)
2618−makeTimestamp y mon d h m s =
2619− UnsafeExpression $ "make_timestamp" <> parenthesized
2620− (renderCommaSeparated renderSQL (y :* mon :* d :* h :* m :* s :* Nil))
2623−Create timestamp with time zone from
2624−year, month, day, hour, minute and seconds fields;
2625−the current time zone is used
2627−>>> printSQL (makeTimestamptz 2013 7 15 8 15 23.5)
2628−make_timestamptz(2013, 7, 15, 8, 15, 23.5)
2631− :: Expression outer grp commons schemas params from (nullity 'PGint4)
2633− -> Expression outer grp commons schemas params from (nullity 'PGint4)
2635− -> Expression outer grp commons schemas params from (nullity 'PGint4)
2637− -> Expression outer grp commons schemas params from (nullity 'PGint4)
2639− -> Expression outer grp commons schemas params from (nullity 'PGint4)
2641− -> Expression outer grp commons schemas params from (nullity 'PGfloat8)
2643− -> Expression outer grp commons schemas params from (nullity 'PGtimestamptz)
2644−makeTimestamptz y mon d h m s =
2645− UnsafeExpression $ "make_timestamptz" <> parenthesized
2646− (renderCommaSeparated renderSQL (y :* mon :* d :* h :* m :* s :* Nil))
2649−Affine space operations on time types.
2651−class TimeOp time diff | time -> diff where
2653− >>> printSQL (makeDate 1984 7 3 !+ 365)
2654− (make_date(1984, 7, 3) + 365)
2657− :: Expression outer grp commons schemas params from (nullity time)
2658− -> Expression outer grp commons schemas params from (nullity diff)
2659− -> Expression outer grp commons schemas params from (nullity time)
2660− (!+) = unsafeBinaryOp "+"
2662− >>> printSQL (365 +! makeDate 1984 7 3)
2663− (365 + make_date(1984, 7, 3))
2666− :: Expression outer grp commons schemas params from (nullity diff)
2667− -> Expression outer grp commons schemas params from (nullity time)
2668− -> Expression outer grp commons schemas params from (nullity time)
2669− (+!) = unsafeBinaryOp "+"
2671− >>> printSQL (makeDate 1984 7 3 !- 365)
2672− (make_date(1984, 7, 3) - 365)
2675− :: Expression outer grp commons schemas params from (nullity time)
2676− -> Expression outer grp commons schemas params from (nullity diff)
2677− -> Expression outer grp commons schemas params from (nullity time)
2678− (!-) = unsafeBinaryOp "-"
2680− >>> printSQL (makeDate 1984 7 3 !-! currentDate)
2681− (make_date(1984, 7, 3) - CURRENT_DATE)
2684− :: Expression outer grp commons schemas params from (nullity time)
2685− -> Expression outer grp commons schemas params from (nullity time)
2686− -> Expression outer grp commons schemas params from (nullity diff)
2687− (!-!) = unsafeBinaryOp "-"
2688−instance TimeOp 'PGtimestamp 'PGinterval
2689−instance TimeOp 'PGtimestamptz 'PGinterval
2690−instance TimeOp 'PGtime 'PGinterval
2691−instance TimeOp 'PGtimetz 'PGinterval
2692−instance TimeOp 'PGinterval 'PGinterval
2693−instance TimeOp 'PGdate 'PGint4