@@ -1,14 +1,13 @@
11{-|
2−Module: Squeal.PostgreSQL.Query
2+Module: Squeal.PostgreSQL.Expression
33Description: Squeal expressions
4−Copyright: (c) Eitan Chatav, 2017
4+Copyright: (c) Eitan Chatav, 2019
55Maintainer: eitan@morphism.tech
66Stability: experimental
77
88Squeal expressions are the atoms used to build statements.
99-}
1010
11−{-# OPTIONS_GHC -fno-warn-redundant-constraints #-}
1211{-# LANGUAGE
1312 AllowAmbiguousTypes
1413 , ConstraintKinds
@@ -16,11 +15,13 @@ Squeal expressions are the atoms used to build statements.
1615 , FlexibleContexts
1716 , FlexibleInstances
1817 , FunctionalDependencies
18+ , GADTs
1919 , GeneralizedNewtypeDeriving
2020 , LambdaCase
2121 , MagicHash
2222 , OverloadedStrings
2323 , ScopedTypeVariables
24+ , StandaloneDeriving
2425 , TypeApplications
2526 , TypeFamilies
2627 , TypeInType
@@ -31,516 +32,351 @@ Squeal expressions are the atoms used to build statements.
3132
3233module Squeal.PostgreSQL.Expression
3334 ( -- * Expression
34− Expression (UnsafeExpression, renderExpression)
35− , HasParameter (parameter)
36− , param
37− -- ** Null
38− , null_
39− , notNull
40− , coalesce
41− , fromNull
42− , isNull
43− , isNotNull
44− , matchNull
45− , nullIf
46− -- ** Collections
47− , array
48− , row
49− -- ** Functions
50− , unsafeBinaryOp
51− , unsafeUnaryOp
35+ Expression (..)
36+ , Expr
37+ , type (-->)
38+ , FunctionDB
5239 , unsafeFunction
53− , unsafeVariadicFunction
54− , atan2_
55− , cast
56− , quot_
57− , rem_
58− , trunc
59− , round_
60− , ceiling_
61− , greatest
62− , least
63− -- ** Conditions
64− , Condition
65− , true
66− , false
67− , not_
68− , (.&&)
69− , (.||)
70− , caseWhenThenElse
71− , ifThenElse
72− , (.==)
73− , (./=)
74− , (.>=)
75− , (.<)
76− , (.<=)
77− , (.>)
78− -- ** Time
79− , currentDate
80− , currentTime
81− , currentTimestamp
82− , localTime
83− , localTimestamp
84− -- ** Text
85− , lower
86− , upper
87− , charLength
88− , like
89− -- ** json or jsonb operators
90− , PGarray
91− , PGarrayOf
92− , PGjsonKey
93− , PGjson_
94− , (.->)
95− , (.->>)
96− , (.#>)
97− , (.#>>)
98− -- *** jsonb only operators
99− , (.@>)
100− , (.<@)
101− , (.?)
102− , (.?|)
103− , (.?&)
104− , (.-.)
105− , (#-.)
106− -- *** Functions
107− , jsonLit
108− , jsonbLit
109− , toJson
110− , toJsonb
111− , arrayToJson
112− , rowToJson
113− , jsonBuildArray
114− , jsonbBuildArray
115− , jsonBuildObject
116− , jsonbBuildObject
117− , jsonObject
118− , jsonbObject
119− , jsonZipObject
120− , jsonbZipObject
121− , jsonArrayLength
122− , jsonbArrayLength
123− , jsonExtractPath
124− , jsonbExtractPath
125− , jsonExtractPathAsText
126− , jsonbExtractPathAsText
127− , jsonObjectKeys
128− , jsonbObjectKeys
129− , jsonTypeof
130− , jsonbTypeof
131− , jsonStripNulls
132− , jsonbStripNulls
133− , jsonbSet
134− , jsonbInsert
135− , jsonbPretty
136− -- ** Aggregation
137− , unsafeAggregate, unsafeAggregateDistinct
138− , sum_, sumDistinct
139− , PGAvg (avg, avgDistinct)
140− , bitAnd, bitOr, boolAnd, boolOr
141− , bitAndDistinct, bitOrDistinct, boolAndDistinct, boolOrDistinct
142− , countStar
143− , count, countDistinct
144− , every, everyDistinct
145− , max_, maxDistinct, min_, minDistinct
146− -- * Types
147− , TypeExpression (UnsafeTypeExpression, renderTypeExpression)
148− , PGTyped (pgtype)
149− , bool
150− , int2
151− , smallint
152− , int4
153− , int
154− , integer
155− , int8
156− , bigint
157− , numeric
158− , float4
159− , real
160− , float8
161− , doublePrecision
162− , text
163− , char
164− , character
165− , varchar
166− , characterVarying
167− , bytea
168− , timestamp
169− , timestampWithTimeZone
170− , date
171− , time
172− , timeWithTimeZone
173− , interval
174− , uuid
175− , inet
176− , json
177− , jsonb
178− , vararray
179− , fixarray
40+ , function
41+ , unsafeLeftOp
42+ , leftOp
43+ , unsafeRightOp
44+ , rightOp
45+ , Operator
46+ , OperatorDB
47+ , unsafeBinaryOp
48+ , binaryOp
49+ , FunctionVar
50+ , unsafeFunctionVar
51+ , type (--->)
52+ , FunctionNDB
53+ , unsafeFunctionN
54+ , functionN
55+ , PGSubset (..)
56+ , PGIntersect (..)
18057 -- * Re-export
18158 , (&)
182− , NP ((:*), Nil)
59+ , K (..)
60+ , unK
18361 ) where
18462
18563import Control.Category
18664import Control.DeepSeq
18765import Data.ByteString (ByteString)
188−import Data.ByteString.Lazy (toStrict)
18966import Data.Function ((&))
19067import Data.Semigroup hiding (All)
191−import qualified Data.Aeson as JSON
192−import Data.Ratio
19368import Data.String
194−import Generics.SOP hiding (from)
69+import Generics.SOP hiding (All, from)
19570import GHC.OverloadedLabels
19671import GHC.TypeLits
72+import Numeric
19773import Prelude hiding (id, (.))
19874
19975import qualified GHC.Generics as GHC
20076
77+import Squeal.PostgreSQL.Alias
78+import Squeal.PostgreSQL.List
20179import Squeal.PostgreSQL.Render
20280import Squeal.PostgreSQL.Schema
20381
82+-- $setup
83+-- >>> import Squeal.PostgreSQL
84+
20485{-----------------------------------------
20586column expressions
20687-----------------------------------------}
20788
20889{- | `Expression`s are used in a variety of contexts,
209−such as in the target list of the `Squeal.PostgreSQL.Query.select` command,
90+such as in the target `Squeal.PostgreSQL.Query.List` of the
91+`Squeal.PostgreSQL.Query.select` command,
21092as new column values in `Squeal.PostgreSQL.Manipulation.insertRow` or
21193`Squeal.PostgreSQL.Manipulation.update`,
212−or in search `Condition`s in a number of commands.
94+or in search `Squeal.PostgreSQL.Logic.Condition`s in a number of commands.
21395
21496The expression syntax allows the calculation of
21597values from primitive expression using arithmetic, logical,
21698and other operations.
99+
100+The type parameters of `Expression` are
101+
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`.
217113-}
218114newtype Expression
219− (schema :: SchemaType)
220− (relations :: RelationsType)
221− (grouping :: Grouping)
115+ (outer :: FromType)
116+ (commons :: FromType)
117+ (grp :: Grouping)
118+ (schemas :: SchemasType)
222119 (params :: [NullityType])
120+ (from :: FromType)
223121 (ty :: NullityType)
224122 = UnsafeExpression { renderExpression :: ByteString }
225123 deriving (GHC.Generic,Show,Eq,Ord,NFData)
226−
227−instance RenderSQL (Expression schema relations grouping params ty) where
124+instance RenderSQL (Expression outer commons grp schemas params from ty) where
228125 renderSQL = renderExpression
229126
230−{- | A `HasParameter` constraint is used to indicate a value that is
231−supplied externally to a SQL statement.
232−`Squeal.PostgreSQL.PQ.manipulateParams`,
233−`Squeal.PostgreSQL.PQ.queryParams` and
234−`Squeal.PostgreSQL.PQ.traversePrepared` support specifying data values
235−separately from the SQL command string, in which case `param`s are used to
236−refer to the out-of-line data values.
127+-- | An `Expr` is a closed `Expression`.
128+-- It is a F@RankNType@ but don't be scared.
129+-- Think of it as an expression which sees no
130+-- namespaces, so you can't use parameters
131+-- or alias references. It can be used as
132+-- a simple piece of more complex `Expression`s.
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
137+
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
142+ -- ^ left input
143+ -> Expression outer commons grp schemas params from x2
144+ -- ^ right input
145+ -> Expression outer commons grp schemas params from y
146+ -- ^ output
147+
148+type OperatorDB schemas x1 x2 y
149+ = forall outer commons grp params from
150+ . Expression outer commons grp schemas params from x1
151+ -- ^ left input
152+ -> Expression outer commons grp schemas params from x2
153+ -- ^ right input
154+ -> Expression outer commons grp schemas params from y
155+ -- ^ output
156+
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`.
162+type (-->) x y
163+ = forall outer commons grp schemas params from
164+ . Expression outer commons grp schemas params from x
165+ -- ^ input
166+ -> Expression outer commons grp schemas params from y
167+ -- ^ output
168+
169+type FunctionDB schemas x y
170+ = forall outer commons grp params from
171+ . Expression outer commons grp schemas params from x
172+ -- ^ input
173+ -> Expression outer commons grp schemas params from y
174+ -- ^ output
175+
176+{- | A @RankNType@ for functions with a fixed-length list of heterogeneous arguments.
177+Use the `*:` operator to end your argument lists, like so.
178+
179+>>> printSQL (unsafeFunctionN "fun" (true :* false :* localTime *: true))
180+fun(TRUE, FALSE, LOCALTIME, TRUE)
237181-}
238−class KnownNat n => HasParameter
239− (n :: Nat)
240− (schema :: SchemaType)
241− (params :: [NullityType])
242− (ty :: NullityType)
243− | n params -> ty where
244− -- | `parameter` takes a `Nat` using type application and a `TypeExpression`.
245− --
246− -- >>> let expr = parameter @1 int4 :: Expression sch rels grp '[ 'Null 'PGint4] ('Null 'PGint4)
247− -- >>> printSQL expr
248− -- ($1 :: int4)
249− parameter
250− :: TypeExpression schema (PGTypeOf ty)
251− -> Expression schema relations grouping params ty
252− parameter ty = UnsafeExpression $ parenthesized $
253− "$" <> renderNat (Proxy @n) <+> "::"
254− <+> renderTypeExpression ty
255−instance {-# OVERLAPPING #-} HasParameter 1 schema (ty1:tys) ty1
256−instance {-# OVERLAPPABLE #-} (KnownNat n, HasParameter (n-1) schema params ty)
257− => HasParameter n schema (ty' : params) ty
258−
259−-- | `param` takes a `Nat` using type application and for basic types,
260−-- infers a `TypeExpression`.
261−--
262−-- >>> let expr = param @1 :: Expression sch rels grp '[ 'Null 'PGint4] ('Null 'PGint4)
263−-- >>> printSQL expr
264−-- ($1 :: int4)
265−param
266− :: forall n schema params relations grouping ty
267− . (PGTyped schema (PGTypeOf ty), HasParameter n schema params ty)
268− => Expression schema relations grouping params ty -- ^ param
269−param = parameter @n pgtype
270−
271−instance (HasUnique relation relations columns, Has column columns ty)
272− => IsLabel column (Expression schema relations 'Ungrouped params ty) where
273− fromLabel = UnsafeExpression $ renderAlias (Alias @column)
274−instance (HasUnique relation relations columns, Has column columns ty)
275− => IsLabel column
276− (Aliased (Expression schema relations 'Ungrouped params) (column ::: ty)) where
277− fromLabel = fromLabel @column `As` Alias @column
278−instance (HasUnique relation relations columns, Has column columns ty)
279− => IsLabel column
280− (NP (Aliased (Expression schema relations 'Ungrouped params)) '[column ::: ty]) where
281− fromLabel = fromLabel @column :* Nil
282−
283−instance (Has relation relations columns, Has column columns ty)
284− => IsQualified relation column (Expression schema relations 'Ungrouped params ty) where
285− relation ! column = UnsafeExpression $
286− renderAlias relation <> "." <> renderAlias column
287−instance (Has relation relations columns, Has column columns ty)
288− => IsQualified relation column
289− (Aliased (Expression schema relations 'Ungrouped params) (column ::: ty)) where
290− relation ! column = relation ! column `As` column
291−instance (Has relation relations columns, Has column columns ty)
292− => IsQualified relation column
293− (NP (Aliased (Expression schema relations 'Ungrouped params)) '[column ::: ty]) where
294− relation ! column = relation ! column :* Nil
182+type (--->) xs y
183+ = forall outer commons grp schemas params from
184+ . NP (Expression outer commons grp schemas params from) xs
185+ -- ^ inputs
186+ -> Expression outer commons grp schemas params from y
187+ -- ^ output
188+
189+type FunctionNDB schemas xs y
190+ = forall outer commons grp params from
191+ . NP (Expression outer commons grp schemas params from) xs
192+ -- ^ inputs
193+ -> Expression outer commons grp schemas params from y
194+ -- ^ output
195+
196+{- | A @RankNType@ for functions with a variable-length list of
197+homogeneous arguments and at least 1 more argument.
198+-}
199+type FunctionVar x0 x1 y
200+ = forall outer commons grp schemas params from
201+ . [Expression outer commons grp schemas params from x0]
202+ -- ^ inputs
203+ -> Expression outer commons grp schemas params from x1
204+ -- ^ must have at least 1 input
205+ -> Expression outer commons grp schemas params from y
206+ -- ^ output
207+
208+{- | >>> printSQL (unsafeFunctionVar "greatest" [true, null_] false)
209+greatest(TRUE, NULL, FALSE)
210+-}
211+unsafeFunctionVar :: ByteString -> FunctionVar x0 x1 y
212+unsafeFunctionVar fun xs x = UnsafeExpression $ fun <> parenthesized
213+ (commaSeparated (renderSQL <$> xs) <> ", " <> renderSQL x)
214+
215+instance (HasUnique tab (Join outer from) row, Has col row ty)
216+ => IsLabel col (Expression outer commons 'Ungrouped schemas params from ty) where
217+ fromLabel = UnsafeExpression $ renderSQL (Alias @col)
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))
222+ => IsLabel col
223+ (Aliased (Expression outer commons 'Ungrouped schemas params from) column) where
224+ fromLabel = fromLabel @col `As` Alias
225+instance (HasUnique tab (Join outer from) row, Has col row ty, columns ~ '[col ::: ty])
226+ => IsLabel col
227+ (NP (Aliased (Expression outer commons 'Ungrouped schemas params from)) columns) where
228+ fromLabel = fromLabel @col :* Nil
229+
230+instance (Has tab (Join outer from) row, Has col row ty)
231+ => IsQualified tab col (Expression outer commons 'Ungrouped schemas params from ty) where
232+ tab ! col = UnsafeExpression $
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
237+instance (Has tab (Join outer from) row, Has col row ty, column ~ (col ::: ty))
238+ => IsQualified tab col
239+ (Aliased (Expression outer commons 'Ungrouped schemas params from) column) where
240+ tab ! col = tab ! col `As` col
241+instance (Has tab (Join outer from) row, Has col row ty, columns ~ '[col ::: ty])
242+ => IsQualified tab col
243+ (NP (Aliased (Expression outer commons 'Ungrouped schemas params from)) columns) where
244+ tab ! col = tab ! col :* Nil
295245
296246instance
297− ( HasUnique relation relations columns
298− , Has column columns ty
299− , GroupedBy relation column bys
300− ) => IsLabel column
301− (Expression schema relations ('Grouped bys) params ty) where
302− fromLabel = UnsafeExpression $ renderAlias (Alias @column)
247+ ( HasUnique tab (Join outer from) row
248+ , Has col row ty
249+ , GroupedBy tab col bys
250+ ) => IsLabel col
251+ (Expression outer commons ('Grouped bys) schemas params from ty) where
252+ fromLabel = UnsafeExpression $ renderSQL (Alias @col)
253+instance
254+ ( HasUnique tab (Join outer from) row
255+ , Has col row ty
256+ , GroupedBy tab col bys
257+ , tys ~ '[ty]
258+ ) => IsLabel col
259+ (NP (Expression outer commons ('Grouped bys) schemas params from) tys) where
260+ fromLabel = fromLabel @col :* Nil
303261instance
304− ( HasUnique relation relations columns
305− , Has column columns ty
306− , GroupedBy relation column bys
307− ) => IsLabel column
308− ( Aliased (Expression schema relations ('Grouped bys) params)
309− (column ::: ty) ) where
310− fromLabel = fromLabel @column `As` Alias @column
262+ ( HasUnique tab (Join outer from) row
263+ , Has col row ty
264+ , GroupedBy tab col bys
265+ , column ~ (col ::: ty)
266+ ) => IsLabel col
267+ (Aliased (Expression outer commons ('Grouped bys) schemas params from) column) where
268+ fromLabel = fromLabel @col `As` Alias
311269instance
312− ( HasUnique relation relations columns
313− , Has column columns ty
314− , GroupedBy relation column bys
315− ) => IsLabel column
316− ( NP (Aliased (Expression schema relations ('Grouped bys) params))
317− '[column ::: ty] ) where
318− fromLabel = fromLabel @column :* Nil
270+ ( HasUnique tab (Join outer from) row
271+ , Has col row ty
272+ , GroupedBy tab col bys
273+ , columns ~ '[col ::: ty]
274+ ) => IsLabel col
275+ (NP (Aliased (Expression outer commons ('Grouped bys) schemas params from)) columns) where
276+ fromLabel = fromLabel @col :* Nil
319277
320278instance
321− ( Has relation relations columns
322− , Has column columns ty
323− , GroupedBy relation column bys
324− ) => IsQualified relation column
325− (Expression schema relations ('Grouped bys) params ty) where
326− relation ! column = UnsafeExpression $
327− renderAlias relation <> "." <> renderAlias column
279+ ( Has tab (Join outer from) row
280+ , Has col row ty
281+ , GroupedBy tab col bys
282+ ) => IsQualified tab col
283+ (Expression outer commons ('Grouped bys) schemas params from ty) where
284+ tab ! col = UnsafeExpression $
285+ renderSQL tab <> "." <> renderSQL col
328286instance
329− ( Has relation relations columns
330− , Has column columns ty
331− , GroupedBy relation column bys
332− ) => IsQualified relation column
333− (Aliased (Expression schema relations ('Grouped bys) params)
334− (column ::: ty)) where
335− relation ! column = relation ! column `As` column
287+ ( Has tab (Join outer from) row
288+ , Has col row ty
289+ , GroupedBy tab col bys
290+ , tys ~ '[ty]
291+ ) => IsQualified tab col
292+ (NP (Expression outer commons ('Grouped bys) schemas params from) tys) where
293+ tab ! col = tab ! col :* Nil
336294instance
337− ( Has relation relations columns
338− , Has column columns ty
339− , GroupedBy relation column bys
340− ) => IsQualified relation column
341− ( NP (Aliased (Expression schema relations ('Grouped bys) params))
342− '[column ::: ty]) where
343− relation ! column = relation ! column :* Nil
344−
345−-- | analagous to `Nothing`
346−--
347−-- >>> printSQL null_
348−-- NULL
349−null_ :: Expression schema rels grouping params ('Null ty)
350−null_ = UnsafeExpression "NULL"
351−
352−-- | analagous to `Just`
353−--
354−-- >>> printSQL $ notNull true
355−-- TRUE
356−notNull
357− :: Expression schema rels grouping params ('NotNull ty)
358− -> Expression schema rels grouping params ('Null ty)
359−notNull = UnsafeExpression . renderExpression
360−
361−-- | return the leftmost value which is not NULL
362−--
363−-- >>> printSQL $ coalesce [null_, notNull true] false
364−-- COALESCE(NULL, TRUE, FALSE)
365−coalesce
366− :: [Expression schema relations grouping params ('Null ty)]
367− -- ^ @NULL@s may be present
368− -> Expression schema relations grouping params ('NotNull ty)
369− -- ^ @NULL@ is absent
370− -> Expression schema relations grouping params ('NotNull ty)
371−coalesce nullxs notNullx = UnsafeExpression $
372− "COALESCE" <> parenthesized (commaSeparated
373− ((renderExpression <$> nullxs) <> [renderExpression notNullx]))
374−
375−-- | analagous to `Data.Maybe.fromMaybe` using @COALESCE@
376−--
377−-- >>> printSQL $ fromNull true null_
378−-- COALESCE(NULL, TRUE)
379−fromNull
380− :: Expression schema relations grouping params ('NotNull ty)
381− -- ^ what to convert @NULL@ to
382− -> Expression schema relations grouping params ('Null ty)
383− -> Expression schema relations grouping params ('NotNull ty)
384−fromNull notNullx nullx = coalesce [nullx] notNullx
385−
386−-- | >>> printSQL $ null_ & isNull
387−-- NULL IS NULL
388−isNull
389− :: Expression schema relations grouping params ('Null ty)
390− -- ^ possibly @NULL@
391− -> Condition schema relations grouping params
392−isNull x = UnsafeExpression $ renderExpression x <+> "IS NULL"
393−
394−-- | >>> printSQL $ null_ & isNotNull
395−-- NULL IS NOT NULL
396−isNotNull
397− :: Expression schema relations grouping params ('Null ty)
398− -- ^ possibly @NULL@
399− -> Condition schema relations grouping params
400−isNotNull x = UnsafeExpression $ renderExpression x <+> "IS NOT NULL"
401−
402−-- | analagous to `maybe` using @IS NULL@
403−--
404−-- >>> printSQL $ matchNull true not_ null_
405−-- CASE WHEN NULL IS NULL THEN TRUE ELSE (NOT NULL) END
406−matchNull
407− :: Expression schema relations grouping params (nullty)
408− -- ^ what to convert @NULL@ to
409− -> ( Expression schema relations grouping params ('NotNull ty)
410− -> Expression schema relations grouping params (nullty) )
411− -- ^ function to perform when @NULL@ is absent
412− -> Expression schema relations grouping params ('Null ty)
413− -> Expression schema relations grouping params (nullty)
414−matchNull y f x = ifThenElse (isNull x) y
415− (f (UnsafeExpression (renderExpression x)))
416−
417−{-| right inverse to `fromNull`, if its arguments are equal then
418−`nullIf` gives @NULL@.
419−
420−>>> :set -XTypeApplications -XDataKinds
421−>>> let expr = nullIf false (param @1) :: Expression schema rels grp '[ 'NotNull 'PGbool] ('Null 'PGbool)
422−>>> printSQL expr
423−NULL IF (FALSE, ($1 :: bool))
424−-}
425−nullIf
426− :: Expression schema relations grouping params ('NotNull ty)
427− -- ^ @NULL@ is absent
428− -> Expression schema relations grouping params ('NotNull ty)
429− -- ^ @NULL@ is absent
430− -> Expression schema relations grouping params ('Null ty)
431−nullIf x y = UnsafeExpression $ "NULL IF" <+> parenthesized
432− (renderExpression x <> ", " <> renderExpression y)
433−
434−-- | >>> printSQL $ array [null_, notNull false, notNull true]
435−-- ARRAY[NULL, FALSE, TRUE]
436−array
437− :: [Expression schema relations grouping params ('Null ty)]
438− -- ^ array elements
439− -> Expression schema relations grouping params (nullity ('PGvararray ty))
440−array xs = UnsafeExpression $
441− "ARRAY[" <> commaSeparated (renderExpression <$> xs) <> "]"
295+ ( Has tab (Join outer from) row
296+ , Has col row ty
297+ , GroupedBy tab col bys
298+ , column ~ (col ::: ty)
299+ ) => IsQualified tab col
300+ (Aliased (Expression outer commons ('Grouped bys) schemas params from) column) where
301+ tab ! col = tab ! col `As` col
302+instance
303+ ( Has tab (Join outer from) row
304+ , Has col row ty
305+ , GroupedBy tab col bys
306+ , columns ~ '[col ::: ty]
307+ ) => IsQualified tab col
308+ (NP (Aliased (Expression outer commons ('Grouped bys) schemas params from)) columns) where
309+ tab ! col = tab ! col :* Nil
442310
443311instance (KnownSymbol label, label `In` labels) => IsPGlabel label
444− (Expression schema relations grouping params (nullity ('PGenum labels))) where
445− label = UnsafeExpression $ renderLabel (PGlabel @label)
446−
447−-- | A row constructor is an expression that builds a row value
448−-- (also called a composite value) using values for its member fields.
449−--
450−-- >>> type Complex = PGcomposite '["real" ::: 'PGfloat8, "imaginary" ::: 'PGfloat8]
451−-- >>> let i = row (0 `as` #real :* 1 `as` #imaginary) :: Expression '[] '[] 'Ungrouped '[] ('NotNull Complex)
452−-- >>> printSQL i
453−-- ROW(0, 1)
454−row
455− :: SListI (Nulls fields)
456− => NP (Aliased (Expression schema relations grouping params)) (Nulls fields)
457− -- ^ zero or more expressions for the row field values
458− -> Expression schema relations grouping params (nullity ('PGcomposite fields))
459−row exprs = UnsafeExpression $ "ROW" <> parenthesized
460− (renderCommaSeparated (\ (expr `As` _) -> renderExpression expr) exprs)
461−
462−instance Has field fields ty => IsLabel field
463− ( Expression schema relation grouping params (nullity ('PGcomposite fields))
464− -> Expression schema relation grouping params ('Null ty) ) where
465− fromLabel expr = UnsafeExpression $
466− parenthesized (renderExpression expr) <> "." <>
467− fromString (symbolVal (Proxy @field))
468−
469−instance Semigroup
470− (Expression schema relations grouping params (nullity ('PGvararray ty))) where
471− (<>) = unsafeBinaryOp "||"
472−
473−instance Monoid
474− (Expression schema relations grouping params (nullity ('PGvararray ty))) where
475− mempty = array []
476− mappend = (<>)
477−
478−-- | >>> let expr = greatest currentTimestamp [param @1] :: Expression sch rels grp '[ 'NotNull 'PGtimestamptz] ('NotNull 'PGtimestamptz)
479−-- >>> printSQL expr
480−-- GREATEST(CURRENT_TIMESTAMP, ($1 :: timestamp with time zone))
481−greatest
482− :: Expression schema relations grouping params (nullty)
483− -- ^ needs at least 1 argument
484− -> [Expression schema relations grouping params (nullty)]
485− -- ^ or more
486− -> Expression schema relations grouping params (nullty)
487−greatest x xs = UnsafeExpression $ "GREATEST("
488− <> commaSeparated (renderExpression <$> (x:xs)) <> ")"
489−
490−-- | >>> printSQL $ least currentTimestamp [null_]
491−-- LEAST(CURRENT_TIMESTAMP, NULL)
492−least
493− :: Expression schema relations grouping params (nullty)
494− -- ^ needs at least 1 argument
495− -> [Expression schema relations grouping params (nullty)]
496− -- ^ or more
497− -> Expression schema relations grouping params (nullty)
498−least x xs = UnsafeExpression $ "LEAST("
499− <> commaSeparated (renderExpression <$> (x:xs)) <> ")"
312+ (Expression outer commons grp schemas params from (null ('PGenum labels))) where
313+ label = UnsafeExpression $ renderSQL (PGlabel @label)
500314
501315-- | >>> printSQL $ unsafeBinaryOp "OR" true false
502316-- (TRUE OR FALSE)
503−unsafeBinaryOp
504− :: ByteString
505− -- ^ operator
506− -> Expression schema relations grouping params (ty0)
507− -> Expression schema relations grouping params (ty1)
508− -> Expression schema relations grouping params (ty2)
317+unsafeBinaryOp :: ByteString -> Operator ty0 ty1 ty2
509318unsafeBinaryOp op x y = UnsafeExpression $ parenthesized $
510− renderExpression x <+> op <+> renderExpression y
319+ renderSQL x <+> op <+> renderSQL y
320+
321+binaryOp
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
511327
512−-- | >>> printSQL $ unsafeUnaryOp "NOT" true
328+-- | >>> printSQL $ unsafeLeftOp "NOT" true
513329-- (NOT TRUE)
514−unsafeUnaryOp
515− :: ByteString
516− -- ^ operator
517− -> Expression schema relations grouping params (ty0)
518− -> Expression schema relations grouping params (ty1)
519−unsafeUnaryOp op x = UnsafeExpression $ parenthesized $
520− op <+> renderExpression x
330+unsafeLeftOp :: ByteString -> x --> y
331+unsafeLeftOp op x = UnsafeExpression $ parenthesized $ op <+> renderSQL x
332+
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
339+
340+-- | >>> printSQL $ true & unsafeRightOp "IS NOT TRUE"
341+-- (TRUE IS NOT TRUE)
342+unsafeRightOp :: ByteString -> x --> y
343+unsafeRightOp op x = UnsafeExpression $ parenthesized $ renderSQL x <+> op
344+
345+rightOp
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
521351
522352-- | >>> printSQL $ unsafeFunction "f" true
523353-- f(TRUE)
524−unsafeFunction
525− :: ByteString
526− -- ^ function
527− -> Expression schema relations grouping params (xty)
528− -> Expression schema relations grouping params (yty)
354+unsafeFunction :: ByteString -> x --> y
529355unsafeFunction fun x = UnsafeExpression $
530− fun <> parenthesized (renderExpression x)
531−
532−-- | Helper for defining variadic functions.
533−unsafeVariadicFunction
534− :: SListI elems
535− => ByteString
536− -- ^ function
537− -> NP (Expression schema relations grouping params) elems
538− -> Expression schema relations grouping params ret
539−unsafeVariadicFunction fun x = UnsafeExpression $
540− fun <> parenthesized (commaSeparated (hcollapse (hmap (K . renderExpression) x)))
541−
542−instance PGNum ty
543− => Num (Expression schema relations grouping params (nullity ty)) where
356+ fun <> parenthesized (renderSQL x)
357+
358+function
359+ :: (Has sch schemas schema, Has fun schema ('Function ('[x] :=> 'Returns y)))
360+ => QualifiedAlias sch fun
361+ -> FunctionDB schemas x y
362+function = unsafeFunction . renderSQL
363+
364+-- | >>> printSQL $ unsafeFunctionN "f" (currentTime :* localTimestamp :* false *: literal 'a')
365+-- f(CURRENT_TIME, LOCALTIMESTAMP, FALSE, E'a')
366+unsafeFunctionN :: SListI xs => ByteString -> xs ---> y
367+unsafeFunctionN fun xs = UnsafeExpression $
368+ fun <> parenthesized (renderCommaSeparated renderSQL xs)
369+
370+functionN
371+ :: ( Has sch schemas schema
372+ , Has fun schema ('Function (xs :=> 'Returns y))
373+ , SListI xs )
374+ => QualifiedAlias sch fun
375+ -> FunctionNDB schemas xs y
376+functionN = unsafeFunctionN . renderSQL
377+
378+instance ty `In` PGNum
379+ => Num (Expression outer commons grp schemas params from (null ty)) where
544380 (+) = unsafeBinaryOp "+"
545381 (-) = unsafeBinaryOp "-"
546382 (*) = unsafeBinaryOp "*"
@@ -551,19 +387,24 @@ instance PGNum ty
551387 . fromString
552388 . show
553389
554−instance (PGNum ty, PGFloating ty) => Fractional
555− (Expression schema relations grouping params (nullity ty)) where
390+instance (ty `In` PGNum, ty `In` PGFloating) => Fractional
391+ (Expression outer commons grp schemas params from (null ty)) where
556392 (/) = unsafeBinaryOp "/"
557− fromRational x = fromInteger (numerator x) / fromInteger (denominator x)
393+ fromRational
394+ = UnsafeExpression
395+ . fromString
396+ . ($ "")
397+ . showFFloat Nothing
398+ . fromRat @Double
558399
559−instance (PGNum ty, PGFloating ty) => Floating
560− (Expression schema relations grouping params (nullity ty)) where
400+instance (ty `In` PGNum, ty `In` PGFloating) => Floating
401+ (Expression outer commons grp schemas params from (null ty)) where
561402 pi = UnsafeExpression "pi()"
562403 exp = unsafeFunction "exp"
563404 log = unsafeFunction "ln"
564405 sqrt = unsafeFunction "sqrt"
565406 b ** x = UnsafeExpression $
566− "power(" <> renderExpression b <> ", " <> renderExpression x <> ")"
407+ "power(" <> renderSQL b <> ", " <> renderSQL x <> ")"
567408 logBase b y = log y / log b
568409 sin = unsafeFunction "sin"
569410 cos = unsafeFunction "cos"
@@ -578,1129 +419,54 @@ instance (PGNum ty, PGFloating ty) => Floating
578419 acosh x = log (x + sqrt (x*x - 1))
579420 atanh x = log ((1 + x) / (1 - x)) / 2
580421
581−-- | >>> :{
582−-- let
583−-- expression :: Expression schema relations grouping params (nullity 'PGfloat4)
584−-- expression = atan2_ pi 2
585−-- in printSQL expression
586−-- :}
587−-- atan2(pi(), 2)
588−atan2_
589− :: PGFloating float
590− => Expression schema relations grouping params (nullity float)
591− -- ^ numerator
592− -> Expression schema relations grouping params (nullity float)
593− -- ^ denominator
594− -> Expression schema relations grouping params (nullity float)
595−atan2_ y x = UnsafeExpression $
596− "atan2(" <> renderExpression y <> ", " <> renderExpression x <> ")"
597−
598−-- When a `cast` is applied to an `Expression` of a known type, it
599−-- represents a run-time type conversion. The cast will succeed only if a
600−-- suitable type conversion operation has been defined.
601−--
602−-- | >>> printSQL $ true & cast int4
603−-- (TRUE :: int4)
604−cast
605− :: TypeExpression schema ty1
606− -- ^ type to cast as
607− -> Expression schema relations grouping params (nullity ty0)
608− -- ^ value to convert
609− -> Expression schema relations grouping params (nullity ty1)
610−cast ty x = UnsafeExpression $ parenthesized $
611− renderExpression x <+> "::" <+> renderTypeExpression ty
612−
613−-- | integer division, truncates the result
614−--
615−-- >>> :{
616−-- let
617−-- expression :: Expression schema relations grouping params (nullity 'PGint2)
618−-- expression = 5 `quot_` 2
619−-- in printSQL expression
620−-- :}
621−-- (5 / 2)
622−quot_
623− :: PGIntegral int
624− => Expression schema relations grouping params (nullity int)
625− -- ^ numerator
626− -> Expression schema relations grouping params (nullity int)
627− -- ^ denominator
628− -> Expression schema relations grouping params (nullity int)
629−quot_ = unsafeBinaryOp "/"
630−
631−-- | remainder upon integer division
632−--
633−-- >>> :{
634−-- let
635−-- expression :: Expression schema relations grouping params (nullity 'PGint2)
636−-- expression = 5 `rem_` 2
637−-- in printSQL expression
638−-- :}
639−-- (5 % 2)
640−rem_
641− :: PGIntegral int
642− => Expression schema relations grouping params (nullity int)
643− -- ^ numerator
644− -> Expression schema relations grouping params (nullity int)
645− -- ^ denominator
646− -> Expression schema relations grouping params (nullity int)
647−rem_ = unsafeBinaryOp "%"
648−
649−-- | >>> :{
650−-- let
651−-- expression :: Expression schema relations grouping params (nullity 'PGfloat4)
652−-- expression = trunc pi
653−-- in printSQL expression
654−-- :}
655−-- trunc(pi())
656−trunc
657− :: PGFloating frac
658− => Expression schema relations grouping params (nullity frac)
659− -- ^ fractional number
660− -> Expression schema relations grouping params (nullity frac)
661−trunc = unsafeFunction "trunc"
662−
663−-- | >>> :{
664−-- let
665−-- expression :: Expression schema relations grouping params (nullity 'PGfloat4)
666−-- expression = round_ pi
667−-- in printSQL expression
668−-- :}
669−-- round(pi())
670−round_
671− :: PGFloating frac
672− => Expression schema relations grouping params (nullity frac)
673− -- ^ fractional number
674− -> Expression schema relations grouping params (nullity frac)
675−round_ = unsafeFunction "round"
676−
677−-- | >>> :{
678−-- let
679−-- expression :: Expression schema relations grouping params (nullity 'PGfloat4)
680−-- expression = ceiling_ pi
681−-- in printSQL expression
682−-- :}
683−-- ceiling(pi())
684−ceiling_
685− :: PGFloating frac
686− => Expression schema relations grouping params (nullity frac)
687− -- ^ fractional number
688− -> Expression schema relations grouping params (nullity frac)
689−ceiling_ = unsafeFunction "ceiling"
690−
691−-- | A `Condition` is a boolean valued `Expression`. While SQL allows
692−-- conditions to have @NULL@, Squeal instead chooses to disallow @NULL@,
693−-- forcing one to handle the case of @NULL@ explicitly to produce
694−-- a `Condition`.
695−type Condition schema relations grouping params =
696− Expression schema relations grouping params ('NotNull 'PGbool)
697−
698−-- | >>> printSQL true
699−-- TRUE
700−true :: Condition schema relations grouping params
701−true = UnsafeExpression "TRUE"
702−
703−-- | >>> printSQL false
704−-- FALSE
705−false :: Condition schema relations grouping params
706−false = UnsafeExpression "FALSE"
707−
708−-- | >>> printSQL $ not_ true
709−-- (NOT TRUE)
710−not_
711− :: Condition schema relations grouping params
712− -> Condition schema relations grouping params
713−not_ = unsafeUnaryOp "NOT"
714−
715−-- | >>> printSQL $ true .&& false
716−-- (TRUE AND FALSE)
717−(.&&)
718− :: Condition schema relations grouping params
719− -> Condition schema relations grouping params
720− -> Condition schema relations grouping params
721−(.&&) = unsafeBinaryOp "AND"
722−
723−-- | >>> printSQL $ true .|| false
724−-- (TRUE OR FALSE)
725−(.||)
726− :: Condition schema relations grouping params
727− -> Condition schema relations grouping params
728− -> Condition schema relations grouping params
729−(.||) = unsafeBinaryOp "OR"
730−
731−-- | >>> :{
732−-- let
733−-- expression :: Expression schema relations grouping params (nullity 'PGint2)
734−-- expression = caseWhenThenElse [(true, 1), (false, 2)] 3
735−-- in printSQL expression
736−-- :}
737−-- CASE WHEN TRUE THEN 1 WHEN FALSE THEN 2 ELSE 3 END
738−caseWhenThenElse
739− :: [ ( Condition schema relations grouping params
740− , Expression schema relations grouping params (ty)
741− ) ]
742− -- ^ whens and thens
743− -> Expression schema relations grouping params (ty)
744− -- ^ else
745− -> Expression schema relations grouping params (ty)
746−caseWhenThenElse whenThens else_ = UnsafeExpression $ mconcat
747− [ "CASE"
748− , mconcat
749− [ mconcat
750− [ " WHEN ", renderExpression when_
751− , " THEN ", renderExpression then_
752− ]
753− | (when_,then_) <- whenThens
754− ]
755− , " ELSE ", renderExpression else_
756− , " END"
757− ]
758−
759−-- | >>> :{
760−-- let
761−-- expression :: Expression schema relations grouping params (nullity 'PGint2)
762−-- expression = ifThenElse true 1 0
763−-- in printSQL expression
764−-- :}
765−-- CASE WHEN TRUE THEN 1 ELSE 0 END
766−ifThenElse
767− :: Condition schema relations grouping params
768− -> Expression schema relations grouping params (ty) -- ^ then
769− -> Expression schema relations grouping params (ty) -- ^ else
770− -> Expression schema relations grouping params (ty)
771−ifThenElse if_ then_ else_ = caseWhenThenElse [(if_,then_)] else_
772−
773−-- | Comparison operations like `.==`, `./=`, `.>`, `.>=`, `.<` and `.<=`
774−-- will produce @NULL@s if one of their arguments is @NULL@.
775−--
776−-- >>> printSQL $ notNull true .== null_
777−-- (TRUE = NULL)
778−(.==)
779− :: Expression schema relations grouping params (nullity ty) -- ^ lhs
780− -> Expression schema relations grouping params (nullity ty) -- ^ rhs
781− -> Expression schema relations grouping params (nullity 'PGbool)
782−(.==) = unsafeBinaryOp "="
783−infix 4 .==
784−
785−-- | >>> printSQL $ notNull true ./= null_
786−-- (TRUE <> NULL)
787−(./=)
788− :: Expression schema relations grouping params (nullity ty) -- ^ lhs
789− -> Expression schema relations grouping params (nullity ty) -- ^ rhs
790− -> Expression schema relations grouping params (nullity 'PGbool)
791−(./=) = unsafeBinaryOp "<>"
792−infix 4 ./=
793−
794−-- | >>> printSQL $ notNull true .>= null_
795−-- (TRUE >= NULL)
796−(.>=)
797− :: Expression schema relations grouping params (nullity ty) -- ^ lhs
798− -> Expression schema relations grouping params (nullity ty) -- ^ rhs
799− -> Expression schema relations grouping params (nullity 'PGbool)
800−(.>=) = unsafeBinaryOp ">="
801−infix 4 .>=
802−
803−-- | >>> printSQL $ notNull true .< null_
804−-- (TRUE < NULL)
805−(.<)
806− :: Expression schema relations grouping params (nullity ty) -- ^ lhs
807− -> Expression schema relations grouping params (nullity ty) -- ^ rhs
808− -> Expression schema relations grouping params (nullity 'PGbool)
809−(.<) = unsafeBinaryOp "<"
810−infix 4 .<
811−
812−-- | >>> printSQL $ notNull true .<= null_
813−-- (TRUE <= NULL)
814−(.<=)
815− :: Expression schema relations grouping params (nullity ty) -- ^ lhs
816− -> Expression schema relations grouping params (nullity ty) -- ^ rhs
817− -> Expression schema relations grouping params (nullity 'PGbool)
818−(.<=) = unsafeBinaryOp "<="
819−infix 4 .<=
820−
821−-- | >>> printSQL $ notNull true .> null_
822−-- (TRUE > NULL)
823−(.>)
824− :: Expression schema relations grouping params (nullity ty) -- ^ lhs
825− -> Expression schema relations grouping params (nullity ty) -- ^ rhs
826− -> Expression schema relations grouping params (nullity 'PGbool)
827−(.>) = unsafeBinaryOp ">"
828−infix 4 .>
829−
830−-- | >>> printSQL currentDate
831−-- CURRENT_DATE
832−currentDate
833− :: Expression schema relations grouping params (nullity 'PGdate)
834−currentDate = UnsafeExpression "CURRENT_DATE"
835−
836−-- | >>> printSQL currentTime
837−-- CURRENT_TIME
838−currentTime
839− :: Expression schema relations grouping params (nullity 'PGtimetz)
840−currentTime = UnsafeExpression "CURRENT_TIME"
841−
842−-- | >>> printSQL currentTimestamp
843−-- CURRENT_TIMESTAMP
844−currentTimestamp
845− :: Expression schema relations grouping params (nullity 'PGtimestamptz)
846−currentTimestamp = UnsafeExpression "CURRENT_TIMESTAMP"
847−
848−-- | >>> printSQL localTime
849−-- LOCALTIME
850−localTime
851− :: Expression schema relations grouping params (nullity 'PGtime)
852−localTime = UnsafeExpression "LOCALTIME"
853−
854−-- | >>> printSQL localTimestamp
855−-- LOCALTIMESTAMP
856−localTimestamp
857− :: Expression schema relations grouping params (nullity 'PGtimestamp)
858−localTimestamp = UnsafeExpression "LOCALTIMESTAMP"
859−
860−{-----------------------------------------
861−text
862−-----------------------------------------}
422+-- | Contained by operators
423+class PGSubset ty where
424+ (@>) :: Operator (null0 ty) (null1 ty) ('Null 'PGbool)
425+ (@>) = unsafeBinaryOp "@>"
426+ (<@) :: Operator (null0 ty) (null1 ty) ('Null 'PGbool)
427+ (<@) = unsafeBinaryOp "<@"
428+instance PGSubset 'PGjsonb
429+instance PGSubset 'PGtsquery
430+instance PGSubset ('PGvararray ty)
431+instance PGSubset ('PGrange ty)
432+
433+class PGIntersect ty where
434+ (@&&) :: Operator (null0 ty) (null1 ty) ('Null 'PGbool)
435+ (@&&) = unsafeBinaryOp "&&"
436+instance PGIntersect ('PGvararray ty)
437+instance PGIntersect ('PGrange ty)
863438
864439instance IsString
865− (Expression schema relations grouping params (nullity 'PGtext)) where
440+ (Expression outer commons grp schemas params from (null 'PGtext)) where
866441 fromString str = UnsafeExpression $
867442 "E\'" <> fromString (escape =<< str) <> "\'"
868− where
869− escape = \case
870− '\NUL' -> "\\0"
871− '\'' -> "''"
872− '"' -> "\\\""
873− '\b' -> "\\b"
874− '\n' -> "\\n"
875− '\r' -> "\\r"
876− '\t' -> "\\t"
877− '\\' -> "\\\\"
878− c -> [c]
443+instance IsString
444+ (Expression outer commons grp schemas params from (null 'PGtsvector)) where
445+ fromString str = UnsafeExpression . parenthesized . (<> " :: tsvector") $
446+ "E\'" <> fromString (escape =<< str) <> "\'"
447+instance IsString
448+ (Expression outer commons grp schemas params from (null 'PGtsquery)) where
449+ fromString str = UnsafeExpression . parenthesized . (<> " :: tsquery") $
450+ "E\'" <> fromString (escape =<< str) <> "\'"
879451
880452instance Semigroup
881− (Expression schema relations grouping params (nullity 'PGtext)) where
453+ (Expression outer commons grp schemas params from (null ('PGvararray ty))) where
454+ (<>) = unsafeBinaryOp "||"
455+instance Semigroup
456+ (Expression outer commons grp schemas params from (null 'PGjsonb)) where
457+ (<>) = unsafeBinaryOp "||"
458+instance Semigroup
459+ (Expression outer commons grp schemas params from (null 'PGtext)) where
460+ (<>) = unsafeBinaryOp "||"
461+instance Semigroup
462+ (Expression outer commons grp schemas params from (null 'PGtsvector)) where
882463 (<>) = unsafeBinaryOp "||"
883464
884465instance Monoid
885− (Expression schema relations grouping params (nullity 'PGtext)) where
466+ (Expression outer commons grp schemas params from (null 'PGtext)) where
467+ mempty = fromString ""
468+ mappend = (<>)
469+instance Monoid
470+ (Expression outer commons grp schemas params from (null 'PGtsvector)) where
886471 mempty = fromString ""
887472 mappend = (<>)
888−
889−-- | >>> printSQL $ lower "ARRRGGG"
890−-- lower(E'ARRRGGG')
891−lower
892− :: Expression schema relations grouping params (nullity 'PGtext)
893− -- ^ string to lower case
894− -> Expression schema relations grouping params (nullity 'PGtext)
895−lower = unsafeFunction "lower"
896−
897−-- | >>> printSQL $ upper "eeee"
898−-- upper(E'eeee')
899−upper
900− :: Expression schema relations grouping params (nullity 'PGtext)
901− -- ^ string to upper case
902− -> Expression schema relations grouping params (nullity 'PGtext)
903−upper = unsafeFunction "upper"
904−
905−-- | >>> printSQL $ charLength "four"
906−-- char_length(E'four')
907−charLength
908− :: Expression schema relations grouping params (nullity 'PGtext)
909− -- ^ string to measure
910− -> Expression schema relations grouping params (nullity 'PGint4)
911−charLength = unsafeFunction "char_length"
912−
913−-- | The `like` expression returns true if the @string@ matches
914−-- the supplied @pattern@. If @pattern@ does not contain percent signs
915−-- or underscores, then the pattern only represents the string itself;
916−-- in that case `like` acts like the equals operator. An underscore (_)
917−-- in pattern stands for (matches) any single character; a percent sign (%)
918−-- matches any sequence of zero or more characters.
919−--
920−-- >>> printSQL $ "abc" `like` "a%"
921−-- (E'abc' LIKE E'a%')
922−like
923− :: Expression schema relations grouping params (nullity 'PGtext)
924− -- ^ string
925− -> Expression schema relations grouping params (nullity 'PGtext)
926− -- ^ pattern
927− -> Expression schema relations grouping params (nullity 'PGbool)
928−like = unsafeBinaryOp "LIKE"
929−
930−{-----------------------------------------
931− -- json and jsonb support
932−
933−See https://www.postgresql.org/docs/10/static/functions-json.html -- most
934−comments lifted directly from this page.
935−
936−Table 9.44: json and jsonb operators
937−-----------------------------------------}
938−
939−-- | Get JSON value (object field or array element) at a key.
940−(.->)
941− :: (PGjson_ json, PGjsonKey key)
942− => Expression schema relations grouping params (nullity json)
943− -> Expression schema relations grouping params (nullity key)
944− -> Expression schema relations grouping params ('Null json)
945−(.->) = unsafeBinaryOp "->"
946−
947−-- | Get JSON value (object field or array element) at a key, as text.
948−(.->>)
949− :: (PGjson_ json, PGjsonKey key)
950− => Expression schema relations grouping params (nullity json)
951− -> Expression schema relations grouping params (nullity key)
952− -> Expression schema relations grouping params ('Null 'PGtext)
953−(.->>) = unsafeBinaryOp "->>"
954−
955−-- | Get JSON value at a specified path.
956−(.#>)
957− :: (PGjson_ json, PGtextArray "(.#>)" path)
958− => Expression schema relations grouping params (nullity json)
959− -> Expression schema relations grouping params (nullity path)
960− -> Expression schema relations grouping params ('Null json)
961−(.#>) = unsafeBinaryOp "#>"
962−
963−-- | Get JSON value at a specified path as text.
964−(.#>>)
965− :: (PGjson_ json, PGtextArray "(.#>>)" path)
966− => Expression schema relations grouping params (nullity json)
967− -> Expression schema relations grouping params (nullity path)
968− -> Expression schema relations grouping params ('Null 'PGtext)
969−(.#>>) = unsafeBinaryOp "#>>"
970−
971−-- Additional jsonb operators
972−
973−-- | Does the left JSON value contain the right JSON path/value entries at the
974−-- top level?
975−(.@>)
976− :: Expression schema relations grouping params (nullity 'PGjsonb)
977− -> Expression schema relations grouping params (nullity 'PGjsonb)
978− -> Condition schema relations grouping params
979−(.@>) = unsafeBinaryOp "@>"
980−
981−-- | Are the left JSON path/value entries contained at the top level within the
982−-- right JSON value?
983−(.<@)
984− :: Expression schema relations grouping params (nullity 'PGjsonb)
985− -> Expression schema relations grouping params (nullity 'PGjsonb)
986− -> Condition schema relations grouping params
987−(.<@) = unsafeBinaryOp "<@"
988−
989−-- | Does the string exist as a top-level key within the JSON value?
990−(.?)
991− :: Expression schema relations grouping params (nullity 'PGjsonb)
992− -> Expression schema relations grouping params (nullity 'PGtext)
993− -> Condition schema relations grouping params
994−(.?) = unsafeBinaryOp "?"
995−
996−-- | Do any of these array strings exist as top-level keys?
997−(.?|)
998− :: Expression schema relations grouping params (nullity 'PGjsonb)
999− -> Expression schema relations grouping params (nullity ('PGvararray 'PGtext))
1000− -> Condition schema relations grouping params
1001−(.?|) = unsafeBinaryOp "?|"
1002−
1003−-- | Do all of these array strings exist as top-level keys?
1004−(.?&)
1005− :: Expression schema relations grouping params (nullity 'PGjsonb)
1006− -> Expression schema relations grouping params (nullity ('PGvararray 'PGtext))
1007− -> Condition schema relations grouping params
1008−(.?&) = unsafeBinaryOp "?&"
1009−
1010−-- | Concatenate two jsonb values into a new jsonb value.
1011−instance
1012− Semigroup (Expression schema relations grouping param (nullity 'PGjsonb)) where
1013− (<>) = unsafeBinaryOp "||"
1014−
1015−-- | Delete a key or keys from a JSON object, or remove an array element.
1016−--
1017−-- If the right operand is..
1018−--
1019−-- @ text @: Delete key/value pair or string element from left operand. Key/value pairs
1020−-- are matched based on their key value.
1021−--
1022−-- @ text[] @: Delete multiple key/value pairs or string elements
1023−-- from left operand. Key/value pairs are matched based on their key value.
1024−--
1025−-- @ integer @: Delete the array element with specified index (Negative integers
1026−-- count from the end). Throws an error if top level container is not an array.
1027−(.-.)
1028− :: (key `In` '[ 'PGtext, 'PGvararray 'PGtext, 'PGint4, 'PGint2 ]) -- hlint error without parens here
1029− => Expression schema relations grouping params (nullity 'PGjsonb)
1030− -> Expression schema relations grouping params (nullity key)
1031− -> Expression schema relations grouping params (nullity 'PGjsonb)
1032−(.-.) = unsafeBinaryOp "-"
1033−
1034−-- | Delete the field or element with specified path (for JSON arrays, negative
1035−-- integers count from the end)
1036−(#-.)
1037− :: PGtextArray "(#-.)" arrayty
1038− => Expression schema relations grouping params (nullity 'PGjsonb)
1039− -> Expression schema relations grouping params (nullity arrayty)
1040− -> Expression schema relations grouping params (nullity 'PGjsonb)
1041−(#-.) = unsafeBinaryOp "#-"
1042−
1043−{-----------------------------------------
1044−Table 9.45: JSON creation functions
1045−-----------------------------------------}
1046−
1047−-- | Literal binary JSON
1048−jsonbLit :: JSON.Value -> Expression schema relations grouping params (nullity 'PGjsonb)
1049−jsonbLit = cast jsonb . UnsafeExpression . singleQuotedUtf8 . toStrict . JSON.encode
1050−
1051−-- | Literal JSON
1052−jsonLit :: JSON.Value -> Expression schema relations grouping params (nullity 'PGjson)
1053−jsonLit = cast json . UnsafeExpression . singleQuotedUtf8 . toStrict . JSON.encode
1054−
1055−-- | Returns the value as json. Arrays and composites are converted
1056−-- (recursively) to arrays and objects; otherwise, if there is a cast from the
1057−-- type to json, the cast function will be used to perform the conversion;
1058−-- otherwise, a scalar value is produced. For any scalar type other than a
1059−-- number, a Boolean, or a null value, the text representation will be used, in
1060−-- such a fashion that it is a valid json value.
1061−toJson
1062− :: Expression schema relations grouping params (nullity ty)
1063− -> Expression schema relations grouping params (nullity 'PGjson)
1064−toJson = unsafeFunction "to_json"
1065−
1066−-- | Returns the value as jsonb. Arrays and composites are converted
1067−-- (recursively) to arrays and objects; otherwise, if there is a cast from the
1068−-- type to json, the cast function will be used to perform the conversion;
1069−-- otherwise, a scalar value is produced. For any scalar type other than a
1070−-- number, a Boolean, or a null value, the text representation will be used, in
1071−-- such a fashion that it is a valid jsonb value.
1072−toJsonb
1073− :: Expression schema relations grouping params (nullity ty)
1074− -> Expression schema relations grouping params (nullity 'PGjsonb)
1075−toJsonb = unsafeFunction "to_jsonb"
1076−
1077−-- | Returns the array as a JSON array. A PostgreSQL multidimensional array
1078−-- becomes a JSON array of arrays.
1079−arrayToJson
1080− :: PGarray "arrayToJson" arr
1081− => Expression schema relations grouping params (nullity arr)
1082− -> Expression schema relations grouping params (nullity 'PGjson)
1083−arrayToJson = unsafeFunction "array_to_json"
1084−
1085−-- | Returns the row as a JSON object.
1086−rowToJson
1087− :: Expression schema relations grouping params (nullity ('PGcomposite ty))
1088− -> Expression schema relations grouping params (nullity 'PGjson)
1089−rowToJson = unsafeFunction "row_to_json"
1090−
1091−-- | Builds a possibly-heterogeneously-typed JSON array out of a variadic
1092−-- argument list.
1093−jsonBuildArray
1094− :: SListI elems
1095− => NP (Expression schema relations grouping params) elems
1096− -> Expression schema relations grouping params (nullity 'PGjson)
1097−jsonBuildArray = unsafeVariadicFunction "json_build_array"
1098−
1099−-- | Builds a possibly-heterogeneously-typed (binary) JSON array out of a
1100−-- variadic argument list.
1101−jsonbBuildArray
1102− :: SListI elems
1103− => NP (Expression schema relations grouping params) elems
1104− -> Expression schema relations grouping params (nullity 'PGjsonb)
1105−jsonbBuildArray = unsafeVariadicFunction "jsonb_build_array"
1106−
1107−unsafeRowFunction
1108− :: All Top elems
1109− => NP (Aliased (Expression schema relations grouping params)) elems
1110− -> [ByteString]
1111−unsafeRowFunction =
1112− (`appEndo` []) . hcfoldMap (Proxy :: Proxy Top)
1113− (\(col `As` name) -> Endo $ \xs ->
1114− renderAliasString name : renderExpression col : xs)
1115−
1116−-- | Builds a possibly-heterogeneously-typed JSON object out of a variadic
1117−-- argument list. The elements of the argument list must alternate between text
1118−-- and values.
1119−jsonBuildObject
1120− :: All Top elems
1121− => NP (Aliased (Expression schema relations grouping params)) elems
1122− -> Expression schema relations grouping params (nullity 'PGjson)
1123−jsonBuildObject
1124− = unsafeFunction "json_build_object"
1125− . UnsafeExpression
1126− . commaSeparated
1127− . unsafeRowFunction
1128−
1129−-- | Builds a possibly-heterogeneously-typed (binary) JSON object out of a
1130−-- variadic argument list. The elements of the argument list must alternate
1131−-- between text and values.
1132−jsonbBuildObject
1133− :: All Top elems
1134− => NP (Aliased (Expression schema relations grouping params)) elems
1135− -> Expression schema relations grouping params (nullity 'PGjsonb)
1136−jsonbBuildObject
1137− = unsafeFunction "jsonb_build_object"
1138− . UnsafeExpression
1139− . commaSeparated
1140− . unsafeRowFunction
1141−
1142−-- | Builds a JSON object out of a text array. The array must have either
1143−-- exactly one dimension with an even number of members, in which case they are
1144−-- taken as alternating key/value pairs, or two dimensions such that each inner
1145−-- array has exactly two elements, which are taken as a key/value pair.
1146−jsonObject
1147− :: PGarrayOf "jsonObject" arr 'PGtext
1148− => Expression schema relations grouping params (nullity arr)
1149− -> Expression schema relations grouping params (nullity 'PGjson)
1150−jsonObject = unsafeFunction "json_object"
1151−
1152−-- | Builds a binary JSON object out of a text array. The array must have either
1153−-- exactly one dimension with an even number of members, in which case they are
1154−-- taken as alternating key/value pairs, or two dimensions such that each inner
1155−-- array has exactly two elements, which are taken as a key/value pair.
1156−jsonbObject
1157− :: PGarrayOf "jsonbObject" arr 'PGtext
1158− => Expression schema relations grouping params (nullity arr)
1159− -> Expression schema relations grouping params (nullity 'PGjsonb)
1160−jsonbObject = unsafeFunction "jsonb_object"
1161−
1162−-- | This is an alternate form of 'jsonObject' that takes two arrays; one for
1163−-- keys and one for values, that are zipped pairwise to create a JSON object.
1164−jsonZipObject
1165− :: ( PGarrayOf "jsonZipObject" keysArray 'PGtext
1166− , PGarrayOf "jsonZipObject" valuesArray 'PGtext)
1167− => Expression schema relations grouping params (nullity keysArray)
1168− -> Expression schema relations grouping params (nullity valuesArray)
1169− -> Expression schema relations grouping params (nullity 'PGjson)
1170−jsonZipObject ks vs =
1171− unsafeVariadicFunction "json_object" (ks :* vs :* Nil)
1172−
1173−-- | This is an alternate form of 'jsonObject' that takes two arrays; one for
1174−-- keys and one for values, that are zipped pairwise to create a binary JSON
1175−-- object.
1176−jsonbZipObject
1177− :: ( PGarrayOf "jsonbZipObject" keysArray 'PGtext
1178− , PGarrayOf "jsonbZipObject" valuesArray 'PGtext)
1179− => Expression schema relations grouping params (nullity keysArray)
1180− -> Expression schema relations grouping params (nullity valuesArray)
1181− -> Expression schema relations grouping params (nullity 'PGjsonb)
1182−jsonbZipObject ks vs =
1183− unsafeVariadicFunction "jsonb_object" (ks :* vs :* Nil)
1184−
1185−{-----------------------------------------
1186−Table 9.46: JSON processing functions
1187−-----------------------------------------}
1188−
1189−-- | Returns the number of elements in the outermost JSON array.
1190−jsonArrayLength
1191− :: Expression schema relations grouping params (nullity 'PGjson)
1192− -> Expression schema relations grouping params (nullity 'PGint4)
1193−jsonArrayLength = unsafeFunction "json_array_length"
1194−
1195−-- | Returns the number of elements in the outermost binary JSON array.
1196−jsonbArrayLength
1197− :: Expression schema relations grouping params (nullity 'PGjsonb)
1198− -> Expression schema relations grouping params (nullity 'PGint4)
1199−jsonbArrayLength = unsafeFunction "jsonb_array_length"
1200−
1201−-- | Returns JSON value pointed to by the given path (equivalent to #>
1202−-- operator).
1203−jsonExtractPath
1204− :: SListI elems
1205− => Expression schema relations grouping params (nullity 'PGjson)
1206− -> NP (Expression schema relations grouping params) elems
1207− -> Expression schema relations grouping params (nullity 'PGjsonb)
1208−jsonExtractPath x xs =
1209− unsafeVariadicFunction "json_extract_path" (x :* xs)
1210−
1211−-- | Returns JSON value pointed to by the given path (equivalent to #>
1212−-- operator).
1213−jsonbExtractPath
1214− :: SListI elems
1215− => Expression schema relations grouping params (nullity 'PGjsonb)
1216− -> NP (Expression schema relations grouping params) elems
1217− -> Expression schema relations grouping params (nullity 'PGjsonb)
1218−jsonbExtractPath x xs =
1219− unsafeVariadicFunction "jsonb_extract_path" (x :* xs)
1220−
1221−-- | Returns JSON value pointed to by the given path (equivalent to #>
1222−-- operator), as text.
1223−jsonExtractPathAsText
1224− :: SListI elems
1225− => Expression schema relations grouping params (nullity 'PGjson)
1226− -> NP (Expression schema relations grouping params) elems
1227− -> Expression schema relations grouping params (nullity 'PGjson)
1228−jsonExtractPathAsText x xs =
1229− unsafeVariadicFunction "json_extract_path_text" (x :* xs)
1230−
1231−-- | Returns JSON value pointed to by the given path (equivalent to #>
1232−-- operator), as text.
1233−jsonbExtractPathAsText
1234− :: SListI elems
1235− => Expression schema relations grouping params (nullity 'PGjsonb)
1236− -> NP (Expression schema relations grouping params) elems
1237− -> Expression schema relations grouping params (nullity 'PGjsonb)
1238−jsonbExtractPathAsText x xs =
1239− unsafeVariadicFunction "jsonb_extract_path_text" (x :* xs)
1240−
1241−-- | Returns set of keys in the outermost JSON object.
1242−jsonObjectKeys
1243− :: Expression schema relations grouping params (nullity 'PGjson)
1244− -> Expression schema relations grouping params (nullity 'PGtext)
1245−jsonObjectKeys = unsafeFunction "json_object_keys"
1246−
1247−-- | Returns set of keys in the outermost JSON object.
1248−jsonbObjectKeys
1249− :: Expression schema relations grouping params (nullity 'PGjsonb)
1250− -> Expression schema relations grouping params (nullity 'PGtext)
1251−jsonbObjectKeys = unsafeFunction "jsonb_object_keys"
1252−
1253−-- | Returns the type of the outermost JSON value as a text string. Possible
1254−-- types are object, array, string, number, boolean, and null.
1255−jsonTypeof
1256− :: Expression schema relations grouping params (nullity 'PGjson)
1257− -> Expression schema relations grouping params (nullity 'PGtext)
1258−jsonTypeof = unsafeFunction "json_typeof"
1259−
1260−-- | Returns the type of the outermost binary JSON value as a text string.
1261−-- Possible types are object, array, string, number, boolean, and null.
1262−jsonbTypeof
1263− :: Expression schema relations grouping params (nullity 'PGjsonb)
1264− -> Expression schema relations grouping params (nullity 'PGtext)
1265−jsonbTypeof = unsafeFunction "jsonb_typeof"
1266−
1267−-- | Returns its argument with all object fields that have null values omitted.
1268−-- Other null values are untouched.
1269−jsonStripNulls
1270− :: Expression schema relations grouping params (nullity 'PGjson)
1271− -> Expression schema relations grouping params (nullity 'PGjson)
1272−jsonStripNulls = unsafeFunction "json_strip_nulls"
1273−
1274−-- | Returns its argument with all object fields that have null values omitted.
1275−-- Other null values are untouched.
1276−jsonbStripNulls
1277− :: Expression schema relations grouping params (nullity 'PGjsonb)
1278− -> Expression schema relations grouping params (nullity 'PGjsonb)
1279−jsonbStripNulls = unsafeFunction "jsonb_strip_nulls"
1280−
1281−-- | @ jsonbSet target path new_value create_missing @
1282−--
1283−-- Returns target with the section designated by path replaced by new_value,
1284−-- or with new_value added if create_missing is true ( default is true) and the
1285−-- item designated by path does not exist. As with the path orientated
1286−-- operators, negative integers that appear in path count from the end of JSON
1287−-- arrays.
1288−jsonbSet
1289− :: PGtextArray "jsonbSet" arr
1290− => Expression schema relations grouping params (nullity 'PGjsonb)
1291− -> Expression schema relations grouping params (nullity arr)
1292− -> Expression schema relations grouping params (nullity 'PGjsonb)
1293− -> Maybe (Expression schema relations grouping params (nullity 'PGbool))
1294− -> Expression schema relations grouping params (nullity 'PGjsonb)
1295−jsonbSet tgt path val createMissing = case createMissing of
1296− Just m -> unsafeVariadicFunction "jsonb_set" (tgt :* path :* val :* m :* Nil)
1297− Nothing -> unsafeVariadicFunction "jsonb_set" (tgt :* path :* val :* Nil)
1298−
1299−-- | @ jsonbInsert target path new_value insert_after @
1300−--
1301−-- Returns target with new_value inserted. If target section designated by
1302−-- path is in a JSONB array, new_value will be inserted before target or after
1303−-- if insert_after is true (default is false). If target section designated by
1304−-- path is in JSONB object, new_value will be inserted only if target does not
1305−-- exist. As with the path orientated operators, negative integers that appear
1306−-- in path count from the end of JSON arrays.
1307−jsonbInsert
1308− :: PGtextArray "jsonbInsert" arr
1309− => Expression schema relations grouping params (nullity 'PGjsonb)
1310− -> Expression schema relations grouping params (nullity arr)
1311− -> Expression schema relations grouping params (nullity 'PGjsonb)
1312− -> Maybe (Expression schema relations grouping params (nullity 'PGbool))
1313− -> Expression schema relations grouping params (nullity 'PGjsonb)
1314−jsonbInsert tgt path val insertAfter = case insertAfter of
1315− Just i -> unsafeVariadicFunction "jsonb_insert" (tgt :* path :* val :* i :* Nil)
1316− Nothing -> unsafeVariadicFunction "jsonb_insert" (tgt :* path :* val :* Nil)
1317−
1318−-- | Returns its argument as indented JSON text.
1319−jsonbPretty
1320− :: Expression schema relations grouping params (nullity 'PGjsonb)
1321− -> Expression schema relations grouping params (nullity 'PGtext)
1322−jsonbPretty = unsafeFunction "jsonb_pretty"
1323−
1324−{-----------------------------------------
1325−aggregation
1326−-----------------------------------------}
1327−
1328−-- | escape hatch to define aggregate functions
1329−unsafeAggregate
1330− :: ByteString -- ^ aggregate function
1331− -> Expression schema relations 'Ungrouped params (xty)
1332− -> Expression schema relations ('Grouped bys) params (yty)
1333−unsafeAggregate fun x = UnsafeExpression $ mconcat
1334− [fun, "(", renderExpression x, ")"]
1335−
1336−-- | escape hatch to define aggregate functions over distinct values
1337−unsafeAggregateDistinct
1338− :: ByteString -- ^ aggregate function
1339− -> Expression schema relations 'Ungrouped params (xty)
1340− -> Expression schema relations ('Grouped bys) params (yty)
1341−unsafeAggregateDistinct fun x = UnsafeExpression $ mconcat
1342− [fun, "(DISTINCT ", renderExpression x, ")"]
1343−
1344−-- | >>> :{
1345−-- let
1346−-- expression :: Expression schema '[tab ::: '["col" ::: 'Null 'PGnumeric]] ('Grouped bys) params ('Null 'PGnumeric)
1347−-- expression = sum_ #col
1348−-- in printSQL expression
1349−-- :}
1350−-- sum("col")
1351−sum_
1352− :: PGNum ty
1353− => Expression schema relations 'Ungrouped params (nullity ty)
1354− -- ^ what to sum
1355− -> Expression schema relations ('Grouped bys) params (nullity ty)
1356−sum_ = unsafeAggregate "sum"
1357−
1358−-- | >>> :{
1359−-- let
1360−-- expression :: Expression schema '[tab ::: '["col" ::: nullity 'PGnumeric]] ('Grouped bys) params (nullity 'PGnumeric)
1361−-- expression = sumDistinct #col
1362−-- in printSQL expression
1363−-- :}
1364−-- sum(DISTINCT "col")
1365−sumDistinct
1366− :: PGNum ty
1367− => Expression schema relations 'Ungrouped params (nullity ty)
1368− -- ^ what to sum
1369− -> Expression schema relations ('Grouped bys) params (nullity ty)
1370−sumDistinct = unsafeAggregateDistinct "sum"
1371−
1372−-- | A constraint for `PGType`s that you can take averages of and the resulting
1373−-- `PGType`.
1374−class PGAvg ty avg | ty -> avg where
1375− avg, avgDistinct
1376− :: Expression schema relations 'Ungrouped params (nullity ty)
1377− -- ^ what to average
1378− -> Expression schema relations ('Grouped bys) params (nullity avg)
1379− avg = unsafeAggregate "avg"
1380− avgDistinct = unsafeAggregateDistinct "avg"
1381−instance PGAvg 'PGint2 'PGnumeric
1382−instance PGAvg 'PGint4 'PGnumeric
1383−instance PGAvg 'PGint8 'PGnumeric
1384−instance PGAvg 'PGnumeric 'PGnumeric
1385−instance PGAvg 'PGfloat4 'PGfloat8
1386−instance PGAvg 'PGfloat8 'PGfloat8
1387−instance PGAvg 'PGinterval 'PGinterval
1388−
1389−-- | >>> :{
1390−-- let
1391−-- expression :: Expression schema '[tab ::: '["col" ::: nullity 'PGint4]] (Grouped bys) params (nullity 'PGint4)
1392−-- expression = bitAnd #col
1393−-- in printSQL expression
1394−-- :}
1395−-- bit_and("col")
1396−bitAnd
1397− :: PGIntegral int
1398− => Expression schema relations 'Ungrouped params (nullity int)
1399− -- ^ what to aggregate
1400− -> Expression schema relations ('Grouped bys) params (nullity int)
1401−bitAnd = unsafeAggregate "bit_and"
1402−
1403−-- | >>> :{
1404−-- let
1405−-- expression :: Expression schema '[tab ::: '["col" ::: nullity 'PGint4]] (Grouped bys) params (nullity 'PGint4)
1406−-- expression = bitOr #col
1407−-- in printSQL expression
1408−-- :}
1409−-- bit_or("col")
1410−bitOr
1411− :: PGIntegral int
1412− => Expression schema relations 'Ungrouped params (nullity int)
1413− -- ^ what to aggregate
1414− -> Expression schema relations ('Grouped bys) params (nullity int)
1415−bitOr = unsafeAggregate "bit_or"
1416−
1417−-- | >>> :{
1418−-- let
1419−-- expression :: Expression schema '[tab ::: '["col" ::: nullity 'PGint4]] (Grouped bys) params (nullity 'PGint4)
1420−-- expression = bitAndDistinct #col
1421−-- in printSQL expression
1422−-- :}
1423−-- bit_and(DISTINCT "col")
1424−bitAndDistinct
1425− :: PGIntegral int
1426− => Expression schema relations 'Ungrouped params (nullity int)
1427− -- ^ what to aggregate
1428− -> Expression schema relations ('Grouped bys) params (nullity int)
1429−bitAndDistinct = unsafeAggregateDistinct "bit_and"
1430−
1431−-- | >>> :{
1432−-- let
1433−-- expression :: Expression schema '[tab ::: '["col" ::: nullity 'PGint4]] (Grouped bys) params (nullity 'PGint4)
1434−-- expression = bitOrDistinct #col
1435−-- in printSQL expression
1436−-- :}
1437−-- bit_or(DISTINCT "col")
1438−bitOrDistinct
1439− :: PGIntegral int
1440− => Expression schema relations 'Ungrouped params (nullity int)
1441− -- ^ what to aggregate
1442− -> Expression schema relations ('Grouped bys) params (nullity int)
1443−bitOrDistinct = unsafeAggregateDistinct "bit_or"
1444−
1445−-- | >>> :{
1446−-- let
1447−-- expression :: Expression schema '[tab ::: '["col" ::: nullity 'PGbool]] (Grouped bys) params (nullity 'PGbool)
1448−-- expression = boolAnd #col
1449−-- in printSQL expression
1450−-- :}
1451−-- bool_and("col")
1452−boolAnd
1453− :: Expression schema relations 'Ungrouped params (nullity 'PGbool)
1454− -- ^ what to aggregate
1455− -> Expression schema relations ('Grouped bys) params (nullity 'PGbool)
1456−boolAnd = unsafeAggregate "bool_and"
1457−
1458−-- | >>> :{
1459−-- let
1460−-- expression :: Expression schema '[tab ::: '["col" ::: nullity 'PGbool]] (Grouped bys) params (nullity 'PGbool)
1461−-- expression = boolOr #col
1462−-- in printSQL expression
1463−-- :}
1464−-- bool_or("col")
1465−boolOr
1466− :: Expression schema relations 'Ungrouped params (nullity 'PGbool)
1467− -- ^ what to aggregate
1468− -> Expression schema relations ('Grouped bys) params (nullity 'PGbool)
1469−boolOr = unsafeAggregate "bool_or"
1470−
1471−-- | >>> :{
1472−-- let
1473−-- expression :: Expression schema '[tab ::: '["col" ::: nullity 'PGbool]] (Grouped bys) params (nullity 'PGbool)
1474−-- expression = boolAndDistinct #col
1475−-- in printSQL expression
1476−-- :}
1477−-- bool_and(DISTINCT "col")
1478−boolAndDistinct
1479− :: Expression schema relations 'Ungrouped params (nullity 'PGbool)
1480− -- ^ what to aggregate
1481− -> Expression schema relations ('Grouped bys) params (nullity 'PGbool)
1482−boolAndDistinct = unsafeAggregateDistinct "bool_and"
1483−
1484−-- | >>> :{
1485−-- let
1486−-- expression :: Expression schema '[tab ::: '["col" ::: nullity 'PGbool]] (Grouped bys) params (nullity 'PGbool)
1487−-- expression = boolOrDistinct #col
1488−-- in printSQL expression
1489−-- :}
1490−-- bool_or(DISTINCT "col")
1491−boolOrDistinct
1492− :: Expression schema relations 'Ungrouped params (nullity 'PGbool)
1493− -- ^ what to aggregate
1494− -> Expression schema relations ('Grouped bys) params (nullity 'PGbool)
1495−boolOrDistinct = unsafeAggregateDistinct "bool_or"
1496−
1497−-- | A special aggregation that does not require an input
1498−--
1499−-- >>> printSQL countStar
1500−-- count(*)
1501−countStar
1502− :: Expression schema relations ('Grouped bys) params ('NotNull 'PGint8)
1503−countStar = UnsafeExpression $ "count(*)"
1504−
1505−-- | >>> :{
1506−-- let
1507−-- expression :: Expression schema '[tab ::: '["col" ::: nullity ty]] (Grouped bys) params ('NotNull 'PGint8)
1508−-- expression = count #col
1509−-- in printSQL expression
1510−-- :}
1511−-- count("col")
1512−count
1513− :: Expression schema relations 'Ungrouped params ty
1514− -- ^ what to count
1515− -> Expression schema relations ('Grouped bys) params ('NotNull 'PGint8)
1516−count = unsafeAggregate "count"
1517−
1518−-- | >>> :{
1519−-- let
1520−-- expression :: Expression schema '[tab ::: '["col" ::: nullity ty]] (Grouped bys) params ('NotNull 'PGint8)
1521−-- expression = countDistinct #col
1522−-- in printSQL expression
1523−-- :}
1524−-- count(DISTINCT "col")
1525−countDistinct
1526− :: Expression schema relations 'Ungrouped params ty
1527− -- ^ what to count
1528− -> Expression schema relations ('Grouped bys) params ('NotNull 'PGint8)
1529−countDistinct = unsafeAggregateDistinct "count"
1530−
1531−-- | synonym for `boolAnd`
1532−--
1533−-- >>> :{
1534−-- let
1535−-- expression :: Expression schema '[tab ::: '["col" ::: nullity 'PGbool]] (Grouped bys) params (nullity 'PGbool)
1536−-- expression = every #col
1537−-- in printSQL expression
1538−-- :}
1539−-- every("col")
1540−every
1541− :: Expression schema relations 'Ungrouped params (nullity 'PGbool)
1542− -- ^ what to aggregate
1543− -> Expression schema relations ('Grouped bys) params (nullity 'PGbool)
1544−every = unsafeAggregate "every"
1545−
1546−-- | synonym for `boolAndDistinct`
1547−--
1548−-- >>> :{
1549−-- let
1550−-- expression :: Expression schema '[tab ::: '["col" ::: nullity 'PGbool]] (Grouped bys) params (nullity 'PGbool)
1551−-- expression = everyDistinct #col
1552−-- in printSQL expression
1553−-- :}
1554−-- every(DISTINCT "col")
1555−everyDistinct
1556− :: Expression schema relations 'Ungrouped params (nullity 'PGbool)
1557− -- ^ what to aggregate
1558− -> Expression schema relations ('Grouped bys) params (nullity 'PGbool)
1559−everyDistinct = unsafeAggregateDistinct "every"
1560−
1561−-- | minimum and maximum aggregation
1562−max_, min_, maxDistinct, minDistinct
1563− :: Expression schema relations 'Ungrouped params (nullity ty)
1564− -- ^ what to aggregate
1565− -> Expression schema relations ('Grouped bys) params (nullity ty)
1566−max_ = unsafeAggregate "max"
1567−min_ = unsafeAggregate "min"
1568−maxDistinct = unsafeAggregateDistinct "max"
1569−minDistinct = unsafeAggregateDistinct "min"
1570−
1571−{-----------------------------------------
1572−type expressions
1573−-----------------------------------------}
1574−
1575−-- | `TypeExpression`s are used in `cast`s and `createTable` commands.
1576−newtype TypeExpression (schema :: SchemaType) (ty :: PGType)
1577− = UnsafeTypeExpression { renderTypeExpression :: ByteString }
1578− deriving (GHC.Generic,Show,Eq,Ord,NFData)
1579−
1580−instance (Has alias schema ('Typedef ty))
1581− => IsLabel alias (TypeExpression schema ty) where
1582− fromLabel = UnsafeTypeExpression (renderAlias (fromLabel @alias))
1583−
1584−-- | logical Boolean (true/false)
1585−bool :: TypeExpression schema 'PGbool
1586−bool = UnsafeTypeExpression "bool"
1587−-- | signed two-byte integer
1588−int2, smallint :: TypeExpression schema 'PGint2
1589−int2 = UnsafeTypeExpression "int2"
1590−smallint = UnsafeTypeExpression "smallint"
1591−-- | signed four-byte integer
1592−int4, int, integer :: TypeExpression schema 'PGint4
1593−int4 = UnsafeTypeExpression "int4"
1594−int = UnsafeTypeExpression "int"
1595−integer = UnsafeTypeExpression "integer"
1596−-- | signed eight-byte integer
1597−int8, bigint :: TypeExpression schema 'PGint8
1598−int8 = UnsafeTypeExpression "int8"
1599−bigint = UnsafeTypeExpression "bigint"
1600−-- | arbitrary precision numeric type
1601−numeric :: TypeExpression schema 'PGnumeric
1602−numeric = UnsafeTypeExpression "numeric"
1603−-- | single precision floating-point number (4 bytes)
1604−float4, real :: TypeExpression schema 'PGfloat4
1605−float4 = UnsafeTypeExpression "float4"
1606−real = UnsafeTypeExpression "real"
1607−-- | double precision floating-point number (8 bytes)
1608−float8, doublePrecision :: TypeExpression schema 'PGfloat8
1609−float8 = UnsafeTypeExpression "float8"
1610−doublePrecision = UnsafeTypeExpression "double precision"
1611−-- | variable-length character string
1612−text :: TypeExpression schema 'PGtext
1613−text = UnsafeTypeExpression "text"
1614−-- | fixed-length character string
1615−char, character
1616− :: (KnownNat n, 1 <= n)
1617− => proxy n
1618− -> TypeExpression schema ('PGchar n)
1619−char p = UnsafeTypeExpression $ "char(" <> renderNat p <> ")"
1620−character p = UnsafeTypeExpression $ "character(" <> renderNat p <> ")"
1621−-- | variable-length character string
1622−varchar, characterVarying
1623− :: (KnownNat n, 1 <= n)
1624− => proxy n
1625− -> TypeExpression schema ('PGvarchar n)
1626−varchar p = UnsafeTypeExpression $ "varchar(" <> renderNat p <> ")"
1627−characterVarying p = UnsafeTypeExpression $
1628− "character varying(" <> renderNat p <> ")"
1629−-- | binary data ("byte array")
1630−bytea :: TypeExpression schema 'PGbytea
1631−bytea = UnsafeTypeExpression "bytea"
1632−-- | date and time (no time zone)
1633−timestamp :: TypeExpression schema 'PGtimestamp
1634−timestamp = UnsafeTypeExpression "timestamp"
1635−-- | date and time, including time zone
1636−timestampWithTimeZone :: TypeExpression schema 'PGtimestamptz
1637−timestampWithTimeZone = UnsafeTypeExpression "timestamp with time zone"
1638−-- | calendar date (year, month, day)
1639−date :: TypeExpression schema 'PGdate
1640−date = UnsafeTypeExpression "date"
1641−-- | time of day (no time zone)
1642−time :: TypeExpression schema 'PGtime
1643−time = UnsafeTypeExpression "time"
1644−-- | time of day, including time zone
1645−timeWithTimeZone :: TypeExpression schema 'PGtimetz
1646−timeWithTimeZone = UnsafeTypeExpression "time with time zone"
1647−-- | time span
1648−interval :: TypeExpression schema 'PGinterval
1649−interval = UnsafeTypeExpression "interval"
1650−-- | universally unique identifier
1651−uuid :: TypeExpression schema 'PGuuid
1652−uuid = UnsafeTypeExpression "uuid"
1653−-- | IPv4 or IPv6 host address
1654−inet :: TypeExpression schema 'PGinet
1655−inet = UnsafeTypeExpression "inet"
1656−-- | textual JSON data
1657−json :: TypeExpression schema 'PGjson
1658−json = UnsafeTypeExpression "json"
1659−-- | binary JSON data, decomposed
1660−jsonb :: TypeExpression schema 'PGjsonb
1661−jsonb = UnsafeTypeExpression "jsonb"
1662−-- | variable length array
1663−vararray
1664− :: TypeExpression schema pg
1665− -> TypeExpression schema ('PGvararray pg)
1666−vararray ty = UnsafeTypeExpression $ renderTypeExpression ty <> "[]"
1667−-- | fixed length array
1668−--
1669−-- >>> renderTypeExpression (fixarray (Proxy @2) json)
1670−-- "json[2]"
1671−fixarray
1672− :: KnownNat n
1673− => proxy n
1674− -> TypeExpression schema pg
1675− -> TypeExpression schema ('PGfixarray n pg)
1676−fixarray p ty = UnsafeTypeExpression $
1677− renderTypeExpression ty <> "[" <> renderNat p <> "]"
1678−
1679−-- | `pgtype` is a demoted version of a `PGType`
1680−class PGTyped schema (ty :: PGType) where pgtype :: TypeExpression schema ty
1681−instance PGTyped schema 'PGbool where pgtype = bool
1682−instance PGTyped schema 'PGint2 where pgtype = int2
1683−instance PGTyped schema 'PGint4 where pgtype = int4
1684−instance PGTyped schema 'PGint8 where pgtype = int8
1685−instance PGTyped schema 'PGnumeric where pgtype = numeric
1686−instance PGTyped schema 'PGfloat4 where pgtype = float4
1687−instance PGTyped schema 'PGfloat8 where pgtype = float8
1688−instance PGTyped schema 'PGtext where pgtype = text
1689−instance (KnownNat n, 1 <= n)
1690− => PGTyped schema ('PGchar n) where pgtype = char (Proxy @n)
1691−instance (KnownNat n, 1 <= n)
1692− => PGTyped schema ('PGvarchar n) where pgtype = varchar (Proxy @n)
1693−instance PGTyped schema 'PGbytea where pgtype = bytea
1694−instance PGTyped schema 'PGtimestamp where pgtype = timestamp
1695−instance PGTyped schema 'PGtimestamptz where pgtype = timestampWithTimeZone
1696−instance PGTyped schema 'PGdate where pgtype = date
1697−instance PGTyped schema 'PGtime where pgtype = time
1698−instance PGTyped schema 'PGtimetz where pgtype = timeWithTimeZone
1699−instance PGTyped schema 'PGinterval where pgtype = interval
1700−instance PGTyped schema 'PGuuid where pgtype = uuid
1701−instance PGTyped schema 'PGjson where pgtype = json
1702−instance PGTyped schema 'PGjsonb where pgtype = jsonb
1703−instance PGTyped schema ty => PGTyped schema ('PGvararray ty) where
1704− pgtype = vararray (pgtype @schema @ty)
1705−instance (KnownNat n, PGTyped schema ty) => PGTyped schema ('PGfixarray n ty) where
1706− pgtype = fixarray (Proxy @n) (pgtype @schema @ty)