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