on dev help sign in
Merge pull request #84 from morphismtech/dev-refactor-select

Add a `Selection` type and more `RenderSQL` instances

commit2762bb4a42fc481960c087e8ef6afa3221e4cb39 authorEitan Chatav <eitan.chatav@gmail.com> dateThu 10 Jan 2019, 09:10 (8 years ago) parent16e8cbefa11dd1
9 files changed+932−952
squeal-postgresql/exe/Example.hs+3−4 squeal-postgresql/src/Squeal/PostgreSQL.hs+2−2 squeal-postgresql/src/Squeal/PostgreSQL/Definition.hs+58−56 squeal-postgresql/src/Squeal/PostgreSQL/Expression.hs+343−338 squeal-postgresql/src/Squeal/PostgreSQL/Manipulation.hs+144−166 squeal-postgresql/src/Squeal/PostgreSQL/Migration.hs+2−2 squeal-postgresql/src/Squeal/PostgreSQL/Query.hs+327−312 squeal-postgresql/src/Squeal/PostgreSQL/Schema.hs+31−46 squeal-postgresql/src/Squeal/PostgreSQL/Transaction.hs+22−26
squeal-postgresql/exe/Example.hs+3−4
@@ -68,18 +68,17 @@ insertUser :: Manipulation DB '[ 'NotNull 'PGtext, 'NotNull ('PGvararray ('Null
6868 '[ "fromOnly" ::: 'NotNull 'PGint4 ]
6969insertUser = insertInto #users
7070 (Values_ (defaultAs #id :* param @1 `as` #name :* param @2 `as` #vec))
71− (OnConflict (OnConstraint #pk_users) DoNothing) (Returning (#id `as` #fromOnly))
71+ (OnConflict (OnConstraint #pk_users) DoNothing) (Returning_ (#id `as` #fromOnly))
7272
7373insertEmail :: Manipulation DB '[ 'NotNull 'PGint4, 'Null 'PGtext] '[]
74−insertEmail = insertInto #emails
74+insertEmail = insertInto_ #emails
7575 (Values_ (defaultAs #id :* param @1 `as` #user_id :* param @2 `as` #email))
76− (OnConflict (OnConstraint #pk_emails) DoNothing) (Returning Nil)
7776
7877getUsers :: Query DB '[]
7978 '[ "userName" ::: 'NotNull 'PGtext
8079 , "userEmail" ::: 'Null 'PGtext
8180 , "userVec" ::: 'NotNull ('PGvararray ('Null 'PGint2))]
82−getUsers = select
81+getUsers = select_
8382 (#u ! #name `as` #userName :* #e ! #email `as` #userEmail :* #u ! #vec `as` #userVec)
8483 ( from (table (#users `as` #u)
8584 & innerJoin (table (#emails `as` #e))
squeal-postgresql/src/Squeal/PostgreSQL.hs+2−2
@@ -123,7 +123,7 @@ let
123123 where
124124 u = insertInto #users
125125 (Values_ (defaultAs #id :* param @1 `as` #name))
126− OnConflictDoRaise (Returning (#id :* param @2 `as` #email))
126+ OnConflictDoRaise (Returning_ (#id :* param @2 `as` #email))
127127 e = insertInto_ #emails
128128 (Select (defaultAs #id :* #u ! #id `as` #user_id :* #u ! #email) (from (common #u)))
129129:}
@@ -141,7 +141,7 @@ let
141141 getUsers :: Query DB '[]
142142 '[ "userName" ::: 'NotNull 'PGtext
143143 , "userEmail" ::: 'Null 'PGtext ]
144− getUsers = select
144+ getUsers = select_
145145 (#u ! #name `as` #userName :* #e ! #email `as` #userEmail)
146146 ( from (table (#users `as` #u)
147147 & innerJoin (table (#emails `as` #e))
squeal-postgresql/src/Squeal/PostgreSQL/Definition.hs+58−56
@@ -29,7 +29,7 @@ Squeal data definition language.
2929
3030module Squeal.PostgreSQL.Definition
3131 ( -- * Definition
32− Definition (UnsafeDefinition, renderDefinition)
32+ Definition (..)
3333 , (>>>)
3434 -- * Tables
3535 -- ** Create
@@ -43,23 +43,21 @@ module Squeal.PostgreSQL.Definition
4343 , primaryKey
4444 , foreignKey
4545 , ForeignKeyed
46− , OnDeleteClause (OnDeleteNoAction, OnDeleteRestrict, OnDeleteCascade)
47− , renderOnDeleteClause
48− , OnUpdateClause (OnUpdateNoAction, OnUpdateRestrict, OnUpdateCascade)
49− , renderOnUpdateClause
46+ , OnDeleteClause (..)
47+ , OnUpdateClause (..)
5048 -- ** Drop
5149 , dropTable
5250 -- ** Alter
5351 , alterTable
5452 , alterTableRename
55− , AlterTable (UnsafeAlterTable, renderAlterTable)
53+ , AlterTable (..)
5654 , addConstraint
5755 , dropConstraint
58− , AddColumn (addColumn)
56+ , AddColumn (..)
5957 , dropColumn
6058 , renameColumn
6159 , alterColumn
62− , AlterColumn (UnsafeAlterColumn, renderAlterColumn)
60+ , AlterColumn (..)
6361 , setDefault
6462 , dropDefault
6563 , setNotNull
@@ -121,7 +119,7 @@ instance RenderSQL (Definition schemas0 schemas1) where
121119instance Category Definition where
122120 id = UnsafeDefinition ";"
123121 ddl1 . ddl0 = UnsafeDefinition $
124− renderDefinition ddl0 <> "\n" <> renderDefinition ddl1
122+ renderSQL ddl0 <> "\n" <> renderSQL ddl1
125123
126124{-----------------------------------------
127125CREATE statements
@@ -132,7 +130,7 @@ createSchema
132130 => Alias sch
133131 -> Definition schemas (Create sch '[] schemas)
134132createSchema sch = UnsafeDefinition $
135− "CREATE" <+> "SCHEMA" <+> renderAlias sch <> ";"
133+ "CREATE" <+> "SCHEMA" <+> renderSQL sch <> ";"
136134
137135createSchemaIfNotExists
138136 :: (KnownSymbol sch, Has sch schemas schema)
@@ -140,7 +138,7 @@ createSchemaIfNotExists
140138 -> Definition schemas schemas
141139createSchemaIfNotExists sch = UnsafeDefinition $
142140 "CREATE" <+> "SCHEMA" <+> "IF" <+> "NOT" <+> "EXISTS"
143− <+> renderAlias sch <> ";"
141+ <+> renderSQL sch <> ";"
144142
145143{- | `createTable` adds a table to the schema.
146144
@@ -227,7 +225,7 @@ renderCreation
227225 -> NP (Aliased (TableConstraintExpression sch tab schemas1)) constraints
228226 -- ^ constraints that must hold for the table
229227 -> ByteString
230−renderCreation tab columns constraints = renderQualifiedAlias tab
228+renderCreation tab columns constraints = renderSQL tab
231229 <+> parenthesized
232230 ( renderCommaSeparated renderColumnDef columns
233231 <> ( case constraints of
@@ -238,12 +236,12 @@ renderCreation tab columns constraints = renderQualifiedAlias tab
238236 where
239237 renderColumnDef :: Aliased (ColumnTypeExpression schemas) x -> ByteString
240238 renderColumnDef (ty `As` column) =
241− renderAlias column <+> renderColumnTypeExpression ty
239+ renderSQL column <+> renderColumnTypeExpression ty
242240 renderConstraint
243241 :: Aliased (TableConstraintExpression sch tab schemas) constraint
244242 -> ByteString
245243 renderConstraint (constraint `As` alias) =
246− "CONSTRAINT" <+> renderAlias alias <+> renderTableConstraintExpression constraint
244+ "CONSTRAINT" <+> renderSQL alias <+> renderSQL constraint
247245
248246-- | Data types are a way to limit the kind of data that can be stored in a
249247-- table. For many applications, however, the constraint they provide is
@@ -265,6 +263,9 @@ newtype TableConstraintExpression
265263 = UnsafeTableConstraintExpression
266264 { renderTableConstraintExpression :: ByteString }
267265 deriving (GHC.Generic,Show,Eq,Ord,NFData)
266+instance RenderSQL
267+ (TableConstraintExpression sch tab schemas constraint) where
268+ renderSQL = renderTableConstraintExpression
268269
269270{-| A `check` constraint is the most generic `TableConstraint` type.
270271It allows you to specify that the value in a certain column must satisfy
@@ -296,11 +297,11 @@ check
296297 , HasAll aliases (TableToRow table) subcolumns )
297298 => NP Alias aliases
298299 -- ^ specify the subcolumns which are getting checked
299− -> (forall t. Condition ('[] :=> schemas) '[t ::: subcolumns] 'Ungrouped '[])
300+ -> (forall t. Condition ('[] :=> schemas) '[] 'Ungrouped '[t ::: subcolumns])
300301 -- ^ a closed `Condition` on those subcolumns
301302 -> TableConstraintExpression sch tab schemas ('Check aliases)
302303check _cols condition = UnsafeTableConstraintExpression $
303− "CHECK" <+> parenthesized (renderExpression condition)
304+ "CHECK" <+> parenthesized (renderSQL condition)
304305
305306{-| A `unique` constraint ensure that the data contained in a column,
306307or a group of columns, is unique among all the rows in the table.
@@ -333,7 +334,7 @@ unique
333334 -- ^ specify subcolumns which together are unique for each row
334335 -> TableConstraintExpression sch tab schemas ('Unique aliases)
335336unique columns = UnsafeTableConstraintExpression $
336− "UNIQUE" <+> parenthesized (commaSeparated (renderAliases columns))
337+ "UNIQUE" <+> parenthesized (renderSQL columns)
337338
338339{-| A `primaryKey` constraint indicates that a column, or group of columns,
339340can be used as a unique identifier for rows in the table.
@@ -368,7 +369,7 @@ primaryKey
368369 -- ^ specify the subcolumns which together form a primary key.
369370 -> TableConstraintExpression sch tab schemas ('PrimaryKey aliases)
370371primaryKey columns = UnsafeTableConstraintExpression $
371− "PRIMARY KEY" <+> parenthesized (commaSeparated (renderAliases columns))
372+ "PRIMARY KEY" <+> parenthesized (renderSQL columns)
372373
373374{-| A `foreignKey` specifies that the values in a column
374375(or a group of columns) must match the values appearing in some row of
@@ -462,11 +463,11 @@ foreignKey
462463 -> TableConstraintExpression sch child schemas
463464 ('ForeignKey columns parent refcolumns)
464465foreignKey keys parent refs ondel onupd = UnsafeTableConstraintExpression $
465− "FOREIGN KEY" <+> parenthesized (commaSeparated (renderAliases keys))
466− <+> "REFERENCES" <+> renderAlias parent
467− <+> parenthesized (commaSeparated (renderAliases refs))
468− <+> renderOnDeleteClause ondel
469− <+> renderOnUpdateClause onupd
466+ "FOREIGN KEY" <+> parenthesized (renderSQL keys)
467+ <+> "REFERENCES" <+> renderSQL parent
468+ <+> parenthesized (renderSQL refs)
469+ <+> renderSQL ondel
470+ <+> renderSQL onupd
470471
471472-- | A constraint synonym between types involved in a foreign key constraint.
472473type ForeignKeyed schemas
@@ -497,13 +498,12 @@ data OnDeleteClause
497498 -- row(s) referencing it should be automatically deleted as well
498499 deriving (GHC.Generic,Show,Eq,Ord)
499500instance NFData OnDeleteClause
500−
501501-- | Render `OnDeleteClause`.
502−renderOnDeleteClause :: OnDeleteClause -> ByteString
503−renderOnDeleteClause = \case
504− OnDeleteNoAction -> "ON DELETE NO ACTION"
505− OnDeleteRestrict -> "ON DELETE RESTRICT"
506− OnDeleteCascade -> "ON DELETE CASCADE"
502+instance RenderSQL OnDeleteClause where
503+ renderSQL = \case
504+ OnDeleteNoAction -> "ON DELETE NO ACTION"
505+ OnDeleteRestrict -> "ON DELETE RESTRICT"
506+ OnDeleteCascade -> "ON DELETE CASCADE"
507507
508508-- | Analagous to `OnDeleteClause` there is also `OnUpdateClause` which is invoked
509509-- when a referenced column is changed (updated).
@@ -519,11 +519,11 @@ data OnUpdateClause
519519instance NFData OnUpdateClause
520520
521521-- | Render `OnUpdateClause`.
522−renderOnUpdateClause :: OnUpdateClause -> ByteString
523−renderOnUpdateClause = \case
524− OnUpdateNoAction -> "ON UPDATE NO ACTION"
525− OnUpdateRestrict -> "ON UPDATE RESTRICT"
526− OnUpdateCascade -> "ON UPDATE CASCADE"
522+instance RenderSQL OnUpdateClause where
523+ renderSQL = \case
524+ OnUpdateNoAction -> "ON UPDATE NO ACTION"
525+ OnUpdateRestrict -> "ON UPDATE RESTRICT"
526+ OnUpdateCascade -> "ON UPDATE CASCADE"
527527
528528{-----------------------------------------
529529DROP statements
@@ -544,7 +544,7 @@ dropTable
544544 , Has tab schema ('Table table))
545545 => QualifiedAlias sch tab -- ^ table to remove
546546 -> Definition schemas (Alter sch (Drop tab schema) schemas)
547−dropTable tab = UnsafeDefinition $ "DROP TABLE" <+> renderQualifiedAlias tab <> ";"
547+dropTable tab = UnsafeDefinition $ "DROP TABLE" <+> renderSQL tab <> ";"
548548
549549{-----------------------------------------
550550ALTER statements
@@ -558,7 +558,7 @@ alterTable
558558 -> Definition schemas (Alter sch (Alter tab ('Table table1) schema) schemas)
559559alterTable tab alteration = UnsafeDefinition $
560560 "ALTER TABLE"
561− <+> renderQualifiedAlias tab
561+ <+> renderSQL tab
562562 <+> renderAlterTable alteration
563563 <> ";"
564564
@@ -572,8 +572,8 @@ alterTableRename
572572 -> Alias table1 -- ^ what to rename it
573573 -> Definition schema (Rename table0 table1 schema)
574574alterTableRename table0 table1 = UnsafeDefinition $
575− "ALTER TABLE" <+> renderAlias table0
576− <+> "RENAME TO" <+> renderAlias table1 <> ";"
575+ "ALTER TABLE" <+> renderSQL table0
576+ <+> "RENAME TO" <+> renderSQL table1 <> ";"
577577
578578-- | An `AlterTable` describes the alteration to perform on the columns
579579-- of a table.
@@ -607,8 +607,8 @@ addConstraint
607607 -- ^ constraint to add
608608 -> AlterTable sch tab schemas table1
609609addConstraint alias constraint = UnsafeAlterTable $
610− "ADD" <+> "CONSTRAINT" <+> renderAlias alias
611− <+> renderTableConstraintExpression constraint
610+ "ADD" <+> "CONSTRAINT" <+> renderSQL alias
611+ <+> renderSQL constraint
612612
613613-- | A `dropConstraint` drops a table constraint.
614614--
@@ -631,7 +631,7 @@ dropConstraint
631631 -- ^ constraint to drop
632632 -> AlterTable sch tab schemas table1
633633dropConstraint constraint = UnsafeAlterTable $
634− "DROP" <+> "CONSTRAINT" <+> renderAlias constraint
634+ "DROP" <+> "CONSTRAINT" <+> renderSQL constraint
635635
636636-- | An `AddColumn` is either @NULL@ or has @DEFAULT@.
637637class AddColumn ty where
@@ -670,7 +670,7 @@ class AddColumn ty where
670670 -> ColumnTypeExpression schemas ty -- ^ type of the new column
671671 -> AlterTable sch tab schemas (constraints :=> Create column ty columns)
672672 addColumn column ty = UnsafeAlterTable $
673− "ADD COLUMN" <+> renderAlias column <+> renderColumnTypeExpression ty
673+ "ADD COLUMN" <+> renderSQL column <+> renderColumnTypeExpression ty
674674instance {-# OVERLAPPING #-} AddColumn ('Def :=> ty)
675675instance {-# OVERLAPPABLE #-} AddColumn ('NoDef :=> 'Null ty)
676676
@@ -699,7 +699,7 @@ dropColumn
699699 => Alias column -- ^ column to remove
700700 -> AlterTable sch tab schemas table1
701701dropColumn column = UnsafeAlterTable $
702− "DROP COLUMN" <+> renderAlias column
702+ "DROP COLUMN" <+> renderSQL column
703703
704704-- | A `renameColumn` renames a column.
705705--
@@ -723,7 +723,7 @@ renameColumn
723723 -> Alias column1 -- ^ what to rename the column
724724 -> AlterTable sch tab schemas table1
725725renameColumn column0 column1 = UnsafeAlterTable $
726− "RENAME COLUMN" <+> renderAlias column0 <+> "TO" <+> renderAlias column1
726+ "RENAME COLUMN" <+> renderSQL column0 <+> "TO" <+> renderSQL column1
727727
728728-- | An `alterColumn` alters a single column.
729729alterColumn
@@ -737,7 +737,7 @@ alterColumn
737737 -> AlterColumn schemas ty0 ty1 -- ^ alteration to perform
738738 -> AlterTable sch tab schemas table1
739739alterColumn column alteration = UnsafeAlterTable $
740− "ALTER COLUMN" <+> renderAlias column <+> renderAlterColumn alteration
740+ "ALTER COLUMN" <+> renderSQL column <+> renderAlterColumn alteration
741741
742742-- | An `AlterColumn` describes the alteration to perform on a single column.
743743newtype AlterColumn (schemas :: SchemasType) (ty0 :: ColumnType) (ty1 :: ColumnType) =
@@ -835,7 +835,7 @@ let
835835 '[ "public" ::: '["abc" ::: 'Table ('[] :=> ABC)]]
836836 '[ "public" ::: '["abc" ::: 'Table ('[] :=> ABC), "bc" ::: 'View BC]]
837837 definition =
838− createView #bc (select (#b :* #c) (from (table #abc)))
838+ createView #bc (select_ (#b :* #c) (from (table #abc)))
839839in printSQL definition
840840:}
841841CREATE VIEW "bc" AS SELECT "b" AS "b", "c" AS "c" FROM "abc" AS "abc";
@@ -846,7 +846,7 @@ createView
846846 -> Query ('[] :=> schemas) '[] view -- ^ query
847847 -> Definition schemas (Alter sch (Create vw ('View view) schema) schemas)
848848createView alias query = UnsafeDefinition $
849− "CREATE" <+> "VIEW" <+> renderQualifiedAlias alias <+> "AS"
849+ "CREATE" <+> "VIEW" <+> renderSQL alias <+> "AS"
850850 <+> renderQuery query <> ";"
851851
852852-- | Drop a view.
@@ -865,7 +865,7 @@ dropView
865865 :: (Has sch schemas schema, Has vw schema ('View view))
866866 => QualifiedAlias sch vw -- ^ view to remove
867867 -> Definition schemas (Alter sch (Drop vw schema) schemas)
868−dropView vw = UnsafeDefinition $ "DROP VIEW" <+> renderQualifiedAlias vw <> ";"
868+dropView vw = UnsafeDefinition $ "DROP VIEW" <+> renderSQL vw <> ";"
869869
870870-- | Enumerated types are created using the `createTypeEnum` command, for example
871871--
@@ -879,8 +879,8 @@ createTypeEnum
879879 -- ^ labels of the enumerated type
880880 -> Definition schemas (Alter sch (Create enum ('Typedef ('PGenum labels)) schema) schemas)
881881createTypeEnum enum labels = UnsafeDefinition $
882− "CREATE" <+> "TYPE" <+> renderQualifiedAlias enum <+> "AS" <+> "ENUM" <+>
883− parenthesized (commaSeparated (renderLabels labels)) <> ";"
882+ "CREATE" <+> "TYPE" <+> renderSQL enum <+> "AS" <+> "ENUM" <+>
883+ parenthesized (renderSQL labels) <> ";"
884884
885885-- | Enumerated types can also be generated from a Haskell type, for example
886886--
@@ -933,12 +933,12 @@ createTypeComposite
933933 -- ^ list of attribute names and data types
934934 -> Definition schemas (Alter sch (Create ty ('Typedef ('PGcomposite fields)) schema) schemas)
935935createTypeComposite ty fields = UnsafeDefinition $
936− "CREATE" <+> "TYPE" <+> renderQualifiedAlias ty <+> "AS" <+> parenthesized
936+ "CREATE" <+> "TYPE" <+> renderSQL ty <+> "AS" <+> parenthesized
937937 (renderCommaSeparated renderField fields) <> ";"
938938 where
939939 renderField :: Aliased (TypeExpression schemas) x -> ByteString
940940 renderField (typ `As` alias) =
941− renderAlias alias <+> renderTypeExpression typ
941+ renderSQL alias <+> renderSQL typ
942942
943943-- | Composite types can also be generated from a Haskell type, for example
944944--
@@ -984,26 +984,28 @@ dropType
984984 => QualifiedAlias sch td
985985 -- ^ name of the user defined type
986986 -> Definition schemas (Alter sch (Drop td schema) schemas)
987−dropType tydef = UnsafeDefinition $ "DROP" <+> "TYPE" <+> renderQualifiedAlias tydef <> ";"
987+dropType tydef = UnsafeDefinition $ "DROP" <+> "TYPE" <+> renderSQL tydef <> ";"
988988
989989-- | `ColumnTypeExpression`s are used in `createTable` commands.
990990newtype ColumnTypeExpression (schemas :: SchemasType) (ty :: ColumnType)
991991 = UnsafeColumnTypeExpression { renderColumnTypeExpression :: ByteString }
992992 deriving (GHC.Generic,Show,Eq,Ord,NFData)
993+instance RenderSQL (ColumnTypeExpression schemas ty) where
994+ renderSQL = renderColumnTypeExpression
993995
994996-- | used in `createTable` commands as a column constraint to note that
995997-- @NULL@ may be present in a column
996998nullable
997999 :: TypeExpression schemas (nullity ty)
9981000 -> ColumnTypeExpression schemas ('NoDef :=> 'Null ty)
999−nullable ty = UnsafeColumnTypeExpression $ renderTypeExpression ty <+> "NULL"
1001+nullable ty = UnsafeColumnTypeExpression $ renderSQL ty <+> "NULL"
10001002
10011003-- | used in `createTable` commands as a column constraint to ensure
10021004-- @NULL@ is not present in a column
10031005notNullable
10041006 :: TypeExpression schemas (nullity ty)
10051007 -> ColumnTypeExpression schemas ('NoDef :=> 'NotNull ty)
1006−notNullable ty = UnsafeColumnTypeExpression $ renderTypeExpression ty <+> "NOT NULL"
1008+notNullable ty = UnsafeColumnTypeExpression $ renderSQL ty <+> "NOT NULL"
10071009
10081010-- | used in `createTable` commands as a column constraint to give a default
10091011default_
@@ -1011,7 +1013,7 @@ default_
10111013 -> ColumnTypeExpression schemas ('NoDef :=> ty)
10121014 -> ColumnTypeExpression schemas ('Def :=> ty)
10131015default_ x ty = UnsafeColumnTypeExpression $
1014− renderColumnTypeExpression ty <+> "DEFAULT" <+> renderExpression x
1016+ renderSQL ty <+> "DEFAULT" <+> renderExpression x
10151017
10161018-- | not a true type, but merely a notational convenience for creating
10171019-- unique identifier columns with type `PGint2`
squeal-postgresql/src/Squeal/PostgreSQL/Expression.hs+343−338
@@ -31,7 +31,7 @@ Squeal expressions are the atoms used to build statements.
3131
3232module Squeal.PostgreSQL.Expression
3333 ( -- * Expression
34− Expression (UnsafeExpression, renderExpression)
34+ Expression (..)
3535 , HasParameter (parameter)
3636 , param
3737 -- ** Null
@@ -142,8 +142,8 @@ module Squeal.PostgreSQL.Expression
142142 , every, everyDistinct
143143 , max_, maxDistinct, min_, minDistinct
144144 -- * Types
145− , TypeExpression (UnsafeTypeExpression, renderTypeExpression)
146− , PGTyped (pgtype)
145+ , TypeExpression (..)
146+ , PGTyped (..)
147147 , typedef
148148 , typetable
149149 , typeview
@@ -219,14 +219,14 @@ and other operations.
219219-}
220220newtype Expression
221221 (db :: DBType)
222− (from :: FromType)
223− (grouping :: Grouping)
224222 (params :: [NullityType])
223+ (grp :: Grouping)
224+ (from :: FromType)
225225 (ty :: NullityType)
226226 = UnsafeExpression { renderExpression :: ByteString }
227227 deriving (GHC.Generic,Show,Eq,Ord,NFData)
228228
229−instance RenderSQL (Expression db from grouping params ty) where
229+instance RenderSQL (Expression db params grp from ty) where
230230 renderSQL = renderExpression
231231
232232{- | A `HasParameter` constraint is used to indicate a value that is
@@ -244,15 +244,15 @@ class KnownNat n => HasParameter
244244 | n params -> ty where
245245 -- | `parameter` takes a `Nat` using type application and a `TypeExpression`.
246246 --
247− -- >>> let expr = parameter @1 int4 :: Expression (DBof schemas) from grp '[ 'Null 'PGint4] ('Null 'PGint4)
247+ -- >>> let expr = parameter @1 int4 :: Expression (DBof schemas) '[ 'Null 'PGint4] grp from ('Null 'PGint4)
248248 -- >>> printSQL expr
249249 -- ($1 :: int4)
250250 parameter
251251 :: TypeExpression schemas ty
252− -> Expression (commons :=> schemas) from grouping params ty
252+ -> Expression (commons :=> schemas) params grp from ty
253253 parameter ty = UnsafeExpression $ parenthesized $
254254 "$" <> renderNat @n <+> "::"
255− <+> renderTypeExpression ty
255+ <+> renderSQL ty
256256instance {-# OVERLAPPING #-} HasParameter 1 (ty1:tys) ty1
257257instance {-# OVERLAPPABLE #-} (KnownNat n, HasParameter (n-1) params ty)
258258 => HasParameter n (ty' : params) ty
@@ -260,88 +260,88 @@ instance {-# OVERLAPPABLE #-} (KnownNat n, HasParameter (n-1) params ty)
260260-- | `param` takes a `Nat` using type application and for basic types,
261261-- infers a `TypeExpression`.
262262--
263−-- >>> let expr = param @1 :: Expression (commons :=> schemas) from grp '[ 'Null 'PGint4] ('Null 'PGint4)
263+-- >>> let expr = param @1 :: Expression (commons :=> schemas) '[ 'Null 'PGint4] grp from ('Null 'PGint4)
264264-- >>> printSQL expr
265265-- ($1 :: int4)
266266param
267− :: forall n db commons schemas params from grouping ty
267+ :: forall n db commons schemas params from grp ty
268268 . (db ~ (commons :=> schemas), PGTyped schemas ty, HasParameter n params ty)
269− => Expression db from grouping params ty -- ^ param
269+ => Expression db params grp from ty -- ^ param
270270param = parameter @n (pgtype @schemas)
271271
272272instance (HasUnique tab from row, Has col row ty)
273− => IsLabel col (Expression db from 'Ungrouped params ty) where
274− fromLabel = UnsafeExpression $ renderAlias (Alias @col)
273+ => IsLabel col (Expression db params 'Ungrouped from ty) where
274+ fromLabel = UnsafeExpression $ renderSQL (Alias @col)
275275instance (HasUnique tab from row, Has col row ty, column ~ (col ::: ty))
276276 => IsLabel col
277− (Aliased (Expression db from 'Ungrouped params) column) where
277+ (Aliased (Expression db params 'Ungrouped from) column) where
278278 fromLabel = fromLabel @col `As` Alias
279279instance (HasUnique tab from row, Has col row ty, columns ~ '[col ::: ty])
280280 => IsLabel col
281− (NP (Aliased (Expression db from 'Ungrouped params)) columns) where
281+ (NP (Aliased (Expression db params 'Ungrouped from)) columns) where
282282 fromLabel = fromLabel @col :* Nil
283283
284284instance (Has tab from row, Has col row ty)
285− => IsQualified tab col (Expression db from 'Ungrouped params ty) where
285+ => IsQualified tab col (Expression db params 'Ungrouped from ty) where
286286 tab ! col = UnsafeExpression $
287− renderAlias tab <> "." <> renderAlias col
287+ renderSQL tab <> "." <> renderSQL col
288288instance (Has tab from row, Has col row ty, column ~ (col ::: ty))
289289 => IsQualified tab col
290− (Aliased (Expression db from 'Ungrouped params) column) where
290+ (Aliased (Expression db params 'Ungrouped from) column) where
291291 tab ! col = tab ! col `As` col
292292instance (Has tab from row, Has col row ty, columns ~ '[col ::: ty])
293293 => IsQualified tab col
294− (NP (Aliased (Expression db from 'Ungrouped params)) columns) where
294+ (NP (Aliased (Expression db params 'Ungrouped from)) columns) where
295295 tab ! col = tab ! col :* Nil
296296
297297instance
298− ( HasUnique table from columns
299− , Has column columns ty
300− , GroupedBy table column bys
301− ) => IsLabel column
302− (Expression db from ('Grouped bys) params ty) where
303− fromLabel = UnsafeExpression $ renderAlias (Alias @column)
298+ ( HasUnique tab from row
299+ , Has col row ty
300+ , GroupedBy tab col bys
301+ ) => IsLabel col
302+ (Expression db params ('Grouped bys) from ty) where
303+ fromLabel = UnsafeExpression $ renderSQL (Alias @col)
304304instance
305− ( HasUnique table from columns
306− , Has column columns ty
307− , GroupedBy table column bys
308− ) => IsLabel column
309− ( Aliased (Expression db from ('Grouped bys) params)
310− (column ::: ty) ) where
311− fromLabel = fromLabel @column `As` Alias @column
305+ ( HasUnique tab from row
306+ , Has col row ty
307+ , GroupedBy tab col bys
308+ , column ~ (col ::: ty)
309+ ) => IsLabel col
310+ (Aliased (Expression db params ('Grouped bys) from) column) where
311+ fromLabel = fromLabel @col `As` Alias
312312instance
313− ( HasUnique table from columns
314− , Has column columns ty
315− , GroupedBy table column bys
316− ) => IsLabel column
317− ( NP (Aliased (Expression db from ('Grouped bys) params))
318− '[column ::: ty] ) where
319− fromLabel = fromLabel @column :* Nil
313+ ( HasUnique tab from row
314+ , Has col row ty
315+ , GroupedBy tab col bys
316+ , columns ~ '[col ::: ty]
317+ ) => IsLabel col
318+ (NP (Aliased (Expression db params ('Grouped bys) from)) columns) where
319+ fromLabel = fromLabel @col :* Nil
320320
321321instance
322− ( Has table from columns
323− , Has column columns ty
324− , GroupedBy table column bys
325− ) => IsQualified table column
326− (Expression db from ('Grouped bys) params ty) where
327− table ! column = UnsafeExpression $
328− renderAlias table <> "." <> renderAlias column
322+ ( Has tab from row
323+ , Has col row ty
324+ , GroupedBy tab col bys
325+ ) => IsQualified tab col
326+ (Expression db params ('Grouped bys) from ty) where
327+ tab ! col = UnsafeExpression $
328+ renderSQL tab <> "." <> renderSQL col
329329instance
330− ( Has table from columns
331− , Has column columns ty
332− , GroupedBy table column bys
333− ) => IsQualified table column
334− (Aliased (Expression db from ('Grouped bys) params)
335− (column ::: ty)) where
336− table ! column = table ! column `As` column
330+ ( Has tab from row
331+ , Has col row ty
332+ , GroupedBy tab col bys
333+ , column ~ (col ::: ty)
334+ ) => IsQualified tab col
335+ (Aliased (Expression db params ('Grouped bys) from) column) where
336+ tab ! col = tab ! col `As` col
337337instance
338− ( Has table from columns
339− , Has column columns ty
340− , GroupedBy table column bys
341− ) => IsQualified table column
342− ( NP (Aliased (Expression db from ('Grouped bys) params))
343− '[column ::: ty]) where
344− table ! column = table ! column :* Nil
338+ ( Has tab from row
339+ , Has col row ty
340+ , GroupedBy tab col bys
341+ , columns ~ '[col ::: ty]
342+ ) => IsQualified tab col
343+ (NP (Aliased (Expression db params ('Grouped bys) from)) columns) where
344+ tab ! col = tab ! col :* Nil
345345
346346-- | analagous to `Nothing`
347347--
@@ -357,102 +357,102 @@ null_ = UnsafeExpression "NULL"
357357notNull
358358 :: Expression db rels grouping params ('NotNull ty)
359359 -> Expression db rels grouping params ('Null ty)
360−notNull = UnsafeExpression . renderExpression
360+notNull = UnsafeExpression . renderSQL
361361
362362-- | return the leftmost value which is not NULL
363363--
364364-- >>> printSQL $ coalesce [null_, true] false
365365-- COALESCE(NULL, TRUE, FALSE)
366366coalesce
367− :: [Expression db from grouping params ('Null ty)]
367+ :: [Expression db params grp from ('Null ty)]
368368 -- ^ @NULL@s may be present
369− -> Expression db from grouping params ('NotNull ty)
369+ -> Expression db params grp from ('NotNull ty)
370370 -- ^ @NULL@ is absent
371− -> Expression db from grouping params ('NotNull ty)
371+ -> Expression db params grp from ('NotNull ty)
372372coalesce nullxs notNullx = UnsafeExpression $
373373 "COALESCE" <> parenthesized (commaSeparated
374− ((renderExpression <$> nullxs) <> [renderExpression notNullx]))
374+ ((renderSQL <$> nullxs) <> [renderSQL notNullx]))
375375
376376-- | analagous to `Data.Maybe.fromMaybe` using @COALESCE@
377377--
378378-- >>> printSQL $ fromNull true null_
379379-- COALESCE(NULL, TRUE)
380380fromNull
381− :: Expression db from grouping params ('NotNull ty)
381+ :: Expression db params grp from ('NotNull ty)
382382 -- ^ what to convert @NULL@ to
383− -> Expression db from grouping params ('Null ty)
384− -> Expression db from grouping params ('NotNull ty)
383+ -> Expression db params grp from ('Null ty)
384+ -> Expression db params grp from ('NotNull ty)
385385fromNull notNullx nullx = coalesce [nullx] notNullx
386386
387387-- | >>> printSQL $ null_ & isNull
388388-- NULL IS NULL
389389isNull
390− :: Expression db from grouping params ('Null ty)
390+ :: Expression db params grp from ('Null ty)
391391 -- ^ possibly @NULL@
392− -> Condition db from grouping params
393−isNull x = UnsafeExpression $ renderExpression x <+> "IS NULL"
392+ -> Condition db params grp from
393+isNull x = UnsafeExpression $ renderSQL x <+> "IS NULL"
394394
395395-- | >>> printSQL $ null_ & isNotNull
396396-- NULL IS NOT NULL
397397isNotNull
398− :: Expression db from grouping params ('Null ty)
398+ :: Expression db params grp from ('Null ty)
399399 -- ^ possibly @NULL@
400− -> Condition db from grouping params
401−isNotNull x = UnsafeExpression $ renderExpression x <+> "IS NOT NULL"
400+ -> Condition db params grp from
401+isNotNull x = UnsafeExpression $ renderSQL x <+> "IS NOT NULL"
402402
403403-- | analagous to `maybe` using @IS NULL@
404404--
405405-- >>> printSQL $ matchNull true not_ null_
406406-- CASE WHEN NULL IS NULL THEN TRUE ELSE (NOT NULL) END
407407matchNull
408− :: Expression db from grouping params (nullty)
408+ :: Expression db params grp from (nullty)
409409 -- ^ what to convert @NULL@ to
410− -> ( Expression db from grouping params ('NotNull ty)
411− -> Expression db from grouping params (nullty) )
410+ -> ( Expression db params grp from ('NotNull ty)
411+ -> Expression db params grp from (nullty) )
412412 -- ^ function to perform when @NULL@ is absent
413− -> Expression db from grouping params ('Null ty)
414− -> Expression db from grouping params (nullty)
413+ -> Expression db params grp from ('Null ty)
414+ -> Expression db params grp from (nullty)
415415matchNull y f x = ifThenElse (isNull x) y
416− (f (UnsafeExpression (renderExpression x)))
416+ (f (UnsafeExpression (renderSQL x)))
417417
418418{-| right inverse to `fromNull`, if its arguments are equal then
419419`nullIf` gives @NULL@.
420420
421421>>> :set -XTypeApplications -XDataKinds
422−>>> let expr = nullIf false (param @1) :: Expression (commons :=> schema) from grp '[ 'NotNull 'PGbool] ('Null 'PGbool)
422+>>> let expr = nullIf false (param @1) :: Expression (commons :=> schema) '[ 'NotNull 'PGbool] grp from ('Null 'PGbool)
423423>>> printSQL expr
424424NULL IF (FALSE, ($1 :: bool))
425425-}
426426nullIf
427− :: Expression db from grouping params ('NotNull ty)
427+ :: Expression db params grp from ('NotNull ty)
428428 -- ^ @NULL@ is absent
429− -> Expression db from grouping params ('NotNull ty)
429+ -> Expression db params grp from ('NotNull ty)
430430 -- ^ @NULL@ is absent
431− -> Expression db from grouping params ('Null ty)
431+ -> Expression db params grp from ('Null ty)
432432nullIf x y = UnsafeExpression $ "NULL IF" <+> parenthesized
433− (renderExpression x <> ", " <> renderExpression y)
433+ (renderSQL x <> ", " <> renderSQL y)
434434
435435-- | >>> printSQL $ array [null_, false, true]
436436-- ARRAY[NULL, FALSE, TRUE]
437437array
438− :: [Expression db from grouping params ty]
438+ :: [Expression db params grp from ty]
439439 -- ^ array elements
440− -> Expression db from grouping params (nullity ('PGvararray ty))
440+ -> Expression db params grp from (nullity ('PGvararray ty))
441441array xs = UnsafeExpression $
442− "ARRAY[" <> commaSeparated (renderExpression <$> xs) <> "]"
442+ "ARRAY[" <> commaSeparated (renderSQL <$> xs) <> "]"
443443
444444-- | >>> printSQL $ array [null_, false, true] & index 2
445445-- (ARRAY[NULL, FALSE, TRUE])[2]
446446index
447447 :: Word64 -- ^ index
448− -> Expression db from grouping params (nullity ('PGvararray ty)) -- ^ array
449− -> Expression db from grouping params (NullifyType ty)
448+ -> Expression db params grp from (nullity ('PGvararray ty)) -- ^ array
449+ -> Expression db params grp from (NullifyType ty)
450450index n expr = UnsafeExpression $
451− parenthesized (renderExpression expr) <> "[" <> fromString (show n) <> "]"
451+ parenthesized (renderSQL expr) <> "[" <> fromString (show n) <> "]"
452452
453453instance (KnownSymbol label, label `In` labels) => IsPGlabel label
454− (Expression db from grouping params (nullity ('PGenum labels))) where
455− label = UnsafeExpression $ renderLabel (PGlabel @label)
454+ (Expression db params grp from (nullity ('PGenum labels))) where
455+ label = UnsafeExpression $ renderSQL (PGlabel @label)
456456
457457-- | A row constructor is an expression that builds a row value
458458-- (also called a composite value) using values for its member fields.
@@ -468,11 +468,11 @@ instance (KnownSymbol label, label `In` labels) => IsPGlabel label
468468-- ROW(0, 1)
469469row
470470 :: SListI row
471− => NP (Aliased (Expression db from grouping params)) row
471+ => NP (Aliased (Expression db params grp from)) row
472472 -- ^ zero or more expressions for the row field values
473− -> Expression db from grouping params (nullity ('PGcomposite row))
473+ -> Expression db params grp from (nullity ('PGcomposite row))
474474row exprs = UnsafeExpression $ "ROW" <> parenthesized
475− (renderCommaSeparated (\ (expr `As` _) -> renderExpression expr) exprs)
475+ (renderCommaSeparated (\ (expr `As` _) -> renderSQL expr) exprs)
476476
477477-- | >>> :{
478478-- type Complex = 'PGcomposite
@@ -491,87 +491,87 @@ field
491491 , Has field row ty)
492492 => QualifiedAlias sch tydef -- ^ row type
493493 -> Alias field -- ^ field name
494− -> Expression (commons :=> schemas) from grouping params ('NotNull ('PGcomposite row))
495− -> Expression (commons :=> schemas) from grouping params ty
494+ -> Expression (commons :=> schemas) params grp from ('NotNull ('PGcomposite row))
495+ -> Expression (commons :=> schemas) params grp from ty
496496field td fld expr = UnsafeExpression $
497− parenthesized (renderExpression expr <> "::" <> renderQualifiedAlias td)
498− <> "." <> renderAlias fld
497+ parenthesized (renderSQL expr <> "::" <> renderSQL td)
498+ <> "." <> renderSQL fld
499499
500500instance Semigroup
501− (Expression db from grouping params (nullity ('PGvararray ty))) where
501+ (Expression db params grp from (nullity ('PGvararray ty))) where
502502 (<>) = unsafeBinaryOp "||"
503503
504504instance Monoid
505− (Expression db from grouping params (nullity ('PGvararray ty))) where
505+ (Expression db params grp from (nullity ('PGvararray ty))) where
506506 mempty = array []
507507 mappend = (<>)
508508
509−-- | >>> let expr = greatest currentTimestamp [param @1] :: Expression (commons :=> schemas) rels grp '[ 'NotNull 'PGtimestamptz] ('NotNull 'PGtimestamptz)
509+-- | >>> let expr = greatest currentTimestamp [param @1] :: Expression (commons :=> schemas) '[ 'NotNull 'PGtimestamptz] grp from ('NotNull 'PGtimestamptz)
510510-- >>> printSQL expr
511511-- GREATEST(CURRENT_TIMESTAMP, ($1 :: timestamp with time zone))
512512greatest
513− :: Expression db from grouping params (nullty)
513+ :: Expression db params grp from (nullty)
514514 -- ^ needs at least 1 argument
515− -> [Expression db from grouping params (nullty)]
515+ -> [Expression db params grp from (nullty)]
516516 -- ^ or more
517− -> Expression db from grouping params (nullty)
517+ -> Expression db params grp from (nullty)
518518greatest x xs = UnsafeExpression $ "GREATEST("
519− <> commaSeparated (renderExpression <$> (x:xs)) <> ")"
519+ <> commaSeparated (renderSQL <$> (x:xs)) <> ")"
520520
521521-- | >>> printSQL $ least currentTimestamp [null_]
522522-- LEAST(CURRENT_TIMESTAMP, NULL)
523523least
524− :: Expression db from grouping params (nullty)
524+ :: Expression db params grp from (nullty)
525525 -- ^ needs at least 1 argument
526− -> [Expression db from grouping params (nullty)]
526+ -> [Expression db params grp from (nullty)]
527527 -- ^ or more
528− -> Expression db from grouping params (nullty)
528+ -> Expression db params grp from (nullty)
529529least x xs = UnsafeExpression $ "LEAST("
530− <> commaSeparated (renderExpression <$> (x:xs)) <> ")"
530+ <> commaSeparated (renderSQL <$> (x:xs)) <> ")"
531531
532532-- | >>> printSQL $ unsafeBinaryOp "OR" true false
533533-- (TRUE OR FALSE)
534534unsafeBinaryOp
535535 :: ByteString
536536 -- ^ operator
537− -> Expression db from grouping params (ty0)
538− -> Expression db from grouping params (ty1)
539− -> Expression db from grouping params (ty2)
537+ -> Expression db params grp from (ty0)
538+ -> Expression db params grp from (ty1)
539+ -> Expression db params grp from (ty2)
540540unsafeBinaryOp op x y = UnsafeExpression $ parenthesized $
541− renderExpression x <+> op <+> renderExpression y
541+ renderSQL x <+> op <+> renderSQL y
542542
543543-- | >>> printSQL $ unsafeUnaryOp "NOT" true
544544-- (NOT TRUE)
545545unsafeUnaryOp
546546 :: ByteString
547547 -- ^ operator
548− -> Expression db from grouping params (ty0)
549− -> Expression db from grouping params (ty1)
548+ -> Expression db params grp from (ty0)
549+ -> Expression db params grp from (ty1)
550550unsafeUnaryOp op x = UnsafeExpression $ parenthesized $
551− op <+> renderExpression x
551+ op <+> renderSQL x
552552
553553-- | >>> printSQL $ unsafeFunction "f" true
554554-- f(TRUE)
555555unsafeFunction
556556 :: ByteString
557557 -- ^ function
558− -> Expression db from grouping params (xty)
559− -> Expression db from grouping params (yty)
558+ -> Expression db params grp from (xty)
559+ -> Expression db params grp from (yty)
560560unsafeFunction fun x = UnsafeExpression $
561− fun <> parenthesized (renderExpression x)
561+ fun <> parenthesized (renderSQL x)
562562
563563-- | Helper for defining variadic functions.
564564unsafeVariadicFunction
565565 :: SListI elems
566566 => ByteString
567567 -- ^ function
568− -> NP (Expression db from grouping params) elems
569− -> Expression db from grouping params ret
568+ -> NP (Expression db params grp from) elems
569+ -> Expression db params grp from ret
570570unsafeVariadicFunction fun x = UnsafeExpression $
571− fun <> parenthesized (commaSeparated (hcollapse (hmap (K . renderExpression) x)))
571+ fun <> parenthesized (commaSeparated (hcollapse (hmap (K . renderSQL) x)))
572572
573573instance ty `In` PGNum
574− => Num (Expression db from grouping params (nullity ty)) where
574+ => Num (Expression db params grp from (nullity ty)) where
575575 (+) = unsafeBinaryOp "+"
576576 (-) = unsafeBinaryOp "-"
577577 (*) = unsafeBinaryOp "*"
@@ -583,18 +583,18 @@ instance ty `In` PGNum
583583 . show
584584
585585instance (ty `In` PGNum, ty `In` PGFloating) => Fractional
586− (Expression db from grouping params (nullity ty)) where
586+ (Expression db params grp from (nullity ty)) where
587587 (/) = unsafeBinaryOp "/"
588588 fromRational x = fromInteger (numerator x) / fromInteger (denominator x)
589589
590590instance (ty `In` PGNum, ty `In` PGFloating) => Floating
591− (Expression db from grouping params (nullity ty)) where
591+ (Expression db params grp from (nullity ty)) where
592592 pi = UnsafeExpression "pi()"
593593 exp = unsafeFunction "exp"
594594 log = unsafeFunction "ln"
595595 sqrt = unsafeFunction "sqrt"
596596 b ** x = UnsafeExpression $
597− "power(" <> renderExpression b <> ", " <> renderExpression x <> ")"
597+ "power(" <> renderSQL b <> ", " <> renderSQL x <> ")"
598598 logBase b y = log y / log b
599599 sin = unsafeFunction "sin"
600600 cos = unsafeFunction "cos"
@@ -611,20 +611,20 @@ instance (ty `In` PGNum, ty `In` PGFloating) => Floating
611611
612612-- | >>> :{
613613-- let
614−-- expression :: Expression db from grouping params (nullity 'PGfloat4)
614+-- expression :: Expression db params grp from (nullity 'PGfloat4)
615615-- expression = atan2_ pi 2
616616-- in printSQL expression
617617-- :}
618618-- atan2(pi(), 2)
619619atan2_
620620 :: float `In` PGFloating
621− => Expression db from grouping params (nullity float)
621+ => Expression db params grp from (nullity float)
622622 -- ^ numerator
623− -> Expression db from grouping params (nullity float)
623+ -> Expression db params grp from (nullity float)
624624 -- ^ denominator
625− -> Expression db from grouping params (nullity float)
625+ -> Expression db params grp from (nullity float)
626626atan2_ y x = UnsafeExpression $
627− "atan2(" <> renderExpression y <> ", " <> renderExpression x <> ")"
627+ "atan2(" <> renderSQL y <> ", " <> renderSQL x <> ")"
628628
629629-- When a `cast` is applied to an `Expression` of a known type, it
630630-- represents a run-time type conversion. The cast will succeed only if a
@@ -635,171 +635,171 @@ atan2_ y x = UnsafeExpression $
635635cast
636636 :: TypeExpression schemas ty1
637637 -- ^ type to cast as
638− -> Expression (commons :=> schemas) from grouping params ty0
638+ -> Expression (commons :=> schemas) params grp from ty0
639639 -- ^ value to convert
640− -> Expression (commons :=> schemas) from grouping params ty1
640+ -> Expression (commons :=> schemas) params grp from ty1
641641cast ty x = UnsafeExpression $ parenthesized $
642− renderExpression x <+> "::" <+> renderTypeExpression ty
642+ renderSQL x <+> "::" <+> renderSQL ty
643643
644644-- | integer division, truncates the result
645645--
646646-- >>> :{
647647-- let
648−-- expression :: Expression db from grouping params (nullity 'PGint2)
648+-- expression :: Expression db params grp from (nullity 'PGint2)
649649-- expression = 5 `quot_` 2
650650-- in printSQL expression
651651-- :}
652652-- (5 / 2)
653653quot_
654654 :: int `In` PGIntegral
655− => Expression db from grouping params (nullity int)
655+ => Expression db params grp from (nullity int)
656656 -- ^ numerator
657− -> Expression db from grouping params (nullity int)
657+ -> Expression db params grp from (nullity int)
658658 -- ^ denominator
659− -> Expression db from grouping params (nullity int)
659+ -> Expression db params grp from (nullity int)
660660quot_ = unsafeBinaryOp "/"
661661
662662-- | remainder upon integer division
663663--
664664-- >>> :{
665665-- let
666−-- expression :: Expression db from grouping params (nullity 'PGint2)
666+-- expression :: Expression db params grp from (nullity 'PGint2)
667667-- expression = 5 `rem_` 2
668668-- in printSQL expression
669669-- :}
670670-- (5 % 2)
671671rem_
672672 :: int `In` PGIntegral
673− => Expression db from grouping params (nullity int)
673+ => Expression db params grp from (nullity int)
674674 -- ^ numerator
675− -> Expression db from grouping params (nullity int)
675+ -> Expression db params grp from (nullity int)
676676 -- ^ denominator
677− -> Expression db from grouping params (nullity int)
677+ -> Expression db params grp from (nullity int)
678678rem_ = unsafeBinaryOp "%"
679679
680680-- | >>> :{
681681-- let
682−-- expression :: Expression db from grouping params (nullity 'PGfloat4)
682+-- expression :: Expression db params grp from (nullity 'PGfloat4)
683683-- expression = trunc pi
684684-- in printSQL expression
685685-- :}
686686-- trunc(pi())
687687trunc
688688 :: frac `In` PGFloating
689− => Expression db from grouping params (nullity frac)
689+ => Expression db params grp from (nullity frac)
690690 -- ^ fractional number
691− -> Expression db from grouping params (nullity frac)
691+ -> Expression db params grp from (nullity frac)
692692trunc = unsafeFunction "trunc"
693693
694694-- | >>> :{
695695-- let
696−-- expression :: Expression db from grouping params (nullity 'PGfloat4)
696+-- expression :: Expression db params grp from (nullity 'PGfloat4)
697697-- expression = round_ pi
698698-- in printSQL expression
699699-- :}
700700-- round(pi())
701701round_
702702 :: frac `In` PGFloating
703− => Expression db from grouping params (nullity frac)
703+ => Expression db params grp from (nullity frac)
704704 -- ^ fractional number
705− -> Expression db from grouping params (nullity frac)
705+ -> Expression db params grp from (nullity frac)
706706round_ = unsafeFunction "round"
707707
708708-- | >>> :{
709709-- let
710−-- expression :: Expression db from grouping params (nullity 'PGfloat4)
710+-- expression :: Expression db params grp from (nullity 'PGfloat4)
711711-- expression = ceiling_ pi
712712-- in printSQL expression
713713-- :}
714714-- ceiling(pi())
715715ceiling_
716716 :: frac `In` PGFloating
717− => Expression db from grouping params (nullity frac)
717+ => Expression db params grp from (nullity frac)
718718 -- ^ fractional number
719− -> Expression db from grouping params (nullity frac)
719+ -> Expression db params grp from (nullity frac)
720720ceiling_ = unsafeFunction "ceiling"
721721
722722-- | A `Condition` is an `Expression`, which can evaluate
723723-- to `true`, `false` or `null_`. This is because SQL uses
724724-- a three valued logic.
725−type Condition db from grouping params =
726− Expression db from grouping params ('Null 'PGbool)
725+type Condition db params grp from =
726+ Expression db params grp from ('Null 'PGbool)
727727
728728-- | >>> printSQL true
729729-- TRUE
730−true :: Expression db from grouping params (nullity 'PGbool)
730+true :: Expression db params grp from (nullity 'PGbool)
731731true = UnsafeExpression "TRUE"
732732
733733-- | >>> printSQL false
734734-- FALSE
735−false :: Expression db from grouping params (nullity 'PGbool)
735+false :: Expression db params grp from (nullity 'PGbool)
736736false = UnsafeExpression "FALSE"
737737
738738-- | >>> printSQL $ not_ true
739739-- (NOT TRUE)
740740not_
741− :: Expression db from grouping params (nullity 'PGbool)
742− -> Expression db from grouping params (nullity 'PGbool)
741+ :: Expression db params grp from (nullity 'PGbool)
742+ -> Expression db params grp from (nullity 'PGbool)
743743not_ = unsafeUnaryOp "NOT"
744744
745745-- | >>> printSQL $ true .&& false
746746-- (TRUE AND FALSE)
747747(.&&)
748− :: Expression db from grouping params (nullity 'PGbool)
749− -> Expression db from grouping params (nullity 'PGbool)
750− -> Expression db from grouping params (nullity 'PGbool)
748+ :: Expression db params grp from (nullity 'PGbool)
749+ -> Expression db params grp from (nullity 'PGbool)
750+ -> Expression db params grp from (nullity 'PGbool)
751751infixr 3 .&&
752752(.&&) = unsafeBinaryOp "AND"
753753
754754-- | >>> printSQL $ true .|| false
755755-- (TRUE OR FALSE)
756756(.||)
757− :: Expression db from grouping params (nullity 'PGbool)
758− -> Expression db from grouping params (nullity 'PGbool)
759− -> Expression db from grouping params (nullity 'PGbool)
757+ :: Expression db params grp from (nullity 'PGbool)
758+ -> Expression db params grp from (nullity 'PGbool)
759+ -> Expression db params grp from (nullity 'PGbool)
760760infixr 2 .||
761761(.||) = unsafeBinaryOp "OR"
762762
763763-- | >>> :{
764764-- let
765−-- expression :: Expression db from grouping params (nullity 'PGint2)
765+-- expression :: Expression db params grp from (nullity 'PGint2)
766766-- expression = caseWhenThenElse [(true, 1), (false, 2)] 3
767767-- in printSQL expression
768768-- :}
769769-- CASE WHEN TRUE THEN 1 WHEN FALSE THEN 2 ELSE 3 END
770770caseWhenThenElse
771− :: [ ( Condition db from grouping params
772− , Expression db from grouping params ty
771+ :: [ ( Condition db params grp from
772+ , Expression db params grp from ty
773773 ) ]
774774 -- ^ whens and thens
775− -> Expression db from grouping params ty
775+ -> Expression db params grp from ty
776776 -- ^ else
777− -> Expression db from grouping params ty
777+ -> Expression db params grp from ty
778778caseWhenThenElse whenThens else_ = UnsafeExpression $ mconcat
779779 [ "CASE"
780780 , mconcat
781781 [ mconcat
782− [ " WHEN ", renderExpression when_
783− , " THEN ", renderExpression then_
782+ [ " WHEN ", renderSQL when_
783+ , " THEN ", renderSQL then_
784784 ]
785785 | (when_,then_) <- whenThens
786786 ]
787− , " ELSE ", renderExpression else_
787+ , " ELSE ", renderSQL else_
788788 , " END"
789789 ]
790790
791791-- | >>> :{
792792-- let
793−-- expression :: Expression db from grouping params (nullity 'PGint2)
793+-- expression :: Expression db params grp from (nullity 'PGint2)
794794-- expression = ifThenElse true 1 0
795795-- in printSQL expression
796796-- :}
797797-- CASE WHEN TRUE THEN 1 ELSE 0 END
798798ifThenElse
799− :: Condition db from grouping params
800− -> Expression db from grouping params ty -- ^ then
801− -> Expression db from grouping params ty -- ^ else
802− -> Expression db from grouping params ty
799+ :: Condition db params grp from
800+ -> Expression db params grp from ty -- ^ then
801+ -> Expression db params grp from ty -- ^ else
802+ -> Expression db params grp from ty
803803ifThenElse if_ then_ else_ = caseWhenThenElse [(if_,then_)] else_
804804
805805-- | Comparison operations like `.==`, `./=`, `.>`, `.>=`, `.<` and `.<=`
@@ -808,85 +808,85 @@ ifThenElse if_ then_ else_ = caseWhenThenElse [(if_,then_)] else_
808808-- >>> printSQL $ true .== null_
809809-- (TRUE = NULL)
810810(.==)
811− :: Expression db from grouping params (nullity0 ty) -- ^ lhs
812− -> Expression db from grouping params (nullity1 ty) -- ^ rhs
813− -> Condition db from grouping params
811+ :: Expression db params grp from (nullity0 ty) -- ^ lhs
812+ -> Expression db params grp from (nullity1 ty) -- ^ rhs
813+ -> Condition db params grp from
814814(.==) = unsafeBinaryOp "="
815815infix 4 .==
816816
817817-- | >>> printSQL $ true ./= null_
818818-- (TRUE <> NULL)
819819(./=)
820− :: Expression db from grouping params (nullity0 ty) -- ^ lhs
821− -> Expression db from grouping params (nullity1 ty) -- ^ rhs
822− -> Condition db from grouping params
820+ :: Expression db params grp from (nullity0 ty) -- ^ lhs
821+ -> Expression db params grp from (nullity1 ty) -- ^ rhs
822+ -> Condition db params grp from
823823(./=) = unsafeBinaryOp "<>"
824824infix 4 ./=
825825
826826-- | >>> printSQL $ true .>= null_
827827-- (TRUE >= NULL)
828828(.>=)
829− :: Expression db from grouping params (nullity0 ty) -- ^ lhs
830− -> Expression db from grouping params (nullity1 ty) -- ^ rhs
831− -> Condition db from grouping params
829+ :: Expression db params grp from (nullity0 ty) -- ^ lhs
830+ -> Expression db params grp from (nullity1 ty) -- ^ rhs
831+ -> Condition db params grp from
832832(.>=) = unsafeBinaryOp ">="
833833infix 4 .>=
834834
835835-- | >>> printSQL $ true .< null_
836836-- (TRUE < NULL)
837837(.<)
838− :: Expression db from grouping params (nullity0 ty) -- ^ lhs
839− -> Expression db from grouping params (nullity1 ty) -- ^ rhs
840− -> Condition db from grouping params
838+ :: Expression db params grp from (nullity0 ty) -- ^ lhs
839+ -> Expression db params grp from (nullity1 ty) -- ^ rhs
840+ -> Condition db params grp from
841841(.<) = unsafeBinaryOp "<"
842842infix 4 .<
843843
844844-- | >>> printSQL $ true .<= null_
845845-- (TRUE <= NULL)
846846(.<=)
847− :: Expression db from grouping params (nullity0 ty) -- ^ lhs
848− -> Expression db from grouping params (nullity1 ty) -- ^ rhs
849− -> Condition db from grouping params
847+ :: Expression db params grp from (nullity0 ty) -- ^ lhs
848+ -> Expression db params grp from (nullity1 ty) -- ^ rhs
849+ -> Condition db params grp from
850850(.<=) = unsafeBinaryOp "<="
851851infix 4 .<=
852852
853853-- | >>> printSQL $ true .> null_
854854-- (TRUE > NULL)
855855(.>)
856− :: Expression db from grouping params (nullity0 ty) -- ^ lhs
857− -> Expression db from grouping params (nullity1 ty) -- ^ rhs
858− -> Condition db from grouping params
856+ :: Expression db params grp from (nullity0 ty) -- ^ lhs
857+ -> Expression db params grp from (nullity1 ty) -- ^ rhs
858+ -> Condition db params grp from
859859(.>) = unsafeBinaryOp ">"
860860infix 4 .>
861861
862862-- | >>> printSQL currentDate
863863-- CURRENT_DATE
864864currentDate
865− :: Expression db from grouping params (nullity 'PGdate)
865+ :: Expression db params grp from (nullity 'PGdate)
866866currentDate = UnsafeExpression "CURRENT_DATE"
867867
868868-- | >>> printSQL currentTime
869869-- CURRENT_TIME
870870currentTime
871− :: Expression db from grouping params (nullity 'PGtimetz)
871+ :: Expression db params grp from (nullity 'PGtimetz)
872872currentTime = UnsafeExpression "CURRENT_TIME"
873873
874874-- | >>> printSQL currentTimestamp
875875-- CURRENT_TIMESTAMP
876876currentTimestamp
877− :: Expression db from grouping params (nullity 'PGtimestamptz)
877+ :: Expression db params grp from (nullity 'PGtimestamptz)
878878currentTimestamp = UnsafeExpression "CURRENT_TIMESTAMP"
879879
880880-- | >>> printSQL localTime
881881-- LOCALTIME
882882localTime
883− :: Expression db from grouping params (nullity 'PGtime)
883+ :: Expression db params grp from (nullity 'PGtime)
884884localTime = UnsafeExpression "LOCALTIME"
885885
886886-- | >>> printSQL localTimestamp
887887-- LOCALTIMESTAMP
888888localTimestamp
889− :: Expression db from grouping params (nullity 'PGtimestamp)
889+ :: Expression db params grp from (nullity 'PGtimestamp)
890890localTimestamp = UnsafeExpression "LOCALTIMESTAMP"
891891
892892{-----------------------------------------
@@ -894,7 +894,7 @@ text
894894-----------------------------------------}
895895
896896instance IsString
897− (Expression db from grouping params (nullity 'PGtext)) where
897+ (Expression db params grp from (nullity 'PGtext)) where
898898 fromString str = UnsafeExpression $
899899 "E\'" <> fromString (escape =<< str) <> "\'"
900900 where
@@ -910,36 +910,36 @@ instance IsString
910910 c -> [c]
911911
912912instance Semigroup
913− (Expression db from grouping params (nullity 'PGtext)) where
913+ (Expression db params grp from (nullity 'PGtext)) where
914914 (<>) = unsafeBinaryOp "||"
915915
916916instance Monoid
917− (Expression db from grouping params (nullity 'PGtext)) where
917+ (Expression db params grp from (nullity 'PGtext)) where
918918 mempty = fromString ""
919919 mappend = (<>)
920920
921921-- | >>> printSQL $ lower "ARRRGGG"
922922-- lower(E'ARRRGGG')
923923lower
924− :: Expression db from grouping params (nullity 'PGtext)
924+ :: Expression db params grp from (nullity 'PGtext)
925925 -- ^ string to lower case
926− -> Expression db from grouping params (nullity 'PGtext)
926+ -> Expression db params grp from (nullity 'PGtext)
927927lower = unsafeFunction "lower"
928928
929929-- | >>> printSQL $ upper "eeee"
930930-- upper(E'eeee')
931931upper
932− :: Expression db from grouping params (nullity 'PGtext)
932+ :: Expression db params grp from (nullity 'PGtext)
933933 -- ^ string to upper case
934− -> Expression db from grouping params (nullity 'PGtext)
934+ -> Expression db params grp from (nullity 'PGtext)
935935upper = unsafeFunction "upper"
936936
937937-- | >>> printSQL $ charLength "four"
938938-- char_length(E'four')
939939charLength
940− :: Expression db from grouping params (nullity 'PGtext)
940+ :: Expression db params grp from (nullity 'PGtext)
941941 -- ^ string to measure
942− -> Expression db from grouping params (nullity 'PGint4)
942+ -> Expression db params grp from (nullity 'PGint4)
943943charLength = unsafeFunction "char_length"
944944
945945-- | The `like` expression returns true if the @string@ matches
@@ -952,11 +952,11 @@ charLength = unsafeFunction "char_length"
952952-- >>> printSQL $ "abc" `like` "a%"
953953-- (E'abc' LIKE E'a%')
954954like
955− :: Expression db from grouping params (nullity 'PGtext)
955+ :: Expression db params grp from (nullity 'PGtext)
956956 -- ^ string
957− -> Expression db from grouping params (nullity 'PGtext)
957+ -> Expression db params grp from (nullity 'PGtext)
958958 -- ^ pattern
959− -> Expression db from grouping params (nullity 'PGbool)
959+ -> Expression db params grp from (nullity 'PGbool)
960960like = unsafeBinaryOp "LIKE"
961961
962962-- | The key word ILIKE can be used instead of LIKE to make the
@@ -965,11 +965,11 @@ like = unsafeBinaryOp "LIKE"
965965-- >>> printSQL $ "abc" `ilike` "a%"
966966-- (E'abc' ILIKE E'a%')
967967ilike
968− :: Expression db from grouping params (nullity 'PGtext)
968+ :: Expression db params grp from (nullity 'PGtext)
969969 -- ^ string
970− -> Expression db from grouping params (nullity 'PGtext)
970+ -> Expression db params grp from (nullity 'PGtext)
971971 -- ^ pattern
972− -> Expression db from grouping params (nullity 'PGbool)
972+ -> Expression db params grp from (nullity 'PGbool)
973973ilike = unsafeBinaryOp "ILIKE"
974974
975975{-----------------------------------------
@@ -984,36 +984,36 @@ Table 9.44: json and jsonb operators
984984-- | Get JSON value (object field or array element) at a key.
985985(.->)
986986 :: (json `In` PGJsonType, key `In` PGJsonKey)
987− => Expression db from grouping params (nullity json)
988− -> Expression db from grouping params (nullity key)
989− -> Expression db from grouping params ('Null json)
987+ => Expression db params grp from (nullity json)
988+ -> Expression db params grp from (nullity key)
989+ -> Expression db params grp from ('Null json)
990990infixl 8 .->
991991(.->) = unsafeBinaryOp "->"
992992
993993-- | Get JSON value (object field or array element) at a key, as text.
994994(.->>)
995995 :: (json `In` PGJsonType, key `In` PGJsonKey)
996− => Expression db from grouping params (nullity json)
997− -> Expression db from grouping params (nullity key)
998− -> Expression db from grouping params ('Null 'PGtext)
996+ => Expression db params grp from (nullity json)
997+ -> Expression db params grp from (nullity key)
998+ -> Expression db params grp from ('Null 'PGtext)
999999infixl 8 .->>
10001000(.->>) = unsafeBinaryOp "->>"
10011001
10021002-- | Get JSON value at a specified path.
10031003(.#>)
10041004 :: (json `In` PGJsonType, PGTextArray "(.#>)" path)
1005− => Expression db from grouping params (nullity json)
1006− -> Expression db from grouping params (nullity path)
1007− -> Expression db from grouping params ('Null json)
1005+ => Expression db params grp from (nullity json)
1006+ -> Expression db params grp from (nullity path)
1007+ -> Expression db params grp from ('Null json)
10081008infixl 8 .#>
10091009(.#>) = unsafeBinaryOp "#>"
10101010
10111011-- | Get JSON value at a specified path as text.
10121012(.#>>)
10131013 :: (json `In` PGJsonType, PGTextArray "(.#>>)" path)
1014− => Expression db from grouping params (nullity json)
1015− -> Expression db from grouping params (nullity path)
1016− -> Expression db from grouping params ('Null 'PGtext)
1014+ => Expression db params grp from (nullity json)
1015+ -> Expression db params grp from (nullity path)
1016+ -> Expression db params grp from ('Null 'PGtext)
10171017infixl 8 .#>>
10181018(.#>>) = unsafeBinaryOp "#>>"
10191019
@@ -1022,42 +1022,42 @@ infixl 8 .#>>
10221022-- | Does the left JSON value contain the right JSON path/value entries at the
10231023-- top level?
10241024(.@>)
1025− :: Expression db from grouping params (nullity 'PGjsonb)
1026− -> Expression db from grouping params (nullity 'PGjsonb)
1027− -> Condition db from grouping params
1025+ :: Expression db params grp from (nullity 'PGjsonb)
1026+ -> Expression db params grp from (nullity 'PGjsonb)
1027+ -> Condition db params grp from
10281028infixl 9 .@>
10291029(.@>) = unsafeBinaryOp "@>"
10301030
10311031-- | Are the left JSON path/value entries contained at the top level within the
10321032-- right JSON value?
10331033(.<@)
1034− :: Expression db from grouping params (nullity 'PGjsonb)
1035− -> Expression db from grouping params (nullity 'PGjsonb)
1036− -> Condition db from grouping params
1034+ :: Expression db params grp from (nullity 'PGjsonb)
1035+ -> Expression db params grp from (nullity 'PGjsonb)
1036+ -> Condition db params grp from
10371037infixl 9 .<@
10381038(.<@) = unsafeBinaryOp "<@"
10391039
10401040-- | Does the string exist as a top-level key within the JSON value?
10411041(.?)
1042− :: Expression db from grouping params (nullity 'PGjsonb)
1043− -> Expression db from grouping params (nullity 'PGtext)
1044− -> Condition db from grouping params
1042+ :: Expression db params grp from (nullity 'PGjsonb)
1043+ -> Expression db params grp from (nullity 'PGtext)
1044+ -> Condition db params grp from
10451045infixl 9 .?
10461046(.?) = unsafeBinaryOp "?"
10471047
10481048-- | Do any of these array strings exist as top-level keys?
10491049(.?|)
1050− :: Expression db from grouping params (nullity 'PGjsonb)
1051− -> Expression db from grouping params (nullity ('PGvararray ('NotNull 'PGtext)))
1052− -> Condition db from grouping params
1050+ :: Expression db params grp from (nullity 'PGjsonb)
1051+ -> Expression db params grp from (nullity ('PGvararray ('NotNull 'PGtext)))
1052+ -> Condition db params grp from
10531053infixl 9 .?|
10541054(.?|) = unsafeBinaryOp "?|"
10551055
10561056-- | Do all of these array strings exist as top-level keys?
10571057(.?&)
1058− :: Expression db from grouping params (nullity 'PGjsonb)
1059− -> Expression db from grouping params (nullity ('PGvararray ('NotNull 'PGtext)))
1060− -> Condition db from grouping params
1058+ :: Expression db params grp from (nullity 'PGjsonb)
1059+ -> Expression db params grp from (nullity ('PGvararray ('NotNull 'PGtext)))
1060+ -> Condition db params grp from
10611061infixl 9 .?&
10621062(.?&) = unsafeBinaryOp "?&"
10631063
@@ -1080,9 +1080,9 @@ instance
10801080-- count from the end). Throws an error if top level container is not an array.
10811081(.-.)
10821082 :: (key `In` '[ 'PGtext, 'PGvararray ('NotNull 'PGtext), 'PGint4, 'PGint2 ]) -- hlint error without parens here
1083− => Expression db from grouping params (nullity 'PGjsonb)
1084− -> Expression db from grouping params (nullity key)
1085− -> Expression db from grouping params (nullity 'PGjsonb)
1083+ => Expression db params grp from (nullity 'PGjsonb)
1084+ -> Expression db params grp from (nullity key)
1085+ -> Expression db params grp from (nullity 'PGjsonb)
10861086infixl 6 .-.
10871087(.-.) = unsafeBinaryOp "-"
10881088
@@ -1090,9 +1090,9 @@ infixl 6 .-.
10901090-- integers count from the end)
10911091(#-.)
10921092 :: PGTextArray "(#-.)" arrayty
1093− => Expression db from grouping params (nullity 'PGjsonb)
1094− -> Expression db from grouping params (nullity arrayty)
1095− -> Expression db from grouping params (nullity 'PGjsonb)
1093+ => Expression db params grp from (nullity 'PGjsonb)
1094+ -> Expression db params grp from (nullity arrayty)
1095+ -> Expression db params grp from (nullity 'PGjsonb)
10961096infixl 6 #-.
10971097(#-.) = unsafeBinaryOp "#-"
10981098
@@ -1103,14 +1103,14 @@ Table 9.45: JSON creation functions
11031103-- | Literal binary JSON
11041104jsonbLit
11051105 :: JSON.ToJSON x
1106− => x -> Expression (commons :=> schemas) from grouping params (nullity 'PGjsonb)
1106+ => x -> Expression (commons :=> schemas) params grp from (nullity 'PGjsonb)
11071107jsonbLit = cast jsonb . UnsafeExpression
11081108 . singleQuotedUtf8 . toStrict . JSON.encode
11091109
11101110-- | Literal JSON
11111111jsonLit
11121112 :: JSON.ToJSON x
1113− => x -> Expression (commons :=> schemas) from grouping params (nullity 'PGjson)
1113+ => x -> Expression (commons :=> schemas) params grp from (nullity 'PGjson)
11141114jsonLit = cast json . UnsafeExpression
11151115 . singleQuotedUtf8 . toStrict . JSON.encode
11161116
@@ -1121,8 +1121,8 @@ jsonLit = cast json . UnsafeExpression
11211121-- number, a Boolean, or a null value, the text representation will be used, in
11221122-- such a fashion that it is a valid json value.
11231123toJson
1124− :: Expression db from grouping params (nullity ty)
1125− -> Expression db from grouping params (nullity 'PGjson)
1124+ :: Expression db params grp from (nullity ty)
1125+ -> Expression db params grp from (nullity 'PGjson)
11261126toJson = unsafeFunction "to_json"
11271127
11281128-- | Returns the value as jsonb. Arrays and composites are converted
@@ -1132,56 +1132,59 @@ toJson = unsafeFunction "to_json"
11321132-- number, a Boolean, or a null value, the text representation will be used, in
11331133-- such a fashion that it is a valid jsonb value.
11341134toJsonb
1135− :: Expression db from grouping params (nullity ty)
1136− -> Expression db from grouping params (nullity 'PGjsonb)
1135+ :: Expression db params grp from (nullity ty)
1136+ -> Expression db params grp from (nullity 'PGjsonb)
11371137toJsonb = unsafeFunction "to_jsonb"
11381138
11391139-- | Returns the array as a JSON array. A PostgreSQL multidimensional array
11401140-- becomes a JSON array of arrays.
11411141arrayToJson
11421142 :: PGArray "arrayToJson" arr
1143− => Expression db from grouping params (nullity arr)
1144− -> Expression db from grouping params (nullity 'PGjson)
1143+ => Expression db params grp from (nullity arr)
1144+ -> Expression db params grp from (nullity 'PGjson)
11451145arrayToJson = unsafeFunction "array_to_json"
11461146
11471147-- | Returns the row as a JSON object.
11481148rowToJson
1149− :: Expression db from grouping params (nullity ('PGcomposite ty))
1150− -> Expression db from grouping params (nullity 'PGjson)
1149+ :: Expression db params grp from (nullity ('PGcomposite ty))
1150+ -> Expression db params grp from (nullity 'PGjson)
11511151rowToJson = unsafeFunction "row_to_json"
11521152
11531153-- | Builds a possibly-heterogeneously-typed JSON array out of a variadic
11541154-- argument list.
11551155jsonBuildArray
11561156 :: SListI elems
1157− => NP (Expression db from grouping params) elems
1158− -> Expression db from grouping params (nullity 'PGjson)
1157+ => NP (Expression db params grp from) elems
1158+ -> Expression db params grp from (nullity 'PGjson)
11591159jsonBuildArray = unsafeVariadicFunction "json_build_array"
11601160
11611161-- | Builds a possibly-heterogeneously-typed (binary) JSON array out of a
11621162-- variadic argument list.
11631163jsonbBuildArray
11641164 :: SListI elems
1165− => NP (Expression db from grouping params) elems
1166− -> Expression db from grouping params (nullity 'PGjsonb)
1165+ => NP (Expression db params grp from) elems
1166+ -> Expression db params grp from (nullity 'PGjsonb)
11671167jsonbBuildArray = unsafeVariadicFunction "jsonb_build_array"
11681168
11691169unsafeRowFunction
11701170 :: All Top elems
1171− => NP (Aliased (Expression db from grouping params)) elems
1171+ => NP (Aliased (Expression db params grp from)) elems
11721172 -> [ByteString]
11731173unsafeRowFunction =
11741174 (`appEndo` []) . hcfoldMap (Proxy :: Proxy Top)
11751175 (\(col `As` name) -> Endo $ \xs ->
1176− renderAliasString name : renderExpression col : xs)
1176+ renderAliasString name : renderSQL col : xs)
1177+ where
1178+ renderAliasString :: KnownSymbol alias => Alias alias -> ByteString
1179+ renderAliasString = singleQuotedText . fromString . symbolVal
11771180
11781181-- | Builds a possibly-heterogeneously-typed JSON object out of a variadic
11791182-- argument list. The elements of the argument list must alternate between text
11801183-- and values.
11811184jsonBuildObject
11821185 :: All Top elems
1183− => NP (Aliased (Expression db from grouping params)) elems
1184− -> Expression db from grouping params (nullity 'PGjson)
1186+ => NP (Aliased (Expression db params grp from)) elems
1187+ -> Expression db params grp from (nullity 'PGjson)
11851188jsonBuildObject
11861189 = unsafeFunction "json_build_object"
11871190 . UnsafeExpression
@@ -1193,8 +1196,8 @@ jsonBuildObject
11931196-- between text and values.
11941197jsonbBuildObject
11951198 :: All Top elems
1196− => NP (Aliased (Expression db from grouping params)) elems
1197− -> Expression db from grouping params (nullity 'PGjsonb)
1199+ => NP (Aliased (Expression db params grp from)) elems
1200+ -> Expression db params grp from (nullity 'PGjsonb)
11981201jsonbBuildObject
11991202 = unsafeFunction "jsonb_build_object"
12001203 . UnsafeExpression
@@ -1207,8 +1210,8 @@ jsonbBuildObject
12071210-- array has exactly two elements, which are taken as a key/value pair.
12081211jsonObject
12091212 :: PGArrayOf "jsonObject" arr ('NotNull 'PGtext)
1210− => Expression db from grouping params (nullity arr)
1211− -> Expression db from grouping params (nullity 'PGjson)
1213+ => Expression db params grp from (nullity arr)
1214+ -> Expression db params grp from (nullity 'PGjson)
12121215jsonObject = unsafeFunction "json_object"
12131216
12141217-- | Builds a binary JSON object out of a text array. The array must have either
@@ -1217,8 +1220,8 @@ jsonObject = unsafeFunction "json_object"
12171220-- array has exactly two elements, which are taken as a key/value pair.
12181221jsonbObject
12191222 :: PGArrayOf "jsonbObject" arr ('NotNull 'PGtext)
1220− => Expression db from grouping params (nullity arr)
1221− -> Expression db from grouping params (nullity 'PGjsonb)
1223+ => Expression db params grp from (nullity arr)
1224+ -> Expression db params grp from (nullity 'PGjsonb)
12221225jsonbObject = unsafeFunction "jsonb_object"
12231226
12241227-- | This is an alternate form of 'jsonObject' that takes two arrays; one for
@@ -1226,9 +1229,9 @@ jsonbObject = unsafeFunction "jsonb_object"
12261229jsonZipObject
12271230 :: ( PGArrayOf "jsonZipObject" keysArray ('NotNull 'PGtext)
12281231 , PGArrayOf "jsonZipObject" valuesArray ('NotNull 'PGtext))
1229− => Expression db from grouping params (nullity keysArray)
1230− -> Expression db from grouping params (nullity valuesArray)
1231− -> Expression db from grouping params (nullity 'PGjson)
1232+ => Expression db params grp from (nullity keysArray)
1233+ -> Expression db params grp from (nullity valuesArray)
1234+ -> Expression db params grp from (nullity 'PGjson)
12321235jsonZipObject ks vs =
12331236 unsafeVariadicFunction "json_object" (ks :* vs :* Nil)
12341237
@@ -1238,9 +1241,9 @@ jsonZipObject ks vs =
12381241jsonbZipObject
12391242 :: ( PGArrayOf "jsonbZipObject" keysArray ('NotNull 'PGtext)
12401243 , PGArrayOf "jsonbZipObject" valuesArray ('NotNull 'PGtext))
1241− => Expression db from grouping params (nullity keysArray)
1242− -> Expression db from grouping params (nullity valuesArray)
1243− -> Expression db from grouping params (nullity 'PGjsonb)
1244+ => Expression db params grp from (nullity keysArray)
1245+ -> Expression db params grp from (nullity valuesArray)
1246+ -> Expression db params grp from (nullity 'PGjsonb)
12441247jsonbZipObject ks vs =
12451248 unsafeVariadicFunction "jsonb_object" (ks :* vs :* Nil)
12461249
@@ -1250,23 +1253,23 @@ Table 9.46: JSON processing functions
12501253
12511254-- | Returns the number of elements in the outermost JSON array.
12521255jsonArrayLength
1253− :: Expression db from grouping params (nullity 'PGjson)
1254− -> Expression db from grouping params (nullity 'PGint4)
1256+ :: Expression db params grp from (nullity 'PGjson)
1257+ -> Expression db params grp from (nullity 'PGint4)
12551258jsonArrayLength = unsafeFunction "json_array_length"
12561259
12571260-- | Returns the number of elements in the outermost binary JSON array.
12581261jsonbArrayLength
1259− :: Expression db from grouping params (nullity 'PGjsonb)
1260− -> Expression db from grouping params (nullity 'PGint4)
1262+ :: Expression db params grp from (nullity 'PGjsonb)
1263+ -> Expression db params grp from (nullity 'PGint4)
12611264jsonbArrayLength = unsafeFunction "jsonb_array_length"
12621265
12631266-- | Returns JSON value pointed to by the given path (equivalent to #>
12641267-- operator).
12651268jsonExtractPath
12661269 :: SListI elems
1267− => Expression db from grouping params (nullity 'PGjson)
1268− -> NP (Expression db from grouping params) elems
1269− -> Expression db from grouping params (nullity 'PGjsonb)
1270+ => Expression db params grp from (nullity 'PGjson)
1271+ -> NP (Expression db params grp from) elems
1272+ -> Expression db params grp from (nullity 'PGjsonb)
12701273jsonExtractPath x xs =
12711274 unsafeVariadicFunction "json_extract_path" (x :* xs)
12721275
@@ -1274,9 +1277,9 @@ jsonExtractPath x xs =
12741277-- operator).
12751278jsonbExtractPath
12761279 :: SListI elems
1277− => Expression db from grouping params (nullity 'PGjsonb)
1278− -> NP (Expression db from grouping params) elems
1279− -> Expression db from grouping params (nullity 'PGjsonb)
1280+ => Expression db params grp from (nullity 'PGjsonb)
1281+ -> NP (Expression db params grp from) elems
1282+ -> Expression db params grp from (nullity 'PGjsonb)
12801283jsonbExtractPath x xs =
12811284 unsafeVariadicFunction "jsonb_extract_path" (x :* xs)
12821285
@@ -1284,9 +1287,9 @@ jsonbExtractPath x xs =
12841287-- operator), as text.
12851288jsonExtractPathAsText
12861289 :: SListI elems
1287− => Expression db from grouping params (nullity 'PGjson)
1288− -> NP (Expression db from grouping params) elems
1289− -> Expression db from grouping params (nullity 'PGjson)
1290+ => Expression db params grp from (nullity 'PGjson)
1291+ -> NP (Expression db params grp from) elems
1292+ -> Expression db params grp from (nullity 'PGjson)
12901293jsonExtractPathAsText x xs =
12911294 unsafeVariadicFunction "json_extract_path_text" (x :* xs)
12921295
@@ -1294,38 +1297,38 @@ jsonExtractPathAsText x xs =
12941297-- operator), as text.
12951298jsonbExtractPathAsText
12961299 :: SListI elems
1297− => Expression db from grouping params (nullity 'PGjsonb)
1298− -> NP (Expression db from grouping params) elems
1299− -> Expression db from grouping params (nullity 'PGjsonb)
1300+ => Expression db params grp from (nullity 'PGjsonb)
1301+ -> NP (Expression db params grp from) elems
1302+ -> Expression db params grp from (nullity 'PGjsonb)
13001303jsonbExtractPathAsText x xs =
13011304 unsafeVariadicFunction "jsonb_extract_path_text" (x :* xs)
13021305
13031306-- | Returns the type of the outermost JSON value as a text string. Possible
13041307-- types are object, array, string, number, boolean, and null.
13051308jsonTypeof
1306− :: Expression db from grouping params (nullity 'PGjson)
1307− -> Expression db from grouping params (nullity 'PGtext)
1309+ :: Expression db params grp from (nullity 'PGjson)
1310+ -> Expression db params grp from (nullity 'PGtext)
13081311jsonTypeof = unsafeFunction "json_typeof"
13091312
13101313-- | Returns the type of the outermost binary JSON value as a text string.
13111314-- Possible types are object, array, string, number, boolean, and null.
13121315jsonbTypeof
1313− :: Expression db from grouping params (nullity 'PGjsonb)
1314− -> Expression db from grouping params (nullity 'PGtext)
1316+ :: Expression db params grp from (nullity 'PGjsonb)
1317+ -> Expression db params grp from (nullity 'PGtext)
13151318jsonbTypeof = unsafeFunction "jsonb_typeof"
13161319
13171320-- | Returns its argument with all object fields that have null values omitted.
13181321-- Other null values are untouched.
13191322jsonStripNulls
1320− :: Expression db from grouping params (nullity 'PGjson)
1321− -> Expression db from grouping params (nullity 'PGjson)
1323+ :: Expression db params grp from (nullity 'PGjson)
1324+ -> Expression db params grp from (nullity 'PGjson)
13221325jsonStripNulls = unsafeFunction "json_strip_nulls"
13231326
13241327-- | Returns its argument with all object fields that have null values omitted.
13251328-- Other null values are untouched.
13261329jsonbStripNulls
1327− :: Expression db from grouping params (nullity 'PGjsonb)
1328− -> Expression db from grouping params (nullity 'PGjsonb)
1330+ :: Expression db params grp from (nullity 'PGjsonb)
1331+ -> Expression db params grp from (nullity 'PGjsonb)
13291332jsonbStripNulls = unsafeFunction "jsonb_strip_nulls"
13301333
13311334-- | @ jsonbSet target path new_value create_missing @
@@ -1337,11 +1340,11 @@ jsonbStripNulls = unsafeFunction "jsonb_strip_nulls"
13371340-- arrays.
13381341jsonbSet
13391342 :: PGTextArray "jsonbSet" arr
1340− => Expression db from grouping params (nullity 'PGjsonb)
1341− -> Expression db from grouping params (nullity arr)
1342− -> Expression db from grouping params (nullity 'PGjsonb)
1343− -> Maybe (Expression db from grouping params (nullity 'PGbool))
1344− -> Expression db from grouping params (nullity 'PGjsonb)
1343+ => Expression db params grp from (nullity 'PGjsonb)
1344+ -> Expression db params grp from (nullity arr)
1345+ -> Expression db params grp from (nullity 'PGjsonb)
1346+ -> Maybe (Expression db params grp from (nullity 'PGbool))
1347+ -> Expression db params grp from (nullity 'PGjsonb)
13451348jsonbSet tgt path val createMissing = case createMissing of
13461349 Just m -> unsafeVariadicFunction "jsonb_set" (tgt :* path :* val :* m :* Nil)
13471350 Nothing -> unsafeVariadicFunction "jsonb_set" (tgt :* path :* val :* Nil)
@@ -1356,19 +1359,19 @@ jsonbSet tgt path val createMissing = case createMissing of
13561359-- in path count from the end of JSON arrays.
13571360jsonbInsert
13581361 :: PGTextArray "jsonbInsert" arr
1359− => Expression db from grouping params (nullity 'PGjsonb)
1360− -> Expression db from grouping params (nullity arr)
1361− -> Expression db from grouping params (nullity 'PGjsonb)
1362− -> Maybe (Expression db from grouping params (nullity 'PGbool))
1363− -> Expression db from grouping params (nullity 'PGjsonb)
1362+ => Expression db params grp from (nullity 'PGjsonb)
1363+ -> Expression db params grp from (nullity arr)
1364+ -> Expression db params grp from (nullity 'PGjsonb)
1365+ -> Maybe (Expression db params grp from (nullity 'PGbool))
1366+ -> Expression db params grp from (nullity 'PGjsonb)
13641367jsonbInsert tgt path val insertAfter = case insertAfter of
13651368 Just i -> unsafeVariadicFunction "jsonb_insert" (tgt :* path :* val :* i :* Nil)
13661369 Nothing -> unsafeVariadicFunction "jsonb_insert" (tgt :* path :* val :* Nil)
13671370
13681371-- | Returns its argument as indented JSON text.
13691372jsonbPretty
1370− :: Expression db from grouping params (nullity 'PGjsonb)
1371− -> Expression db from grouping params (nullity 'PGtext)
1373+ :: Expression db params grp from (nullity 'PGjsonb)
1374+ -> Expression db params grp from (nullity 'PGtext)
13721375jsonbPretty = unsafeFunction "jsonb_pretty"
13731376
13741377{-----------------------------------------
@@ -1381,7 +1384,7 @@ unsafeAggregate
13811384 -> Expression db from 'Ungrouped params (xty)
13821385 -> Expression db from ('Grouped bys) params (yty)
13831386unsafeAggregate fun x = UnsafeExpression $ mconcat
1384− [fun, "(", renderExpression x, ")"]
1387+ [fun, "(", renderSQL x, ")"]
13851388
13861389-- | escape hatch to define aggregate functions over distinct values
13871390unsafeAggregateDistinct
@@ -1389,11 +1392,11 @@ unsafeAggregateDistinct
13891392 -> Expression db from 'Ungrouped params (xty)
13901393 -> Expression db from ('Grouped bys) params (yty)
13911394unsafeAggregateDistinct fun x = UnsafeExpression $ mconcat
1392− [fun, "(DISTINCT ", renderExpression x, ")"]
1395+ [fun, "(DISTINCT ", renderSQL x, ")"]
13931396
13941397-- | >>> :{
13951398-- let
1396−-- expression :: Expression db '[tab ::: '["col" ::: 'Null 'PGnumeric]] ('Grouped bys) params ('Null 'PGnumeric)
1399+-- expression :: Expression db params ('Grouped bys) '[tab ::: '["col" ::: 'Null 'PGnumeric]] ('Null 'PGnumeric)
13971400-- expression = sum_ #col
13981401-- in printSQL expression
13991402-- :}
@@ -1407,7 +1410,7 @@ sum_ = unsafeAggregate "sum"
14071410
14081411-- | >>> :{
14091412-- let
1410−-- expression :: Expression db '[tab ::: '["col" ::: nullity 'PGnumeric]] ('Grouped bys) params (nullity 'PGnumeric)
1413+-- expression :: Expression db params ('Grouped bys) '[tab ::: '["col" ::: nullity 'PGnumeric]] (nullity 'PGnumeric)
14111414-- expression = sumDistinct #col
14121415-- in printSQL expression
14131416-- :}
@@ -1438,7 +1441,7 @@ instance PGAvg 'PGinterval 'PGinterval
14381441
14391442-- | >>> :{
14401443-- let
1441−-- expression :: Expression db '[tab ::: '["col" ::: nullity 'PGint4]] (Grouped bys) params (nullity 'PGint4)
1444+-- expression :: Expression db params (Grouped bys) '[tab ::: '["col" ::: nullity 'PGint4]] (nullity 'PGint4)
14421445-- expression = bitAnd #col
14431446-- in printSQL expression
14441447-- :}
@@ -1452,7 +1455,7 @@ bitAnd = unsafeAggregate "bit_and"
14521455
14531456-- | >>> :{
14541457-- let
1455−-- expression :: Expression db '[tab ::: '["col" ::: nullity 'PGint4]] (Grouped bys) params (nullity 'PGint4)
1458+-- expression :: Expression db params ('Grouped bys) '[tab ::: '["col" ::: nullity 'PGint4]] (nullity 'PGint4)
14561459-- expression = bitOr #col
14571460-- in printSQL expression
14581461-- :}
@@ -1466,7 +1469,7 @@ bitOr = unsafeAggregate "bit_or"
14661469
14671470-- | >>> :{
14681471-- let
1469−-- expression :: Expression db '[tab ::: '["col" ::: nullity 'PGint4]] (Grouped bys) params (nullity 'PGint4)
1472+-- expression :: Expression db params ('Grouped bys) '[tab ::: '["col" ::: nullity 'PGint4]] (nullity 'PGint4)
14701473-- expression = bitAndDistinct #col
14711474-- in printSQL expression
14721475-- :}
@@ -1480,7 +1483,7 @@ bitAndDistinct = unsafeAggregateDistinct "bit_and"
14801483
14811484-- | >>> :{
14821485-- let
1483−-- expression :: Expression db '[tab ::: '["col" ::: nullity 'PGint4]] (Grouped bys) params (nullity 'PGint4)
1486+-- expression :: Expression db params (Grouped bys) '[tab ::: '["col" ::: nullity 'PGint4]] (nullity 'PGint4)
14841487-- expression = bitOrDistinct #col
14851488-- in printSQL expression
14861489-- :}
@@ -1494,7 +1497,7 @@ bitOrDistinct = unsafeAggregateDistinct "bit_or"
14941497
14951498-- | >>> :{
14961499-- let
1497−-- expression :: Expression db '[tab ::: '["col" ::: nullity 'PGbool]] (Grouped bys) params (nullity 'PGbool)
1500+-- expression :: Expression db params (Grouped bys) '[tab ::: '["col" ::: nullity 'PGbool]] (nullity 'PGbool)
14981501-- expression = boolAnd #col
14991502-- in printSQL expression
15001503-- :}
@@ -1507,7 +1510,7 @@ boolAnd = unsafeAggregate "bool_and"
15071510
15081511-- | >>> :{
15091512-- let
1510−-- expression :: Expression db '[tab ::: '["col" ::: nullity 'PGbool]] (Grouped bys) params (nullity 'PGbool)
1513+-- expression :: Expression db params (Grouped bys) '[tab ::: '["col" ::: nullity 'PGbool]] (nullity 'PGbool)
15111514-- expression = boolOr #col
15121515-- in printSQL expression
15131516-- :}
@@ -1520,7 +1523,7 @@ boolOr = unsafeAggregate "bool_or"
15201523
15211524-- | >>> :{
15221525-- let
1523−-- expression :: Expression db '[tab ::: '["col" ::: nullity 'PGbool]] (Grouped bys) params (nullity 'PGbool)
1526+-- expression :: Expression db params (Grouped bys) '[tab ::: '["col" ::: nullity 'PGbool]] (nullity 'PGbool)
15241527-- expression = boolAndDistinct #col
15251528-- in printSQL expression
15261529-- :}
@@ -1533,7 +1536,7 @@ boolAndDistinct = unsafeAggregateDistinct "bool_and"
15331536
15341537-- | >>> :{
15351538-- let
1536−-- expression :: Expression db '[tab ::: '["col" ::: nullity 'PGbool]] (Grouped bys) params (nullity 'PGbool)
1539+-- expression :: Expression db params (Grouped bys) '[tab ::: '["col" ::: nullity 'PGbool]] (nullity 'PGbool)
15371540-- expression = boolOrDistinct #col
15381541-- in printSQL expression
15391542-- :}
@@ -1554,7 +1557,7 @@ countStar = UnsafeExpression $ "count(*)"
15541557
15551558-- | >>> :{
15561559-- let
1557−-- expression :: Expression db '[tab ::: '["col" ::: nullity ty]] (Grouped bys) params ('NotNull 'PGint8)
1560+-- expression :: Expression db params (Grouped bys) '[tab ::: '["col" ::: nullity ty]] ('NotNull 'PGint8)
15581561-- expression = count #col
15591562-- in printSQL expression
15601563-- :}
@@ -1567,7 +1570,7 @@ count = unsafeAggregate "count"
15671570
15681571-- | >>> :{
15691572-- let
1570−-- expression :: Expression db '[tab ::: '["col" ::: nullity ty]] (Grouped bys) params ('NotNull 'PGint8)
1573+-- expression :: Expression db params (Grouped bys) '[tab ::: '["col" ::: nullity ty]] ('NotNull 'PGint8)
15711574-- expression = countDistinct #col
15721575-- in printSQL expression
15731576-- :}
@@ -1582,7 +1585,7 @@ countDistinct = unsafeAggregateDistinct "count"
15821585--
15831586-- >>> :{
15841587-- let
1585−-- expression :: Expression db '[tab ::: '["col" ::: nullity 'PGbool]] (Grouped bys) params (nullity 'PGbool)
1588+-- expression :: Expression db params (Grouped bys) '[tab ::: '["col" ::: nullity 'PGbool]] (nullity 'PGbool)
15861589-- expression = every #col
15871590-- in printSQL expression
15881591-- :}
@@ -1597,7 +1600,7 @@ every = unsafeAggregate "every"
15971600--
15981601-- >>> :{
15991602-- let
1600−-- expression :: Expression db '[tab ::: '["col" ::: nullity 'PGbool]] (Grouped bys) params (nullity 'PGbool)
1603+-- expression :: Expression db params (Grouped bys) '[tab ::: '["col" ::: nullity 'PGbool]] (nullity 'PGbool)
16011604-- expression = everyDistinct #col
16021605-- in printSQL expression
16031606-- :}
@@ -1626,13 +1629,15 @@ type expressions
16261629newtype TypeExpression (schemas :: SchemasType) (ty :: NullityType)
16271630 = UnsafeTypeExpression { renderTypeExpression :: ByteString }
16281631 deriving (GHC.Generic,Show,Eq,Ord,NFData)
1632+instance RenderSQL (TypeExpression schemas ty) where
1633+ renderSQL = renderTypeExpression
16291634
16301635-- | The enum or composite type in a `Typedef` can be expressed by its alias.
16311636typedef
16321637 :: (Has sch schemas schema, Has td schema ('Typedef ty))
16331638 => QualifiedAlias sch td
16341639 -> TypeExpression schemas (nullity ty)
1635−typedef = UnsafeTypeExpression . renderQualifiedAlias
1640+typedef = UnsafeTypeExpression . renderSQL
16361641
16371642-- | The composite type corresponding to a `Table` definition can be expressed
16381643-- by its alias.
@@ -1640,7 +1645,7 @@ typetable
16401645 :: (Has sch schemas schema, Has tab schema ('Table table))
16411646 => QualifiedAlias sch tab
16421647 -> TypeExpression schemas (nullity ('PGcomposite (TableToRow table)))
1643−typetable = UnsafeTypeExpression . renderQualifiedAlias
1648+typetable = UnsafeTypeExpression . renderSQL
16441649
16451650-- | The composite type corresponding to a `View` definition can be expressed
16461651-- by its alias.
@@ -1648,7 +1653,7 @@ typeview
16481653 :: (Has sch schemas schema, Has vw schema ('View view))
16491654 => QualifiedAlias sch vw
16501655 -> TypeExpression schemas (nullity ('PGcomposite view))
1651−typeview = UnsafeTypeExpression . renderQualifiedAlias
1656+typeview = UnsafeTypeExpression . renderSQL
16521657
16531658-- | logical Boolean (true/false)
16541659bool :: TypeExpression schemas (nullity 'PGbool)
@@ -1730,17 +1735,17 @@ jsonb = UnsafeTypeExpression "jsonb"
17301735vararray
17311736 :: TypeExpression schemas pg
17321737 -> TypeExpression schemas (nullity ('PGvararray pg))
1733−vararray ty = UnsafeTypeExpression $ renderTypeExpression ty <> "[]"
1738+vararray ty = UnsafeTypeExpression $ renderSQL ty <> "[]"
17341739-- | fixed length array
17351740--
1736−-- >>> renderTypeExpression (fixarray @2 json)
1741+-- >>> renderSQL (fixarray @2 json)
17371742-- "json[2]"
17381743fixarray
17391744 :: forall n schemas nullity pg. KnownNat n
17401745 => TypeExpression schemas pg
17411746 -> TypeExpression schemas (nullity ('PGfixarray n pg))
17421747fixarray ty = UnsafeTypeExpression $
1743− renderTypeExpression ty <> "[" <> renderNat @n <> "]"
1748+ renderSQL ty <> "[" <> renderNat @n <> "]"
17441749
17451750-- | `pgtype` is a demoted version of a `PGType`
17461751class PGTyped schemas (ty :: NullityType) where
squeal-postgresql/src/Squeal/PostgreSQL/Manipulation.hs+144−166
@@ -35,6 +35,7 @@ module Squeal.PostgreSQL.Manipulation
3535 , DefaultAliasable (..)
3636 , ColumnExpression (..)
3737 , ReturningClause (..)
38+ , pattern Returning_
3839 , ConflictClause (..)
3940 , ConflictTarget (..)
4041 , ConflictAction (..)
@@ -42,10 +43,6 @@ module Squeal.PostgreSQL.Manipulation
4243 -- * Insert
4344 , insertInto
4445 , insertInto_
45− , renderReturningClause
46− , renderConflictClause
47− , renderConflictTarget
48− , renderConflictAction
4946 -- * Update
5047 , update
5148 , update_
@@ -123,7 +120,7 @@ let
123120 (Values_ ("John Smith" `as` #name :* "john@smith.com" `as` #email))
124121 (OnConflict (OnConstraint #uq)
125122 (DoUpdate (((#excluded ! #email) <> "; " <> (#customers ! #email)) `as` #email) []))
126− (Returning Nil)
123+ (Returning_ Nil)
127124in printSQL manipulation
128125:}
129126INSERT INTO "customers" ("name", "email") VALUES (E'John Smith', E'john@smith.com') ON CONFLICT ON CONSTRAINT "uq" DO UPDATE SET "email" = ("excluded"."email" || (E'; ' || "customers"."email"))
@@ -133,7 +130,7 @@ query insert:
133130>>> :{
134131let
135132 manipulation :: Manipulation (DBof (Public Schema)) '[] '[]
136− manipulation = insertInto_ #tab (Subquery (selectStar (from (table #tab))))
133+ manipulation = insertInto_ #tab (Subquery (select Star (from (table #tab))))
137134in printSQL manipulation
138135:}
139136INSERT INTO "tab" SELECT * FROM "tab" AS "tab"
@@ -155,7 +152,7 @@ let
155152 manipulation :: Manipulation (DBof (Public Schema)) '[]
156153 '[ "col1" ::: 'NotNull 'PGint4
157154 , "col2" ::: 'NotNull 'PGint4 ]
158− manipulation = deleteFrom #tab NoUsing (#col1 .== #col2) ReturningStar
155+ manipulation = deleteFrom #tab NoUsing (#col1 .== #col2) (Returning Star)
159156in printSQL manipulation
160157:}
161158DELETE FROM "tab" WHERE ("col1" = "col2") RETURNING *
@@ -188,8 +185,8 @@ with manipulation:
188185let
189186 manipulation :: Manipulation (DBof (Public ProductsSchema)) '[ 'NotNull 'PGdate] '[]
190187 manipulation = with
191− (deleteFrom #products NoUsing (#date .< param @1) ReturningStar `as` #del)
192− (insertInto_ #products_deleted (Subquery (selectStar (from (common #del)))))
188+ (deleteFrom #products NoUsing (#date .< param @1) (Returning Star) `as` #del)
189+ (insertInto_ #products_deleted (Subquery (select Star (from (common #del)))))
193190in printSQL manipulation
194191:}
195192WITH "del" AS (DELETE FROM "products" WHERE ("date" < ($1 :: date)) RETURNING *) INSERT INTO "products_deleted" SELECT * FROM "del" AS "del"
@@ -206,14 +203,14 @@ instance RenderSQL (Manipulation db params columns) where
206203instance With Manipulation where
207204 with Done manip = manip
208205 with (cte :>> ctes) manip = UnsafeManipulation $
209− "WITH" <+> renderCommonTableExpressions renderManipulation cte ctes
210− <+> renderManipulation manip
206+ "WITH" <+> renderCommonTableExpressions renderSQL cte ctes
207+ <+> renderSQL manip
211208
212209-- | Convert a `Query` into a `Manipulation`.
213210queryStatement
214211 :: Query db params columns
215212 -> Manipulation db params columns
216−queryStatement q = UnsafeManipulation $ renderQuery q
213+queryStatement q = UnsafeManipulation $ renderSQL q
217214
218215{-----------------------------------------
219216INSERT statements
@@ -231,19 +228,19 @@ insertInto
231228 , Has sch schemas schema
232229 , Has tab schema ('Table table)
233230 , columns ~ TableToColumns table
234− , row ~ TableToRow table
231+ , row0 ~ TableToRow table
235232 , SOP.SListI columns
236− , SOP.SListI result )
233+ , SOP.SListI row1 )
237234 => QualifiedAlias sch tab
238235 -> QueryClause db params columns
239236 -> ConflictClause tab db params table
240− -> ReturningClause db params row result
241− -> Manipulation db params result
237+ -> ReturningClause db params '[tab ::: row0] row1
238+ -> Manipulation db params row1
242239insertInto tab qry conflict ret = UnsafeManipulation $
243− "INSERT" <+> "INTO" <+> renderQualifiedAlias tab
244− <+> renderQueryClause qry
245− <> renderConflictClause conflict
246− <> renderReturningClause ret
240+ "INSERT" <+> "INTO" <+> renderSQL tab
241+ <+> renderSQL qry
242+ <> renderSQL conflict
243+ <> renderSQL ret
247244
248245insertInto_
249246 :: ( db ~ (commons :=> schemas)
@@ -256,147 +253,143 @@ insertInto_
256253 -> QueryClause db params columns
257254 -> Manipulation db params '[]
258255insertInto_ tab qry =
259− insertInto tab qry OnConflictDoRaise (Returning Nil)
256+ insertInto tab qry OnConflictDoRaise (Returning_ Nil)
260257
261258data QueryClause db params columns where
262259 Values
263260 :: SOP.SListI columns
264− => NP (ColumnExpression db '[] 'Ungrouped params) columns
265− -> [NP (ColumnExpression db '[] 'Ungrouped params) columns]
261+ => NP (ColumnExpression db params 'Ungrouped '[]) columns
262+ -> [NP (ColumnExpression db params 'Ungrouped '[]) columns]
266263 -> QueryClause db params columns
267264 Select
268265 :: SOP.SListI columns
269− => NP (ColumnExpression db from grp params) columns
270− -> TableExpression db params from grp
266+ => NP (ColumnExpression db params grp from) columns
267+ -> TableExpression db params grp from
271268 -> QueryClause db params columns
272269 Subquery
273270 :: ColumnsToRow columns ~ row
274271 => Query db params row
275272 -> QueryClause db params columns
276273
277−renderQueryClause
278− :: QueryClause db params columns
279− -> ByteString
280−renderQueryClause = \case
281− Values row0 rows ->
282− parenthesized (renderCommaSeparated renderAliasPart row0)
283− <+> "VALUES"
284− <+> commaSeparated
285− ( parenthesized
286− . renderCommaSeparated renderValuePart <$> row0 : rows )
287− Select row0 tab ->
288− parenthesized (renderCommaSeparatedMaybe renderAliasPartMaybe row0)
289− <+> "SELECT"
290− <+> renderCommaSeparatedMaybe renderValuePartMaybe row0
291− <+> renderTableExpression tab
292− Subquery qry -> renderQuery qry
293− where
294− renderAliasPartMaybe, renderValuePartMaybe
295− :: ColumnExpression db from grp params column -> Maybe ByteString
296− renderAliasPartMaybe = \case
297− DefaultAs _ -> Nothing
298− Specific (_ `As` name) -> Just $ renderAlias name
299− renderValuePartMaybe = \case
300− DefaultAs _ -> Nothing
301− Specific (value `As` _) -> Just $ renderExpression value
302− renderAliasPart, renderValuePart
303− :: ColumnExpression db from grp params column -> ByteString
304− renderAliasPart = \case
305− DefaultAs name -> renderAlias name
306− Specific (_ `As` name) -> renderAlias name
307− renderValuePart = \case
308− DefaultAs _ -> "DEFAULT"
309− Specific (value `As` _) -> renderExpression value
274+instance RenderSQL (QueryClause db params columns) where
275+ renderSQL = \case
276+ Values row0 rows ->
277+ parenthesized (renderCommaSeparated renderSQLPart row0)
278+ <+> "VALUES"
279+ <+> commaSeparated
280+ ( parenthesized
281+ . renderCommaSeparated renderValuePart <$> row0 : rows )
282+ Select row0 tab ->
283+ parenthesized (renderCommaSeparatedMaybe renderSQLPartMaybe row0)
284+ <+> "SELECT"
285+ <+> renderCommaSeparatedMaybe renderValuePartMaybe row0
286+ <+> renderSQL tab
287+ Subquery qry -> renderQuery qry
288+ where
289+ renderSQLPartMaybe, renderValuePartMaybe
290+ :: ColumnExpression db params grp from column -> Maybe ByteString
291+ renderSQLPartMaybe = \case
292+ DefaultAs _ -> Nothing
293+ Specific (_ `As` name) -> Just $ renderSQL name
294+ renderValuePartMaybe = \case
295+ DefaultAs _ -> Nothing
296+ Specific (value `As` _) -> Just $ renderExpression value
297+ renderSQLPart, renderValuePart
298+ :: ColumnExpression db params grp from column -> ByteString
299+ renderSQLPart = \case
300+ DefaultAs name -> renderSQL name
301+ Specific (_ `As` name) -> renderSQL name
302+ renderValuePart = \case
303+ DefaultAs _ -> "DEFAULT"
304+ Specific (value `As` _) -> renderExpression value
310305
311306pattern Values_
312307 :: SOP.SListI columns
313− => NP (ColumnExpression db '[] 'Ungrouped params) columns
308+ => NP (ColumnExpression db params 'Ungrouped '[]) columns
314309 -> QueryClause db params columns
315310pattern Values_ vals = Values vals []
316311
317−data ColumnExpression db from grp params column where
312+data ColumnExpression db params grp from column where
318313 DefaultAs
319314 :: KnownSymbol col
320315 => Alias col
321− -> ColumnExpression db from grp params (col ::: 'Def :=> ty)
316+ -> ColumnExpression db params grp from (col ::: 'Def :=> ty)
322317 Specific
323− :: Aliased (Expression db from grp params) (col ::: ty)
324− -> ColumnExpression db from grp params (col ::: defness :=> ty)
318+ :: Aliased (Expression db params grp from) (col ::: ty)
319+ -> ColumnExpression db params grp from (col ::: defness :=> ty)
325320
326321instance (KnownSymbol col, column ~ (col ::: defness :=> ty))
327322 => Aliasable col
328− (Expression db from grp params ty)
329− (ColumnExpression db from grp params column) where
323+ (Expression db params grp from ty)
324+ (ColumnExpression db params grp from column) where
330325 expression `as` col = Specific (expression `As` col)
331326instance (KnownSymbol col, columns ~ '[col ::: defness :=> ty])
332327 => Aliasable col
333− (Expression db from grp params ty)
334− (NP (ColumnExpression db from grp params) columns) where
328+ (Expression db params grp from ty)
329+ (NP (ColumnExpression db params grp from) columns) where
335330 expression `as` col = expression `as` col :* Nil
336331instance (KnownSymbol col, column ~ (col ::: 'Def :=> ty))
337− => DefaultAliasable col (ColumnExpression db from grp params column) where
332+ => DefaultAliasable col (ColumnExpression db params grp from column) where
338333 defaultAs = DefaultAs
339334instance (KnownSymbol col, columns ~ '[col ::: 'Def :=> ty])
340− => DefaultAliasable col (NP (ColumnExpression db from grp params) columns) where
335+ => DefaultAliasable col (NP (ColumnExpression db params grp from) columns) where
341336 defaultAs col = defaultAs col :* Nil
342337
343−instance (HasUnique tab from row, Has col row ty, colty ~ (col ::: defness :=> ty))
344− => IsLabel col (ColumnExpression db from 'Ungrouped params colty) where
338+instance (HasUnique tab from row, Has col row ty, column ~ (col ::: defness :=> ty))
339+ => IsLabel col (ColumnExpression db params 'Ungrouped from column) where
345340 fromLabel = fromLabel @col `as` Alias
346−instance (HasUnique tab from row, Has col row ty, coltys ~ '[col ::: defness :=> ty])
341+instance (HasUnique tab from row, Has col row ty, columns ~ '[col ::: defness :=> ty])
347342 => IsLabel col
348− (NP (ColumnExpression db from 'Ungrouped params) coltys) where
343+ (NP (ColumnExpression db params 'Ungrouped from) columns) where
349344 fromLabel = fromLabel @col `as` Alias
350345
351−instance (Has tab from row, Has col row ty, colty ~ (col ::: defness :=> ty))
352− => IsQualified tab col (ColumnExpression db from 'Ungrouped params colty) where
346+instance (Has tab from row, Has col row ty, column ~ (col ::: defness :=> ty))
347+ => IsQualified tab col (ColumnExpression db params 'Ungrouped from column) where
353348 tab ! col = tab ! col `as` col
354−instance (Has tab from row, Has col row ty, coltys ~ '[col ::: defness :=> ty])
355− => IsQualified tab col (NP (ColumnExpression db from 'Ungrouped params) coltys) where
349+instance (Has tab from row, Has col row ty, columns ~ '[col ::: defness :=> ty])
350+ => IsQualified tab col (NP (ColumnExpression db params 'Ungrouped from) columns) where
356351 tab ! col = tab ! col `as` col
357352
358353instance
359354 ( HasUnique tab from row
360355 , Has col row ty
361356 , GroupedBy tab col bys
362− , colty ~ (col ::: defness :=> ty)
357+ , column ~ (col ::: defness :=> ty)
363358 ) => IsLabel col
364− (ColumnExpression db from ('Grouped bys) params colty) where
359+ (ColumnExpression db params ('Grouped bys) from column) where
365360 fromLabel = fromLabel @col `as` Alias
366361instance
367362 ( HasUnique tab from row
368363 , Has col row ty
369364 , GroupedBy tab col bys
370− , coltys ~ '[col ::: defness :=> ty]
365+ , columns ~ '[col ::: defness :=> ty]
371366 ) => IsLabel col
372− (NP (ColumnExpression db from ('Grouped bys) params) coltys) where
367+ (NP (ColumnExpression db params ('Grouped bys) from) columns) where
373368 fromLabel = fromLabel @col `as` Alias
374369
375370instance
376371 ( Has tab from row
377372 , Has col row ty
378373 , GroupedBy tab col bys
379− , colty ~ (col ::: defness :=> ty)
374+ , column ~ (col ::: defness :=> ty)
380375 ) => IsQualified tab col
381− (ColumnExpression db from ('Grouped bys) params colty) where
376+ (ColumnExpression db params ('Grouped bys) from column) where
382377 tab ! col = tab ! col `as` col
383378instance
384379 ( Has tab from row
385380 , Has col row ty
386381 , GroupedBy tab col bys
387− , coltys ~ '[col ::: defness :=> ty]
382+ , columns ~ '[col ::: defness :=> ty]
388383 ) => IsQualified tab col
389− (NP (ColumnExpression db from ('Grouped bys) params) coltys) where
384+ (NP (ColumnExpression db params ('Grouped bys) from) columns) where
390385 tab ! col = tab ! col :* Nil
391386
392−renderColumnExpression
393− :: ColumnExpression db from grp params column
394− -> ByteString
395−renderColumnExpression = \case
396− DefaultAs col ->
397− renderAlias col <+> "=" <+> "DEFAULT"
398− Specific (expression `As` col) ->
399− renderAlias col <+> "=" <+> renderExpression expression
387+instance RenderSQL (ColumnExpression db params grp from column) where
388+ renderSQL = \case
389+ DefaultAs col ->
390+ renderSQL col <+> "=" <+> "DEFAULT"
391+ Specific (expression `As` col) ->
392+ renderSQL col <+> "=" <+> renderSQL expression
400393
401394-- | A `ReturningClause` computes and return value(s) based
402395-- on each row actually inserted, updated or deleted. This is primarily
@@ -408,28 +401,19 @@ renderColumnExpression = \case
408401-- the row will not be returned. `ReturningStar` will return all columns
409402-- in the row. Use @Returning Nil@ in the common case where no return
410403-- values are desired.
411−data ReturningClause
412− (db :: DBType)
413− (params :: [NullityType])
414− (row0 :: RowType)
415− (row1 :: RowType)
416− where
417− ReturningStar
418− :: ReturningClause db params row row
419− Returning
420− :: NP (Aliased (Expression db '[table ::: row0] 'Ungrouped params)) row1
421− -> ReturningClause db params row0 row1
422−
423−-- | Render a `ReturningClause`.
424−renderReturningClause
425− :: SOP.SListI results
426− => ReturningClause db params columns results
427− -> ByteString
428−renderReturningClause = \case
429− ReturningStar -> " RETURNING *"
430− Returning Nil -> ""
431− Returning results -> " RETURNING"
432− <+> renderCommaSeparated (renderAliasedAs renderExpression) results
404+newtype ReturningClause db params from row =
405+ Returning (Selection db params 'Ungrouped from row)
406+
407+instance RenderSQL (ReturningClause db params from row) where
408+ renderSQL = \case
409+ Returning (List Nil) -> ""
410+ Returning selection -> " RETURNING" <+> renderSQL selection
411+
412+pattern Returning_
413+ :: SOP.SListI row
414+ => NP (Aliased (Expression db params 'Ungrouped from)) row
415+ -> ReturningClause db params from row
416+pattern Returning_ list = Returning (List list)
433417
434418-- | A `ConflictClause` specifies an action to perform upon a constraint
435419-- violation. `OnConflictDoRaise` will raise an error.
@@ -444,14 +428,12 @@ data ConflictClause tab db params table where
444428 -> ConflictClause tab db params (constraints :=> columns)
445429
446430-- | Render a `ConflictClause`.
447−renderConflictClause
448− :: SOP.SListI (TableToColumns table)
449− => ConflictClause tab db params table
450− -> ByteString
451−renderConflictClause = \case
452− OnConflictDoRaise -> ""
453− OnConflict target action -> " ON CONFLICT"
454− <+> renderConflictTarget target <+> renderConflictAction action
431+instance SOP.SListI (TableToColumns table)
432+ => RenderSQL (ConflictClause tab db params table) where
433+ renderSQL = \case
434+ OnConflictDoRaise -> ""
435+ OnConflict target action -> " ON CONFLICT"
436+ <+> renderSQL target <+> renderSQL action
455437
456438data ConflictAction tab db params columns where
457439 DoNothing :: ConflictAction tab db params columns
@@ -461,21 +443,19 @@ data ConflictAction tab db params columns where
461443 , columns ~ (col0 ': cols)
462444 , SOP.All (HasIn columns) subcolumns
463445 , AllUnique subcolumns )
464− => NP (ColumnExpression db '[tab ::: row, "excluded" ::: row] 'Ungrouped params) subcolumns
465− -> [Condition db '[tab ::: row, "excluded" ::: row] 'Ungrouped params]
446+ => NP (ColumnExpression db params 'Ungrouped '[tab ::: row, "excluded" ::: row]) subcolumns
447+ -> [Condition db params 'Ungrouped '[tab ::: row, "excluded" ::: row]]
466448 -> ConflictAction tab db params columns
467449
468−renderConflictAction
469− :: ConflictAction tab db params columns
470− -> ByteString
471−renderConflictAction = \case
472− DoNothing -> "DO NOTHING"
473− DoUpdate updates whs'
474− -> "DO UPDATE SET"
475− <+> renderCommaSeparated renderColumnExpression updates
476− <> case whs' of
477− [] -> ""
478− wh:whs -> " WHERE" <+> renderExpression (foldr (.&&) wh whs)
450+instance RenderSQL (ConflictAction tab db params columns) where
451+ renderSQL = \case
452+ DoNothing -> "DO NOTHING"
453+ DoUpdate updates whs'
454+ -> "DO UPDATE SET"
455+ <+> renderCommaSeparated renderSQL updates
456+ <> case whs' of
457+ [] -> ""
458+ wh:whs -> " WHERE" <+> renderSQL (foldr (.&&) wh whs)
479459
480460-- | A `ConflictTarget` specifies the constraint violation that triggers a
481461-- `ConflictAction`.
@@ -486,11 +466,9 @@ data ConflictTarget constraints where
486466 -> ConflictTarget constraints
487467
488468-- | Render a `ConflictTarget`
489−renderConflictTarget
490− :: ConflictTarget constraints
491− -> ByteString
492−renderConflictTarget (OnConstraint con) =
493− "ON" <+> "CONSTRAINT" <+> renderAlias con
469+instance RenderSQL (ConflictTarget constraints) where
470+ renderSQL (OnConstraint con) =
471+ "ON" <+> "CONSTRAINT" <+> renderSQL con
494472
495473{-----------------------------------------
496474UPDATE statements
@@ -500,28 +478,28 @@ UPDATE statements
500478-- in all rows that satisfy the condition.
501479update
502480 :: ( SOP.SListI columns
503− , SOP.SListI results
481+ , SOP.SListI row1
504482 , db ~ (commons :=> schemas)
505483 , Has sch schemas schema
506484 , Has tab schema ('Table table)
507− , row ~ TableToRow table
485+ , row0 ~ TableToRow table
508486 , columns ~ TableToColumns table
509487 , SOP.All (HasIn columns) subcolumns
510488 , AllUnique subcolumns )
511489 => QualifiedAlias sch tab -- ^ table to update
512− -> NP (ColumnExpression db '[tab ::: row] 'Ungrouped params) subcolumns
490+ -> NP (ColumnExpression db params 'Ungrouped '[tab ::: row0]) subcolumns
513491 -- ^ modified values to replace old values
514− -> Condition db '[tab ::: row] 'Ungrouped params
492+ -> Condition db params 'Ungrouped '[tab ::: row0]
515493 -- ^ condition under which to perform update on a row
516− -> ReturningClause db params row results -- ^ results to return
517− -> Manipulation db params results
494+ -> ReturningClause db params '[tab ::: row0] row1 -- ^ results to return
495+ -> Manipulation db params row1
518496update tab columns wh returning = UnsafeManipulation $
519497 "UPDATE"
520− <+> renderQualifiedAlias tab
498+ <+> renderSQL tab
521499 <+> "SET"
522− <+> renderCommaSeparated renderColumnExpression columns
523− <+> "WHERE" <+> renderExpression wh
524− <> renderReturningClause returning
500+ <+> renderCommaSeparated renderSQL columns
501+ <+> "WHERE" <+> renderSQL wh
502+ <> renderSQL returning
525503
526504-- | Update a row returning `Nil`.
527505update_
@@ -534,12 +512,12 @@ update_
534512 , SOP.All (HasIn columns) subcolumns
535513 , AllUnique subcolumns )
536514 => QualifiedAlias sch tab -- ^ table to update
537− -> NP (ColumnExpression db '[tab ::: row] 'Ungrouped params) subcolumns
515+ -> NP (ColumnExpression db params 'Ungrouped '[tab ::: row]) subcolumns
538516 -- ^ modified values to replace old values
539− -> Condition db '[tab ::: row] 'Ungrouped params
517+ -> Condition db params 'Ungrouped '[tab ::: row]
540518 -- ^ condition under which to perform update on a row
541519 -> Manipulation db params '[]
542−update_ tab columns wh = update tab columns wh (Returning Nil)
520+update_ tab columns wh = update tab columns wh (Returning_ Nil)
543521
544522{-----------------------------------------
545523DELETE statements
@@ -553,26 +531,26 @@ data UsingClause db params from where
553531
554532-- | Delete rows from a table.
555533deleteFrom
556− :: ( SOP.SListI results
534+ :: ( SOP.SListI row1
557535 , db ~ (commons :=> schemas)
558536 , Has sch schemas schema
559537 , Has tab schema ('Table table)
560− , row ~ TableToRow table
538+ , row0 ~ TableToRow table
561539 , columns ~ TableToColumns table )
562540 => QualifiedAlias sch tab -- ^ table to delete from
563541 -> UsingClause db params from
564− -> Condition db (tab ::: row ': from) 'Ungrouped params
542+ -> Condition db params 'Ungrouped (tab ::: row0 ': from)
565543 -- ^ condition under which to delete a row
566− -> ReturningClause db params row results -- ^ results to return
567− -> Manipulation db params results
544+ -> ReturningClause db params '[tab ::: row0] row1 -- ^ results to return
545+ -> Manipulation db params row1
568546deleteFrom tab using wh returning = UnsafeManipulation $
569547 "DELETE FROM"
570− <+> renderQualifiedAlias tab
548+ <+> renderSQL tab
571549 <> case using of
572550 NoUsing -> ""
573− Using tables -> " USING" <+> renderFromClause tables
574− <+> "WHERE" <+> renderExpression wh
575− <> renderReturningClause returning
551+ Using tables -> " USING" <+> renderSQL tables
552+ <+> "WHERE" <+> renderSQL wh
553+ <> renderSQL returning
576554
577555-- | Delete rows returning `Nil`.
578556deleteFrom_
@@ -583,10 +561,10 @@ deleteFrom_
583561 , columns ~ TableToColumns table )
584562 => QualifiedAlias sch tab -- ^ table to delete from
585563 -> UsingClause db params from
586− -> Condition db (tab ::: row ': from) 'Ungrouped params
564+ -> Condition db params 'Ungrouped (tab ::: row ': from)
587565 -- ^ condition under which to delete a row
588566 -> Manipulation db params '[]
589−deleteFrom_ tab uses wh = deleteFrom tab uses wh (Returning Nil)
567+deleteFrom_ tab uses wh = deleteFrom tab uses wh (Returning_ Nil)
590568
591569-- | This has the behaviour of a cartesian product, taking all
592570-- possible combinations between @left@ and @right@ - exactly like a
@@ -600,4 +578,4 @@ also
600578 -- ^ left
601579 -> FromClause schema params (Join left right)
602580also right left = UnsafeFromClause $
603− renderFromClause left <> "," <+> renderFromClause right
581+ renderSQL left <> "," <+> renderSQL right
squeal-postgresql/src/Squeal/PostgreSQL/Migration.hs+2−2
@@ -71,7 +71,7 @@ let
7171 :: Has "migrations" schemas MigrationsSchema
7272 => PQ schemas schemas IO ()
7373 numMigrations = do
74− result <- runQuery (selectStar (from (table (#migrations ! #schema_migrations `as` #m))))
74+ result <- runQuery (select Star (from (table (#migrations ! #schema_migrations `as` #m))))
7575 num <- ntuples result
7676 liftBase $ print num
7777:}
@@ -291,7 +291,7 @@ selectMigration
291291 :: Has "migrations" schemas MigrationsSchema
292292 => Query ('[] :=> schemas) '[ 'NotNull 'PGtext ]
293293 '[ "executed_at" ::: 'NotNull 'PGtimestamptz ]
294−selectMigration = select
294+selectMigration = select_
295295 (#executed_at `as` #executed_at)
296296 ( from (table ((#migrations ! #schema_migrations) `as` #m))
297297 & where_ (#name .== param @1))
squeal-postgresql/src/Squeal/PostgreSQL/Query.hs+327−312
@@ -18,7 +18,9 @@ Squeal queries.
1818 , LambdaCase
1919 , MultiParamTypeClasses
2020 , OverloadedStrings
21+ , ScopedTypeVariables
2122 , StandaloneDeriving
23+ , TypeApplications
2224 , TypeFamilies
2325 , TypeInType
2426 , TypeOperators
@@ -28,14 +30,13 @@ Squeal queries.
2830
2931module Squeal.PostgreSQL.Query
3032 ( -- * Queries
31− Query (UnsafeQuery, renderQuery)
33+ Query (..)
3234 -- ** Select
3335 , select
36+ , select_
3437 , selectDistinct
35− , selectStar
36− , selectDistinctStar
37− , selectDotStar
38− , selectDistinctDotStar
38+ , selectDistinct_
39+ , Selection (..)
3940 -- ** Values
4041 , values
4142 , values_
@@ -47,7 +48,7 @@ module Squeal.PostgreSQL.Query
4748 , except
4849 , exceptAll
4950 -- ** With
50− , With (with)
51+ , With (..)
5152 , CommonTableExpression (..)
5253 , renderCommonTableExpression
5354 , renderCommonTableExpressions
@@ -68,7 +69,6 @@ module Squeal.PostgreSQL.Query
6869 , jsonbToRecordSet
6970 -- * Table Expressions
7071 , TableExpression (..)
71− , renderTableExpression
7272 , from
7373 , where_
7474 , groupBy
@@ -88,15 +88,11 @@ module Squeal.PostgreSQL.Query
8888 , rightOuterJoin
8989 , fullOuterJoin
9090 -- * Grouping
91− , By (By1, By2)
92− , renderBy
93− , GroupByClause (NoGroups, Group)
94− , renderGroupByClause
95− , HavingClause (NoHaving, Having)
96− , renderHavingClause
91+ , By (..)
92+ , GroupByClause (..)
93+ , HavingClause (..)
9794 -- * Sorting
9895 , SortExpression (..)
99− , renderSortExpression
10096 -- * Subquery Expressions
10197 , in_
10298 , rowIn
@@ -150,7 +146,7 @@ simple query:
150146>>> :{
151147let
152148 query :: Query (DBof (Public Schema)) '[] '["col1" ::: 'NotNull 'PGint4, "col2" ::: 'NotNull 'PGint4]
153− query = selectStar (from (table #tab))
149+ query = select Star (from (table #tab))
154150in printSQL query
155151:}
156152SELECT * FROM "tab" AS "tab"
@@ -161,7 +157,7 @@ restricted query:
161157let
162158 query :: Query (DBof (Public Schema)) '[] '["sum" ::: 'NotNull 'PGint4, "col1" ::: 'NotNull 'PGint4]
163159 query =
164− select ((#col1 + #col2) `as` #sum :* #col1)
160+ select_ ((#col1 + #col2) `as` #sum :* #col1)
165161 ( from (table #tab)
166162 & where_ (#col1 .> #col2)
167163 & where_ (#col2 .> 0) )
@@ -174,7 +170,7 @@ subquery:
174170>>> :{
175171let
176172 query :: Query (DBof (Public Schema)) '[] '["col1" ::: 'NotNull 'PGint4, "col2" ::: 'NotNull 'PGint4]
177− query = selectStar (from (subquery (selectStar (from (table #tab)) `as` #sub)))
173+ query = select Star (from (subquery (select Star (from (table #tab)) `as` #sub)))
178174in printSQL query
179175:}
180176SELECT * FROM (SELECT * FROM "tab" AS "tab") AS "sub"
@@ -184,7 +180,7 @@ limits and offsets:
184180>>> :{
185181let
186182 query :: Query (DBof (Public Schema)) '[] '["col1" ::: 'NotNull 'PGint4, "col2" ::: 'NotNull 'PGint4]
187− query = selectStar (from (table #tab) & limit 100 & offset 2 & limit 50 & offset 2)
183+ query = select Star (from (table #tab) & limit 100 & offset 2 & limit 50 & offset 2)
188184in printSQL query
189185:}
190186SELECT * FROM "tab" AS "tab" LIMIT 50 OFFSET 4
@@ -194,7 +190,7 @@ parameterized query:
194190>>> :{
195191let
196192 query :: Query (DBof (Public Schema)) '[ 'NotNull 'PGint4] '["col1" ::: 'NotNull 'PGint4, "col2" ::: 'NotNull 'PGint4]
197− query = selectStar (from (table #tab) & where_ (#col1 .> param @1))
193+ query = select Star (from (table #tab) & where_ (#col1 .> param @1))
198194in printSQL query
199195:}
200196SELECT * FROM "tab" AS "tab" WHERE ("col1" > ($1 :: int4))
@@ -205,7 +201,7 @@ aggregation query:
205201let
206202 query :: Query (DBof (Public Schema)) '[] '["sum" ::: 'NotNull 'PGint4, "col1" ::: 'NotNull 'PGint4 ]
207203 query =
208− select (sum_ #col2 `as` #sum :* #col1)
204+ select_ (sum_ #col2 `as` #sum :* #col1)
209205 ( from (table (#tab `as` #table1))
210206 & groupBy #col1
211207 & having (#col1 + sum_ #col2 .> 1) )
@@ -218,7 +214,7 @@ sorted query:
218214>>> :{
219215let
220216 query :: Query (DBof (Public Schema)) '[] '["col1" ::: 'NotNull 'PGint4, "col2" ::: 'NotNull 'PGint4]
221− query = selectStar (from (table #tab) & orderBy [#col1 & Asc])
217+ query = select Star (from (table #tab) & orderBy [#col1 & Asc])
222218in printSQL query
223219:}
224220SELECT * FROM "tab" AS "tab" ORDER BY "col1" ASC
@@ -260,7 +256,7 @@ let
260256 , "customer_name" ::: 'NotNull 'PGtext
261257 , "shipper_name" ::: 'NotNull 'PGtext
262258 ]
263− query = select
259+ query = select_
264260 ( #o ! #price `as` #order_price :*
265261 #c ! #name `as` #customer_name :*
266262 #s ! #name `as` #shipper_name )
@@ -278,7 +274,7 @@ self-join:
278274>>> :{
279275let
280276 query :: Query (DBof (Public Schema)) '[] '["col1" ::: 'NotNull 'PGint4, "col2" ::: 'NotNull 'PGint4]
281− query = selectDotStar #t1 (from (table (#tab `as` #t1) & crossJoin (table (#tab `as` #t2))))
277+ query = select (#t1 & DotStar) (from (table (#tab `as` #t1) & crossJoin (table (#tab `as` #t2))))
282278in printSQL query
283279:}
284280SELECT "t1".* FROM "tab" AS "t1" CROSS JOIN "tab" AS "t2"
@@ -298,7 +294,7 @@ set operations:
298294>>> :{
299295let
300296 query :: Query (DBof (Public Schema)) '[] '["col1" ::: 'NotNull 'PGint4, "col2" ::: 'NotNull 'PGint4]
301− query = selectStar (from (table #tab)) `unionAll` selectStar (from (table #tab))
297+ query = select Star (from (table #tab)) `unionAll` select Star (from (table #tab))
302298in printSQL query
303299:}
304300(SELECT * FROM "tab" AS "tab") UNION ALL (SELECT * FROM "tab" AS "tab")
@@ -309,9 +305,9 @@ with queries:
309305let
310306 query :: Query (DBof (Public Schema)) '[] '["col1" ::: 'NotNull 'PGint4, "col2" ::: 'NotNull 'PGint4]
311307 query = with (
312− selectStar (from (table #tab)) `as` #cte1 :>>
313− selectStar (from (common #cte1)) `as` #cte2
314− ) (selectStar (from (common #cte2)))
308+ select Star (from (table #tab)) `as` #cte1 :>>
309+ select Star (from (common #cte1)) `as` #cte2
310+ ) (select Star (from (common #cte2)))
315311in printSQL query
316312:}
317313WITH "cte1" AS (SELECT * FROM "tab" AS "tab"), "cte2" AS (SELECT * FROM "cte1" AS "cte1") SELECT * FROM "cte2" AS "cte2"
@@ -331,9 +327,9 @@ union
331327 -> Query db params columns
332328 -> Query db params columns
333329q1 `union` q2 = UnsafeQuery $
334− parenthesized (renderQuery q1)
330+ parenthesized (renderSQL q1)
335331 <+> "UNION"
336− <+> parenthesized (renderQuery q2)
332+ <+> parenthesized (renderSQL q2)
337333
338334-- | The results of two queries can be combined using the set operation
339335-- `unionAll`, the disjoint union. Duplicate rows are retained.
@@ -342,9 +338,9 @@ unionAll
342338 -> Query db params columns
343339 -> Query db params columns
344340q1 `unionAll` q2 = UnsafeQuery $
345− parenthesized (renderQuery q1)
341+ parenthesized (renderSQL q1)
346342 <+> "UNION" <+> "ALL"
347− <+> parenthesized (renderQuery q2)
343+ <+> parenthesized (renderSQL q2)
348344
349345-- | The results of two queries can be combined using the set operation
350346-- `intersect`, the intersection. Duplicate rows are eliminated.
@@ -353,9 +349,9 @@ intersect
353349 -> Query db params columns
354350 -> Query db params columns
355351q1 `intersect` q2 = UnsafeQuery $
356− parenthesized (renderQuery q1)
352+ parenthesized (renderSQL q1)
357353 <+> "INTERSECT"
358− <+> parenthesized (renderQuery q2)
354+ <+> parenthesized (renderSQL q2)
359355
360356-- | The results of two queries can be combined using the set operation
361357-- `intersectAll`, the intersection. Duplicate rows are retained.
@@ -364,9 +360,9 @@ intersectAll
364360 -> Query db params columns
365361 -> Query db params columns
366362q1 `intersectAll` q2 = UnsafeQuery $
367− parenthesized (renderQuery q1)
363+ parenthesized (renderSQL q1)
368364 <+> "INTERSECT" <+> "ALL"
369− <+> parenthesized (renderQuery q2)
365+ <+> parenthesized (renderSQL q2)
370366
371367-- | The results of two queries can be combined using the set operation
372368-- `except`, the set difference. Duplicate rows are eliminated.
@@ -375,9 +371,9 @@ except
375371 -> Query db params columns
376372 -> Query db params columns
377373q1 `except` q2 = UnsafeQuery $
378− parenthesized (renderQuery q1)
374+ parenthesized (renderSQL q1)
379375 <+> "EXCEPT"
380− <+> parenthesized (renderQuery q2)
376+ <+> parenthesized (renderSQL q2)
381377
382378-- | The results of two queries can be combined using the set operation
383379-- `exceptAll`, the set difference. Duplicate rows are retained.
@@ -386,88 +382,109 @@ exceptAll
386382 -> Query db params columns
387383 -> Query db params columns
388384q1 `exceptAll` q2 = UnsafeQuery $
389− parenthesized (renderQuery q1)
385+ parenthesized (renderSQL q1)
390386 <+> "EXCEPT" <+> "ALL"
391− <+> parenthesized (renderQuery q2)
387+ <+> parenthesized (renderSQL q2)
392388
393389{-----------------------------------------
394390SELECT queries
395391-----------------------------------------}
396392
393+data Selection db params grp from row where
394+ List
395+ :: SListI row
396+ => NP (Aliased (Expression db params grp from)) row
397+ -> Selection db params grp from row
398+ Star
399+ :: HasUnique tab from row
400+ => Selection db params 'Ungrouped from row
401+ DotStar
402+ :: Has tab from row
403+ => Alias tab
404+ -> Selection db params 'Ungrouped from row
405+ Also
406+ :: Selection db params grp from right
407+ -> Selection db params grp from left
408+ -> Selection db params grp from (Join left right)
409+instance (KnownSymbol col, row ~ '[col ::: ty])
410+ => Aliasable col
411+ (Expression db params grp from ty)
412+ (Selection db params grp from row) where
413+ expr `as` col = List (expr `as` col)
414+instance (Has tab from row0, Has col row0 ty, row1 ~ '[col ::: ty])
415+ => IsQualified tab col (Selection db params 'Ungrouped from row1) where
416+ tab ! col = tab ! col `as` col
417+instance
418+ ( Has tab from row0
419+ , Has col row0 ty
420+ , row1 ~ '[col ::: ty]
421+ , GroupedBy tab col bys )
422+ => IsQualified tab col (Selection db params ('Grouped bys) from row1) where
423+ tab ! col = tab ! col `as` col
424+instance (HasUnique tab from row0, Has col row0 ty, row1 ~ '[col ::: ty])
425+ => IsLabel col (Selection db params 'Ungrouped from row1) where
426+ fromLabel = fromLabel @col `as` Alias
427+instance
428+ ( HasUnique tab from row0
429+ , Has col row0 ty
430+ , row1 ~ '[col ::: ty]
431+ , GroupedBy tab col bys )
432+ => IsLabel col (Selection db params ('Grouped bys) from row1) where
433+ fromLabel = fromLabel @col `as` Alias
434+
435+instance RenderSQL (Selection db params grp from row) where
436+ renderSQL = \case
437+ List list -> renderCommaSeparated (renderAliased renderSQL) list
438+ Star -> "*"
439+ DotStar tab -> renderSQL tab <> ".*"
440+ Also right left -> renderSQL left <> ", " <> renderSQL right
441+
397442-- | the `TableExpression` in the `select` command constructs an intermediate
398443-- virtual table by possibly combining tables, views, eliminating rows,
399444-- grouping, etc. This table is finally passed on to processing by
400−-- the select list. The select list determines which columns of
445+-- the select list. The `Selection` determines which columns of
401446-- the intermediate table are actually output.
402447select
403− :: (SListI columns, columns ~ (col ': cols))
404− => NP (Aliased (Expression db from grouping params)) columns
448+ :: (SListI row, row ~ (x ': xs))
449+ => Selection db params grp from row
405450 -- ^ select list
406− -> TableExpression db params from grouping
451+ -> TableExpression db params grp from
407452 -- ^ intermediate virtual table
408− -> Query db params columns
409−select list rels = UnsafeQuery $
453+ -> Query db params row
454+select selection tabexpr = UnsafeQuery $
410455 "SELECT"
411− <+> renderCommaSeparated (renderAliasedAs renderExpression) list
412− <+> renderTableExpression rels
456+ <+> renderSQL selection
457+ <+> renderSQL tabexpr
458+
459+select_
460+ :: (SListI row, row ~ (x ': xs))
461+ => NP (Aliased (Expression db params grp from)) row
462+ -> TableExpression db params grp from
463+ -> Query db params row
464+select_ list = select (List list)
413465
414466-- | After the select list has been processed, the result table can
415467-- be subject to the elimination of duplicate rows using `selectDistinct`.
416468selectDistinct
417469 :: (SListI columns, columns ~ (col ': cols))
418− => NP (Aliased (Expression db from 'Ungrouped params)) columns
470+ => Selection db params 'Ungrouped from columns
419471 -- ^ select list
420− -> TableExpression db params from 'Ungrouped
472+ -> TableExpression db params 'Ungrouped from
421473 -- ^ intermediate virtual table
422474 -> Query db params columns
423−selectDistinct list rels = UnsafeQuery $
475+selectDistinct selection tabexpr = UnsafeQuery $
424476 "SELECT DISTINCT"
425− <+> renderCommaSeparated (renderAliasedAs renderExpression) list
426− <+> renderTableExpression rels
427−
428−-- | The simplest kind of query is `selectStar` which emits all columns
429−-- that the table expression produces.
430−selectStar
431− :: HasUnique table from columns
432− => TableExpression db params from 'Ungrouped
433− -- ^ intermediate virtual table
434− -> Query db params columns
435−selectStar rels = UnsafeQuery $ "SELECT" <+> "*" <+> renderTableExpression rels
477+ <+> renderSQL selection
478+ <+> renderSQL tabexpr
436479
437−-- | A `selectDistinctStar` emits all columns that the table expression
438−-- produces and eliminates duplicate rows.
439−selectDistinctStar
440− :: HasUnique table from columns
441− => TableExpression db params from 'Ungrouped
442− -- ^ intermediate virtual table
443− -> Query db params columns
444−selectDistinctStar rels = UnsafeQuery $
445− "SELECT DISTINCT" <+> "*" <+> renderTableExpression rels
446−
447−-- | When working with multiple tables, it can also be useful to ask
448−-- for all the columns of a particular table, using `selectDotStar`.
449−selectDotStar
450− :: Has table from columns
451− => Alias table
452− -- ^ particular virtual subtable
453− -> TableExpression db params from 'Ungrouped
454− -- ^ intermediate virtual table
455− -> Query db params columns
456−selectDotStar rel tab = UnsafeQuery $
457− "SELECT" <+> renderAlias rel <> ".*" <+> renderTableExpression tab
458−
459−-- | A `selectDistinctDotStar` asks for all the columns of a particular table,
460−-- and eliminates duplicate rows.
461−selectDistinctDotStar
462− :: Has table from columns
463− => Alias table
464− -- ^ particular virtual table
465− -> TableExpression db params from 'Ungrouped
480+selectDistinct_
481+ :: (SListI columns, columns ~ (col ': cols))
482+ => NP (Aliased (Expression db params 'Ungrouped from)) columns
483+ -- ^ select list
484+ -> TableExpression db params 'Ungrouped from
466485 -- ^ intermediate virtual table
467486 -> Query db params columns
468−selectDistinctDotStar rel tab = UnsafeQuery $
469− "SELECT DISTINCT" <+> renderAlias rel <> ".*"
470− <+> renderTableExpression tab
487+selectDistinct_ list = select (List list)
471488
472489-- | `values` computes a row value or set of row values
473490-- specified by value expressions. It is most commonly used
@@ -480,8 +497,8 @@ selectDistinctDotStar rel tab = UnsafeQuery $
480497-- SELECT * FROM (VALUES (1, E'one')) AS t ("a", "b")
481498values
482499 :: SListI cols
483− => NP (Aliased (Expression db '[] 'Ungrouped params)) cols
484− -> [NP (Aliased (Expression db '[] 'Ungrouped params)) cols]
500+ => NP (Aliased (Expression db params 'Ungrouped '[] )) cols
501+ -> [NP (Aliased (Expression db params 'Ungrouped '[] )) cols]
485502 -- ^ When more than one row is specified, all the rows must
486503 -- must have the same number of elements
487504 -> Query db params cols
@@ -495,15 +512,15 @@ values rw rws = UnsafeQuery $ "SELECT * FROM"
495512 <+> parenthesized (renderCommaSeparated renderAliasPart rw)
496513 where
497514 renderAliasPart, renderValuePart
498− :: Aliased (Expression db '[] 'Ungrouped params) ty -> ByteString
499− renderAliasPart (_ `As` name) = renderAlias name
500− renderValuePart (value `As` _) = renderExpression value
515+ :: Aliased (Expression db params 'Ungrouped '[] ) ty -> ByteString
516+ renderAliasPart (_ `As` name) = renderSQL name
517+ renderValuePart (value `As` _) = renderSQL value
501518
502519-- | `values_` computes a row value or set of row values
503520-- specified by value expressions.
504521values_
505522 :: SListI cols
506− => NP (Aliased (Expression db '[] 'Ungrouped params)) cols
523+ => NP (Aliased (Expression db params 'Ungrouped '[] )) cols
507524 -- ^ one row of values
508525 -> Query db params cols
509526values_ rw = values rw []
@@ -521,13 +538,13 @@ Table Expressions
521538data TableExpression
522539 (db :: DBType)
523540 (params :: [NullityType])
541+ (grp :: Grouping)
524542 (from :: FromType)
525− (grouping :: Grouping)
526543 = TableExpression
527544 { fromClause :: FromClause db params from
528545 -- ^ A table reference that can be a table name, or a derived table such
529546 -- as a subquery, a @JOIN@ construct, or complex combinations of these.
530− , whereClause :: [Condition db from 'Ungrouped params]
547+ , whereClause :: [Condition db params 'Ungrouped from]
531548 -- ^ optional search coditions, combined with `.&&`. After the processing
532549 -- of the `fromClause` is done, each row of the derived virtual table
533550 -- is checked against the search condition. If the result of the
@@ -536,20 +553,20 @@ data TableExpression
536553 -- at least one column of the table generated in the `fromClause`;
537554 -- this is not required, but otherwise the WHERE clause will
538555 -- be fairly useless.
539− , groupByClause :: GroupByClause from grouping
556+ , groupByClause :: GroupByClause grp from
540557 -- ^ The `groupByClause` is used to group together those rows in a table
541558 -- that have the same values in all the columns listed. The order in which
542559 -- the columns are listed does not matter. The effect is to combine each
543560 -- set of rows having common values into one group row that represents all
544561 -- rows in the group. This is done to eliminate redundancy in the output
545562 -- and/or compute aggregates that apply to these groups.
546− , havingClause :: HavingClause db from grouping params
563+ , havingClause :: HavingClause db params grp from
547564 -- ^ If a table has been grouped using `groupBy`, but only certain groups
548565 -- are of interest, the `havingClause` can be used, much like a
549566 -- `whereClause`, to eliminate groups from the result. Expressions in the
550567 -- `havingClause` can refer both to grouped expressions and to ungrouped
551568 -- expressions (which necessarily involve an aggregate function).
552− , orderByClause :: [SortExpression db from grouping params]
569+ , orderByClause :: [SortExpression db params grp from]
553570 -- ^ The `orderByClause` is for optional sorting. When more than one
554571 -- `SortExpression` is specified, the later (right) values are used to sort
555572 -- rows that are equal according to the earlier (left) values.
@@ -566,34 +583,32 @@ data TableExpression
566583 }
567584
568585-- | Render a `TableExpression`
569−renderTableExpression
570− :: TableExpression db params from grouping
571− -> ByteString
572−renderTableExpression
573− (TableExpression frm' whs' grps' hvs' srts' lims' offs') = mconcat
574− [ "FROM ", renderFromClause frm'
575− , renderWheres whs'
576− , renderGroupByClause grps'
577− , renderHavingClause hvs'
578− , renderOrderByClause srts'
579− , renderLimits lims'
580− , renderOffsets offs'
581− ]
582− where
583− renderWheres = \case
584− [] -> ""
585− wh:[] -> " WHERE" <+> renderExpression wh
586− wh:whs -> " WHERE" <+> renderExpression (foldr (.&&) wh whs)
587− renderOrderByClause = \case
588− [] -> ""
589− srts -> " ORDER BY"
590− <+> commaSeparated (renderSortExpression <$> srts)
591− renderLimits = \case
592− [] -> ""
593− lims -> " LIMIT" <+> fromString (show (minimum lims))
594− renderOffsets = \case
595− [] -> ""
596− offs -> " OFFSET" <+> fromString (show (sum offs))
586+instance RenderSQL (TableExpression db params grp from) where
587+ renderSQL
588+ (TableExpression frm' whs' grps' hvs' srts' lims' offs') = mconcat
589+ [ "FROM ", renderSQL frm'
590+ , renderWheres whs'
591+ , renderSQL grps'
592+ , renderSQL hvs'
593+ , renderOrderByClause srts'
594+ , renderLimits lims'
595+ , renderOffsets offs'
596+ ]
597+ where
598+ renderWheres = \case
599+ [] -> ""
600+ wh:[] -> " WHERE" <+> renderSQL wh
601+ wh:whs -> " WHERE" <+> renderSQL (foldr (.&&) wh whs)
602+ renderOrderByClause = \case
603+ [] -> ""
604+ srts -> " ORDER BY"
605+ <+> commaSeparated (renderSQL <$> srts)
606+ renderLimits = \case
607+ [] -> ""
608+ lims -> " LIMIT" <+> fromString (show (minimum lims))
609+ renderOffsets = \case
610+ [] -> ""
611+ offs -> " OFFSET" <+> fromString (show (sum offs))
597612
598613-- | A `from` generates a `TableExpression` from a table reference that can be
599614-- a table name, or a derived table such as a subquery, a JOIN construct,
@@ -602,15 +617,15 @@ renderTableExpression
602617-- to match the left-to-right sequencing of their placement in SQL.
603618from
604619 :: FromClause db params from -- ^ table reference
605− -> TableExpression db params from 'Ungrouped
620+ -> TableExpression db params 'Ungrouped from
606621from rels = TableExpression rels [] NoGroups NoHaving [] [] []
607622
608623-- | A `where_` is an endomorphism of `TableExpression`s which adds a
609624-- search condition to the `whereClause`.
610625where_
611− :: Condition db from 'Ungrouped params -- ^ filtering condition
612− -> TableExpression db params from grouping
613− -> TableExpression db params from grouping
626+ :: Condition db params 'Ungrouped from -- ^ filtering condition
627+ -> TableExpression db params grp from
628+ -> TableExpression db params grp from
614629where_ wh rels = rels {whereClause = wh : whereClause rels}
615630
616631-- | A `groupBy` is a transformation of `TableExpression`s which switches
@@ -619,8 +634,8 @@ where_ wh rels = rels {whereClause = wh : whereClause rels}
619634groupBy
620635 :: SListI bys
621636 => NP (By from) bys -- ^ grouped columns
622− -> TableExpression db params from 'Ungrouped
623− -> TableExpression db params from ('Grouped bys)
637+ -> TableExpression db params 'Ungrouped from
638+ -> TableExpression db params ('Grouped bys) from
624639groupBy bys rels = TableExpression
625640 { fromClause = fromClause rels
626641 , whereClause = whereClause rels
@@ -634,34 +649,34 @@ groupBy bys rels = TableExpression
634649-- | A `having` is an endomorphism of `TableExpression`s which adds a
635650-- search condition to the `havingClause`.
636651having
637− :: Condition db from ('Grouped bys) params -- ^ having condition
638− -> TableExpression db params from ('Grouped bys)
639− -> TableExpression db params from ('Grouped bys)
652+ :: Condition db params ('Grouped bys) from -- ^ having condition
653+ -> TableExpression db params ('Grouped bys) from
654+ -> TableExpression db params ('Grouped bys) from
640655having hv rels = rels
641656 { havingClause = case havingClause rels of Having hvs -> Having (hv:hvs) }
642657
643658-- | An `orderBy` is an endomorphism of `TableExpression`s which appends an
644659-- ordering to the right of the `orderByClause`.
645660orderBy
646− :: [SortExpression db from grouping params] -- ^ sort expressions
647− -> TableExpression db params from grouping
648− -> TableExpression db params from grouping
661+ :: [SortExpression db params grp from] -- ^ sort expressions
662+ -> TableExpression db params grp from
663+ -> TableExpression db params grp from
649664orderBy srts rels = rels {orderByClause = orderByClause rels ++ srts}
650665
651666-- | A `limit` is an endomorphism of `TableExpression`s which adds to the
652667-- `limitClause`.
653668limit
654669 :: Word64 -- ^ limit parameter
655− -> TableExpression db params from grouping
656− -> TableExpression db params from grouping
670+ -> TableExpression db params grp from
671+ -> TableExpression db params grp from
657672limit lim rels = rels {limitClause = lim : limitClause rels}
658673
659674-- | An `offset` is an endomorphism of `TableExpression`s which adds to the
660675-- `offsetClause`.
661676offset
662677 :: Word64 -- ^ offset parameter
663− -> TableExpression db params from grouping
664− -> TableExpression db params from grouping
678+ -> TableExpression db params grp from
679+ -> TableExpression db params grp from
665680offset off rels = rels {offsetClause = off : offsetClause rels}
666681
667682{-----------------------------------------
@@ -670,66 +685,66 @@ JSON stuff
670685
671686unsafeSetOfFunction
672687 :: ByteString
673− -> Expression db '[] 'Ungrouped params ty
688+ -> Expression db params 'Ungrouped '[] ty
674689 -> Query db params row
675690unsafeSetOfFunction fun expr = UnsafeQuery $
676− "SELECT * FROM " <> fun <> "(" <> renderExpression expr <> ")"
691+ "SELECT * FROM " <> fun <> "(" <> renderSQL expr <> ")"
677692
678693-- | Expands the outermost JSON object into a set of key/value pairs.
679694jsonEach
680− :: Expression db '[] 'Ungrouped params (nullity 'PGjson) -- ^ json object
695+ :: Expression db params 'Ungrouped '[] (nullity 'PGjson) -- ^ json object
681696 -> Query db params
682697 '["key" ::: 'NotNull 'PGtext, "value" ::: 'NotNull 'PGjson]
683698jsonEach = unsafeSetOfFunction "json_each"
684699
685700-- | Expands the outermost binary JSON object into a set of key/value pairs.
686701jsonbEach
687− :: Expression db '[] 'Ungrouped params (nullity 'PGjsonb) -- ^ jsonb object
702+ :: Expression db params 'Ungrouped '[] (nullity 'PGjsonb) -- ^ jsonb object
688703 -> Query db params
689704 '["key" ::: 'NotNull 'PGtext, "value" ::: 'NotNull 'PGjsonb]
690705jsonbEach = unsafeSetOfFunction "jsonb_each"
691706
692707-- | Expands the outermost JSON object into a set of key/value pairs.
693708jsonEachAsText
694− :: Expression db '[] 'Ungrouped params (nullity 'PGjson) -- ^ json object
709+ :: Expression db params 'Ungrouped '[] (nullity 'PGjson) -- ^ json object
695710 -> Query db params
696711 '["key" ::: 'NotNull 'PGtext, "value" ::: 'NotNull 'PGtext]
697712jsonEachAsText = unsafeSetOfFunction "json_each_text"
698713
699714-- | Expands the outermost binary JSON object into a set of key/value pairs.
700715jsonbEachAsText
701− :: Expression db '[] 'Ungrouped params (nullity 'PGjsonb) -- ^ jsonb object
716+ :: Expression db params 'Ungrouped '[] (nullity 'PGjsonb) -- ^ jsonb object
702717 -> Query db params
703718 '["key" ::: 'NotNull 'PGtext, "value" ::: 'NotNull 'PGtext]
704719jsonbEachAsText = unsafeSetOfFunction "jsonb_each_text"
705720
706721-- | Returns set of keys in the outermost JSON object.
707722jsonObjectKeys
708− :: Expression db '[] 'Ungrouped params (nullity 'PGjson) -- ^ json object
723+ :: Expression db params 'Ungrouped '[] (nullity 'PGjson) -- ^ json object
709724 -> Query db params '["json_object_keys" ::: 'NotNull 'PGtext]
710725jsonObjectKeys = unsafeSetOfFunction "json_object_keys"
711726
712727-- | Returns set of keys in the outermost JSON object.
713728jsonbObjectKeys
714− :: Expression db '[] 'Ungrouped params (nullity 'PGjsonb) -- ^ jsonb object
729+ :: Expression db params 'Ungrouped '[] (nullity 'PGjsonb) -- ^ jsonb object
715730 -> Query db params '["jsonb_object_keys" ::: 'NotNull 'PGtext]
716731jsonbObjectKeys = unsafeSetOfFunction "jsonb_object_keys"
717732
718733unsafePopulateFunction
719734 :: ByteString
720735 -> TypeExpression schemas (nullity ('PGcomposite row))
721− -> Expression (commons :=> schemas) '[] 'Ungrouped params ty
736+ -> Expression (commons :=> schemas) params 'Ungrouped '[] ty
722737 -> Query (commons :=> schemas) params row
723738unsafePopulateFunction fun ty expr = UnsafeQuery $
724739 "SELECT * FROM " <> fun <> "("
725− <> "null::" <> renderTypeExpression ty <> ", "
726− <> renderExpression expr <> ")"
740+ <> "null::" <> renderSQL ty <> ", "
741+ <> renderSQL expr <> ")"
727742
728743-- | Expands the JSON expression to a row whose columns match the record
729744-- type defined by the given table.
730745jsonPopulateRecord
731746 :: TypeExpression schemas (nullity ('PGcomposite row)) -- ^ row type
732− -> Expression (commons :=> schemas) '[] 'Ungrouped params (nullity 'PGjson) -- ^ json object
747+ -> Expression (commons :=> schemas) params 'Ungrouped '[] (nullity 'PGjson) -- ^ json object
733748 -> Query (commons :=> schemas) params row
734749jsonPopulateRecord = unsafePopulateFunction "json_populate_record"
735750
@@ -737,7 +752,7 @@ jsonPopulateRecord = unsafePopulateFunction "json_populate_record"
737752-- type defined by the given table.
738753jsonbPopulateRecord
739754 :: TypeExpression schemas (nullity ('PGcomposite row)) -- ^ row type
740− -> Expression (commons :=> schemas) '[] 'Ungrouped params (nullity 'PGjsonb) -- ^ jsonb object
755+ -> Expression (commons :=> schemas) params 'Ungrouped '[] (nullity 'PGjsonb) -- ^ jsonb object
741756 -> Query (commons :=> schemas) params row
742757jsonbPopulateRecord = unsafePopulateFunction "jsonb_populate_record"
743758
@@ -745,7 +760,7 @@ jsonbPopulateRecord = unsafePopulateFunction "jsonb_populate_record"
745760-- set of rows whose columns match the record type defined by the given table.
746761jsonPopulateRecordSet
747762 :: TypeExpression schemas (nullity ('PGcomposite row)) -- ^ row type
748− -> Expression (commons :=> schemas) '[] 'Ungrouped params (nullity 'PGjson) -- ^ json array
763+ -> Expression (commons :=> schemas) params 'Ungrouped '[] (nullity 'PGjson) -- ^ json array
749764 -> Query (commons :=> schemas) params row
750765jsonPopulateRecordSet = unsafePopulateFunction "json_populate_record_set"
751766
@@ -754,29 +769,29 @@ jsonPopulateRecordSet = unsafePopulateFunction "json_populate_record_set"
754769-- table.
755770jsonbPopulateRecordSet
756771 :: TypeExpression schemas (nullity ('PGcomposite row)) -- ^ row type
757− -> Expression (commons :=> schemas) '[] 'Ungrouped params (nullity 'PGjsonb) -- ^ jsonb array
772+ -> Expression (commons :=> schemas) params 'Ungrouped '[] (nullity 'PGjsonb) -- ^ jsonb array
758773 -> Query (commons :=> schemas) params row
759774jsonbPopulateRecordSet = unsafePopulateFunction "jsonb_populate_record_set"
760775
761776unsafeRecordFunction
762777 :: (SListI record, json `In` PGJsonType)
763778 => ByteString
764− -> Expression (commons :=> schemas) '[] 'Ungrouped params (nullity json)
779+ -> Expression (commons :=> schemas) params 'Ungrouped '[] (nullity json)
765780 -> NP (Aliased (TypeExpression schemas)) record
766781 -> Query (commons :=> schemas) params record
767782unsafeRecordFunction fun expr types = UnsafeQuery $
768783 "SELECT * FROM " <> fun <> "("
769− <> renderExpression expr <> ")"
784+ <> renderSQL expr <> ")"
770785 <+> "AS" <+> "x" <> parenthesized (renderCommaSeparated renderTy types)
771786 where
772787 renderTy :: Aliased (TypeExpression db) ty -> ByteString
773788 renderTy (ty `As` alias) =
774− renderAlias alias <+> renderTypeExpression ty
789+ renderSQL alias <+> renderSQL ty
775790
776791-- | Builds an arbitrary record from a JSON object.
777792jsonToRecord
778793 :: SListI record
779− => Expression (commons :=> schemas) '[] 'Ungrouped params (nullity 'PGjson) -- ^ json object
794+ => Expression (commons :=> schemas) params 'Ungrouped '[] (nullity 'PGjson) -- ^ json object
780795 -> NP (Aliased (TypeExpression schemas)) record -- ^ record types
781796 -> Query (commons :=> schemas) params record
782797jsonToRecord = unsafeRecordFunction "json_to_record"
@@ -784,7 +799,7 @@ jsonToRecord = unsafeRecordFunction "json_to_record"
784799-- | Builds an arbitrary record from a binary JSON object.
785800jsonbToRecord
786801 :: SListI record
787− => Expression (commons :=> schemas) '[] 'Ungrouped params (nullity 'PGjsonb) -- ^ jsonb object
802+ => Expression (commons :=> schemas) params 'Ungrouped '[] (nullity 'PGjsonb) -- ^ jsonb object
788803 -> NP (Aliased (TypeExpression schemas)) record -- ^ record types
789804 -> Query (commons :=> schemas) params record
790805jsonbToRecord = unsafeRecordFunction "jsonb_to_record"
@@ -792,7 +807,7 @@ jsonbToRecord = unsafeRecordFunction "jsonb_to_record"
792807-- | Builds an arbitrary set of records from a JSON array of objects.
793808jsonToRecordSet
794809 :: SListI record
795− => Expression (commons :=> schemas) '[] 'Ungrouped params (nullity 'PGjson) -- ^ json array
810+ => Expression (commons :=> schemas) params 'Ungrouped '[] (nullity 'PGjson) -- ^ json array
796811 -> NP (Aliased (TypeExpression schemas)) record -- ^ record types
797812 -> Query (commons :=> schemas) params record
798813jsonToRecordSet = unsafeRecordFunction "json_to_record_set"
@@ -800,7 +815,7 @@ jsonToRecordSet = unsafeRecordFunction "json_to_record_set"
800815-- | Builds an arbitrary set of records from a binary JSON array of objects.
801816jsonbToRecordSet
802817 :: SListI record
803− => Expression (commons :=> schemas) '[] 'Ungrouped params (nullity 'PGjsonb) -- ^ jsonb array
818+ => Expression (commons :=> schemas) params 'Ungrouped '[] (nullity 'PGjsonb) -- ^ jsonb array
804819 -> NP (Aliased (TypeExpression schemas)) record -- ^ record types
805820 -> Query (commons :=> schemas) params record
806821jsonbToRecordSet = unsafeRecordFunction "jsonb_to_record_set"
@@ -816,6 +831,8 @@ as a subquery, a @JOIN@ construct, or complex combinations of these.
816831newtype FromClause db params from
817832 = UnsafeFromClause { renderFromClause :: ByteString }
818833 deriving (GHC.Generic,Show,Eq,Ord,NFData)
834+instance RenderSQL (FromClause db params from) where
835+ renderSQL = renderFromClause
819836
820837-- | A real `table` is a table from the database.
821838table
@@ -823,13 +840,13 @@ table
823840 => Aliased (QualifiedAlias sch) (alias ::: tab)
824841 -> FromClause (commons :=> schemas) params '[alias ::: TableToRow table]
825842table (tab `As` alias) = UnsafeFromClause $
826− renderQualifiedAlias tab <+> "AS" <+> renderAlias alias
843+ renderSQL tab <+> "AS" <+> renderSQL alias
827844
828845-- | `subquery` derives a table from a `Query`.
829846subquery
830847 :: Aliased (Query db params) query
831848 -> FromClause db params '[query]
832−subquery = UnsafeFromClause . renderAliasedAs (parenthesized . renderQuery)
849+subquery = UnsafeFromClause . renderAliased (parenthesized . renderQuery)
833850
834851-- | `view` derives a table from a `View`.
835852view
@@ -837,14 +854,14 @@ view
837854 => Aliased (QualifiedAlias sch) (alias ::: vw)
838855 -> FromClause (commons :=> schemas) params '[alias ::: view]
839856view (vw `As` alias) = UnsafeFromClause $
840− renderQualifiedAlias vw <+> "AS" <+> renderAlias alias
857+ renderSQL vw <+> "AS" <+> renderSQL alias
841858
842859common
843860 :: Has cte commons common
844861 => Aliased Alias (alias ::: cte)
845862 -> FromClause (commons :=> schemas) params '[alias ::: common]
846863common (cte `As` alias) = UnsafeFromClause $
847− renderAlias cte <+> "AS" <+> renderAlias alias
864+ renderSQL cte <+> "AS" <+> renderSQL alias
848865
849866{- | @left & crossJoin right@. For every possible combination of rows from
850867 @left@ and @right@ (i.e., a Cartesian product), the joined table will contain
@@ -859,7 +876,7 @@ crossJoin
859876 -- ^ left
860877 -> FromClause db params (Join left right)
861878crossJoin right left = UnsafeFromClause $
862− renderFromClause left <+> "CROSS JOIN" <+> renderFromClause right
879+ renderSQL left <+> "CROSS JOIN" <+> renderSQL right
863880
864881{- | @left & innerJoin right on@. The joined table is filtered by
865882the @on@ condition.
@@ -867,14 +884,14 @@ the @on@ condition.
867884innerJoin
868885 :: FromClause db params right
869886 -- ^ right
870− -> Condition db (Join left right) 'Ungrouped params
887+ -> Condition db params 'Ungrouped (Join left right)
871888 -- ^ @on@ condition
872889 -> FromClause db params left
873890 -- ^ left
874891 -> FromClause db params (Join left right)
875892innerJoin right on left = UnsafeFromClause $
876− renderFromClause left <+> "INNER JOIN" <+> renderFromClause right
877− <+> "ON" <+> renderExpression on
893+ renderSQL left <+> "INNER JOIN" <+> renderSQL right
894+ <+> "ON" <+> renderSQL on
878895
879896{- | @left & leftOuterJoin right on@. First, an inner join is performed.
880897 Then, for each row in @left@ that does not satisfy the @on@ condition with
@@ -884,14 +901,14 @@ innerJoin right on left = UnsafeFromClause $
884901leftOuterJoin
885902 :: FromClause db params right
886903 -- ^ right
887− -> Condition db (Join left right) 'Ungrouped params
904+ -> Condition db params 'Ungrouped (Join left right)
888905 -- ^ @on@ condition
889906 -> FromClause db params left
890907 -- ^ left
891908 -> FromClause db params (Join left (NullifyFrom right))
892909leftOuterJoin right on left = UnsafeFromClause $
893− renderFromClause left <+> "LEFT OUTER JOIN" <+> renderFromClause right
894− <+> "ON" <+> renderExpression on
910+ renderSQL left <+> "LEFT OUTER JOIN" <+> renderSQL right
911+ <+> "ON" <+> renderSQL on
895912
896913{- | @left & rightOuterJoin right on@. First, an inner join is performed.
897914 Then, for each row in @right@ that does not satisfy the @on@ condition with
@@ -902,14 +919,14 @@ leftOuterJoin right on left = UnsafeFromClause $
902919rightOuterJoin
903920 :: FromClause db params right
904921 -- ^ right
905− -> Condition db (Join left right) 'Ungrouped params
922+ -> Condition db params 'Ungrouped (Join left right)
906923 -- ^ @on@ condition
907924 -> FromClause db params left
908925 -- ^ left
909926 -> FromClause db params (Join (NullifyFrom left) right)
910927rightOuterJoin right on left = UnsafeFromClause $
911− renderFromClause left <+> "RIGHT OUTER JOIN" <+> renderFromClause right
912− <+> "ON" <+> renderExpression on
928+ renderSQL left <+> "RIGHT OUTER JOIN" <+> renderSQL right
929+ <+> "ON" <+> renderSQL on
913930
914931{- | @left & fullOuterJoin right on@. First, an inner join is performed.
915932 Then, for each row in @left@ that does not satisfy the @on@ condition with
@@ -921,15 +938,15 @@ rightOuterJoin right on left = UnsafeFromClause $
921938fullOuterJoin
922939 :: FromClause db params right
923940 -- ^ right
924− -> Condition db (Join left right) 'Ungrouped params
941+ -> Condition db params 'Ungrouped (Join left right)
925942 -- ^ @on@ condition
926943 -> FromClause db params left
927944 -- ^ left
928945 -> FromClause db params
929946 (Join (NullifyFrom left) (NullifyFrom right))
930947fullOuterJoin right on left = UnsafeFromClause $
931− renderFromClause left <+> "FULL OUTER JOIN" <+> renderFromClause right
932− <+> "ON" <+> renderExpression on
948+ renderSQL left <+> "FULL OUTER JOIN" <+> renderSQL right
949+ <+> "ON" <+> renderSQL on
933950
934951{-----------------------------------------
935952Grouping
@@ -955,6 +972,10 @@ data By
955972deriving instance Show (By from by)
956973deriving instance Eq (By from by)
957974deriving instance Ord (By from by)
975+instance RenderSQL (By from by) where
976+ renderSQL = \case
977+ By1 column -> renderSQL column
978+ By2 rel column -> renderSQL rel <> "." <> renderSQL column
958979
959980instance (HasUnique rel rels cols, Has col cols ty, by ~ '(rel, col))
960981 => IsLabel col (By rels by) where fromLabel = By1 fromLabel
@@ -966,52 +987,46 @@ instance (Has rel rels cols, Has col cols ty, bys ~ '[ '(rel, col)])
966987 => IsQualified rel col (NP (By rels) bys) where
967988 rel ! col = By2 rel col :* Nil
968989
969−-- | Renders a `By`.
970−renderBy :: By from by -> ByteString
971−renderBy = \case
972− By1 column -> renderAlias column
973− By2 rel column -> renderAlias rel <> "." <> renderAlias column
974−
975990-- | A `GroupByClause` indicates the `Grouping` of a `TableExpression`.
976991-- A `NoGroups` indicates `Ungrouped` while a `Group` indicates `Grouped`.
977992-- @NoGroups@ is distinguised from @Group Nil@ since no aggregation can be
978993-- done on @NoGroups@ while all output `Expression`s must be aggregated
979994-- in @Group Nil@. In general, all output `Expression`s in the
980995-- complement of @bys@ must be aggregated in @Group bys@.
981−data GroupByClause from grouping where
982− NoGroups :: GroupByClause from 'Ungrouped
996+data GroupByClause grp from where
997+ NoGroups :: GroupByClause 'Ungrouped from
983998 Group
984999 :: SListI bys
9851000 => NP (By from) bys
986− -> GroupByClause from ('Grouped bys)
1001+ -> GroupByClause ('Grouped bys) from
9871002
9881003-- | Renders a `GroupByClause`.
989−renderGroupByClause :: GroupByClause from grouping -> ByteString
990−renderGroupByClause = \case
991− NoGroups -> ""
992− Group Nil -> ""
993− Group bys -> " GROUP BY" <+> renderCommaSeparated renderBy bys
1004+instance RenderSQL (GroupByClause grp from) where
1005+ renderSQL = \case
1006+ NoGroups -> ""
1007+ Group Nil -> ""
1008+ Group bys -> " GROUP BY" <+> renderCommaSeparated renderSQL bys
9941009
9951010-- | A `HavingClause` is used to eliminate groups that are not of interest.
9961011-- An `Ungrouped` `TableExpression` may only use `NoHaving` while a `Grouped`
9971012-- `TableExpression` must use `Having` whose conditions are combined with
9981013-- `.&&`.
999−data HavingClause db from grouping params where
1000− NoHaving :: HavingClause db from 'Ungrouped params
1014+data HavingClause db params grp from where
1015+ NoHaving :: HavingClause db params 'Ungrouped from
10011016 Having
1002− :: [Condition db from ('Grouped bys) params]
1003− -> HavingClause db from ('Grouped bys) params
1004−deriving instance Show (HavingClause db from grouping params)
1005−deriving instance Eq (HavingClause db from grouping params)
1006−deriving instance Ord (HavingClause db from grouping params)
1017+ :: [Condition db params ('Grouped bys) from]
1018+ -> HavingClause db params ('Grouped bys) from
1019+deriving instance Show (HavingClause db params grp from)
1020+deriving instance Eq (HavingClause db params grp from)
1021+deriving instance Ord (HavingClause db params grp from)
10071022
10081023-- | Render a `HavingClause`.
1009−renderHavingClause :: HavingClause db from grouping params -> ByteString
1010−renderHavingClause = \case
1011− NoHaving -> ""
1012− Having [] -> ""
1013− Having conditions ->
1014− " HAVING" <+> commaSeparated (renderExpression <$> conditions)
1024+instance RenderSQL (HavingClause db params grp from) where
1025+ renderSQL = \case
1026+ NoHaving -> ""
1027+ Having [] -> ""
1028+ Having conditions ->
1029+ " HAVING" <+> commaSeparated (renderSQL <$> conditions)
10151030
10161031{-----------------------------------------
10171032Sorting
@@ -1025,55 +1040,55 @@ Sorting
10251040-- `AscNullsLast`, `DescNullsFirst` and `DescNullsLast` options are used to
10261041-- determine whether nulls appear before or after non-null values in the sort
10271042-- ordering of a `Null` result column.
1028−data SortExpression db from grouping params where
1043+data SortExpression db params grp from where
10291044 Asc
1030− :: Expression db from grouping params ('NotNull ty)
1031− -> SortExpression db from grouping params
1045+ :: Expression db params grp from ('NotNull ty)
1046+ -> SortExpression db params grp from
10321047 Desc
1033− :: Expression db from grouping params ('NotNull ty)
1034− -> SortExpression db from grouping params
1048+ :: Expression db params grp from ('NotNull ty)
1049+ -> SortExpression db params grp from
10351050 AscNullsFirst
1036− :: Expression db from grouping params ('Null ty)
1037− -> SortExpression db from grouping params
1051+ :: Expression db params grp from ('Null ty)
1052+ -> SortExpression db params grp from
10381053 AscNullsLast
1039− :: Expression db from grouping params ('Null ty)
1040− -> SortExpression db from grouping params
1054+ :: Expression db params grp from ('Null ty)
1055+ -> SortExpression db params grp from
10411056 DescNullsFirst
1042− :: Expression db from grouping params ('Null ty)
1043− -> SortExpression db from grouping params
1057+ :: Expression db params grp from ('Null ty)
1058+ -> SortExpression db params grp from
10441059 DescNullsLast
1045− :: Expression db from grouping params ('Null ty)
1046− -> SortExpression db from grouping params
1047−deriving instance Show (SortExpression db from grouping params)
1060+ :: Expression db params grp from ('Null ty)
1061+ -> SortExpression db params grp from
1062+deriving instance Show (SortExpression db params grp from)
10481063
10491064-- | Render a `SortExpression`.
1050−renderSortExpression :: SortExpression db from grouping params -> ByteString
1051−renderSortExpression = \case
1052− Asc expression -> renderExpression expression <+> "ASC"
1053− Desc expression -> renderExpression expression <+> "DESC"
1054− AscNullsFirst expression -> renderExpression expression
1055− <+> "ASC NULLS FIRST"
1056− DescNullsFirst expression -> renderExpression expression
1057− <+> "DESC NULLS FIRST"
1058− AscNullsLast expression -> renderExpression expression <+> "ASC NULLS LAST"
1059− DescNullsLast expression -> renderExpression expression <+> "DESC NULLS LAST"
1065+instance RenderSQL (SortExpression db params grp from) where
1066+ renderSQL = \case
1067+ Asc expression -> renderSQL expression <+> "ASC"
1068+ Desc expression -> renderSQL expression <+> "DESC"
1069+ AscNullsFirst expression -> renderSQL expression
1070+ <+> "ASC NULLS FIRST"
1071+ DescNullsFirst expression -> renderSQL expression
1072+ <+> "DESC NULLS FIRST"
1073+ AscNullsLast expression -> renderSQL expression <+> "ASC NULLS LAST"
1074+ DescNullsLast expression -> renderSQL expression <+> "DESC NULLS LAST"
10601075
10611076unsafeSubqueryExpression
10621077 :: ByteString
1063− -> Expression db from grp params ty
1078+ -> Expression db params grp from ty
10641079 -> Query db params '[alias ::: ty]
1065− -> Expression db from grp params (nullity 'PGbool)
1080+ -> Expression db params grp from (nullity 'PGbool)
10661081unsafeSubqueryExpression op x q = UnsafeExpression $
1067− renderExpression x <+> op <+> parenthesized (renderQuery q)
1082+ renderSQL x <+> op <+> parenthesized (renderSQL q)
10681083
10691084unsafeRowSubqueryExpression
10701085 :: SListI row
10711086 => ByteString
1072− -> NP (Aliased (Expression db from grp params)) row
1087+ -> NP (Aliased (Expression db params grp from)) row
10731088 -> Query db params row
1074− -> Expression db from grp params (nullity 'PGbool)
1089+ -> Expression db params grp from (nullity 'PGbool)
10751090unsafeRowSubqueryExpression op xs q = UnsafeExpression $
1076− renderExpression (row xs) <+> op <+> parenthesized (renderQuery q)
1091+ renderSQL (row xs) <+> op <+> parenthesized (renderSQL q)
10771092
10781093-- | The right-hand side is a sub`Query`, which must return exactly one column.
10791094-- The left-hand expression is evaluated and compared to each row of the
@@ -1084,9 +1099,9 @@ unsafeRowSubqueryExpression op xs q = UnsafeExpression $
10841099-- >>> printSQL $ true `in_` values_ (true `as` #foo)
10851100-- TRUE IN (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
10861101in_
1087− :: Expression db from grp params ty -- ^ expression
1102+ :: Expression db params grp from ty -- ^ expression
10881103 -> Query db params '[alias ::: ty] -- ^ subquery
1089− -> Expression db from grp params (nullity 'PGbool)
1104+ -> Expression db params grp from (nullity 'PGbool)
10901105in_ = unsafeSubqueryExpression "IN"
10911106
10921107{- | The left-hand side of this form of `rowIn` is a row constructor.
@@ -1099,231 +1114,231 @@ is `true` if any equal subquery row is found.
10991114The result is `false` if no equal row is found
11001115(including the case where the subquery returns no rows).
11011116
1102−>>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db from grp params)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1117+>>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db params grp from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
11031118>>> printSQL $ myRow `rowIn` values_ myRow
11041119ROW(1, FALSE) IN (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
11051120-}
11061121rowIn
11071122 :: SListI row
1108− => NP (Aliased (Expression db from grp params)) row -- ^ row constructor
1123+ => NP (Aliased (Expression db params grp from)) row -- ^ row constructor
11091124 -> Query db params row -- ^ subquery
1110− -> Expression db from grp params (nullity 'PGbool)
1125+ -> Expression db params grp from (nullity 'PGbool)
11111126rowIn = unsafeRowSubqueryExpression "IN"
11121127
11131128-- | >>> printSQL $ true `eqAll` values_ (true `as` #foo)
11141129-- TRUE = ALL (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
11151130eqAll
1116− :: Expression db from grp params ty -- ^ expression
1131+ :: Expression db params grp from ty -- ^ expression
11171132 -> Query db params '[alias ::: ty] -- ^ subquery
1118− -> Expression db from grp params (nullity 'PGbool)
1133+ -> Expression db params grp from (nullity 'PGbool)
11191134eqAll = unsafeSubqueryExpression "= ALL"
11201135
1121−-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db from grp params)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1136+-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db params grp from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
11221137-- >>> printSQL $ myRow `rowEqAll` values_ myRow
11231138-- ROW(1, FALSE) = ALL (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
11241139rowEqAll
11251140 :: SListI row
1126− => NP (Aliased (Expression db from grp params)) row -- ^ row constructor
1141+ => NP (Aliased (Expression db params grp from)) row -- ^ row constructor
11271142 -> Query db params row -- ^ subquery
1128− -> Expression db from grp params (nullity 'PGbool)
1143+ -> Expression db params grp from (nullity 'PGbool)
11291144rowEqAll = unsafeRowSubqueryExpression "= ALL"
11301145
11311146-- | >>> printSQL $ true `eqAny` values_ (true `as` #foo)
11321147-- TRUE = ANY (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
11331148eqAny
1134− :: Expression db from grp params ty -- ^ expression
1149+ :: Expression db params grp from ty -- ^ expression
11351150 -> Query db params '[alias ::: ty] -- ^ subquery
1136− -> Expression db from grp params (nullity 'PGbool)
1151+ -> Expression db params grp from (nullity 'PGbool)
11371152eqAny = unsafeSubqueryExpression "= ANY"
11381153
1139−-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db from grp params)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1154+-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db params grp from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
11401155-- >>> printSQL $ myRow `rowEqAny` values_ myRow
11411156-- ROW(1, FALSE) = ANY (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
11421157rowEqAny
11431158 :: SListI row
1144− => NP (Aliased (Expression db from grp params)) row -- ^ row constructor
1159+ => NP (Aliased (Expression db params grp from)) row -- ^ row constructor
11451160 -> Query db params row -- ^ subquery
1146− -> Expression db from grp params (nullity 'PGbool)
1161+ -> Expression db params grp from (nullity 'PGbool)
11471162rowEqAny = unsafeRowSubqueryExpression "= ANY"
11481163
11491164-- | >>> printSQL $ true `neqAll` values_ (true `as` #foo)
11501165-- TRUE <> ALL (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
11511166neqAll
1152− :: Expression db from grp params ty -- ^ expression
1167+ :: Expression db params grp from ty -- ^ expression
11531168 -> Query db params '[alias ::: ty] -- ^ subquery
1154− -> Expression db from grp params (nullity 'PGbool)
1169+ -> Expression db params grp from (nullity 'PGbool)
11551170neqAll = unsafeSubqueryExpression "<> ALL"
11561171
1157−-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db from grp params)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1172+-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db params grp from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
11581173-- >>> printSQL $ myRow `rowNeqAll` values_ myRow
11591174-- ROW(1, FALSE) <> ALL (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
11601175rowNeqAll
11611176 :: SListI row
1162− => NP (Aliased (Expression db from grp params)) row -- ^ row constructor
1177+ => NP (Aliased (Expression db params grp from)) row -- ^ row constructor
11631178 -> Query db params row -- ^ subquery
1164− -> Expression db from grp params (nullity 'PGbool)
1179+ -> Expression db params grp from (nullity 'PGbool)
11651180rowNeqAll = unsafeRowSubqueryExpression "<> ALL"
11661181
11671182-- | >>> printSQL $ true `neqAny` values_ (true `as` #foo)
11681183-- TRUE <> ANY (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
11691184neqAny
1170− :: Expression db from grp params ty -- ^ expression
1185+ :: Expression db params grp from ty -- ^ expression
11711186 -> Query db params '[alias ::: ty] -- ^ subquery
1172− -> Expression db from grp params (nullity 'PGbool)
1187+ -> Expression db params grp from (nullity 'PGbool)
11731188neqAny = unsafeSubqueryExpression "<> ANY"
11741189
1175−-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db from grp params)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1190+-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db params grp from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
11761191-- >>> printSQL $ myRow `rowNeqAny` values_ myRow
11771192-- ROW(1, FALSE) <> ANY (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
11781193rowNeqAny
11791194 :: SListI row
1180− => NP (Aliased (Expression db from grp params)) row -- ^ row constructor
1195+ => NP (Aliased (Expression db params grp from)) row -- ^ row constructor
11811196 -> Query db params row -- ^ subquery
1182− -> Expression db from grp params (nullity 'PGbool)
1197+ -> Expression db params grp from (nullity 'PGbool)
11831198rowNeqAny = unsafeRowSubqueryExpression "<> ANY"
11841199
11851200-- | >>> printSQL $ true `allLt` values_ (true `as` #foo)
11861201-- TRUE ALL < (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
11871202allLt
1188− :: Expression db from grp params ty -- ^ expression
1203+ :: Expression db params grp from ty -- ^ expression
11891204 -> Query db params '[alias ::: ty] -- ^ subquery
1190− -> Expression db from grp params (nullity 'PGbool)
1205+ -> Expression db params grp from (nullity 'PGbool)
11911206allLt = unsafeSubqueryExpression "ALL <"
11921207
1193−-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db from grp params)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1208+-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db params grp from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
11941209-- >>> printSQL $ myRow `rowLtAll` values_ myRow
11951210-- ROW(1, FALSE) ALL < (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
11961211rowLtAll
11971212 :: SListI row
1198− => NP (Aliased (Expression db from grp params)) row -- ^ row constructor
1213+ => NP (Aliased (Expression db params grp from)) row -- ^ row constructor
11991214 -> Query db params row -- ^ subquery
1200− -> Expression db from grp params (nullity 'PGbool)
1215+ -> Expression db params grp from (nullity 'PGbool)
12011216rowLtAll = unsafeRowSubqueryExpression "ALL <"
12021217
12031218-- | >>> printSQL $ true `ltAny` values_ (true `as` #foo)
12041219-- TRUE ANY < (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
12051220ltAny
1206− :: Expression db from grp params ty -- ^ expression
1221+ :: Expression db params grp from ty -- ^ expression
12071222 -> Query db params '[alias ::: ty] -- ^ subquery
1208− -> Expression db from grp params (nullity 'PGbool)
1223+ -> Expression db params grp from (nullity 'PGbool)
12091224ltAny = unsafeSubqueryExpression "ANY <"
12101225
1211−-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db from grp params)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1226+-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db params grp from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
12121227-- >>> printSQL $ myRow `rowLtAll` values_ myRow
12131228-- ROW(1, FALSE) ALL < (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
12141229rowLtAny
12151230 :: SListI row
1216− => NP (Aliased (Expression db from grp params)) row -- ^ row constructor
1231+ => NP (Aliased (Expression db params grp from)) row -- ^ row constructor
12171232 -> Query db params row -- ^ subquery
1218− -> Expression db from grp params (nullity 'PGbool)
1233+ -> Expression db params grp from (nullity 'PGbool)
12191234rowLtAny = unsafeRowSubqueryExpression "ANY <"
12201235
12211236-- | >>> printSQL $ true `lteAll` values_ (true `as` #foo)
12221237-- TRUE <= ALL (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
12231238lteAll
1224− :: Expression db from grp params ty -- ^ expression
1239+ :: Expression db params grp from ty -- ^ expression
12251240 -> Query db params '[alias ::: ty] -- ^ subquery
1226− -> Expression db from grp params (nullity 'PGbool)
1241+ -> Expression db params grp from (nullity 'PGbool)
12271242lteAll = unsafeSubqueryExpression "<= ALL"
12281243
1229−-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db from grp params)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1244+-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db params grp from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
12301245-- >>> printSQL $ myRow `rowLteAll` values_ myRow
12311246-- ROW(1, FALSE) <= ALL (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
12321247rowLteAll
12331248 :: SListI row
1234− => NP (Aliased (Expression db from grp params)) row -- ^ row constructor
1249+ => NP (Aliased (Expression db params grp from)) row -- ^ row constructor
12351250 -> Query db params row -- ^ subquery
1236− -> Expression db from grp params (nullity 'PGbool)
1251+ -> Expression db params grp from (nullity 'PGbool)
12371252rowLteAll = unsafeRowSubqueryExpression "<= ALL"
12381253
12391254-- | >>> printSQL $ true `lteAny` values_ (true `as` #foo)
12401255-- TRUE <= ANY (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
12411256lteAny
1242− :: Expression db from grp params ty -- ^ expression
1257+ :: Expression db params grp from ty -- ^ expression
12431258 -> Query db params '[alias ::: ty] -- ^ subquery
1244− -> Expression db from grp params (nullity 'PGbool)
1259+ -> Expression db params grp from (nullity 'PGbool)
12451260lteAny = unsafeSubqueryExpression "<= ANY"
12461261
1247−-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db from grp params)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1262+-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db params grp from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
12481263-- >>> printSQL $ myRow `rowLteAny` values_ myRow
12491264-- ROW(1, FALSE) <= ANY (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
12501265rowLteAny
12511266 :: SListI row
1252− => NP (Aliased (Expression db from grp params)) row -- ^ row constructor
1267+ => NP (Aliased (Expression db params grp from)) row -- ^ row constructor
12531268 -> Query db params row -- ^ subquery
1254− -> Expression db from grp params (nullity 'PGbool)
1269+ -> Expression db params grp from (nullity 'PGbool)
12551270rowLteAny = unsafeRowSubqueryExpression "<= ANY"
12561271
12571272-- | >>> printSQL $ true `gtAll` values_ (true `as` #foo)
12581273-- TRUE > ALL (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
12591274gtAll
1260− :: Expression db from grp params ty -- ^ expression
1275+ :: Expression db params grp from ty -- ^ expression
12611276 -> Query db params '[alias ::: ty] -- ^ subquery
1262− -> Expression db from grp params (nullity 'PGbool)
1277+ -> Expression db params grp from (nullity 'PGbool)
12631278gtAll = unsafeSubqueryExpression "> ALL"
12641279
1265−-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db from grp params)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1280+-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db params grp from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
12661281-- >>> printSQL $ myRow `rowGtAll` values_ myRow
12671282-- ROW(1, FALSE) > ALL (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
12681283rowGtAll
12691284 :: SListI row
1270− => NP (Aliased (Expression db from grp params)) row -- ^ row constructor
1285+ => NP (Aliased (Expression db params grp from)) row -- ^ row constructor
12711286 -> Query db params row -- ^ subquery
1272− -> Expression db from grp params (nullity 'PGbool)
1287+ -> Expression db params grp from (nullity 'PGbool)
12731288rowGtAll = unsafeRowSubqueryExpression "> ALL"
12741289
12751290-- | >>> printSQL $ true `gtAny` values_ (true `as` #foo)
12761291-- TRUE > ANY (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
12771292gtAny
1278− :: Expression db from grp params ty -- ^ expression
1293+ :: Expression db params grp from ty -- ^ expression
12791294 -> Query db params '[alias ::: ty] -- ^ subquery
1280− -> Expression db from grp params (nullity 'PGbool)
1295+ -> Expression db params grp from (nullity 'PGbool)
12811296gtAny = unsafeSubqueryExpression "> ANY"
12821297
1283−-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db from grp params)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1298+-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db params grp from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
12841299-- >>> printSQL $ myRow `rowGtAny` values_ myRow
12851300-- ROW(1, FALSE) > ANY (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
12861301rowGtAny
12871302 :: SListI row
1288− => NP (Aliased (Expression db from grp params)) row -- ^ row constructor
1303+ => NP (Aliased (Expression db params grp from)) row -- ^ row constructor
12891304 -> Query db params row -- ^ subquery
1290− -> Expression db from grp params (nullity 'PGbool)
1305+ -> Expression db params grp from (nullity 'PGbool)
12911306rowGtAny = unsafeRowSubqueryExpression "> ANY"
12921307
12931308-- | >>> printSQL $ true `gteAll` values_ (true `as` #foo)
12941309-- TRUE >= ALL (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
12951310gteAll
1296− :: Expression db from grp params ty -- ^ expression
1311+ :: Expression db params grp from ty -- ^ expression
12971312 -> Query db params '[alias ::: ty] -- ^ subquery
1298− -> Expression db from grp params (nullity 'PGbool)
1313+ -> Expression db params grp from (nullity 'PGbool)
12991314gteAll = unsafeSubqueryExpression ">= ALL"
13001315
1301−-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db from grp params)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1316+-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db params grp from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
13021317-- >>> printSQL $ myRow `rowGteAll` values_ myRow
13031318-- ROW(1, FALSE) >= ALL (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
13041319rowGteAll
13051320 :: SListI row
1306− => NP (Aliased (Expression db from grp params)) row -- ^ row constructor
1321+ => NP (Aliased (Expression db params grp from)) row -- ^ row constructor
13071322 -> Query db params row -- ^ subquery
1308− -> Expression db from grp params (nullity 'PGbool)
1323+ -> Expression db params grp from (nullity 'PGbool)
13091324rowGteAll = unsafeRowSubqueryExpression ">= ALL"
13101325
13111326-- | >>> printSQL $ true `gteAny` values_ (true `as` #foo)
13121327-- TRUE >= ANY (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
13131328gteAny
1314− :: Expression db from grp params ty -- ^ expression
1329+ :: Expression db params grp from ty -- ^ expression
13151330 -> Query db params '[alias ::: ty] -- ^ subquery
1316− -> Expression db from grp params (nullity 'PGbool)
1331+ -> Expression db params grp from (nullity 'PGbool)
13171332gteAny = unsafeSubqueryExpression ">= ANY"
13181333
1319−-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db from grp params)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1334+-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db params grp from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
13201335-- >>> printSQL $ myRow `rowGteAny` values_ myRow
13211336-- ROW(1, FALSE) >= ANY (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
13221337rowGteAny
13231338 :: SListI row
1324− => NP (Aliased (Expression db from grp params)) row -- ^ row constructor
1339+ => NP (Aliased (Expression db params grp from)) row -- ^ row constructor
13251340 -> Query db params row -- ^ subquery
1326− -> Expression db from grp params (nullity 'PGbool)
1341+ -> Expression db params grp from (nullity 'PGbool)
13271342rowGteAny = unsafeRowSubqueryExpression ">= ANY"
13281343
13291344-- | A `CommonTableExpression` is an auxiliary statement in a `with` clause.
@@ -1358,7 +1373,7 @@ renderCommonTableExpression
13581373 -> CommonTableExpression statement params db0 db1 -> ByteString
13591374renderCommonTableExpression renderStatement
13601375 (CommonTableExpression (statement `As` alias)) =
1361− renderAlias alias <+> "AS" <+> parenthesized (renderStatement statement)
1376+ renderSQL alias <+> "AS" <+> parenthesized (renderStatement statement)
13621377
13631378-- | render a non-empty `AlignedList` of `CommonTableExpression`s.
13641379renderCommonTableExpressions
@@ -1385,5 +1400,5 @@ class With statement where
13851400instance With Query where
13861401 with Done query = query
13871402 with (cte :>> ctes) query = UnsafeQuery $
1388− "WITH" <+> renderCommonTableExpressions renderQuery cte ctes
1389− <+> renderQuery query
1403+ "WITH" <+> renderCommonTableExpressions renderSQL cte ctes
1404+ <+> renderSQL query
squeal-postgresql/src/Squeal/PostgreSQL/Schema.hs+31−46
@@ -68,12 +68,9 @@ module Squeal.PostgreSQL.Schema
6868 , (:::)
6969 , Alias (..)
7070 , IsLabel (..)
71− , renderAlias
72− , renderAliasString
73− , renderAliases
7471 , Aliased (As)
7572 , Aliasable (as)
76− , renderAliasedAs
73+ , renderAliased
7774 , Has
7875 , HasUnique
7976 , HasAll
@@ -83,12 +80,9 @@ module Squeal.PostgreSQL.Schema
8380 , IsNotElem
8481 , AllUnique
8582 , DefaultAliasable (..)
86− , renderQualifiedAlias
8783 -- * Enumerated Labels
8884 , IsPGlabel (..)
8985 , PGlabel (..)
90− , renderLabel
91− , renderLabels
9286 , LabelsPG
9387 -- * Grouping
9488 , Grouping (..)
@@ -377,25 +371,19 @@ instance alias1 ~ alias2 => IsLabel alias1 (Alias alias2) where
377371 fromLabel = Alias
378372instance aliases ~ '[alias] => IsLabel alias (NP Alias aliases) where
379373 fromLabel = fromLabel :* Nil
380−instance KnownSymbol alias => RenderSQL (Alias alias) where renderSQL = renderAlias
381−
382−-- | >>> renderAlias #jimbob
383−-- "\"jimbob\""
384−renderAlias :: KnownSymbol alias => Alias alias -> ByteString
385−renderAlias = doubleQuoted . fromString . symbolVal
386−
387−-- | >>> renderAliasString #ohmahgerd
388−-- "'ohmahgerd'"
389−renderAliasString :: KnownSymbol alias => Alias alias -> ByteString
390−renderAliasString = singleQuotedText . fromString . symbolVal
374+-- | >>> printSQL (#jimbob :: Alias "jimbob")
375+-- "jimbob"
376+instance KnownSymbol alias => RenderSQL (Alias alias) where
377+ renderSQL = doubleQuoted . fromString . symbolVal
391378
392379-- | >>> import Generics.SOP (NP(..))
393−-- >>> renderAliases (#jimbob :* #kandi)
394−-- ["\"jimbob\"","\"kandi\""]
395−renderAliases
396− :: All KnownSymbol aliases => NP Alias aliases -> [ByteString]
397−renderAliases = hcollapse
398− . hcmap (Proxy @KnownSymbol) (K . renderAlias)
380+-- >>> printSQL (#jimbob :* #kandi :: NP Alias '["jimbob", "kandi"])
381+-- "jimbob", "kandi"
382+instance All KnownSymbol aliases => RenderSQL (NP Alias aliases) where
383+ renderSQL
384+ = commaSeparated
385+ . hcollapse
386+ . hcmap (Proxy @KnownSymbol) (K . renderSQL)
399387
400388-- | The `As` operator is used to name an expression. `As` is like a demoted
401389-- version of `:::`.
@@ -436,14 +424,14 @@ instance (KnownSymbol alias, tys ~ '[alias ::: ty]) => Aliasable alias
436424 expression `as` alias = expression `As` alias :* Nil
437425
438426-- | >>> let renderMaybe = fromString . maybe "Nothing" (const "Just")
439−-- >>> renderAliasedAs renderMaybe (Just (3::Int) `As` #an_int)
427+-- >>> renderAliased renderMaybe (Just (3::Int) `As` #an_int)
440428-- "Just AS \"an_int\""
441−renderAliasedAs
429+renderAliased
442430 :: (forall ty. expression ty -> ByteString)
443431 -> Aliased expression aliased
444432 -> ByteString
445−renderAliasedAs render (expression `As` alias) =
446− render expression <> " AS " <> renderAlias alias
433+renderAliased render (expression `As` alias) =
434+ render expression <> " AS " <> renderSQL alias
447435
448436-- | @HasUnique alias fields field@ is a constraint that proves that
449437-- @fields@ is a singleton of @alias ::: field@.
@@ -514,15 +502,14 @@ instance (q ~ "public", a0 ~ a1, a1 ~ a2, KnownSymbol a2) =>
514502 IsLabel a0 (Aliased (QualifiedAlias q) (a1 ::: a2)) where
515503 fromLabel = QualifiedAlias `As` Alias
516504
517−renderQualifiedAlias
518− :: forall q a. (KnownSymbol q, KnownSymbol a)
519− => QualifiedAlias q a -> ByteString
520−renderQualifiedAlias _ =
521− let
522− qualifier = renderAlias (Alias @q)
523− alias = renderAlias (Alias @a)
524− in
525− if qualifier == "\"public\"" then alias else qualifier <> "." <> alias
505+instance (KnownSymbol q, KnownSymbol a)
506+ => RenderSQL (QualifiedAlias q a) where
507+ renderSQL _ =
508+ let
509+ qualifier = renderSQL (Alias @q)
510+ alias = renderSQL (Alias @a)
511+ in
512+ if qualifier == "\"public\"" then alias else qualifier <> "." <> alias
526513
527514-- | @Elem@ is a promoted `Data.List.elem`.
528515type family Elem x xs where
@@ -730,15 +717,13 @@ instance labels ~ '[label]
730717 => IsPGlabel label (NP PGlabel labels) where label = PGlabel :* Nil
731718-- | A `PGlabel` unit type with an `IsPGlabel` instance
732719data PGlabel (label :: Symbol) = PGlabel
733−-- | Renders a label
734−renderLabel :: KnownSymbol label => proxy label -> ByteString
735−renderLabel (_ :: proxy label) =
736− "\'" <> renderSymbol @label <> "\'"
737−-- | Renders a list of labels
738−renderLabels
739− :: All KnownSymbol labels => NP PGlabel labels -> [ByteString]
740−renderLabels = hcollapse
741− . hcmap (Proxy @KnownSymbol) (K . renderLabel)
720+instance KnownSymbol label => RenderSQL (PGlabel label) where
721+ renderSQL _ = "\'" <> renderSymbol @label <> "\'"
722+instance All KnownSymbol labels => RenderSQL (NP PGlabel labels) where
723+ renderSQL
724+ = commaSeparated
725+ . hcollapse
726+ . hcmap (Proxy @KnownSymbol) (K . renderSQL)
742727
743728{- | The `PG` type family embeds a subset of Haskell types
744729as Postgres types. As an open type family, `PG` is extensible.
squeal-postgresql/src/Squeal/PostgreSQL/Transaction.hs+22−26
@@ -30,17 +30,13 @@ module Squeal.PostgreSQL.Transaction
3030 , defaultMode
3131 , longRunningMode
3232 , IsolationLevel (..)
33− , renderIsolationLevel
3433 , AccessMode (..)
35− , renderAccessMode
3634 , DeferrableMode (..)
37− , renderDeferrableMode
3835 ) where
3936
4037import Control.Exception.Lifted
4138import Control.Monad.Base
4239import Control.Monad.Trans.Control
43−import Data.ByteString
4440import Generics.SOP
4541
4642import qualified Database.PostgreSQL.LibPQ as LibPQ
@@ -72,7 +68,7 @@ transactionally_ = transactionally defaultMode
7268-- | @BEGIN@ a transaction.
7369begin :: MonadPQ schemas tx => TransactionMode -> tx (K Result ('[] :: RowType))
7470begin mode = manipulate . UnsafeManipulation $
75− "BEGIN" <+> renderTransactionMode mode <> ";"
71+ "BEGIN" <+> renderSQL mode <> ";"
7672
7773-- | @COMMIT@ a schema invariant transaction.
7874commit :: MonadPQ schemas tx => tx (K Result ('[] :: RowType))
@@ -90,7 +86,7 @@ transactionallySchema
9086 -> PQ schemas0 schemas1 io x
9187transactionallySchema mode u = PQ $ \ conn -> mask $ \ restore -> do
9288 _ <- liftBase . LibPQ.exec (unK conn) $
93− "BEGIN" <+> renderTransactionMode mode <> ";"
89+ "BEGIN" <+> renderSQL mode <> ";"
9490 x <- restore (unPQ u conn)
9591 `onException` (liftBase (LibPQ.exec (unK conn) "ROLLBACK"))
9692 _ <- liftBase $ LibPQ.exec (unK conn) "COMMIT"
@@ -123,12 +119,12 @@ longRunningMode :: TransactionMode
123119longRunningMode = TransactionMode Serializable ReadOnly Deferrable
124120
125121-- | Render a `TransactionMode`.
126−renderTransactionMode :: TransactionMode -> ByteString
127−renderTransactionMode mode =
128− "ISOLATION LEVEL"
129− <+> renderIsolationLevel (isolationLevel mode)
130− <+> renderAccessMode (accessMode mode)
131− <+> renderDeferrableMode (deferrableMode mode)
122+instance RenderSQL TransactionMode where
123+ renderSQL mode =
124+ "ISOLATION LEVEL"
125+ <+> renderSQL (isolationLevel mode)
126+ <+> renderSQL (accessMode mode)
127+ <+> renderSQL (deferrableMode mode)
132128
133129-- | The SQL standard defines four levels of transaction isolation.
134130-- The most strict is `Serializable`, which is defined by the standard in a paragraph
@@ -179,12 +175,12 @@ data IsolationLevel
179175 deriving (Show, Eq)
180176
181177-- | Render an `IsolationLevel`.
182−renderIsolationLevel :: IsolationLevel -> ByteString
183−renderIsolationLevel = \case
184− Serializable -> "SERIALIZABLE"
185− ReadCommitted -> "READ COMMITTED"
186− ReadUncommitted -> "READ UNCOMMITTED"
187− RepeatableRead -> "REPEATABLE READ"
178+instance RenderSQL IsolationLevel where
179+ renderSQL = \case
180+ Serializable -> "SERIALIZABLE"
181+ ReadCommitted -> "READ COMMITTED"
182+ ReadUncommitted -> "READ UNCOMMITTED"
183+ RepeatableRead -> "REPEATABLE READ"
188184
189185-- | The transaction access mode determines whether the transaction is `ReadWrite` or `ReadOnly`.
190186-- `ReadWrite` is the default. When a transaction is `ReadOnly`,
@@ -201,10 +197,10 @@ data AccessMode
201197 deriving (Show, Eq)
202198
203199-- | Render an `AccessMode`.
204−renderAccessMode :: AccessMode -> ByteString
205−renderAccessMode = \case
206− ReadWrite -> "READ WRITE"
207− ReadOnly -> "READ ONLY"
200+instance RenderSQL AccessMode where
201+ renderSQL = \case
202+ ReadWrite -> "READ WRITE"
203+ ReadOnly -> "READ ONLY"
208204
209205-- | The `Deferrable` transaction property has no effect
210206-- unless the transaction is also `Serializable` and `ReadOnly`.
@@ -220,7 +216,7 @@ data DeferrableMode
220216 deriving (Show, Eq)
221217
222218-- | Render a `DeferrableMode`.
223−renderDeferrableMode :: DeferrableMode -> ByteString
224−renderDeferrableMode = \case
225− Deferrable -> "DEFERRABLE"
226− NotDeferrable -> "NOT DEFERRABLE"
219+instance RenderSQL DeferrableMode where
220+ renderSQL = \case
221+ Deferrable -> "DEFERRABLE"
222+ NotDeferrable -> "NOT DEFERRABLE"