on dev help sign in
Merge pull request #84 from morphismtech/dev-refactor-select
2762bb4Eitan Chatav
squeal-postgresql/exe/Example.hs+3−4
@@ -68,18 +68,17 @@ insertUser :: Manipulation DB '[ 'NotNull 'PGtext, 'NotNull ('PGvararray ('Null
68 '[ "fromOnly" ::: 'NotNull 'PGint4 ]
68 '[ "fromOnly" ::: 'NotNull 'PGint4 ]
69insertUser = insertInto #users
69insertUser = insertInto #users
70 (Values_ (defaultAs #id :* param @1 `as` #name :* param @2 `as` #vec))
70 (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))
72
72
73insertEmail :: Manipulation DB '[ 'NotNull 'PGint4, 'Null 'PGtext] '[]
73insertEmail :: Manipulation DB '[ 'NotNull 'PGint4, 'Null 'PGtext] '[]
74−insertEmail = insertInto #emails
74+insertEmail = insertInto_ #emails
75 (Values_ (defaultAs #id :* param @1 `as` #user_id :* param @2 `as` #email))
75 (Values_ (defaultAs #id :* param @1 `as` #user_id :* param @2 `as` #email))
76− (OnConflict (OnConstraint #pk_emails) DoNothing) (Returning Nil)
77
76
78getUsers :: Query DB '[]
77getUsers :: Query DB '[]
79 '[ "userName" ::: 'NotNull 'PGtext
78 '[ "userName" ::: 'NotNull 'PGtext
80 , "userEmail" ::: 'Null 'PGtext
79 , "userEmail" ::: 'Null 'PGtext
81 , "userVec" ::: 'NotNull ('PGvararray ('Null 'PGint2))]
80 , "userVec" ::: 'NotNull ('PGvararray ('Null 'PGint2))]
82−getUsers = select
81+getUsers = select_
83 (#u ! #name `as` #userName :* #e ! #email `as` #userEmail :* #u ! #vec `as` #userVec)
82 (#u ! #name `as` #userName :* #e ! #email `as` #userEmail :* #u ! #vec `as` #userVec)
84 ( from (table (#users `as` #u)
83 ( from (table (#users `as` #u)
85 & innerJoin (table (#emails `as` #e))
84 & innerJoin (table (#emails `as` #e))
squeal-postgresql/src/Squeal/PostgreSQL.hs+2−2
@@ -123,7 +123,7 @@ let
123 where
123 where
124 u = insertInto #users
124 u = insertInto #users
125 (Values_ (defaultAs #id :* param @1 `as` #name))
125 (Values_ (defaultAs #id :* param @1 `as` #name))
126− OnConflictDoRaise (Returning (#id :* param @2 `as` #email))
126+ OnConflictDoRaise (Returning_ (#id :* param @2 `as` #email))
127 e = insertInto_ #emails
127 e = insertInto_ #emails
128 (Select (defaultAs #id :* #u ! #id `as` #user_id :* #u ! #email) (from (common #u)))
128 (Select (defaultAs #id :* #u ! #id `as` #user_id :* #u ! #email) (from (common #u)))
129:}
129:}
@@ -141,7 +141,7 @@ let
141 getUsers :: Query DB '[]
141 getUsers :: Query DB '[]
142 '[ "userName" ::: 'NotNull 'PGtext
142 '[ "userName" ::: 'NotNull 'PGtext
143 , "userEmail" ::: 'Null 'PGtext ]
143 , "userEmail" ::: 'Null 'PGtext ]
144− getUsers = select
144+ getUsers = select_
145 (#u ! #name `as` #userName :* #e ! #email `as` #userEmail)
145 (#u ! #name `as` #userName :* #e ! #email `as` #userEmail)
146 ( from (table (#users `as` #u)
146 ( from (table (#users `as` #u)
147 & innerJoin (table (#emails `as` #e))
147 & innerJoin (table (#emails `as` #e))
squeal-postgresql/src/Squeal/PostgreSQL/Definition.hs+58−56
@@ -29,7 +29,7 @@ Squeal data definition language.
29
29
30module Squeal.PostgreSQL.Definition
30module Squeal.PostgreSQL.Definition
31 ( -- * Definition
31 ( -- * Definition
32− Definition (UnsafeDefinition, renderDefinition)
32+ Definition (..)
33 , (>>>)
33 , (>>>)
34 -- * Tables
34 -- * Tables
35 -- ** Create
35 -- ** Create
@@ -43,23 +43,21 @@ module Squeal.PostgreSQL.Definition
43 , primaryKey
43 , primaryKey
44 , foreignKey
44 , foreignKey
45 , ForeignKeyed
45 , ForeignKeyed
46− , OnDeleteClause (OnDeleteNoAction, OnDeleteRestrict, OnDeleteCascade)
46+ , OnDeleteClause (..)
47− , renderOnDeleteClause
47+ , OnUpdateClause (..)
48− , OnUpdateClause (OnUpdateNoAction, OnUpdateRestrict, OnUpdateCascade)
49− , renderOnUpdateClause
50 -- ** Drop
48 -- ** Drop
51 , dropTable
49 , dropTable
52 -- ** Alter
50 -- ** Alter
53 , alterTable
51 , alterTable
54 , alterTableRename
52 , alterTableRename
55− , AlterTable (UnsafeAlterTable, renderAlterTable)
53+ , AlterTable (..)
56 , addConstraint
54 , addConstraint
57 , dropConstraint
55 , dropConstraint
58− , AddColumn (addColumn)
56+ , AddColumn (..)
59 , dropColumn
57 , dropColumn
60 , renameColumn
58 , renameColumn
61 , alterColumn
59 , alterColumn
62− , AlterColumn (UnsafeAlterColumn, renderAlterColumn)
60+ , AlterColumn (..)
63 , setDefault
61 , setDefault
64 , dropDefault
62 , dropDefault
65 , setNotNull
63 , setNotNull
@@ -121,7 +119,7 @@ instance RenderSQL (Definition schemas0 schemas1) where
121instance Category Definition where
119instance Category Definition where
122 id = UnsafeDefinition ";"
120 id = UnsafeDefinition ";"
123 ddl1 . ddl0 = UnsafeDefinition $
121 ddl1 . ddl0 = UnsafeDefinition $
124− renderDefinition ddl0 <> "\n" <> renderDefinition ddl1
122+ renderSQL ddl0 <> "\n" <> renderSQL ddl1
125
123
126{-----------------------------------------
124{-----------------------------------------
127CREATE statements
125CREATE statements
@@ -132,7 +130,7 @@ createSchema
132 => Alias sch
130 => Alias sch
133 -> Definition schemas (Create sch '[] schemas)
131 -> Definition schemas (Create sch '[] schemas)
134createSchema sch = UnsafeDefinition $
132createSchema sch = UnsafeDefinition $
135− "CREATE" <+> "SCHEMA" <+> renderAlias sch <> ";"
133+ "CREATE" <+> "SCHEMA" <+> renderSQL sch <> ";"
136
134
137createSchemaIfNotExists
135createSchemaIfNotExists
138 :: (KnownSymbol sch, Has sch schemas schema)
136 :: (KnownSymbol sch, Has sch schemas schema)
@@ -140,7 +138,7 @@ createSchemaIfNotExists
140 -> Definition schemas schemas
138 -> Definition schemas schemas
141createSchemaIfNotExists sch = UnsafeDefinition $
139createSchemaIfNotExists sch = UnsafeDefinition $
142 "CREATE" <+> "SCHEMA" <+> "IF" <+> "NOT" <+> "EXISTS"
140 "CREATE" <+> "SCHEMA" <+> "IF" <+> "NOT" <+> "EXISTS"
143− <+> renderAlias sch <> ";"
141+ <+> renderSQL sch <> ";"
144
142
145{- | `createTable` adds a table to the schema.
143{- | `createTable` adds a table to the schema.
146
144
@@ -227,7 +225,7 @@ renderCreation
227 -> NP (Aliased (TableConstraintExpression sch tab schemas1)) constraints
225 -> NP (Aliased (TableConstraintExpression sch tab schemas1)) constraints
228 -- ^ constraints that must hold for the table
226 -- ^ constraints that must hold for the table
229 -> ByteString
227 -> ByteString
230−renderCreation tab columns constraints = renderQualifiedAlias tab
228+renderCreation tab columns constraints = renderSQL tab
231 <+> parenthesized
229 <+> parenthesized
232 ( renderCommaSeparated renderColumnDef columns
230 ( renderCommaSeparated renderColumnDef columns
233 <> ( case constraints of
231 <> ( case constraints of
@@ -238,12 +236,12 @@ renderCreation tab columns constraints = renderQualifiedAlias tab
238 where
236 where
239 renderColumnDef :: Aliased (ColumnTypeExpression schemas) x -> ByteString
237 renderColumnDef :: Aliased (ColumnTypeExpression schemas) x -> ByteString
240 renderColumnDef (ty `As` column) =
238 renderColumnDef (ty `As` column) =
241− renderAlias column <+> renderColumnTypeExpression ty
239+ renderSQL column <+> renderColumnTypeExpression ty
242 renderConstraint
240 renderConstraint
243 :: Aliased (TableConstraintExpression sch tab schemas) constraint
241 :: Aliased (TableConstraintExpression sch tab schemas) constraint
244 -> ByteString
242 -> ByteString
245 renderConstraint (constraint `As` alias) =
243 renderConstraint (constraint `As` alias) =
246− "CONSTRAINT" <+> renderAlias alias <+> renderTableConstraintExpression constraint
244+ "CONSTRAINT" <+> renderSQL alias <+> renderSQL constraint
247
245
248-- | Data types are a way to limit the kind of data that can be stored in a
246-- | Data types are a way to limit the kind of data that can be stored in a
249-- table. For many applications, however, the constraint they provide is
247-- table. For many applications, however, the constraint they provide is
@@ -265,6 +263,9 @@ newtype TableConstraintExpression
265 = UnsafeTableConstraintExpression
263 = UnsafeTableConstraintExpression
266 { renderTableConstraintExpression :: ByteString }
264 { renderTableConstraintExpression :: ByteString }
267 deriving (GHC.Generic,Show,Eq,Ord,NFData)
265 deriving (GHC.Generic,Show,Eq,Ord,NFData)
266+instance RenderSQL
267+ (TableConstraintExpression sch tab schemas constraint) where
268+ renderSQL = renderTableConstraintExpression
268
269
269{-| A `check` constraint is the most generic `TableConstraint` type.
270{-| A `check` constraint is the most generic `TableConstraint` type.
270It allows you to specify that the value in a certain column must satisfy
271It allows you to specify that the value in a certain column must satisfy
@@ -296,11 +297,11 @@ check
296 , HasAll aliases (TableToRow table) subcolumns )
297 , HasAll aliases (TableToRow table) subcolumns )
297 => NP Alias aliases
298 => NP Alias aliases
298 -- ^ specify the subcolumns which are getting checked
299 -- ^ specify the subcolumns which are getting checked
299− -> (forall t. Condition ('[] :=> schemas) '[t ::: subcolumns] 'Ungrouped '[])
300+ -> (forall t. Condition ('[] :=> schemas) '[] 'Ungrouped '[t ::: subcolumns])
300 -- ^ a closed `Condition` on those subcolumns
301 -- ^ a closed `Condition` on those subcolumns
301 -> TableConstraintExpression sch tab schemas ('Check aliases)
302 -> TableConstraintExpression sch tab schemas ('Check aliases)
302check _cols condition = UnsafeTableConstraintExpression $
303check _cols condition = UnsafeTableConstraintExpression $
303− "CHECK" <+> parenthesized (renderExpression condition)
304+ "CHECK" <+> parenthesized (renderSQL condition)
304
305
305{-| A `unique` constraint ensure that the data contained in a column,
306{-| A `unique` constraint ensure that the data contained in a column,
306or a group of columns, is unique among all the rows in the table.
307or a group of columns, is unique among all the rows in the table.
@@ -333,7 +334,7 @@ unique
333 -- ^ specify subcolumns which together are unique for each row
334 -- ^ specify subcolumns which together are unique for each row
334 -> TableConstraintExpression sch tab schemas ('Unique aliases)
335 -> TableConstraintExpression sch tab schemas ('Unique aliases)
335unique columns = UnsafeTableConstraintExpression $
336unique columns = UnsafeTableConstraintExpression $
336− "UNIQUE" <+> parenthesized (commaSeparated (renderAliases columns))
337+ "UNIQUE" <+> parenthesized (renderSQL columns)
337
338
338{-| A `primaryKey` constraint indicates that a column, or group of columns,
339{-| A `primaryKey` constraint indicates that a column, or group of columns,
339can be used as a unique identifier for rows in the table.
340can be used as a unique identifier for rows in the table.
@@ -368,7 +369,7 @@ primaryKey
368 -- ^ specify the subcolumns which together form a primary key.
369 -- ^ specify the subcolumns which together form a primary key.
369 -> TableConstraintExpression sch tab schemas ('PrimaryKey aliases)
370 -> TableConstraintExpression sch tab schemas ('PrimaryKey aliases)
370primaryKey columns = UnsafeTableConstraintExpression $
371primaryKey columns = UnsafeTableConstraintExpression $
371− "PRIMARY KEY" <+> parenthesized (commaSeparated (renderAliases columns))
372+ "PRIMARY KEY" <+> parenthesized (renderSQL columns)
372
373
373{-| A `foreignKey` specifies that the values in a column
374{-| A `foreignKey` specifies that the values in a column
374(or a group of columns) must match the values appearing in some row of
375(or a group of columns) must match the values appearing in some row of
@@ -462,11 +463,11 @@ foreignKey
462 -> TableConstraintExpression sch child schemas
463 -> TableConstraintExpression sch child schemas
463 ('ForeignKey columns parent refcolumns)
464 ('ForeignKey columns parent refcolumns)
464foreignKey keys parent refs ondel onupd = UnsafeTableConstraintExpression $
465foreignKey keys parent refs ondel onupd = UnsafeTableConstraintExpression $
465− "FOREIGN KEY" <+> parenthesized (commaSeparated (renderAliases keys))
466+ "FOREIGN KEY" <+> parenthesized (renderSQL keys)
466− <+> "REFERENCES" <+> renderAlias parent
467+ <+> "REFERENCES" <+> renderSQL parent
467− <+> parenthesized (commaSeparated (renderAliases refs))
468+ <+> parenthesized (renderSQL refs)
468− <+> renderOnDeleteClause ondel
469+ <+> renderSQL ondel
469− <+> renderOnUpdateClause onupd
470+ <+> renderSQL onupd
470
471
471-- | A constraint synonym between types involved in a foreign key constraint.
472-- | A constraint synonym between types involved in a foreign key constraint.
472type ForeignKeyed schemas
473type ForeignKeyed schemas
@@ -497,13 +498,12 @@ data OnDeleteClause
497 -- row(s) referencing it should be automatically deleted as well
498 -- row(s) referencing it should be automatically deleted as well
498 deriving (GHC.Generic,Show,Eq,Ord)
499 deriving (GHC.Generic,Show,Eq,Ord)
499instance NFData OnDeleteClause
500instance NFData OnDeleteClause
500−
501-- | Render `OnDeleteClause`.
501-- | Render `OnDeleteClause`.
502−renderOnDeleteClause :: OnDeleteClause -> ByteString
502+instance RenderSQL OnDeleteClause where
503−renderOnDeleteClause = \case
503+ renderSQL = \case
504− OnDeleteNoAction -> "ON DELETE NO ACTION"
504+ OnDeleteNoAction -> "ON DELETE NO ACTION"
505− OnDeleteRestrict -> "ON DELETE RESTRICT"
505+ OnDeleteRestrict -> "ON DELETE RESTRICT"
506− OnDeleteCascade -> "ON DELETE CASCADE"
506+ OnDeleteCascade -> "ON DELETE CASCADE"
507
507
508-- | Analagous to `OnDeleteClause` there is also `OnUpdateClause` which is invoked
508-- | Analagous to `OnDeleteClause` there is also `OnUpdateClause` which is invoked
509-- when a referenced column is changed (updated).
509-- when a referenced column is changed (updated).
@@ -519,11 +519,11 @@ data OnUpdateClause
519instance NFData OnUpdateClause
519instance NFData OnUpdateClause
520
520
521-- | Render `OnUpdateClause`.
521-- | Render `OnUpdateClause`.
522−renderOnUpdateClause :: OnUpdateClause -> ByteString
522+instance RenderSQL OnUpdateClause where
523−renderOnUpdateClause = \case
523+ renderSQL = \case
524− OnUpdateNoAction -> "ON UPDATE NO ACTION"
524+ OnUpdateNoAction -> "ON UPDATE NO ACTION"
525− OnUpdateRestrict -> "ON UPDATE RESTRICT"
525+ OnUpdateRestrict -> "ON UPDATE RESTRICT"
526− OnUpdateCascade -> "ON UPDATE CASCADE"
526+ OnUpdateCascade -> "ON UPDATE CASCADE"
527
527
528{-----------------------------------------
528{-----------------------------------------
529DROP statements
529DROP statements
@@ -544,7 +544,7 @@ dropTable
544 , Has tab schema ('Table table))
544 , Has tab schema ('Table table))
545 => QualifiedAlias sch tab -- ^ table to remove
545 => QualifiedAlias sch tab -- ^ table to remove
546 -> Definition schemas (Alter sch (Drop tab schema) schemas)
546 -> Definition schemas (Alter sch (Drop tab schema) schemas)
547−dropTable tab = UnsafeDefinition $ "DROP TABLE" <+> renderQualifiedAlias tab <> ";"
547+dropTable tab = UnsafeDefinition $ "DROP TABLE" <+> renderSQL tab <> ";"
548
548
549{-----------------------------------------
549{-----------------------------------------
550ALTER statements
550ALTER statements
@@ -558,7 +558,7 @@ alterTable
558 -> Definition schemas (Alter sch (Alter tab ('Table table1) schema) schemas)
558 -> Definition schemas (Alter sch (Alter tab ('Table table1) schema) schemas)
559alterTable tab alteration = UnsafeDefinition $
559alterTable tab alteration = UnsafeDefinition $
560 "ALTER TABLE"
560 "ALTER TABLE"
561− <+> renderQualifiedAlias tab
561+ <+> renderSQL tab
562 <+> renderAlterTable alteration
562 <+> renderAlterTable alteration
563 <> ";"
563 <> ";"
564
564
@@ -572,8 +572,8 @@ alterTableRename
572 -> Alias table1 -- ^ what to rename it
572 -> Alias table1 -- ^ what to rename it
573 -> Definition schema (Rename table0 table1 schema)
573 -> Definition schema (Rename table0 table1 schema)
574alterTableRename table0 table1 = UnsafeDefinition $
574alterTableRename table0 table1 = UnsafeDefinition $
575− "ALTER TABLE" <+> renderAlias table0
575+ "ALTER TABLE" <+> renderSQL table0
576− <+> "RENAME TO" <+> renderAlias table1 <> ";"
576+ <+> "RENAME TO" <+> renderSQL table1 <> ";"
577
577
578-- | An `AlterTable` describes the alteration to perform on the columns
578-- | An `AlterTable` describes the alteration to perform on the columns
579-- of a table.
579-- of a table.
@@ -607,8 +607,8 @@ addConstraint
607 -- ^ constraint to add
607 -- ^ constraint to add
608 -> AlterTable sch tab schemas table1
608 -> AlterTable sch tab schemas table1
609addConstraint alias constraint = UnsafeAlterTable $
609addConstraint alias constraint = UnsafeAlterTable $
610− "ADD" <+> "CONSTRAINT" <+> renderAlias alias
610+ "ADD" <+> "CONSTRAINT" <+> renderSQL alias
611− <+> renderTableConstraintExpression constraint
611+ <+> renderSQL constraint
612
612
613-- | A `dropConstraint` drops a table constraint.
613-- | A `dropConstraint` drops a table constraint.
614--
614--
@@ -631,7 +631,7 @@ dropConstraint
631 -- ^ constraint to drop
631 -- ^ constraint to drop
632 -> AlterTable sch tab schemas table1
632 -> AlterTable sch tab schemas table1
633dropConstraint constraint = UnsafeAlterTable $
633dropConstraint constraint = UnsafeAlterTable $
634− "DROP" <+> "CONSTRAINT" <+> renderAlias constraint
634+ "DROP" <+> "CONSTRAINT" <+> renderSQL constraint
635
635
636-- | An `AddColumn` is either @NULL@ or has @DEFAULT@.
636-- | An `AddColumn` is either @NULL@ or has @DEFAULT@.
637class AddColumn ty where
637class AddColumn ty where
@@ -670,7 +670,7 @@ class AddColumn ty where
670 -> ColumnTypeExpression schemas ty -- ^ type of the new column
670 -> ColumnTypeExpression schemas ty -- ^ type of the new column
671 -> AlterTable sch tab schemas (constraints :=> Create column ty columns)
671 -> AlterTable sch tab schemas (constraints :=> Create column ty columns)
672 addColumn column ty = UnsafeAlterTable $
672 addColumn column ty = UnsafeAlterTable $
673− "ADD COLUMN" <+> renderAlias column <+> renderColumnTypeExpression ty
673+ "ADD COLUMN" <+> renderSQL column <+> renderColumnTypeExpression ty
674instance {-# OVERLAPPING #-} AddColumn ('Def :=> ty)
674instance {-# OVERLAPPING #-} AddColumn ('Def :=> ty)
675instance {-# OVERLAPPABLE #-} AddColumn ('NoDef :=> 'Null ty)
675instance {-# OVERLAPPABLE #-} AddColumn ('NoDef :=> 'Null ty)
676
676
@@ -699,7 +699,7 @@ dropColumn
699 => Alias column -- ^ column to remove
699 => Alias column -- ^ column to remove
700 -> AlterTable sch tab schemas table1
700 -> AlterTable sch tab schemas table1
701dropColumn column = UnsafeAlterTable $
701dropColumn column = UnsafeAlterTable $
702− "DROP COLUMN" <+> renderAlias column
702+ "DROP COLUMN" <+> renderSQL column
703
703
704-- | A `renameColumn` renames a column.
704-- | A `renameColumn` renames a column.
705--
705--
@@ -723,7 +723,7 @@ renameColumn
723 -> Alias column1 -- ^ what to rename the column
723 -> Alias column1 -- ^ what to rename the column
724 -> AlterTable sch tab schemas table1
724 -> AlterTable sch tab schemas table1
725renameColumn column0 column1 = UnsafeAlterTable $
725renameColumn column0 column1 = UnsafeAlterTable $
726− "RENAME COLUMN" <+> renderAlias column0 <+> "TO" <+> renderAlias column1
726+ "RENAME COLUMN" <+> renderSQL column0 <+> "TO" <+> renderSQL column1
727
727
728-- | An `alterColumn` alters a single column.
728-- | An `alterColumn` alters a single column.
729alterColumn
729alterColumn
@@ -737,7 +737,7 @@ alterColumn
737 -> AlterColumn schemas ty0 ty1 -- ^ alteration to perform
737 -> AlterColumn schemas ty0 ty1 -- ^ alteration to perform
738 -> AlterTable sch tab schemas table1
738 -> AlterTable sch tab schemas table1
739alterColumn column alteration = UnsafeAlterTable $
739alterColumn column alteration = UnsafeAlterTable $
740− "ALTER COLUMN" <+> renderAlias column <+> renderAlterColumn alteration
740+ "ALTER COLUMN" <+> renderSQL column <+> renderAlterColumn alteration
741
741
742-- | An `AlterColumn` describes the alteration to perform on a single column.
742-- | An `AlterColumn` describes the alteration to perform on a single column.
743newtype AlterColumn (schemas :: SchemasType) (ty0 :: ColumnType) (ty1 :: ColumnType) =
743newtype AlterColumn (schemas :: SchemasType) (ty0 :: ColumnType) (ty1 :: ColumnType) =
@@ -835,7 +835,7 @@ let
835 '[ "public" ::: '["abc" ::: 'Table ('[] :=> ABC)]]
835 '[ "public" ::: '["abc" ::: 'Table ('[] :=> ABC)]]
836 '[ "public" ::: '["abc" ::: 'Table ('[] :=> ABC), "bc" ::: 'View BC]]
836 '[ "public" ::: '["abc" ::: 'Table ('[] :=> ABC), "bc" ::: 'View BC]]
837 definition =
837 definition =
838− createView #bc (select (#b :* #c) (from (table #abc)))
838+ createView #bc (select_ (#b :* #c) (from (table #abc)))
839in printSQL definition
839in printSQL definition
840:}
840:}
841CREATE VIEW "bc" AS SELECT "b" AS "b", "c" AS "c" FROM "abc" AS "abc";
841CREATE VIEW "bc" AS SELECT "b" AS "b", "c" AS "c" FROM "abc" AS "abc";
@@ -846,7 +846,7 @@ createView
846 -> Query ('[] :=> schemas) '[] view -- ^ query
846 -> Query ('[] :=> schemas) '[] view -- ^ query
847 -> Definition schemas (Alter sch (Create vw ('View view) schema) schemas)
847 -> Definition schemas (Alter sch (Create vw ('View view) schema) schemas)
848createView alias query = UnsafeDefinition $
848createView alias query = UnsafeDefinition $
849− "CREATE" <+> "VIEW" <+> renderQualifiedAlias alias <+> "AS"
849+ "CREATE" <+> "VIEW" <+> renderSQL alias <+> "AS"
850 <+> renderQuery query <> ";"
850 <+> renderQuery query <> ";"
851
851
852-- | Drop a view.
852-- | Drop a view.
@@ -865,7 +865,7 @@ dropView
865 :: (Has sch schemas schema, Has vw schema ('View view))
865 :: (Has sch schemas schema, Has vw schema ('View view))
866 => QualifiedAlias sch vw -- ^ view to remove
866 => QualifiedAlias sch vw -- ^ view to remove
867 -> Definition schemas (Alter sch (Drop vw schema) schemas)
867 -> Definition schemas (Alter sch (Drop vw schema) schemas)
868−dropView vw = UnsafeDefinition $ "DROP VIEW" <+> renderQualifiedAlias vw <> ";"
868+dropView vw = UnsafeDefinition $ "DROP VIEW" <+> renderSQL vw <> ";"
869
869
870-- | Enumerated types are created using the `createTypeEnum` command, for example
870-- | Enumerated types are created using the `createTypeEnum` command, for example
871--
871--
@@ -879,8 +879,8 @@ createTypeEnum
879 -- ^ labels of the enumerated type
879 -- ^ labels of the enumerated type
880 -> Definition schemas (Alter sch (Create enum ('Typedef ('PGenum labels)) schema) schemas)
880 -> Definition schemas (Alter sch (Create enum ('Typedef ('PGenum labels)) schema) schemas)
881createTypeEnum enum labels = UnsafeDefinition $
881createTypeEnum enum labels = UnsafeDefinition $
882− "CREATE" <+> "TYPE" <+> renderQualifiedAlias enum <+> "AS" <+> "ENUM" <+>
882+ "CREATE" <+> "TYPE" <+> renderSQL enum <+> "AS" <+> "ENUM" <+>
883− parenthesized (commaSeparated (renderLabels labels)) <> ";"
883+ parenthesized (renderSQL labels) <> ";"
884
884
885-- | Enumerated types can also be generated from a Haskell type, for example
885-- | Enumerated types can also be generated from a Haskell type, for example
886--
886--
@@ -933,12 +933,12 @@ createTypeComposite
933 -- ^ list of attribute names and data types
933 -- ^ list of attribute names and data types
934 -> Definition schemas (Alter sch (Create ty ('Typedef ('PGcomposite fields)) schema) schemas)
934 -> Definition schemas (Alter sch (Create ty ('Typedef ('PGcomposite fields)) schema) schemas)
935createTypeComposite ty fields = UnsafeDefinition $
935createTypeComposite ty fields = UnsafeDefinition $
936− "CREATE" <+> "TYPE" <+> renderQualifiedAlias ty <+> "AS" <+> parenthesized
936+ "CREATE" <+> "TYPE" <+> renderSQL ty <+> "AS" <+> parenthesized
937 (renderCommaSeparated renderField fields) <> ";"
937 (renderCommaSeparated renderField fields) <> ";"
938 where
938 where
939 renderField :: Aliased (TypeExpression schemas) x -> ByteString
939 renderField :: Aliased (TypeExpression schemas) x -> ByteString
940 renderField (typ `As` alias) =
940 renderField (typ `As` alias) =
941− renderAlias alias <+> renderTypeExpression typ
941+ renderSQL alias <+> renderSQL typ
942
942
943-- | Composite types can also be generated from a Haskell type, for example
943-- | Composite types can also be generated from a Haskell type, for example
944--
944--
@@ -984,26 +984,28 @@ dropType
984 => QualifiedAlias sch td
984 => QualifiedAlias sch td
985 -- ^ name of the user defined type
985 -- ^ name of the user defined type
986 -> Definition schemas (Alter sch (Drop td schema) schemas)
986 -> Definition schemas (Alter sch (Drop td schema) schemas)
987−dropType tydef = UnsafeDefinition $ "DROP" <+> "TYPE" <+> renderQualifiedAlias tydef <> ";"
987+dropType tydef = UnsafeDefinition $ "DROP" <+> "TYPE" <+> renderSQL tydef <> ";"
988
988
989-- | `ColumnTypeExpression`s are used in `createTable` commands.
989-- | `ColumnTypeExpression`s are used in `createTable` commands.
990newtype ColumnTypeExpression (schemas :: SchemasType) (ty :: ColumnType)
990newtype ColumnTypeExpression (schemas :: SchemasType) (ty :: ColumnType)
991 = UnsafeColumnTypeExpression { renderColumnTypeExpression :: ByteString }
991 = UnsafeColumnTypeExpression { renderColumnTypeExpression :: ByteString }
992 deriving (GHC.Generic,Show,Eq,Ord,NFData)
992 deriving (GHC.Generic,Show,Eq,Ord,NFData)
993+instance RenderSQL (ColumnTypeExpression schemas ty) where
994+ renderSQL = renderColumnTypeExpression
993
995
994-- | used in `createTable` commands as a column constraint to note that
996-- | used in `createTable` commands as a column constraint to note that
995-- @NULL@ may be present in a column
997-- @NULL@ may be present in a column
996nullable
998nullable
997 :: TypeExpression schemas (nullity ty)
999 :: TypeExpression schemas (nullity ty)
998 -> ColumnTypeExpression schemas ('NoDef :=> 'Null ty)
1000 -> ColumnTypeExpression schemas ('NoDef :=> 'Null ty)
999−nullable ty = UnsafeColumnTypeExpression $ renderTypeExpression ty <+> "NULL"
1001+nullable ty = UnsafeColumnTypeExpression $ renderSQL ty <+> "NULL"
1000
1002
1001-- | used in `createTable` commands as a column constraint to ensure
1003-- | used in `createTable` commands as a column constraint to ensure
1002-- @NULL@ is not present in a column
1004-- @NULL@ is not present in a column
1003notNullable
1005notNullable
1004 :: TypeExpression schemas (nullity ty)
1006 :: TypeExpression schemas (nullity ty)
1005 -> ColumnTypeExpression schemas ('NoDef :=> 'NotNull ty)
1007 -> ColumnTypeExpression schemas ('NoDef :=> 'NotNull ty)
1006−notNullable ty = UnsafeColumnTypeExpression $ renderTypeExpression ty <+> "NOT NULL"
1008+notNullable ty = UnsafeColumnTypeExpression $ renderSQL ty <+> "NOT NULL"
1007
1009
1008-- | used in `createTable` commands as a column constraint to give a default
1010-- | used in `createTable` commands as a column constraint to give a default
1009default_
1011default_
@@ -1011,7 +1013,7 @@ default_
1011 -> ColumnTypeExpression schemas ('NoDef :=> ty)
1013 -> ColumnTypeExpression schemas ('NoDef :=> ty)
1012 -> ColumnTypeExpression schemas ('Def :=> ty)
1014 -> ColumnTypeExpression schemas ('Def :=> ty)
1013default_ x ty = UnsafeColumnTypeExpression $
1015default_ x ty = UnsafeColumnTypeExpression $
1014− renderColumnTypeExpression ty <+> "DEFAULT" <+> renderExpression x
1016+ renderSQL ty <+> "DEFAULT" <+> renderExpression x
1015
1017
1016-- | not a true type, but merely a notational convenience for creating
1018-- | not a true type, but merely a notational convenience for creating
1017-- unique identifier columns with type `PGint2`
1019-- 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.
31
31
32module Squeal.PostgreSQL.Expression
32module Squeal.PostgreSQL.Expression
33 ( -- * Expression
33 ( -- * Expression
34− Expression (UnsafeExpression, renderExpression)
34+ Expression (..)
35 , HasParameter (parameter)
35 , HasParameter (parameter)
36 , param
36 , param
37 -- ** Null
37 -- ** Null
@@ -142,8 +142,8 @@ module Squeal.PostgreSQL.Expression
142 , every, everyDistinct
142 , every, everyDistinct
143 , max_, maxDistinct, min_, minDistinct
143 , max_, maxDistinct, min_, minDistinct
144 -- * Types
144 -- * Types
145− , TypeExpression (UnsafeTypeExpression, renderTypeExpression)
145+ , TypeExpression (..)
146− , PGTyped (pgtype)
146+ , PGTyped (..)
147 , typedef
147 , typedef
148 , typetable
148 , typetable
149 , typeview
149 , typeview
@@ -219,14 +219,14 @@ and other operations.
219-}
219-}
220newtype Expression
220newtype Expression
221 (db :: DBType)
221 (db :: DBType)
222− (from :: FromType)
223− (grouping :: Grouping)
224 (params :: [NullityType])
222 (params :: [NullityType])
223+ (grp :: Grouping)
224+ (from :: FromType)
225 (ty :: NullityType)
225 (ty :: NullityType)
226 = UnsafeExpression { renderExpression :: ByteString }
226 = UnsafeExpression { renderExpression :: ByteString }
227 deriving (GHC.Generic,Show,Eq,Ord,NFData)
227 deriving (GHC.Generic,Show,Eq,Ord,NFData)
228
228
229−instance RenderSQL (Expression db from grouping params ty) where
229+instance RenderSQL (Expression db params grp from ty) where
230 renderSQL = renderExpression
230 renderSQL = renderExpression
231
231
232{- | A `HasParameter` constraint is used to indicate a value that is
232{- | A `HasParameter` constraint is used to indicate a value that is
@@ -244,15 +244,15 @@ class KnownNat n => HasParameter
244 | n params -> ty where
244 | n params -> ty where
245 -- | `parameter` takes a `Nat` using type application and a `TypeExpression`.
245 -- | `parameter` takes a `Nat` using type application and a `TypeExpression`.
246 --
246 --
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)
248 -- >>> printSQL expr
248 -- >>> printSQL expr
249 -- ($1 :: int4)
249 -- ($1 :: int4)
250 parameter
250 parameter
251 :: TypeExpression schemas ty
251 :: TypeExpression schemas ty
252− -> Expression (commons :=> schemas) from grouping params ty
252+ -> Expression (commons :=> schemas) params grp from ty
253 parameter ty = UnsafeExpression $ parenthesized $
253 parameter ty = UnsafeExpression $ parenthesized $
254 "$" <> renderNat @n <+> "::"
254 "$" <> renderNat @n <+> "::"
255− <+> renderTypeExpression ty
255+ <+> renderSQL ty
256instance {-# OVERLAPPING #-} HasParameter 1 (ty1:tys) ty1
256instance {-# OVERLAPPING #-} HasParameter 1 (ty1:tys) ty1
257instance {-# OVERLAPPABLE #-} (KnownNat n, HasParameter (n-1) params ty)
257instance {-# OVERLAPPABLE #-} (KnownNat n, HasParameter (n-1) params ty)
258 => HasParameter n (ty' : params) ty
258 => HasParameter n (ty' : params) ty
@@ -260,88 +260,88 @@ instance {-# OVERLAPPABLE #-} (KnownNat n, HasParameter (n-1) params ty)
260-- | `param` takes a `Nat` using type application and for basic types,
260-- | `param` takes a `Nat` using type application and for basic types,
261-- infers a `TypeExpression`.
261-- infers a `TypeExpression`.
262--
262--
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)
264-- >>> printSQL expr
264-- >>> printSQL expr
265-- ($1 :: int4)
265-- ($1 :: int4)
266param
266param
267− :: forall n db commons schemas params from grouping ty
267+ :: forall n db commons schemas params from grp ty
268 . (db ~ (commons :=> schemas), PGTyped schemas ty, HasParameter n params ty)
268 . (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
270param = parameter @n (pgtype @schemas)
270param = parameter @n (pgtype @schemas)
271
271
272instance (HasUnique tab from row, Has col row ty)
272instance (HasUnique tab from row, Has col row ty)
273− => IsLabel col (Expression db from 'Ungrouped params ty) where
273+ => IsLabel col (Expression db params 'Ungrouped from ty) where
274− fromLabel = UnsafeExpression $ renderAlias (Alias @col)
274+ fromLabel = UnsafeExpression $ renderSQL (Alias @col)
275instance (HasUnique tab from row, Has col row ty, column ~ (col ::: ty))
275instance (HasUnique tab from row, Has col row ty, column ~ (col ::: ty))
276 => IsLabel col
276 => IsLabel col
277− (Aliased (Expression db from 'Ungrouped params) column) where
277+ (Aliased (Expression db params 'Ungrouped from) column) where
278 fromLabel = fromLabel @col `As` Alias
278 fromLabel = fromLabel @col `As` Alias
279instance (HasUnique tab from row, Has col row ty, columns ~ '[col ::: ty])
279instance (HasUnique tab from row, Has col row ty, columns ~ '[col ::: ty])
280 => IsLabel col
280 => IsLabel col
281− (NP (Aliased (Expression db from 'Ungrouped params)) columns) where
281+ (NP (Aliased (Expression db params 'Ungrouped from)) columns) where
282 fromLabel = fromLabel @col :* Nil
282 fromLabel = fromLabel @col :* Nil
283
283
284instance (Has tab from row, Has col row ty)
284instance (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
286 tab ! col = UnsafeExpression $
286 tab ! col = UnsafeExpression $
287− renderAlias tab <> "." <> renderAlias col
287+ renderSQL tab <> "." <> renderSQL col
288instance (Has tab from row, Has col row ty, column ~ (col ::: ty))
288instance (Has tab from row, Has col row ty, column ~ (col ::: ty))
289 => IsQualified tab col
289 => IsQualified tab col
290− (Aliased (Expression db from 'Ungrouped params) column) where
290+ (Aliased (Expression db params 'Ungrouped from) column) where
291 tab ! col = tab ! col `As` col
291 tab ! col = tab ! col `As` col
292instance (Has tab from row, Has col row ty, columns ~ '[col ::: ty])
292instance (Has tab from row, Has col row ty, columns ~ '[col ::: ty])
293 => IsQualified tab col
293 => IsQualified tab col
294− (NP (Aliased (Expression db from 'Ungrouped params)) columns) where
294+ (NP (Aliased (Expression db params 'Ungrouped from)) columns) where
295 tab ! col = tab ! col :* Nil
295 tab ! col = tab ! col :* Nil
296
296
297instance
297instance
298− ( HasUnique table from columns
298+ ( HasUnique tab from row
299− , Has column columns ty
299+ , Has col row ty
300− , GroupedBy table column bys
300+ , GroupedBy tab col bys
301− ) => IsLabel column
301+ ) => IsLabel col
302− (Expression db from ('Grouped bys) params ty) where
302+ (Expression db params ('Grouped bys) from ty) where
303− fromLabel = UnsafeExpression $ renderAlias (Alias @column)
303+ fromLabel = UnsafeExpression $ renderSQL (Alias @col)
304instance
304instance
305− ( HasUnique table from columns
305+ ( HasUnique tab from row
306− , Has column columns ty
306+ , Has col row ty
307− , GroupedBy table column bys
307+ , GroupedBy tab col bys
308+ , column ~ (col ::: ty)
308− ) => IsLabel column
309+ ) => IsLabel col
309− ( Aliased (Expression db from ('Grouped bys) params)
310+ (Aliased (Expression db params ('Grouped bys) from) column) where
310− (column ::: ty) ) where
311− fromLabel = fromLabel @column `As` Alias @column
311+ fromLabel = fromLabel @col `As` Alias
312instance
312instance
313− ( HasUnique table from columns
313+ ( HasUnique tab from row
314− , Has column columns ty
314+ , Has col row ty
315− , GroupedBy table column bys
315+ , GroupedBy tab col bys
316+ , columns ~ '[col ::: ty]
316− ) => IsLabel column
317+ ) => IsLabel col
317− ( NP (Aliased (Expression db from ('Grouped bys) params))
318+ (NP (Aliased (Expression db params ('Grouped bys) from)) columns) where
318− '[column ::: ty] ) where
319− fromLabel = fromLabel @column :* Nil
319+ fromLabel = fromLabel @col :* Nil
320
320
321instance
321instance
322− ( Has table from columns
322+ ( Has tab from row
323− , Has column columns ty
323+ , Has col row ty
324− , GroupedBy table column bys
324+ , GroupedBy tab col bys
325− ) => IsQualified table column
325+ ) => IsQualified tab col
326− (Expression db from ('Grouped bys) params ty) where
326+ (Expression db params ('Grouped bys) from ty) where
327− table ! column = UnsafeExpression $
327+ tab ! col = UnsafeExpression $
328− renderAlias table <> "." <> renderAlias column
328+ renderSQL tab <> "." <> renderSQL col
329instance
329instance
330− ( Has table from columns
330+ ( Has tab from row
331− , Has column columns ty
331+ , Has col row ty
332− , GroupedBy table column bys
332+ , GroupedBy tab col bys
333+ , column ~ (col ::: ty)
333− ) => IsQualified table column
334+ ) => IsQualified tab col
334− (Aliased (Expression db from ('Grouped bys) params)
335+ (Aliased (Expression db params ('Grouped bys) from) column) where
335− (column ::: ty)) where
336+ tab ! col = tab ! col `As` col
336− table ! column = table ! column `As` column
337instance
337instance
338− ( Has table from columns
338+ ( Has tab from row
339− , Has column columns ty
339+ , Has col row ty
340− , GroupedBy table column bys
340+ , GroupedBy tab col bys
341+ , columns ~ '[col ::: ty]
341− ) => IsQualified table column
342+ ) => IsQualified tab col
342− ( NP (Aliased (Expression db from ('Grouped bys) params))
343+ (NP (Aliased (Expression db params ('Grouped bys) from)) columns) where
343− '[column ::: ty]) where
344+ tab ! col = tab ! col :* Nil
344− table ! column = table ! column :* Nil
345
345
346-- | analagous to `Nothing`
346-- | analagous to `Nothing`
347--
347--
@@ -357,102 +357,102 @@ null_ = UnsafeExpression "NULL"
357notNull
357notNull
358 :: Expression db rels grouping params ('NotNull ty)
358 :: Expression db rels grouping params ('NotNull ty)
359 -> Expression db rels grouping params ('Null ty)
359 -> Expression db rels grouping params ('Null ty)
360−notNull = UnsafeExpression . renderExpression
360+notNull = UnsafeExpression . renderSQL
361
361
362-- | return the leftmost value which is not NULL
362-- | return the leftmost value which is not NULL
363--
363--
364-- >>> printSQL $ coalesce [null_, true] false
364-- >>> printSQL $ coalesce [null_, true] false
365-- COALESCE(NULL, TRUE, FALSE)
365-- COALESCE(NULL, TRUE, FALSE)
366coalesce
366coalesce
367− :: [Expression db from grouping params ('Null ty)]
367+ :: [Expression db params grp from ('Null ty)]
368 -- ^ @NULL@s may be present
368 -- ^ @NULL@s may be present
369− -> Expression db from grouping params ('NotNull ty)
369+ -> Expression db params grp from ('NotNull ty)
370 -- ^ @NULL@ is absent
370 -- ^ @NULL@ is absent
371− -> Expression db from grouping params ('NotNull ty)
371+ -> Expression db params grp from ('NotNull ty)
372coalesce nullxs notNullx = UnsafeExpression $
372coalesce nullxs notNullx = UnsafeExpression $
373 "COALESCE" <> parenthesized (commaSeparated
373 "COALESCE" <> parenthesized (commaSeparated
374− ((renderExpression <$> nullxs) <> [renderExpression notNullx]))
374+ ((renderSQL <$> nullxs) <> [renderSQL notNullx]))
375
375
376-- | analagous to `Data.Maybe.fromMaybe` using @COALESCE@
376-- | analagous to `Data.Maybe.fromMaybe` using @COALESCE@
377--
377--
378-- >>> printSQL $ fromNull true null_
378-- >>> printSQL $ fromNull true null_
379-- COALESCE(NULL, TRUE)
379-- COALESCE(NULL, TRUE)
380fromNull
380fromNull
381− :: Expression db from grouping params ('NotNull ty)
381+ :: Expression db params grp from ('NotNull ty)
382 -- ^ what to convert @NULL@ to
382 -- ^ what to convert @NULL@ to
383− -> Expression db from grouping params ('Null ty)
383+ -> Expression db params grp from ('Null ty)
384− -> Expression db from grouping params ('NotNull ty)
384+ -> Expression db params grp from ('NotNull ty)
385fromNull notNullx nullx = coalesce [nullx] notNullx
385fromNull notNullx nullx = coalesce [nullx] notNullx
386
386
387-- | >>> printSQL $ null_ & isNull
387-- | >>> printSQL $ null_ & isNull
388-- NULL IS NULL
388-- NULL IS NULL
389isNull
389isNull
390− :: Expression db from grouping params ('Null ty)
390+ :: Expression db params grp from ('Null ty)
391 -- ^ possibly @NULL@
391 -- ^ possibly @NULL@
392− -> Condition db from grouping params
392+ -> Condition db params grp from
393−isNull x = UnsafeExpression $ renderExpression x <+> "IS NULL"
393+isNull x = UnsafeExpression $ renderSQL x <+> "IS NULL"
394
394
395-- | >>> printSQL $ null_ & isNotNull
395-- | >>> printSQL $ null_ & isNotNull
396-- NULL IS NOT NULL
396-- NULL IS NOT NULL
397isNotNull
397isNotNull
398− :: Expression db from grouping params ('Null ty)
398+ :: Expression db params grp from ('Null ty)
399 -- ^ possibly @NULL@
399 -- ^ possibly @NULL@
400− -> Condition db from grouping params
400+ -> Condition db params grp from
401−isNotNull x = UnsafeExpression $ renderExpression x <+> "IS NOT NULL"
401+isNotNull x = UnsafeExpression $ renderSQL x <+> "IS NOT NULL"
402
402
403-- | analagous to `maybe` using @IS NULL@
403-- | analagous to `maybe` using @IS NULL@
404--
404--
405-- >>> printSQL $ matchNull true not_ null_
405-- >>> printSQL $ matchNull true not_ null_
406-- CASE WHEN NULL IS NULL THEN TRUE ELSE (NOT NULL) END
406-- CASE WHEN NULL IS NULL THEN TRUE ELSE (NOT NULL) END
407matchNull
407matchNull
408− :: Expression db from grouping params (nullty)
408+ :: Expression db params grp from (nullty)
409 -- ^ what to convert @NULL@ to
409 -- ^ what to convert @NULL@ to
410− -> ( Expression db from grouping params ('NotNull ty)
410+ -> ( Expression db params grp from ('NotNull ty)
411− -> Expression db from grouping params (nullty) )
411+ -> Expression db params grp from (nullty) )
412 -- ^ function to perform when @NULL@ is absent
412 -- ^ function to perform when @NULL@ is absent
413− -> Expression db from grouping params ('Null ty)
413+ -> Expression db params grp from ('Null ty)
414− -> Expression db from grouping params (nullty)
414+ -> Expression db params grp from (nullty)
415matchNull y f x = ifThenElse (isNull x) y
415matchNull y f x = ifThenElse (isNull x) y
416− (f (UnsafeExpression (renderExpression x)))
416+ (f (UnsafeExpression (renderSQL x)))
417
417
418{-| right inverse to `fromNull`, if its arguments are equal then
418{-| right inverse to `fromNull`, if its arguments are equal then
419`nullIf` gives @NULL@.
419`nullIf` gives @NULL@.
420
420
421>>> :set -XTypeApplications -XDataKinds
421>>> :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)
423>>> printSQL expr
423>>> printSQL expr
424NULL IF (FALSE, ($1 :: bool))
424NULL IF (FALSE, ($1 :: bool))
425-}
425-}
426nullIf
426nullIf
427− :: Expression db from grouping params ('NotNull ty)
427+ :: Expression db params grp from ('NotNull ty)
428 -- ^ @NULL@ is absent
428 -- ^ @NULL@ is absent
429− -> Expression db from grouping params ('NotNull ty)
429+ -> Expression db params grp from ('NotNull ty)
430 -- ^ @NULL@ is absent
430 -- ^ @NULL@ is absent
431− -> Expression db from grouping params ('Null ty)
431+ -> Expression db params grp from ('Null ty)
432nullIf x y = UnsafeExpression $ "NULL IF" <+> parenthesized
432nullIf x y = UnsafeExpression $ "NULL IF" <+> parenthesized
433− (renderExpression x <> ", " <> renderExpression y)
433+ (renderSQL x <> ", " <> renderSQL y)
434
434
435-- | >>> printSQL $ array [null_, false, true]
435-- | >>> printSQL $ array [null_, false, true]
436-- ARRAY[NULL, FALSE, TRUE]
436-- ARRAY[NULL, FALSE, TRUE]
437array
437array
438− :: [Expression db from grouping params ty]
438+ :: [Expression db params grp from ty]
439 -- ^ array elements
439 -- ^ array elements
440− -> Expression db from grouping params (nullity ('PGvararray ty))
440+ -> Expression db params grp from (nullity ('PGvararray ty))
441array xs = UnsafeExpression $
441array xs = UnsafeExpression $
442− "ARRAY[" <> commaSeparated (renderExpression <$> xs) <> "]"
442+ "ARRAY[" <> commaSeparated (renderSQL <$> xs) <> "]"
443
443
444-- | >>> printSQL $ array [null_, false, true] & index 2
444-- | >>> printSQL $ array [null_, false, true] & index 2
445-- (ARRAY[NULL, FALSE, TRUE])[2]
445-- (ARRAY[NULL, FALSE, TRUE])[2]
446index
446index
447 :: Word64 -- ^ index
447 :: Word64 -- ^ index
448− -> Expression db from grouping params (nullity ('PGvararray ty)) -- ^ array
448+ -> Expression db params grp from (nullity ('PGvararray ty)) -- ^ array
449− -> Expression db from grouping params (NullifyType ty)
449+ -> Expression db params grp from (NullifyType ty)
450index n expr = UnsafeExpression $
450index n expr = UnsafeExpression $
451− parenthesized (renderExpression expr) <> "[" <> fromString (show n) <> "]"
451+ parenthesized (renderSQL expr) <> "[" <> fromString (show n) <> "]"
452
452
453instance (KnownSymbol label, label `In` labels) => IsPGlabel label
453instance (KnownSymbol label, label `In` labels) => IsPGlabel label
454− (Expression db from grouping params (nullity ('PGenum labels))) where
454+ (Expression db params grp from (nullity ('PGenum labels))) where
455− label = UnsafeExpression $ renderLabel (PGlabel @label)
455+ label = UnsafeExpression $ renderSQL (PGlabel @label)
456
456
457-- | A row constructor is an expression that builds a row value
457-- | A row constructor is an expression that builds a row value
458-- (also called a composite value) using values for its member fields.
458-- (also called a composite value) using values for its member fields.
@@ -468,11 +468,11 @@ instance (KnownSymbol label, label `In` labels) => IsPGlabel label
468-- ROW(0, 1)
468-- ROW(0, 1)
469row
469row
470 :: SListI row
470 :: SListI row
471− => NP (Aliased (Expression db from grouping params)) row
471+ => NP (Aliased (Expression db params grp from)) row
472 -- ^ zero or more expressions for the row field values
472 -- ^ 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))
474row exprs = UnsafeExpression $ "ROW" <> parenthesized
474row exprs = UnsafeExpression $ "ROW" <> parenthesized
475− (renderCommaSeparated (\ (expr `As` _) -> renderExpression expr) exprs)
475+ (renderCommaSeparated (\ (expr `As` _) -> renderSQL expr) exprs)
476
476
477-- | >>> :{
477-- | >>> :{
478-- type Complex = 'PGcomposite
478-- type Complex = 'PGcomposite
@@ -491,87 +491,87 @@ field
491 , Has field row ty)
491 , Has field row ty)
492 => QualifiedAlias sch tydef -- ^ row type
492 => QualifiedAlias sch tydef -- ^ row type
493 -> Alias field -- ^ field name
493 -> Alias field -- ^ field name
494− -> Expression (commons :=> schemas) from grouping params ('NotNull ('PGcomposite row))
494+ -> Expression (commons :=> schemas) params grp from ('NotNull ('PGcomposite row))
495− -> Expression (commons :=> schemas) from grouping params ty
495+ -> Expression (commons :=> schemas) params grp from ty
496field td fld expr = UnsafeExpression $
496field td fld expr = UnsafeExpression $
497− parenthesized (renderExpression expr <> "::" <> renderQualifiedAlias td)
497+ parenthesized (renderSQL expr <> "::" <> renderSQL td)
498− <> "." <> renderAlias fld
498+ <> "." <> renderSQL fld
499
499
500instance Semigroup
500instance Semigroup
501− (Expression db from grouping params (nullity ('PGvararray ty))) where
501+ (Expression db params grp from (nullity ('PGvararray ty))) where
502 (<>) = unsafeBinaryOp "||"
502 (<>) = unsafeBinaryOp "||"
503
503
504instance Monoid
504instance Monoid
505− (Expression db from grouping params (nullity ('PGvararray ty))) where
505+ (Expression db params grp from (nullity ('PGvararray ty))) where
506 mempty = array []
506 mempty = array []
507 mappend = (<>)
507 mappend = (<>)
508
508
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)
510-- >>> printSQL expr
510-- >>> printSQL expr
511-- GREATEST(CURRENT_TIMESTAMP, ($1 :: timestamp with time zone))
511-- GREATEST(CURRENT_TIMESTAMP, ($1 :: timestamp with time zone))
512greatest
512greatest
513− :: Expression db from grouping params (nullty)
513+ :: Expression db params grp from (nullty)
514 -- ^ needs at least 1 argument
514 -- ^ needs at least 1 argument
515− -> [Expression db from grouping params (nullty)]
515+ -> [Expression db params grp from (nullty)]
516 -- ^ or more
516 -- ^ or more
517− -> Expression db from grouping params (nullty)
517+ -> Expression db params grp from (nullty)
518greatest x xs = UnsafeExpression $ "GREATEST("
518greatest x xs = UnsafeExpression $ "GREATEST("
519− <> commaSeparated (renderExpression <$> (x:xs)) <> ")"
519+ <> commaSeparated (renderSQL <$> (x:xs)) <> ")"
520
520
521-- | >>> printSQL $ least currentTimestamp [null_]
521-- | >>> printSQL $ least currentTimestamp [null_]
522-- LEAST(CURRENT_TIMESTAMP, NULL)
522-- LEAST(CURRENT_TIMESTAMP, NULL)
523least
523least
524− :: Expression db from grouping params (nullty)
524+ :: Expression db params grp from (nullty)
525 -- ^ needs at least 1 argument
525 -- ^ needs at least 1 argument
526− -> [Expression db from grouping params (nullty)]
526+ -> [Expression db params grp from (nullty)]
527 -- ^ or more
527 -- ^ or more
528− -> Expression db from grouping params (nullty)
528+ -> Expression db params grp from (nullty)
529least x xs = UnsafeExpression $ "LEAST("
529least x xs = UnsafeExpression $ "LEAST("
530− <> commaSeparated (renderExpression <$> (x:xs)) <> ")"
530+ <> commaSeparated (renderSQL <$> (x:xs)) <> ")"
531
531
532-- | >>> printSQL $ unsafeBinaryOp "OR" true false
532-- | >>> printSQL $ unsafeBinaryOp "OR" true false
533-- (TRUE OR FALSE)
533-- (TRUE OR FALSE)
534unsafeBinaryOp
534unsafeBinaryOp
535 :: ByteString
535 :: ByteString
536 -- ^ operator
536 -- ^ operator
537− -> Expression db from grouping params (ty0)
537+ -> Expression db params grp from (ty0)
538− -> Expression db from grouping params (ty1)
538+ -> Expression db params grp from (ty1)
539− -> Expression db from grouping params (ty2)
539+ -> Expression db params grp from (ty2)
540unsafeBinaryOp op x y = UnsafeExpression $ parenthesized $
540unsafeBinaryOp op x y = UnsafeExpression $ parenthesized $
541− renderExpression x <+> op <+> renderExpression y
541+ renderSQL x <+> op <+> renderSQL y
542
542
543-- | >>> printSQL $ unsafeUnaryOp "NOT" true
543-- | >>> printSQL $ unsafeUnaryOp "NOT" true
544-- (NOT TRUE)
544-- (NOT TRUE)
545unsafeUnaryOp
545unsafeUnaryOp
546 :: ByteString
546 :: ByteString
547 -- ^ operator
547 -- ^ operator
548− -> Expression db from grouping params (ty0)
548+ -> Expression db params grp from (ty0)
549− -> Expression db from grouping params (ty1)
549+ -> Expression db params grp from (ty1)
550unsafeUnaryOp op x = UnsafeExpression $ parenthesized $
550unsafeUnaryOp op x = UnsafeExpression $ parenthesized $
551− op <+> renderExpression x
551+ op <+> renderSQL x
552
552
553-- | >>> printSQL $ unsafeFunction "f" true
553-- | >>> printSQL $ unsafeFunction "f" true
554-- f(TRUE)
554-- f(TRUE)
555unsafeFunction
555unsafeFunction
556 :: ByteString
556 :: ByteString
557 -- ^ function
557 -- ^ function
558− -> Expression db from grouping params (xty)
558+ -> Expression db params grp from (xty)
559− -> Expression db from grouping params (yty)
559+ -> Expression db params grp from (yty)
560unsafeFunction fun x = UnsafeExpression $
560unsafeFunction fun x = UnsafeExpression $
561− fun <> parenthesized (renderExpression x)
561+ fun <> parenthesized (renderSQL x)
562
562
563-- | Helper for defining variadic functions.
563-- | Helper for defining variadic functions.
564unsafeVariadicFunction
564unsafeVariadicFunction
565 :: SListI elems
565 :: SListI elems
566 => ByteString
566 => ByteString
567 -- ^ function
567 -- ^ function
568− -> NP (Expression db from grouping params) elems
568+ -> NP (Expression db params grp from) elems
569− -> Expression db from grouping params ret
569+ -> Expression db params grp from ret
570unsafeVariadicFunction fun x = UnsafeExpression $
570unsafeVariadicFunction fun x = UnsafeExpression $
571− fun <> parenthesized (commaSeparated (hcollapse (hmap (K . renderExpression) x)))
571+ fun <> parenthesized (commaSeparated (hcollapse (hmap (K . renderSQL) x)))
572
572
573instance ty `In` PGNum
573instance ty `In` PGNum
574− => Num (Expression db from grouping params (nullity ty)) where
574+ => Num (Expression db params grp from (nullity ty)) where
575 (+) = unsafeBinaryOp "+"
575 (+) = unsafeBinaryOp "+"
576 (-) = unsafeBinaryOp "-"
576 (-) = unsafeBinaryOp "-"
577 (*) = unsafeBinaryOp "*"
577 (*) = unsafeBinaryOp "*"
@@ -583,18 +583,18 @@ instance ty `In` PGNum
583 . show
583 . show
584
584
585instance (ty `In` PGNum, ty `In` PGFloating) => Fractional
585instance (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
587 (/) = unsafeBinaryOp "/"
587 (/) = unsafeBinaryOp "/"
588 fromRational x = fromInteger (numerator x) / fromInteger (denominator x)
588 fromRational x = fromInteger (numerator x) / fromInteger (denominator x)
589
589
590instance (ty `In` PGNum, ty `In` PGFloating) => Floating
590instance (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
592 pi = UnsafeExpression "pi()"
592 pi = UnsafeExpression "pi()"
593 exp = unsafeFunction "exp"
593 exp = unsafeFunction "exp"
594 log = unsafeFunction "ln"
594 log = unsafeFunction "ln"
595 sqrt = unsafeFunction "sqrt"
595 sqrt = unsafeFunction "sqrt"
596 b ** x = UnsafeExpression $
596 b ** x = UnsafeExpression $
597− "power(" <> renderExpression b <> ", " <> renderExpression x <> ")"
597+ "power(" <> renderSQL b <> ", " <> renderSQL x <> ")"
598 logBase b y = log y / log b
598 logBase b y = log y / log b
599 sin = unsafeFunction "sin"
599 sin = unsafeFunction "sin"
600 cos = unsafeFunction "cos"
600 cos = unsafeFunction "cos"
@@ -611,20 +611,20 @@ instance (ty `In` PGNum, ty `In` PGFloating) => Floating
611
611
612-- | >>> :{
612-- | >>> :{
613-- let
613-- let
614−-- expression :: Expression db from grouping params (nullity 'PGfloat4)
614+-- expression :: Expression db params grp from (nullity 'PGfloat4)
615-- expression = atan2_ pi 2
615-- expression = atan2_ pi 2
616-- in printSQL expression
616-- in printSQL expression
617-- :}
617-- :}
618-- atan2(pi(), 2)
618-- atan2(pi(), 2)
619atan2_
619atan2_
620 :: float `In` PGFloating
620 :: float `In` PGFloating
621− => Expression db from grouping params (nullity float)
621+ => Expression db params grp from (nullity float)
622 -- ^ numerator
622 -- ^ numerator
623− -> Expression db from grouping params (nullity float)
623+ -> Expression db params grp from (nullity float)
624 -- ^ denominator
624 -- ^ denominator
625− -> Expression db from grouping params (nullity float)
625+ -> Expression db params grp from (nullity float)
626atan2_ y x = UnsafeExpression $
626atan2_ y x = UnsafeExpression $
627− "atan2(" <> renderExpression y <> ", " <> renderExpression x <> ")"
627+ "atan2(" <> renderSQL y <> ", " <> renderSQL x <> ")"
628
628
629-- When a `cast` is applied to an `Expression` of a known type, it
629-- When a `cast` is applied to an `Expression` of a known type, it
630-- represents a run-time type conversion. The cast will succeed only if a
630-- represents a run-time type conversion. The cast will succeed only if a
@@ -635,171 +635,171 @@ atan2_ y x = UnsafeExpression $
635cast
635cast
636 :: TypeExpression schemas ty1
636 :: TypeExpression schemas ty1
637 -- ^ type to cast as
637 -- ^ type to cast as
638− -> Expression (commons :=> schemas) from grouping params ty0
638+ -> Expression (commons :=> schemas) params grp from ty0
639 -- ^ value to convert
639 -- ^ value to convert
640− -> Expression (commons :=> schemas) from grouping params ty1
640+ -> Expression (commons :=> schemas) params grp from ty1
641cast ty x = UnsafeExpression $ parenthesized $
641cast ty x = UnsafeExpression $ parenthesized $
642− renderExpression x <+> "::" <+> renderTypeExpression ty
642+ renderSQL x <+> "::" <+> renderSQL ty
643
643
644-- | integer division, truncates the result
644-- | integer division, truncates the result
645--
645--
646-- >>> :{
646-- >>> :{
647-- let
647-- let
648−-- expression :: Expression db from grouping params (nullity 'PGint2)
648+-- expression :: Expression db params grp from (nullity 'PGint2)
649-- expression = 5 `quot_` 2
649-- expression = 5 `quot_` 2
650-- in printSQL expression
650-- in printSQL expression
651-- :}
651-- :}
652-- (5 / 2)
652-- (5 / 2)
653quot_
653quot_
654 :: int `In` PGIntegral
654 :: int `In` PGIntegral
655− => Expression db from grouping params (nullity int)
655+ => Expression db params grp from (nullity int)
656 -- ^ numerator
656 -- ^ numerator
657− -> Expression db from grouping params (nullity int)
657+ -> Expression db params grp from (nullity int)
658 -- ^ denominator
658 -- ^ denominator
659− -> Expression db from grouping params (nullity int)
659+ -> Expression db params grp from (nullity int)
660quot_ = unsafeBinaryOp "/"
660quot_ = unsafeBinaryOp "/"
661
661
662-- | remainder upon integer division
662-- | remainder upon integer division
663--
663--
664-- >>> :{
664-- >>> :{
665-- let
665-- let
666−-- expression :: Expression db from grouping params (nullity 'PGint2)
666+-- expression :: Expression db params grp from (nullity 'PGint2)
667-- expression = 5 `rem_` 2
667-- expression = 5 `rem_` 2
668-- in printSQL expression
668-- in printSQL expression
669-- :}
669-- :}
670-- (5 % 2)
670-- (5 % 2)
671rem_
671rem_
672 :: int `In` PGIntegral
672 :: int `In` PGIntegral
673− => Expression db from grouping params (nullity int)
673+ => Expression db params grp from (nullity int)
674 -- ^ numerator
674 -- ^ numerator
675− -> Expression db from grouping params (nullity int)
675+ -> Expression db params grp from (nullity int)
676 -- ^ denominator
676 -- ^ denominator
677− -> Expression db from grouping params (nullity int)
677+ -> Expression db params grp from (nullity int)
678rem_ = unsafeBinaryOp "%"
678rem_ = unsafeBinaryOp "%"
679
679
680-- | >>> :{
680-- | >>> :{
681-- let
681-- let
682−-- expression :: Expression db from grouping params (nullity 'PGfloat4)
682+-- expression :: Expression db params grp from (nullity 'PGfloat4)
683-- expression = trunc pi
683-- expression = trunc pi
684-- in printSQL expression
684-- in printSQL expression
685-- :}
685-- :}
686-- trunc(pi())
686-- trunc(pi())
687trunc
687trunc
688 :: frac `In` PGFloating
688 :: frac `In` PGFloating
689− => Expression db from grouping params (nullity frac)
689+ => Expression db params grp from (nullity frac)
690 -- ^ fractional number
690 -- ^ fractional number
691− -> Expression db from grouping params (nullity frac)
691+ -> Expression db params grp from (nullity frac)
692trunc = unsafeFunction "trunc"
692trunc = unsafeFunction "trunc"
693
693
694-- | >>> :{
694-- | >>> :{
695-- let
695-- let
696−-- expression :: Expression db from grouping params (nullity 'PGfloat4)
696+-- expression :: Expression db params grp from (nullity 'PGfloat4)
697-- expression = round_ pi
697-- expression = round_ pi
698-- in printSQL expression
698-- in printSQL expression
699-- :}
699-- :}
700-- round(pi())
700-- round(pi())
701round_
701round_
702 :: frac `In` PGFloating
702 :: frac `In` PGFloating
703− => Expression db from grouping params (nullity frac)
703+ => Expression db params grp from (nullity frac)
704 -- ^ fractional number
704 -- ^ fractional number
705− -> Expression db from grouping params (nullity frac)
705+ -> Expression db params grp from (nullity frac)
706round_ = unsafeFunction "round"
706round_ = unsafeFunction "round"
707
707
708-- | >>> :{
708-- | >>> :{
709-- let
709-- let
710−-- expression :: Expression db from grouping params (nullity 'PGfloat4)
710+-- expression :: Expression db params grp from (nullity 'PGfloat4)
711-- expression = ceiling_ pi
711-- expression = ceiling_ pi
712-- in printSQL expression
712-- in printSQL expression
713-- :}
713-- :}
714-- ceiling(pi())
714-- ceiling(pi())
715ceiling_
715ceiling_
716 :: frac `In` PGFloating
716 :: frac `In` PGFloating
717− => Expression db from grouping params (nullity frac)
717+ => Expression db params grp from (nullity frac)
718 -- ^ fractional number
718 -- ^ fractional number
719− -> Expression db from grouping params (nullity frac)
719+ -> Expression db params grp from (nullity frac)
720ceiling_ = unsafeFunction "ceiling"
720ceiling_ = unsafeFunction "ceiling"
721
721
722-- | A `Condition` is an `Expression`, which can evaluate
722-- | A `Condition` is an `Expression`, which can evaluate
723-- to `true`, `false` or `null_`. This is because SQL uses
723-- to `true`, `false` or `null_`. This is because SQL uses
724-- a three valued logic.
724-- a three valued logic.
725−type Condition db from grouping params =
725+type Condition db params grp from =
726− Expression db from grouping params ('Null 'PGbool)
726+ Expression db params grp from ('Null 'PGbool)
727
727
728-- | >>> printSQL true
728-- | >>> printSQL true
729-- TRUE
729-- TRUE
730−true :: Expression db from grouping params (nullity 'PGbool)
730+true :: Expression db params grp from (nullity 'PGbool)
731true = UnsafeExpression "TRUE"
731true = UnsafeExpression "TRUE"
732
732
733-- | >>> printSQL false
733-- | >>> printSQL false
734-- FALSE
734-- FALSE
735−false :: Expression db from grouping params (nullity 'PGbool)
735+false :: Expression db params grp from (nullity 'PGbool)
736false = UnsafeExpression "FALSE"
736false = UnsafeExpression "FALSE"
737
737
738-- | >>> printSQL $ not_ true
738-- | >>> printSQL $ not_ true
739-- (NOT TRUE)
739-- (NOT TRUE)
740not_
740not_
741− :: Expression db from grouping params (nullity 'PGbool)
741+ :: Expression db params grp from (nullity 'PGbool)
742− -> Expression db from grouping params (nullity 'PGbool)
742+ -> Expression db params grp from (nullity 'PGbool)
743not_ = unsafeUnaryOp "NOT"
743not_ = unsafeUnaryOp "NOT"
744
744
745-- | >>> printSQL $ true .&& false
745-- | >>> printSQL $ true .&& false
746-- (TRUE AND FALSE)
746-- (TRUE AND FALSE)
747(.&&)
747(.&&)
748− :: Expression db from grouping params (nullity 'PGbool)
748+ :: Expression db params grp from (nullity 'PGbool)
749− -> Expression db from grouping params (nullity 'PGbool)
749+ -> Expression db params grp from (nullity 'PGbool)
750− -> Expression db from grouping params (nullity 'PGbool)
750+ -> Expression db params grp from (nullity 'PGbool)
751infixr 3 .&&
751infixr 3 .&&
752(.&&) = unsafeBinaryOp "AND"
752(.&&) = unsafeBinaryOp "AND"
753
753
754-- | >>> printSQL $ true .|| false
754-- | >>> printSQL $ true .|| false
755-- (TRUE OR FALSE)
755-- (TRUE OR FALSE)
756(.||)
756(.||)
757− :: Expression db from grouping params (nullity 'PGbool)
757+ :: Expression db params grp from (nullity 'PGbool)
758− -> Expression db from grouping params (nullity 'PGbool)
758+ -> Expression db params grp from (nullity 'PGbool)
759− -> Expression db from grouping params (nullity 'PGbool)
759+ -> Expression db params grp from (nullity 'PGbool)
760infixr 2 .||
760infixr 2 .||
761(.||) = unsafeBinaryOp "OR"
761(.||) = unsafeBinaryOp "OR"
762
762
763-- | >>> :{
763-- | >>> :{
764-- let
764-- let
765−-- expression :: Expression db from grouping params (nullity 'PGint2)
765+-- expression :: Expression db params grp from (nullity 'PGint2)
766-- expression = caseWhenThenElse [(true, 1), (false, 2)] 3
766-- expression = caseWhenThenElse [(true, 1), (false, 2)] 3
767-- in printSQL expression
767-- in printSQL expression
768-- :}
768-- :}
769-- CASE WHEN TRUE THEN 1 WHEN FALSE THEN 2 ELSE 3 END
769-- CASE WHEN TRUE THEN 1 WHEN FALSE THEN 2 ELSE 3 END
770caseWhenThenElse
770caseWhenThenElse
771− :: [ ( Condition db from grouping params
771+ :: [ ( Condition db params grp from
772− , Expression db from grouping params ty
772+ , Expression db params grp from ty
773 ) ]
773 ) ]
774 -- ^ whens and thens
774 -- ^ whens and thens
775− -> Expression db from grouping params ty
775+ -> Expression db params grp from ty
776 -- ^ else
776 -- ^ else
777− -> Expression db from grouping params ty
777+ -> Expression db params grp from ty
778caseWhenThenElse whenThens else_ = UnsafeExpression $ mconcat
778caseWhenThenElse whenThens else_ = UnsafeExpression $ mconcat
779 [ "CASE"
779 [ "CASE"
780 , mconcat
780 , mconcat
781 [ mconcat
781 [ mconcat
782− [ " WHEN ", renderExpression when_
782+ [ " WHEN ", renderSQL when_
783− , " THEN ", renderExpression then_
783+ , " THEN ", renderSQL then_
784 ]
784 ]
785 | (when_,then_) <- whenThens
785 | (when_,then_) <- whenThens
786 ]
786 ]
787− , " ELSE ", renderExpression else_
787+ , " ELSE ", renderSQL else_
788 , " END"
788 , " END"
789 ]
789 ]
790
790
791-- | >>> :{
791-- | >>> :{
792-- let
792-- let
793−-- expression :: Expression db from grouping params (nullity 'PGint2)
793+-- expression :: Expression db params grp from (nullity 'PGint2)
794-- expression = ifThenElse true 1 0
794-- expression = ifThenElse true 1 0
795-- in printSQL expression
795-- in printSQL expression
796-- :}
796-- :}
797-- CASE WHEN TRUE THEN 1 ELSE 0 END
797-- CASE WHEN TRUE THEN 1 ELSE 0 END
798ifThenElse
798ifThenElse
799− :: Condition db from grouping params
799+ :: Condition db params grp from
800− -> Expression db from grouping params ty -- ^ then
800+ -> Expression db params grp from ty -- ^ then
801− -> Expression db from grouping params ty -- ^ else
801+ -> Expression db params grp from ty -- ^ else
802− -> Expression db from grouping params ty
802+ -> Expression db params grp from ty
803ifThenElse if_ then_ else_ = caseWhenThenElse [(if_,then_)] else_
803ifThenElse if_ then_ else_ = caseWhenThenElse [(if_,then_)] else_
804
804
805-- | Comparison operations like `.==`, `./=`, `.>`, `.>=`, `.<` and `.<=`
805-- | Comparison operations like `.==`, `./=`, `.>`, `.>=`, `.<` and `.<=`
@@ -808,85 +808,85 @@ ifThenElse if_ then_ else_ = caseWhenThenElse [(if_,then_)] else_
808-- >>> printSQL $ true .== null_
808-- >>> printSQL $ true .== null_
809-- (TRUE = NULL)
809-- (TRUE = NULL)
810(.==)
810(.==)
811− :: Expression db from grouping params (nullity0 ty) -- ^ lhs
811+ :: Expression db params grp from (nullity0 ty) -- ^ lhs
812− -> Expression db from grouping params (nullity1 ty) -- ^ rhs
812+ -> Expression db params grp from (nullity1 ty) -- ^ rhs
813− -> Condition db from grouping params
813+ -> Condition db params grp from
814(.==) = unsafeBinaryOp "="
814(.==) = unsafeBinaryOp "="
815infix 4 .==
815infix 4 .==
816
816
817-- | >>> printSQL $ true ./= null_
817-- | >>> printSQL $ true ./= null_
818-- (TRUE <> NULL)
818-- (TRUE <> NULL)
819(./=)
819(./=)
820− :: Expression db from grouping params (nullity0 ty) -- ^ lhs
820+ :: Expression db params grp from (nullity0 ty) -- ^ lhs
821− -> Expression db from grouping params (nullity1 ty) -- ^ rhs
821+ -> Expression db params grp from (nullity1 ty) -- ^ rhs
822− -> Condition db from grouping params
822+ -> Condition db params grp from
823(./=) = unsafeBinaryOp "<>"
823(./=) = unsafeBinaryOp "<>"
824infix 4 ./=
824infix 4 ./=
825
825
826-- | >>> printSQL $ true .>= null_
826-- | >>> printSQL $ true .>= null_
827-- (TRUE >= NULL)
827-- (TRUE >= NULL)
828(.>=)
828(.>=)
829− :: Expression db from grouping params (nullity0 ty) -- ^ lhs
829+ :: Expression db params grp from (nullity0 ty) -- ^ lhs
830− -> Expression db from grouping params (nullity1 ty) -- ^ rhs
830+ -> Expression db params grp from (nullity1 ty) -- ^ rhs
831− -> Condition db from grouping params
831+ -> Condition db params grp from
832(.>=) = unsafeBinaryOp ">="
832(.>=) = unsafeBinaryOp ">="
833infix 4 .>=
833infix 4 .>=
834
834
835-- | >>> printSQL $ true .< null_
835-- | >>> printSQL $ true .< null_
836-- (TRUE < NULL)
836-- (TRUE < NULL)
837(.<)
837(.<)
838− :: Expression db from grouping params (nullity0 ty) -- ^ lhs
838+ :: Expression db params grp from (nullity0 ty) -- ^ lhs
839− -> Expression db from grouping params (nullity1 ty) -- ^ rhs
839+ -> Expression db params grp from (nullity1 ty) -- ^ rhs
840− -> Condition db from grouping params
840+ -> Condition db params grp from
841(.<) = unsafeBinaryOp "<"
841(.<) = unsafeBinaryOp "<"
842infix 4 .<
842infix 4 .<
843
843
844-- | >>> printSQL $ true .<= null_
844-- | >>> printSQL $ true .<= null_
845-- (TRUE <= NULL)
845-- (TRUE <= NULL)
846(.<=)
846(.<=)
847− :: Expression db from grouping params (nullity0 ty) -- ^ lhs
847+ :: Expression db params grp from (nullity0 ty) -- ^ lhs
848− -> Expression db from grouping params (nullity1 ty) -- ^ rhs
848+ -> Expression db params grp from (nullity1 ty) -- ^ rhs
849− -> Condition db from grouping params
849+ -> Condition db params grp from
850(.<=) = unsafeBinaryOp "<="
850(.<=) = unsafeBinaryOp "<="
851infix 4 .<=
851infix 4 .<=
852
852
853-- | >>> printSQL $ true .> null_
853-- | >>> printSQL $ true .> null_
854-- (TRUE > NULL)
854-- (TRUE > NULL)
855(.>)
855(.>)
856− :: Expression db from grouping params (nullity0 ty) -- ^ lhs
856+ :: Expression db params grp from (nullity0 ty) -- ^ lhs
857− -> Expression db from grouping params (nullity1 ty) -- ^ rhs
857+ -> Expression db params grp from (nullity1 ty) -- ^ rhs
858− -> Condition db from grouping params
858+ -> Condition db params grp from
859(.>) = unsafeBinaryOp ">"
859(.>) = unsafeBinaryOp ">"
860infix 4 .>
860infix 4 .>
861
861
862-- | >>> printSQL currentDate
862-- | >>> printSQL currentDate
863-- CURRENT_DATE
863-- CURRENT_DATE
864currentDate
864currentDate
865− :: Expression db from grouping params (nullity 'PGdate)
865+ :: Expression db params grp from (nullity 'PGdate)
866currentDate = UnsafeExpression "CURRENT_DATE"
866currentDate = UnsafeExpression "CURRENT_DATE"
867
867
868-- | >>> printSQL currentTime
868-- | >>> printSQL currentTime
869-- CURRENT_TIME
869-- CURRENT_TIME
870currentTime
870currentTime
871− :: Expression db from grouping params (nullity 'PGtimetz)
871+ :: Expression db params grp from (nullity 'PGtimetz)
872currentTime = UnsafeExpression "CURRENT_TIME"
872currentTime = UnsafeExpression "CURRENT_TIME"
873
873
874-- | >>> printSQL currentTimestamp
874-- | >>> printSQL currentTimestamp
875-- CURRENT_TIMESTAMP
875-- CURRENT_TIMESTAMP
876currentTimestamp
876currentTimestamp
877− :: Expression db from grouping params (nullity 'PGtimestamptz)
877+ :: Expression db params grp from (nullity 'PGtimestamptz)
878currentTimestamp = UnsafeExpression "CURRENT_TIMESTAMP"
878currentTimestamp = UnsafeExpression "CURRENT_TIMESTAMP"
879
879
880-- | >>> printSQL localTime
880-- | >>> printSQL localTime
881-- LOCALTIME
881-- LOCALTIME
882localTime
882localTime
883− :: Expression db from grouping params (nullity 'PGtime)
883+ :: Expression db params grp from (nullity 'PGtime)
884localTime = UnsafeExpression "LOCALTIME"
884localTime = UnsafeExpression "LOCALTIME"
885
885
886-- | >>> printSQL localTimestamp
886-- | >>> printSQL localTimestamp
887-- LOCALTIMESTAMP
887-- LOCALTIMESTAMP
888localTimestamp
888localTimestamp
889− :: Expression db from grouping params (nullity 'PGtimestamp)
889+ :: Expression db params grp from (nullity 'PGtimestamp)
890localTimestamp = UnsafeExpression "LOCALTIMESTAMP"
890localTimestamp = UnsafeExpression "LOCALTIMESTAMP"
891
891
892{-----------------------------------------
892{-----------------------------------------
@@ -894,7 +894,7 @@ text
894-----------------------------------------}
894-----------------------------------------}
895
895
896instance IsString
896instance IsString
897− (Expression db from grouping params (nullity 'PGtext)) where
897+ (Expression db params grp from (nullity 'PGtext)) where
898 fromString str = UnsafeExpression $
898 fromString str = UnsafeExpression $
899 "E\'" <> fromString (escape =<< str) <> "\'"
899 "E\'" <> fromString (escape =<< str) <> "\'"
900 where
900 where
@@ -910,36 +910,36 @@ instance IsString
910 c -> [c]
910 c -> [c]
911
911
912instance Semigroup
912instance Semigroup
913− (Expression db from grouping params (nullity 'PGtext)) where
913+ (Expression db params grp from (nullity 'PGtext)) where
914 (<>) = unsafeBinaryOp "||"
914 (<>) = unsafeBinaryOp "||"
915
915
916instance Monoid
916instance Monoid
917− (Expression db from grouping params (nullity 'PGtext)) where
917+ (Expression db params grp from (nullity 'PGtext)) where
918 mempty = fromString ""
918 mempty = fromString ""
919 mappend = (<>)
919 mappend = (<>)
920
920
921-- | >>> printSQL $ lower "ARRRGGG"
921-- | >>> printSQL $ lower "ARRRGGG"
922-- lower(E'ARRRGGG')
922-- lower(E'ARRRGGG')
923lower
923lower
924− :: Expression db from grouping params (nullity 'PGtext)
924+ :: Expression db params grp from (nullity 'PGtext)
925 -- ^ string to lower case
925 -- ^ string to lower case
926− -> Expression db from grouping params (nullity 'PGtext)
926+ -> Expression db params grp from (nullity 'PGtext)
927lower = unsafeFunction "lower"
927lower = unsafeFunction "lower"
928
928
929-- | >>> printSQL $ upper "eeee"
929-- | >>> printSQL $ upper "eeee"
930-- upper(E'eeee')
930-- upper(E'eeee')
931upper
931upper
932− :: Expression db from grouping params (nullity 'PGtext)
932+ :: Expression db params grp from (nullity 'PGtext)
933 -- ^ string to upper case
933 -- ^ string to upper case
934− -> Expression db from grouping params (nullity 'PGtext)
934+ -> Expression db params grp from (nullity 'PGtext)
935upper = unsafeFunction "upper"
935upper = unsafeFunction "upper"
936
936
937-- | >>> printSQL $ charLength "four"
937-- | >>> printSQL $ charLength "four"
938-- char_length(E'four')
938-- char_length(E'four')
939charLength
939charLength
940− :: Expression db from grouping params (nullity 'PGtext)
940+ :: Expression db params grp from (nullity 'PGtext)
941 -- ^ string to measure
941 -- ^ string to measure
942− -> Expression db from grouping params (nullity 'PGint4)
942+ -> Expression db params grp from (nullity 'PGint4)
943charLength = unsafeFunction "char_length"
943charLength = unsafeFunction "char_length"
944
944
945-- | The `like` expression returns true if the @string@ matches
945-- | The `like` expression returns true if the @string@ matches
@@ -952,11 +952,11 @@ charLength = unsafeFunction "char_length"
952-- >>> printSQL $ "abc" `like` "a%"
952-- >>> printSQL $ "abc" `like` "a%"
953-- (E'abc' LIKE E'a%')
953-- (E'abc' LIKE E'a%')
954like
954like
955− :: Expression db from grouping params (nullity 'PGtext)
955+ :: Expression db params grp from (nullity 'PGtext)
956 -- ^ string
956 -- ^ string
957− -> Expression db from grouping params (nullity 'PGtext)
957+ -> Expression db params grp from (nullity 'PGtext)
958 -- ^ pattern
958 -- ^ pattern
959− -> Expression db from grouping params (nullity 'PGbool)
959+ -> Expression db params grp from (nullity 'PGbool)
960like = unsafeBinaryOp "LIKE"
960like = unsafeBinaryOp "LIKE"
961
961
962-- | The key word ILIKE can be used instead of LIKE to make the
962-- | The key word ILIKE can be used instead of LIKE to make the
@@ -965,11 +965,11 @@ like = unsafeBinaryOp "LIKE"
965-- >>> printSQL $ "abc" `ilike` "a%"
965-- >>> printSQL $ "abc" `ilike` "a%"
966-- (E'abc' ILIKE E'a%')
966-- (E'abc' ILIKE E'a%')
967ilike
967ilike
968− :: Expression db from grouping params (nullity 'PGtext)
968+ :: Expression db params grp from (nullity 'PGtext)
969 -- ^ string
969 -- ^ string
970− -> Expression db from grouping params (nullity 'PGtext)
970+ -> Expression db params grp from (nullity 'PGtext)
971 -- ^ pattern
971 -- ^ pattern
972− -> Expression db from grouping params (nullity 'PGbool)
972+ -> Expression db params grp from (nullity 'PGbool)
973ilike = unsafeBinaryOp "ILIKE"
973ilike = unsafeBinaryOp "ILIKE"
974
974
975{-----------------------------------------
975{-----------------------------------------
@@ -984,36 +984,36 @@ Table 9.44: json and jsonb operators
984-- | Get JSON value (object field or array element) at a key.
984-- | Get JSON value (object field or array element) at a key.
985(.->)
985(.->)
986 :: (json `In` PGJsonType, key `In` PGJsonKey)
986 :: (json `In` PGJsonType, key `In` PGJsonKey)
987− => Expression db from grouping params (nullity json)
987+ => Expression db params grp from (nullity json)
988− -> Expression db from grouping params (nullity key)
988+ -> Expression db params grp from (nullity key)
989− -> Expression db from grouping params ('Null json)
989+ -> Expression db params grp from ('Null json)
990infixl 8 .->
990infixl 8 .->
991(.->) = unsafeBinaryOp "->"
991(.->) = unsafeBinaryOp "->"
992
992
993-- | Get JSON value (object field or array element) at a key, as text.
993-- | Get JSON value (object field or array element) at a key, as text.
994(.->>)
994(.->>)
995 :: (json `In` PGJsonType, key `In` PGJsonKey)
995 :: (json `In` PGJsonType, key `In` PGJsonKey)
996− => Expression db from grouping params (nullity json)
996+ => Expression db params grp from (nullity json)
997− -> Expression db from grouping params (nullity key)
997+ -> Expression db params grp from (nullity key)
998− -> Expression db from grouping params ('Null 'PGtext)
998+ -> Expression db params grp from ('Null 'PGtext)
999infixl 8 .->>
999infixl 8 .->>
1000(.->>) = unsafeBinaryOp "->>"
1000(.->>) = unsafeBinaryOp "->>"
1001
1001
1002-- | Get JSON value at a specified path.
1002-- | Get JSON value at a specified path.
1003(.#>)
1003(.#>)
1004 :: (json `In` PGJsonType, PGTextArray "(.#>)" path)
1004 :: (json `In` PGJsonType, PGTextArray "(.#>)" path)
1005− => Expression db from grouping params (nullity json)
1005+ => Expression db params grp from (nullity json)
1006− -> Expression db from grouping params (nullity path)
1006+ -> Expression db params grp from (nullity path)
1007− -> Expression db from grouping params ('Null json)
1007+ -> Expression db params grp from ('Null json)
1008infixl 8 .#>
1008infixl 8 .#>
1009(.#>) = unsafeBinaryOp "#>"
1009(.#>) = unsafeBinaryOp "#>"
1010
1010
1011-- | Get JSON value at a specified path as text.
1011-- | Get JSON value at a specified path as text.
1012(.#>>)
1012(.#>>)
1013 :: (json `In` PGJsonType, PGTextArray "(.#>>)" path)
1013 :: (json `In` PGJsonType, PGTextArray "(.#>>)" path)
1014− => Expression db from grouping params (nullity json)
1014+ => Expression db params grp from (nullity json)
1015− -> Expression db from grouping params (nullity path)
1015+ -> Expression db params grp from (nullity path)
1016− -> Expression db from grouping params ('Null 'PGtext)
1016+ -> Expression db params grp from ('Null 'PGtext)
1017infixl 8 .#>>
1017infixl 8 .#>>
1018(.#>>) = unsafeBinaryOp "#>>"
1018(.#>>) = unsafeBinaryOp "#>>"
1019
1019
@@ -1022,42 +1022,42 @@ infixl 8 .#>>
1022-- | Does the left JSON value contain the right JSON path/value entries at the
1022-- | Does the left JSON value contain the right JSON path/value entries at the
1023-- top level?
1023-- top level?
1024(.@>)
1024(.@>)
1025− :: Expression db from grouping params (nullity 'PGjsonb)
1025+ :: Expression db params grp from (nullity 'PGjsonb)
1026− -> Expression db from grouping params (nullity 'PGjsonb)
1026+ -> Expression db params grp from (nullity 'PGjsonb)
1027− -> Condition db from grouping params
1027+ -> Condition db params grp from
1028infixl 9 .@>
1028infixl 9 .@>
1029(.@>) = unsafeBinaryOp "@>"
1029(.@>) = unsafeBinaryOp "@>"
1030
1030
1031-- | Are the left JSON path/value entries contained at the top level within the
1031-- | Are the left JSON path/value entries contained at the top level within the
1032-- right JSON value?
1032-- right JSON value?
1033(.<@)
1033(.<@)
1034− :: Expression db from grouping params (nullity 'PGjsonb)
1034+ :: Expression db params grp from (nullity 'PGjsonb)
1035− -> Expression db from grouping params (nullity 'PGjsonb)
1035+ -> Expression db params grp from (nullity 'PGjsonb)
1036− -> Condition db from grouping params
1036+ -> Condition db params grp from
1037infixl 9 .<@
1037infixl 9 .<@
1038(.<@) = unsafeBinaryOp "<@"
1038(.<@) = unsafeBinaryOp "<@"
1039
1039
1040-- | Does the string exist as a top-level key within the JSON value?
1040-- | Does the string exist as a top-level key within the JSON value?
1041(.?)
1041(.?)
1042− :: Expression db from grouping params (nullity 'PGjsonb)
1042+ :: Expression db params grp from (nullity 'PGjsonb)
1043− -> Expression db from grouping params (nullity 'PGtext)
1043+ -> Expression db params grp from (nullity 'PGtext)
1044− -> Condition db from grouping params
1044+ -> Condition db params grp from
1045infixl 9 .?
1045infixl 9 .?
1046(.?) = unsafeBinaryOp "?"
1046(.?) = unsafeBinaryOp "?"
1047
1047
1048-- | Do any of these array strings exist as top-level keys?
1048-- | Do any of these array strings exist as top-level keys?
1049(.?|)
1049(.?|)
1050− :: Expression db from grouping params (nullity 'PGjsonb)
1050+ :: Expression db params grp from (nullity 'PGjsonb)
1051− -> Expression db from grouping params (nullity ('PGvararray ('NotNull 'PGtext)))
1051+ -> Expression db params grp from (nullity ('PGvararray ('NotNull 'PGtext)))
1052− -> Condition db from grouping params
1052+ -> Condition db params grp from
1053infixl 9 .?|
1053infixl 9 .?|
1054(.?|) = unsafeBinaryOp "?|"
1054(.?|) = unsafeBinaryOp "?|"
1055
1055
1056-- | Do all of these array strings exist as top-level keys?
1056-- | Do all of these array strings exist as top-level keys?
1057(.?&)
1057(.?&)
1058− :: Expression db from grouping params (nullity 'PGjsonb)
1058+ :: Expression db params grp from (nullity 'PGjsonb)
1059− -> Expression db from grouping params (nullity ('PGvararray ('NotNull 'PGtext)))
1059+ -> Expression db params grp from (nullity ('PGvararray ('NotNull 'PGtext)))
1060− -> Condition db from grouping params
1060+ -> Condition db params grp from
1061infixl 9 .?&
1061infixl 9 .?&
1062(.?&) = unsafeBinaryOp "?&"
1062(.?&) = unsafeBinaryOp "?&"
1063
1063
@@ -1080,9 +1080,9 @@ instance
1080-- count from the end). Throws an error if top level container is not an array.
1080-- count from the end). Throws an error if top level container is not an array.
1081(.-.)
1081(.-.)
1082 :: (key `In` '[ 'PGtext, 'PGvararray ('NotNull 'PGtext), 'PGint4, 'PGint2 ]) -- hlint error without parens here
1082 :: (key `In` '[ 'PGtext, 'PGvararray ('NotNull 'PGtext), 'PGint4, 'PGint2 ]) -- hlint error without parens here
1083− => Expression db from grouping params (nullity 'PGjsonb)
1083+ => Expression db params grp from (nullity 'PGjsonb)
1084− -> Expression db from grouping params (nullity key)
1084+ -> Expression db params grp from (nullity key)
1085− -> Expression db from grouping params (nullity 'PGjsonb)
1085+ -> Expression db params grp from (nullity 'PGjsonb)
1086infixl 6 .-.
1086infixl 6 .-.
1087(.-.) = unsafeBinaryOp "-"
1087(.-.) = unsafeBinaryOp "-"
1088
1088
@@ -1090,9 +1090,9 @@ infixl 6 .-.
1090-- integers count from the end)
1090-- integers count from the end)
1091(#-.)
1091(#-.)
1092 :: PGTextArray "(#-.)" arrayty
1092 :: PGTextArray "(#-.)" arrayty
1093− => Expression db from grouping params (nullity 'PGjsonb)
1093+ => Expression db params grp from (nullity 'PGjsonb)
1094− -> Expression db from grouping params (nullity arrayty)
1094+ -> Expression db params grp from (nullity arrayty)
1095− -> Expression db from grouping params (nullity 'PGjsonb)
1095+ -> Expression db params grp from (nullity 'PGjsonb)
1096infixl 6 #-.
1096infixl 6 #-.
1097(#-.) = unsafeBinaryOp "#-"
1097(#-.) = unsafeBinaryOp "#-"
1098
1098
@@ -1103,14 +1103,14 @@ Table 9.45: JSON creation functions
1103-- | Literal binary JSON
1103-- | Literal binary JSON
1104jsonbLit
1104jsonbLit
1105 :: JSON.ToJSON x
1105 :: JSON.ToJSON x
1106− => x -> Expression (commons :=> schemas) from grouping params (nullity 'PGjsonb)
1106+ => x -> Expression (commons :=> schemas) params grp from (nullity 'PGjsonb)
1107jsonbLit = cast jsonb . UnsafeExpression
1107jsonbLit = cast jsonb . UnsafeExpression
1108 . singleQuotedUtf8 . toStrict . JSON.encode
1108 . singleQuotedUtf8 . toStrict . JSON.encode
1109
1109
1110-- | Literal JSON
1110-- | Literal JSON
1111jsonLit
1111jsonLit
1112 :: JSON.ToJSON x
1112 :: JSON.ToJSON x
1113− => x -> Expression (commons :=> schemas) from grouping params (nullity 'PGjson)
1113+ => x -> Expression (commons :=> schemas) params grp from (nullity 'PGjson)
1114jsonLit = cast json . UnsafeExpression
1114jsonLit = cast json . UnsafeExpression
1115 . singleQuotedUtf8 . toStrict . JSON.encode
1115 . singleQuotedUtf8 . toStrict . JSON.encode
1116
1116
@@ -1121,8 +1121,8 @@ jsonLit = cast json . UnsafeExpression
1121-- number, a Boolean, or a null value, the text representation will be used, in
1121-- number, a Boolean, or a null value, the text representation will be used, in
1122-- such a fashion that it is a valid json value.
1122-- such a fashion that it is a valid json value.
1123toJson
1123toJson
1124− :: Expression db from grouping params (nullity ty)
1124+ :: Expression db params grp from (nullity ty)
1125− -> Expression db from grouping params (nullity 'PGjson)
1125+ -> Expression db params grp from (nullity 'PGjson)
1126toJson = unsafeFunction "to_json"
1126toJson = unsafeFunction "to_json"
1127
1127
1128-- | Returns the value as jsonb. Arrays and composites are converted
1128-- | Returns the value as jsonb. Arrays and composites are converted
@@ -1132,56 +1132,59 @@ toJson = unsafeFunction "to_json"
1132-- number, a Boolean, or a null value, the text representation will be used, in
1132-- number, a Boolean, or a null value, the text representation will be used, in
1133-- such a fashion that it is a valid jsonb value.
1133-- such a fashion that it is a valid jsonb value.
1134toJsonb
1134toJsonb
1135− :: Expression db from grouping params (nullity ty)
1135+ :: Expression db params grp from (nullity ty)
1136− -> Expression db from grouping params (nullity 'PGjsonb)
1136+ -> Expression db params grp from (nullity 'PGjsonb)
1137toJsonb = unsafeFunction "to_jsonb"
1137toJsonb = unsafeFunction "to_jsonb"
1138
1138
1139-- | Returns the array as a JSON array. A PostgreSQL multidimensional array
1139-- | Returns the array as a JSON array. A PostgreSQL multidimensional array
1140-- becomes a JSON array of arrays.
1140-- becomes a JSON array of arrays.
1141arrayToJson
1141arrayToJson
1142 :: PGArray "arrayToJson" arr
1142 :: PGArray "arrayToJson" arr
1143− => Expression db from grouping params (nullity arr)
1143+ => Expression db params grp from (nullity arr)
1144− -> Expression db from grouping params (nullity 'PGjson)
1144+ -> Expression db params grp from (nullity 'PGjson)
1145arrayToJson = unsafeFunction "array_to_json"
1145arrayToJson = unsafeFunction "array_to_json"
1146
1146
1147-- | Returns the row as a JSON object.
1147-- | Returns the row as a JSON object.
1148rowToJson
1148rowToJson
1149− :: Expression db from grouping params (nullity ('PGcomposite ty))
1149+ :: Expression db params grp from (nullity ('PGcomposite ty))
1150− -> Expression db from grouping params (nullity 'PGjson)
1150+ -> Expression db params grp from (nullity 'PGjson)
1151rowToJson = unsafeFunction "row_to_json"
1151rowToJson = unsafeFunction "row_to_json"
1152
1152
1153-- | Builds a possibly-heterogeneously-typed JSON array out of a variadic
1153-- | Builds a possibly-heterogeneously-typed JSON array out of a variadic
1154-- argument list.
1154-- argument list.
1155jsonBuildArray
1155jsonBuildArray
1156 :: SListI elems
1156 :: SListI elems
1157− => NP (Expression db from grouping params) elems
1157+ => NP (Expression db params grp from) elems
1158− -> Expression db from grouping params (nullity 'PGjson)
1158+ -> Expression db params grp from (nullity 'PGjson)
1159jsonBuildArray = unsafeVariadicFunction "json_build_array"
1159jsonBuildArray = unsafeVariadicFunction "json_build_array"
1160
1160
1161-- | Builds a possibly-heterogeneously-typed (binary) JSON array out of a
1161-- | Builds a possibly-heterogeneously-typed (binary) JSON array out of a
1162-- variadic argument list.
1162-- variadic argument list.
1163jsonbBuildArray
1163jsonbBuildArray
1164 :: SListI elems
1164 :: SListI elems
1165− => NP (Expression db from grouping params) elems
1165+ => NP (Expression db params grp from) elems
1166− -> Expression db from grouping params (nullity 'PGjsonb)
1166+ -> Expression db params grp from (nullity 'PGjsonb)
1167jsonbBuildArray = unsafeVariadicFunction "jsonb_build_array"
1167jsonbBuildArray = unsafeVariadicFunction "jsonb_build_array"
1168
1168
1169unsafeRowFunction
1169unsafeRowFunction
1170 :: All Top elems
1170 :: All Top elems
1171− => NP (Aliased (Expression db from grouping params)) elems
1171+ => NP (Aliased (Expression db params grp from)) elems
1172 -> [ByteString]
1172 -> [ByteString]
1173unsafeRowFunction =
1173unsafeRowFunction =
1174 (`appEndo` []) . hcfoldMap (Proxy :: Proxy Top)
1174 (`appEndo` []) . hcfoldMap (Proxy :: Proxy Top)
1175 (\(col `As` name) -> Endo $ \xs ->
1175 (\(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
1177
1180
1178-- | Builds a possibly-heterogeneously-typed JSON object out of a variadic
1181-- | Builds a possibly-heterogeneously-typed JSON object out of a variadic
1179-- argument list. The elements of the argument list must alternate between text
1182-- argument list. The elements of the argument list must alternate between text
1180-- and values.
1183-- and values.
1181jsonBuildObject
1184jsonBuildObject
1182 :: All Top elems
1185 :: All Top elems
1183− => NP (Aliased (Expression db from grouping params)) elems
1186+ => NP (Aliased (Expression db params grp from)) elems
1184− -> Expression db from grouping params (nullity 'PGjson)
1187+ -> Expression db params grp from (nullity 'PGjson)
1185jsonBuildObject
1188jsonBuildObject
1186 = unsafeFunction "json_build_object"
1189 = unsafeFunction "json_build_object"
1187 . UnsafeExpression
1190 . UnsafeExpression
@@ -1193,8 +1196,8 @@ jsonBuildObject
1193-- between text and values.
1196-- between text and values.
1194jsonbBuildObject
1197jsonbBuildObject
1195 :: All Top elems
1198 :: All Top elems
1196− => NP (Aliased (Expression db from grouping params)) elems
1199+ => NP (Aliased (Expression db params grp from)) elems
1197− -> Expression db from grouping params (nullity 'PGjsonb)
1200+ -> Expression db params grp from (nullity 'PGjsonb)
1198jsonbBuildObject
1201jsonbBuildObject
1199 = unsafeFunction "jsonb_build_object"
1202 = unsafeFunction "jsonb_build_object"
1200 . UnsafeExpression
1203 . UnsafeExpression
@@ -1207,8 +1210,8 @@ jsonbBuildObject
1207-- array has exactly two elements, which are taken as a key/value pair.
1210-- array has exactly two elements, which are taken as a key/value pair.
1208jsonObject
1211jsonObject
1209 :: PGArrayOf "jsonObject" arr ('NotNull 'PGtext)
1212 :: PGArrayOf "jsonObject" arr ('NotNull 'PGtext)
1210− => Expression db from grouping params (nullity arr)
1213+ => Expression db params grp from (nullity arr)
1211− -> Expression db from grouping params (nullity 'PGjson)
1214+ -> Expression db params grp from (nullity 'PGjson)
1212jsonObject = unsafeFunction "json_object"
1215jsonObject = unsafeFunction "json_object"
1213
1216
1214-- | Builds a binary JSON object out of a text array. The array must have either
1217-- | Builds a binary JSON object out of a text array. The array must have either
@@ -1217,8 +1220,8 @@ jsonObject = unsafeFunction "json_object"
1217-- array has exactly two elements, which are taken as a key/value pair.
1220-- array has exactly two elements, which are taken as a key/value pair.
1218jsonbObject
1221jsonbObject
1219 :: PGArrayOf "jsonbObject" arr ('NotNull 'PGtext)
1222 :: PGArrayOf "jsonbObject" arr ('NotNull 'PGtext)
1220− => Expression db from grouping params (nullity arr)
1223+ => Expression db params grp from (nullity arr)
1221− -> Expression db from grouping params (nullity 'PGjsonb)
1224+ -> Expression db params grp from (nullity 'PGjsonb)
1222jsonbObject = unsafeFunction "jsonb_object"
1225jsonbObject = unsafeFunction "jsonb_object"
1223
1226
1224-- | This is an alternate form of 'jsonObject' that takes two arrays; one for
1227-- | This is an alternate form of 'jsonObject' that takes two arrays; one for
@@ -1226,9 +1229,9 @@ jsonbObject = unsafeFunction "jsonb_object"
1226jsonZipObject
1229jsonZipObject
1227 :: ( PGArrayOf "jsonZipObject" keysArray ('NotNull 'PGtext)
1230 :: ( PGArrayOf "jsonZipObject" keysArray ('NotNull 'PGtext)
1228 , PGArrayOf "jsonZipObject" valuesArray ('NotNull 'PGtext))
1231 , PGArrayOf "jsonZipObject" valuesArray ('NotNull 'PGtext))
1229− => Expression db from grouping params (nullity keysArray)
1232+ => Expression db params grp from (nullity keysArray)
1230− -> Expression db from grouping params (nullity valuesArray)
1233+ -> Expression db params grp from (nullity valuesArray)
1231− -> Expression db from grouping params (nullity 'PGjson)
1234+ -> Expression db params grp from (nullity 'PGjson)
1232jsonZipObject ks vs =
1235jsonZipObject ks vs =
1233 unsafeVariadicFunction "json_object" (ks :* vs :* Nil)
1236 unsafeVariadicFunction "json_object" (ks :* vs :* Nil)
1234
1237
@@ -1238,9 +1241,9 @@ jsonZipObject ks vs =
1238jsonbZipObject
1241jsonbZipObject
1239 :: ( PGArrayOf "jsonbZipObject" keysArray ('NotNull 'PGtext)
1242 :: ( PGArrayOf "jsonbZipObject" keysArray ('NotNull 'PGtext)
1240 , PGArrayOf "jsonbZipObject" valuesArray ('NotNull 'PGtext))
1243 , PGArrayOf "jsonbZipObject" valuesArray ('NotNull 'PGtext))
1241− => Expression db from grouping params (nullity keysArray)
1244+ => Expression db params grp from (nullity keysArray)
1242− -> Expression db from grouping params (nullity valuesArray)
1245+ -> Expression db params grp from (nullity valuesArray)
1243− -> Expression db from grouping params (nullity 'PGjsonb)
1246+ -> Expression db params grp from (nullity 'PGjsonb)
1244jsonbZipObject ks vs =
1247jsonbZipObject ks vs =
1245 unsafeVariadicFunction "jsonb_object" (ks :* vs :* Nil)
1248 unsafeVariadicFunction "jsonb_object" (ks :* vs :* Nil)
1246
1249
@@ -1250,23 +1253,23 @@ Table 9.46: JSON processing functions
1250
1253
1251-- | Returns the number of elements in the outermost JSON array.
1254-- | Returns the number of elements in the outermost JSON array.
1252jsonArrayLength
1255jsonArrayLength
1253− :: Expression db from grouping params (nullity 'PGjson)
1256+ :: Expression db params grp from (nullity 'PGjson)
1254− -> Expression db from grouping params (nullity 'PGint4)
1257+ -> Expression db params grp from (nullity 'PGint4)
1255jsonArrayLength = unsafeFunction "json_array_length"
1258jsonArrayLength = unsafeFunction "json_array_length"
1256
1259
1257-- | Returns the number of elements in the outermost binary JSON array.
1260-- | Returns the number of elements in the outermost binary JSON array.
1258jsonbArrayLength
1261jsonbArrayLength
1259− :: Expression db from grouping params (nullity 'PGjsonb)
1262+ :: Expression db params grp from (nullity 'PGjsonb)
1260− -> Expression db from grouping params (nullity 'PGint4)
1263+ -> Expression db params grp from (nullity 'PGint4)
1261jsonbArrayLength = unsafeFunction "jsonb_array_length"
1264jsonbArrayLength = unsafeFunction "jsonb_array_length"
1262
1265
1263-- | Returns JSON value pointed to by the given path (equivalent to #>
1266-- | Returns JSON value pointed to by the given path (equivalent to #>
1264-- operator).
1267-- operator).
1265jsonExtractPath
1268jsonExtractPath
1266 :: SListI elems
1269 :: SListI elems
1267− => Expression db from grouping params (nullity 'PGjson)
1270+ => Expression db params grp from (nullity 'PGjson)
1268− -> NP (Expression db from grouping params) elems
1271+ -> NP (Expression db params grp from) elems
1269− -> Expression db from grouping params (nullity 'PGjsonb)
1272+ -> Expression db params grp from (nullity 'PGjsonb)
1270jsonExtractPath x xs =
1273jsonExtractPath x xs =
1271 unsafeVariadicFunction "json_extract_path" (x :* xs)
1274 unsafeVariadicFunction "json_extract_path" (x :* xs)
1272
1275
@@ -1274,9 +1277,9 @@ jsonExtractPath x xs =
1274-- operator).
1277-- operator).
1275jsonbExtractPath
1278jsonbExtractPath
1276 :: SListI elems
1279 :: SListI elems
1277− => Expression db from grouping params (nullity 'PGjsonb)
1280+ => Expression db params grp from (nullity 'PGjsonb)
1278− -> NP (Expression db from grouping params) elems
1281+ -> NP (Expression db params grp from) elems
1279− -> Expression db from grouping params (nullity 'PGjsonb)
1282+ -> Expression db params grp from (nullity 'PGjsonb)
1280jsonbExtractPath x xs =
1283jsonbExtractPath x xs =
1281 unsafeVariadicFunction "jsonb_extract_path" (x :* xs)
1284 unsafeVariadicFunction "jsonb_extract_path" (x :* xs)
1282
1285
@@ -1284,9 +1287,9 @@ jsonbExtractPath x xs =
1284-- operator), as text.
1287-- operator), as text.
1285jsonExtractPathAsText
1288jsonExtractPathAsText
1286 :: SListI elems
1289 :: SListI elems
1287− => Expression db from grouping params (nullity 'PGjson)
1290+ => Expression db params grp from (nullity 'PGjson)
1288− -> NP (Expression db from grouping params) elems
1291+ -> NP (Expression db params grp from) elems
1289− -> Expression db from grouping params (nullity 'PGjson)
1292+ -> Expression db params grp from (nullity 'PGjson)
1290jsonExtractPathAsText x xs =
1293jsonExtractPathAsText x xs =
1291 unsafeVariadicFunction "json_extract_path_text" (x :* xs)
1294 unsafeVariadicFunction "json_extract_path_text" (x :* xs)
1292
1295
@@ -1294,38 +1297,38 @@ jsonExtractPathAsText x xs =
1294-- operator), as text.
1297-- operator), as text.
1295jsonbExtractPathAsText
1298jsonbExtractPathAsText
1296 :: SListI elems
1299 :: SListI elems
1297− => Expression db from grouping params (nullity 'PGjsonb)
1300+ => Expression db params grp from (nullity 'PGjsonb)
1298− -> NP (Expression db from grouping params) elems
1301+ -> NP (Expression db params grp from) elems
1299− -> Expression db from grouping params (nullity 'PGjsonb)
1302+ -> Expression db params grp from (nullity 'PGjsonb)
1300jsonbExtractPathAsText x xs =
1303jsonbExtractPathAsText x xs =
1301 unsafeVariadicFunction "jsonb_extract_path_text" (x :* xs)
1304 unsafeVariadicFunction "jsonb_extract_path_text" (x :* xs)
1302
1305
1303-- | Returns the type of the outermost JSON value as a text string. Possible
1306-- | Returns the type of the outermost JSON value as a text string. Possible
1304-- types are object, array, string, number, boolean, and null.
1307-- types are object, array, string, number, boolean, and null.
1305jsonTypeof
1308jsonTypeof
1306− :: Expression db from grouping params (nullity 'PGjson)
1309+ :: Expression db params grp from (nullity 'PGjson)
1307− -> Expression db from grouping params (nullity 'PGtext)
1310+ -> Expression db params grp from (nullity 'PGtext)
1308jsonTypeof = unsafeFunction "json_typeof"
1311jsonTypeof = unsafeFunction "json_typeof"
1309
1312
1310-- | Returns the type of the outermost binary JSON value as a text string.
1313-- | Returns the type of the outermost binary JSON value as a text string.
1311-- Possible types are object, array, string, number, boolean, and null.
1314-- Possible types are object, array, string, number, boolean, and null.
1312jsonbTypeof
1315jsonbTypeof
1313− :: Expression db from grouping params (nullity 'PGjsonb)
1316+ :: Expression db params grp from (nullity 'PGjsonb)
1314− -> Expression db from grouping params (nullity 'PGtext)
1317+ -> Expression db params grp from (nullity 'PGtext)
1315jsonbTypeof = unsafeFunction "jsonb_typeof"
1318jsonbTypeof = unsafeFunction "jsonb_typeof"
1316
1319
1317-- | Returns its argument with all object fields that have null values omitted.
1320-- | Returns its argument with all object fields that have null values omitted.
1318-- Other null values are untouched.
1321-- Other null values are untouched.
1319jsonStripNulls
1322jsonStripNulls
1320− :: Expression db from grouping params (nullity 'PGjson)
1323+ :: Expression db params grp from (nullity 'PGjson)
1321− -> Expression db from grouping params (nullity 'PGjson)
1324+ -> Expression db params grp from (nullity 'PGjson)
1322jsonStripNulls = unsafeFunction "json_strip_nulls"
1325jsonStripNulls = unsafeFunction "json_strip_nulls"
1323
1326
1324-- | Returns its argument with all object fields that have null values omitted.
1327-- | Returns its argument with all object fields that have null values omitted.
1325-- Other null values are untouched.
1328-- Other null values are untouched.
1326jsonbStripNulls
1329jsonbStripNulls
1327− :: Expression db from grouping params (nullity 'PGjsonb)
1330+ :: Expression db params grp from (nullity 'PGjsonb)
1328− -> Expression db from grouping params (nullity 'PGjsonb)
1331+ -> Expression db params grp from (nullity 'PGjsonb)
1329jsonbStripNulls = unsafeFunction "jsonb_strip_nulls"
1332jsonbStripNulls = unsafeFunction "jsonb_strip_nulls"
1330
1333
1331-- | @ jsonbSet target path new_value create_missing @
1334-- | @ jsonbSet target path new_value create_missing @
@@ -1337,11 +1340,11 @@ jsonbStripNulls = unsafeFunction "jsonb_strip_nulls"
1337-- arrays.
1340-- arrays.
1338jsonbSet
1341jsonbSet
1339 :: PGTextArray "jsonbSet" arr
1342 :: PGTextArray "jsonbSet" arr
1340− => Expression db from grouping params (nullity 'PGjsonb)
1343+ => Expression db params grp from (nullity 'PGjsonb)
1341− -> Expression db from grouping params (nullity arr)
1344+ -> Expression db params grp from (nullity arr)
1342− -> Expression db from grouping params (nullity 'PGjsonb)
1345+ -> Expression db params grp from (nullity 'PGjsonb)
1343− -> Maybe (Expression db from grouping params (nullity 'PGbool))
1346+ -> Maybe (Expression db params grp from (nullity 'PGbool))
1344− -> Expression db from grouping params (nullity 'PGjsonb)
1347+ -> Expression db params grp from (nullity 'PGjsonb)
1345jsonbSet tgt path val createMissing = case createMissing of
1348jsonbSet tgt path val createMissing = case createMissing of
1346 Just m -> unsafeVariadicFunction "jsonb_set" (tgt :* path :* val :* m :* Nil)
1349 Just m -> unsafeVariadicFunction "jsonb_set" (tgt :* path :* val :* m :* Nil)
1347 Nothing -> unsafeVariadicFunction "jsonb_set" (tgt :* path :* val :* Nil)
1350 Nothing -> unsafeVariadicFunction "jsonb_set" (tgt :* path :* val :* Nil)
@@ -1356,19 +1359,19 @@ jsonbSet tgt path val createMissing = case createMissing of
1356-- in path count from the end of JSON arrays.
1359-- in path count from the end of JSON arrays.
1357jsonbInsert
1360jsonbInsert
1358 :: PGTextArray "jsonbInsert" arr
1361 :: PGTextArray "jsonbInsert" arr
1359− => Expression db from grouping params (nullity 'PGjsonb)
1362+ => Expression db params grp from (nullity 'PGjsonb)
1360− -> Expression db from grouping params (nullity arr)
1363+ -> Expression db params grp from (nullity arr)
1361− -> Expression db from grouping params (nullity 'PGjsonb)
1364+ -> Expression db params grp from (nullity 'PGjsonb)
1362− -> Maybe (Expression db from grouping params (nullity 'PGbool))
1365+ -> Maybe (Expression db params grp from (nullity 'PGbool))
1363− -> Expression db from grouping params (nullity 'PGjsonb)
1366+ -> Expression db params grp from (nullity 'PGjsonb)
1364jsonbInsert tgt path val insertAfter = case insertAfter of
1367jsonbInsert tgt path val insertAfter = case insertAfter of
1365 Just i -> unsafeVariadicFunction "jsonb_insert" (tgt :* path :* val :* i :* Nil)
1368 Just i -> unsafeVariadicFunction "jsonb_insert" (tgt :* path :* val :* i :* Nil)
1366 Nothing -> unsafeVariadicFunction "jsonb_insert" (tgt :* path :* val :* Nil)
1369 Nothing -> unsafeVariadicFunction "jsonb_insert" (tgt :* path :* val :* Nil)
1367
1370
1368-- | Returns its argument as indented JSON text.
1371-- | Returns its argument as indented JSON text.
1369jsonbPretty
1372jsonbPretty
1370− :: Expression db from grouping params (nullity 'PGjsonb)
1373+ :: Expression db params grp from (nullity 'PGjsonb)
1371− -> Expression db from grouping params (nullity 'PGtext)
1374+ -> Expression db params grp from (nullity 'PGtext)
1372jsonbPretty = unsafeFunction "jsonb_pretty"
1375jsonbPretty = unsafeFunction "jsonb_pretty"
1373
1376
1374{-----------------------------------------
1377{-----------------------------------------
@@ -1381,7 +1384,7 @@ unsafeAggregate
1381 -> Expression db from 'Ungrouped params (xty)
1384 -> Expression db from 'Ungrouped params (xty)
1382 -> Expression db from ('Grouped bys) params (yty)
1385 -> Expression db from ('Grouped bys) params (yty)
1383unsafeAggregate fun x = UnsafeExpression $ mconcat
1386unsafeAggregate fun x = UnsafeExpression $ mconcat
1384− [fun, "(", renderExpression x, ")"]
1387+ [fun, "(", renderSQL x, ")"]
1385
1388
1386-- | escape hatch to define aggregate functions over distinct values
1389-- | escape hatch to define aggregate functions over distinct values
1387unsafeAggregateDistinct
1390unsafeAggregateDistinct
@@ -1389,11 +1392,11 @@ unsafeAggregateDistinct
1389 -> Expression db from 'Ungrouped params (xty)
1392 -> Expression db from 'Ungrouped params (xty)
1390 -> Expression db from ('Grouped bys) params (yty)
1393 -> Expression db from ('Grouped bys) params (yty)
1391unsafeAggregateDistinct fun x = UnsafeExpression $ mconcat
1394unsafeAggregateDistinct fun x = UnsafeExpression $ mconcat
1392− [fun, "(DISTINCT ", renderExpression x, ")"]
1395+ [fun, "(DISTINCT ", renderSQL x, ")"]
1393
1396
1394-- | >>> :{
1397-- | >>> :{
1395-- let
1398-- 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)
1397-- expression = sum_ #col
1400-- expression = sum_ #col
1398-- in printSQL expression
1401-- in printSQL expression
1399-- :}
1402-- :}
@@ -1407,7 +1410,7 @@ sum_ = unsafeAggregate "sum"
1407
1410
1408-- | >>> :{
1411-- | >>> :{
1409-- let
1412-- 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)
1411-- expression = sumDistinct #col
1414-- expression = sumDistinct #col
1412-- in printSQL expression
1415-- in printSQL expression
1413-- :}
1416-- :}
@@ -1438,7 +1441,7 @@ instance PGAvg 'PGinterval 'PGinterval
1438
1441
1439-- | >>> :{
1442-- | >>> :{
1440-- let
1443-- 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)
1442-- expression = bitAnd #col
1445-- expression = bitAnd #col
1443-- in printSQL expression
1446-- in printSQL expression
1444-- :}
1447-- :}
@@ -1452,7 +1455,7 @@ bitAnd = unsafeAggregate "bit_and"
1452
1455
1453-- | >>> :{
1456-- | >>> :{
1454-- let
1457-- 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)
1456-- expression = bitOr #col
1459-- expression = bitOr #col
1457-- in printSQL expression
1460-- in printSQL expression
1458-- :}
1461-- :}
@@ -1466,7 +1469,7 @@ bitOr = unsafeAggregate "bit_or"
1466
1469
1467-- | >>> :{
1470-- | >>> :{
1468-- let
1471-- 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)
1470-- expression = bitAndDistinct #col
1473-- expression = bitAndDistinct #col
1471-- in printSQL expression
1474-- in printSQL expression
1472-- :}
1475-- :}
@@ -1480,7 +1483,7 @@ bitAndDistinct = unsafeAggregateDistinct "bit_and"
1480
1483
1481-- | >>> :{
1484-- | >>> :{
1482-- let
1485-- 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)
1484-- expression = bitOrDistinct #col
1487-- expression = bitOrDistinct #col
1485-- in printSQL expression
1488-- in printSQL expression
1486-- :}
1489-- :}
@@ -1494,7 +1497,7 @@ bitOrDistinct = unsafeAggregateDistinct "bit_or"
1494
1497
1495-- | >>> :{
1498-- | >>> :{
1496-- let
1499-- 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)
1498-- expression = boolAnd #col
1501-- expression = boolAnd #col
1499-- in printSQL expression
1502-- in printSQL expression
1500-- :}
1503-- :}
@@ -1507,7 +1510,7 @@ boolAnd = unsafeAggregate "bool_and"
1507
1510
1508-- | >>> :{
1511-- | >>> :{
1509-- let
1512-- 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)
1511-- expression = boolOr #col
1514-- expression = boolOr #col
1512-- in printSQL expression
1515-- in printSQL expression
1513-- :}
1516-- :}
@@ -1520,7 +1523,7 @@ boolOr = unsafeAggregate "bool_or"
1520
1523
1521-- | >>> :{
1524-- | >>> :{
1522-- let
1525-- 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)
1524-- expression = boolAndDistinct #col
1527-- expression = boolAndDistinct #col
1525-- in printSQL expression
1528-- in printSQL expression
1526-- :}
1529-- :}
@@ -1533,7 +1536,7 @@ boolAndDistinct = unsafeAggregateDistinct "bool_and"
1533
1536
1534-- | >>> :{
1537-- | >>> :{
1535-- let
1538-- 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)
1537-- expression = boolOrDistinct #col
1540-- expression = boolOrDistinct #col
1538-- in printSQL expression
1541-- in printSQL expression
1539-- :}
1542-- :}
@@ -1554,7 +1557,7 @@ countStar = UnsafeExpression $ "count(*)"
1554
1557
1555-- | >>> :{
1558-- | >>> :{
1556-- let
1559-- 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)
1558-- expression = count #col
1561-- expression = count #col
1559-- in printSQL expression
1562-- in printSQL expression
1560-- :}
1563-- :}
@@ -1567,7 +1570,7 @@ count = unsafeAggregate "count"
1567
1570
1568-- | >>> :{
1571-- | >>> :{
1569-- let
1572-- 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)
1571-- expression = countDistinct #col
1574-- expression = countDistinct #col
1572-- in printSQL expression
1575-- in printSQL expression
1573-- :}
1576-- :}
@@ -1582,7 +1585,7 @@ countDistinct = unsafeAggregateDistinct "count"
1582--
1585--
1583-- >>> :{
1586-- >>> :{
1584-- let
1587-- 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)
1586-- expression = every #col
1589-- expression = every #col
1587-- in printSQL expression
1590-- in printSQL expression
1588-- :}
1591-- :}
@@ -1597,7 +1600,7 @@ every = unsafeAggregate "every"
1597--
1600--
1598-- >>> :{
1601-- >>> :{
1599-- let
1602-- 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)
1601-- expression = everyDistinct #col
1604-- expression = everyDistinct #col
1602-- in printSQL expression
1605-- in printSQL expression
1603-- :}
1606-- :}
@@ -1626,13 +1629,15 @@ type expressions
1626newtype TypeExpression (schemas :: SchemasType) (ty :: NullityType)
1629newtype TypeExpression (schemas :: SchemasType) (ty :: NullityType)
1627 = UnsafeTypeExpression { renderTypeExpression :: ByteString }
1630 = UnsafeTypeExpression { renderTypeExpression :: ByteString }
1628 deriving (GHC.Generic,Show,Eq,Ord,NFData)
1631 deriving (GHC.Generic,Show,Eq,Ord,NFData)
1632+instance RenderSQL (TypeExpression schemas ty) where
1633+ renderSQL = renderTypeExpression
1629
1634
1630-- | The enum or composite type in a `Typedef` can be expressed by its alias.
1635-- | The enum or composite type in a `Typedef` can be expressed by its alias.
1631typedef
1636typedef
1632 :: (Has sch schemas schema, Has td schema ('Typedef ty))
1637 :: (Has sch schemas schema, Has td schema ('Typedef ty))
1633 => QualifiedAlias sch td
1638 => QualifiedAlias sch td
1634 -> TypeExpression schemas (nullity ty)
1639 -> TypeExpression schemas (nullity ty)
1635−typedef = UnsafeTypeExpression . renderQualifiedAlias
1640+typedef = UnsafeTypeExpression . renderSQL
1636
1641
1637-- | The composite type corresponding to a `Table` definition can be expressed
1642-- | The composite type corresponding to a `Table` definition can be expressed
1638-- by its alias.
1643-- by its alias.
@@ -1640,7 +1645,7 @@ typetable
1640 :: (Has sch schemas schema, Has tab schema ('Table table))
1645 :: (Has sch schemas schema, Has tab schema ('Table table))
1641 => QualifiedAlias sch tab
1646 => QualifiedAlias sch tab
1642 -> TypeExpression schemas (nullity ('PGcomposite (TableToRow table)))
1647 -> TypeExpression schemas (nullity ('PGcomposite (TableToRow table)))
1643−typetable = UnsafeTypeExpression . renderQualifiedAlias
1648+typetable = UnsafeTypeExpression . renderSQL
1644
1649
1645-- | The composite type corresponding to a `View` definition can be expressed
1650-- | The composite type corresponding to a `View` definition can be expressed
1646-- by its alias.
1651-- by its alias.
@@ -1648,7 +1653,7 @@ typeview
1648 :: (Has sch schemas schema, Has vw schema ('View view))
1653 :: (Has sch schemas schema, Has vw schema ('View view))
1649 => QualifiedAlias sch vw
1654 => QualifiedAlias sch vw
1650 -> TypeExpression schemas (nullity ('PGcomposite view))
1655 -> TypeExpression schemas (nullity ('PGcomposite view))
1651−typeview = UnsafeTypeExpression . renderQualifiedAlias
1656+typeview = UnsafeTypeExpression . renderSQL
1652
1657
1653-- | logical Boolean (true/false)
1658-- | logical Boolean (true/false)
1654bool :: TypeExpression schemas (nullity 'PGbool)
1659bool :: TypeExpression schemas (nullity 'PGbool)
@@ -1730,17 +1735,17 @@ jsonb = UnsafeTypeExpression "jsonb"
1730vararray
1735vararray
1731 :: TypeExpression schemas pg
1736 :: TypeExpression schemas pg
1732 -> TypeExpression schemas (nullity ('PGvararray pg))
1737 -> TypeExpression schemas (nullity ('PGvararray pg))
1733−vararray ty = UnsafeTypeExpression $ renderTypeExpression ty <> "[]"
1738+vararray ty = UnsafeTypeExpression $ renderSQL ty <> "[]"
1734-- | fixed length array
1739-- | fixed length array
1735--
1740--
1736−-- >>> renderTypeExpression (fixarray @2 json)
1741+-- >>> renderSQL (fixarray @2 json)
1737-- "json[2]"
1742-- "json[2]"
1738fixarray
1743fixarray
1739 :: forall n schemas nullity pg. KnownNat n
1744 :: forall n schemas nullity pg. KnownNat n
1740 => TypeExpression schemas pg
1745 => TypeExpression schemas pg
1741 -> TypeExpression schemas (nullity ('PGfixarray n pg))
1746 -> TypeExpression schemas (nullity ('PGfixarray n pg))
1742fixarray ty = UnsafeTypeExpression $
1747fixarray ty = UnsafeTypeExpression $
1743− renderTypeExpression ty <> "[" <> renderNat @n <> "]"
1748+ renderSQL ty <> "[" <> renderNat @n <> "]"
1744
1749
1745-- | `pgtype` is a demoted version of a `PGType`
1750-- | `pgtype` is a demoted version of a `PGType`
1746class PGTyped schemas (ty :: NullityType) where
1751class PGTyped schemas (ty :: NullityType) where
squeal-postgresql/src/Squeal/PostgreSQL/Manipulation.hs+144−166
@@ -35,6 +35,7 @@ module Squeal.PostgreSQL.Manipulation
35 , DefaultAliasable (..)
35 , DefaultAliasable (..)
36 , ColumnExpression (..)
36 , ColumnExpression (..)
37 , ReturningClause (..)
37 , ReturningClause (..)
38+ , pattern Returning_
38 , ConflictClause (..)
39 , ConflictClause (..)
39 , ConflictTarget (..)
40 , ConflictTarget (..)
40 , ConflictAction (..)
41 , ConflictAction (..)
@@ -42,10 +43,6 @@ module Squeal.PostgreSQL.Manipulation
42 -- * Insert
43 -- * Insert
43 , insertInto
44 , insertInto
44 , insertInto_
45 , insertInto_
45− , renderReturningClause
46− , renderConflictClause
47− , renderConflictTarget
48− , renderConflictAction
49 -- * Update
46 -- * Update
50 , update
47 , update
51 , update_
48 , update_
@@ -123,7 +120,7 @@ let
123 (Values_ ("John Smith" `as` #name :* "john@smith.com" `as` #email))
120 (Values_ ("John Smith" `as` #name :* "john@smith.com" `as` #email))
124 (OnConflict (OnConstraint #uq)
121 (OnConflict (OnConstraint #uq)
125 (DoUpdate (((#excluded ! #email) <> "; " <> (#customers ! #email)) `as` #email) []))
122 (DoUpdate (((#excluded ! #email) <> "; " <> (#customers ! #email)) `as` #email) []))
126− (Returning Nil)
123+ (Returning_ Nil)
127in printSQL manipulation
124in printSQL manipulation
128:}
125:}
129INSERT 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"))
126INSERT 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:
133>>> :{
130>>> :{
134let
131let
135 manipulation :: Manipulation (DBof (Public Schema)) '[] '[]
132 manipulation :: Manipulation (DBof (Public Schema)) '[] '[]
136− manipulation = insertInto_ #tab (Subquery (selectStar (from (table #tab))))
133+ manipulation = insertInto_ #tab (Subquery (select Star (from (table #tab))))
137in printSQL manipulation
134in printSQL manipulation
138:}
135:}
139INSERT INTO "tab" SELECT * FROM "tab" AS "tab"
136INSERT INTO "tab" SELECT * FROM "tab" AS "tab"
@@ -155,7 +152,7 @@ let
155 manipulation :: Manipulation (DBof (Public Schema)) '[]
152 manipulation :: Manipulation (DBof (Public Schema)) '[]
156 '[ "col1" ::: 'NotNull 'PGint4
153 '[ "col1" ::: 'NotNull 'PGint4
157 , "col2" ::: 'NotNull 'PGint4 ]
154 , "col2" ::: 'NotNull 'PGint4 ]
158− manipulation = deleteFrom #tab NoUsing (#col1 .== #col2) ReturningStar
155+ manipulation = deleteFrom #tab NoUsing (#col1 .== #col2) (Returning Star)
159in printSQL manipulation
156in printSQL manipulation
160:}
157:}
161DELETE FROM "tab" WHERE ("col1" = "col2") RETURNING *
158DELETE FROM "tab" WHERE ("col1" = "col2") RETURNING *
@@ -188,8 +185,8 @@ with manipulation:
188let
185let
189 manipulation :: Manipulation (DBof (Public ProductsSchema)) '[ 'NotNull 'PGdate] '[]
186 manipulation :: Manipulation (DBof (Public ProductsSchema)) '[ 'NotNull 'PGdate] '[]
190 manipulation = with
187 manipulation = with
191− (deleteFrom #products NoUsing (#date .< param @1) ReturningStar `as` #del)
188+ (deleteFrom #products NoUsing (#date .< param @1) (Returning Star) `as` #del)
192− (insertInto_ #products_deleted (Subquery (selectStar (from (common #del)))))
189+ (insertInto_ #products_deleted (Subquery (select Star (from (common #del)))))
193in printSQL manipulation
190in printSQL manipulation
194:}
191:}
195WITH "del" AS (DELETE FROM "products" WHERE ("date" < ($1 :: date)) RETURNING *) INSERT INTO "products_deleted" SELECT * FROM "del" AS "del"
192WITH "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
206instance With Manipulation where
203instance With Manipulation where
207 with Done manip = manip
204 with Done manip = manip
208 with (cte :>> ctes) manip = UnsafeManipulation $
205 with (cte :>> ctes) manip = UnsafeManipulation $
209− "WITH" <+> renderCommonTableExpressions renderManipulation cte ctes
206+ "WITH" <+> renderCommonTableExpressions renderSQL cte ctes
210− <+> renderManipulation manip
207+ <+> renderSQL manip
211
208
212-- | Convert a `Query` into a `Manipulation`.
209-- | Convert a `Query` into a `Manipulation`.
213queryStatement
210queryStatement
214 :: Query db params columns
211 :: Query db params columns
215 -> Manipulation db params columns
212 -> Manipulation db params columns
216−queryStatement q = UnsafeManipulation $ renderQuery q
213+queryStatement q = UnsafeManipulation $ renderSQL q
217
214
218{-----------------------------------------
215{-----------------------------------------
219INSERT statements
216INSERT statements
@@ -231,19 +228,19 @@ insertInto
231 , Has sch schemas schema
228 , Has sch schemas schema
232 , Has tab schema ('Table table)
229 , Has tab schema ('Table table)
233 , columns ~ TableToColumns table
230 , columns ~ TableToColumns table
234− , row ~ TableToRow table
231+ , row0 ~ TableToRow table
235 , SOP.SListI columns
232 , SOP.SListI columns
236− , SOP.SListI result )
233+ , SOP.SListI row1 )
237 => QualifiedAlias sch tab
234 => QualifiedAlias sch tab
238 -> QueryClause db params columns
235 -> QueryClause db params columns
239 -> ConflictClause tab db params table
236 -> ConflictClause tab db params table
240− -> ReturningClause db params row result
237+ -> ReturningClause db params '[tab ::: row0] row1
241− -> Manipulation db params result
238+ -> Manipulation db params row1
242insertInto tab qry conflict ret = UnsafeManipulation $
239insertInto tab qry conflict ret = UnsafeManipulation $
243− "INSERT" <+> "INTO" <+> renderQualifiedAlias tab
240+ "INSERT" <+> "INTO" <+> renderSQL tab
244− <+> renderQueryClause qry
241+ <+> renderSQL qry
245− <> renderConflictClause conflict
242+ <> renderSQL conflict
246− <> renderReturningClause ret
243+ <> renderSQL ret
247
244
248insertInto_
245insertInto_
249 :: ( db ~ (commons :=> schemas)
246 :: ( db ~ (commons :=> schemas)
@@ -256,147 +253,143 @@ insertInto_
256 -> QueryClause db params columns
253 -> QueryClause db params columns
257 -> Manipulation db params '[]
254 -> Manipulation db params '[]
258insertInto_ tab qry =
255insertInto_ tab qry =
259− insertInto tab qry OnConflictDoRaise (Returning Nil)
256+ insertInto tab qry OnConflictDoRaise (Returning_ Nil)
260
257
261data QueryClause db params columns where
258data QueryClause db params columns where
262 Values
259 Values
263 :: SOP.SListI columns
260 :: SOP.SListI columns
264− => NP (ColumnExpression db '[] 'Ungrouped params) columns
261+ => NP (ColumnExpression db params 'Ungrouped '[]) columns
265− -> [NP (ColumnExpression db '[] 'Ungrouped params) columns]
262+ -> [NP (ColumnExpression db params 'Ungrouped '[]) columns]
266 -> QueryClause db params columns
263 -> QueryClause db params columns
267 Select
264 Select
268 :: SOP.SListI columns
265 :: SOP.SListI columns
269− => NP (ColumnExpression db from grp params) columns
266+ => NP (ColumnExpression db params grp from) columns
270− -> TableExpression db params from grp
267+ -> TableExpression db params grp from
271 -> QueryClause db params columns
268 -> QueryClause db params columns
272 Subquery
269 Subquery
273 :: ColumnsToRow columns ~ row
270 :: ColumnsToRow columns ~ row
274 => Query db params row
271 => Query db params row
275 -> QueryClause db params columns
272 -> QueryClause db params columns
276
273
277−renderQueryClause
278− :: QueryClause db params columns
274+instance RenderSQL (QueryClause db params columns) where
279− -> ByteString
275+ renderSQL = \case
280−renderQueryClause = \case
281− Values row0 rows ->
276+ Values row0 rows ->
282− parenthesized (renderCommaSeparated renderAliasPart row0)
277+ parenthesized (renderCommaSeparated renderSQLPart row0)
283− <+> "VALUES"
278+ <+> "VALUES"
284− <+> commaSeparated
279+ <+> commaSeparated
285− ( parenthesized
280+ ( parenthesized
286− . renderCommaSeparated renderValuePart <$> row0 : rows )
281+ . renderCommaSeparated renderValuePart <$> row0 : rows )
287− Select row0 tab ->
282+ Select row0 tab ->
288− parenthesized (renderCommaSeparatedMaybe renderAliasPartMaybe row0)
283+ parenthesized (renderCommaSeparatedMaybe renderSQLPartMaybe row0)
289− <+> "SELECT"
284+ <+> "SELECT"
290− <+> renderCommaSeparatedMaybe renderValuePartMaybe row0
285+ <+> renderCommaSeparatedMaybe renderValuePartMaybe row0
291− <+> renderTableExpression tab
286+ <+> renderSQL tab
292− Subquery qry -> renderQuery qry
287+ Subquery qry -> renderQuery qry
293− where
288+ where
294− renderAliasPartMaybe, renderValuePartMaybe
289+ renderSQLPartMaybe, renderValuePartMaybe
295− :: ColumnExpression db from grp params column -> Maybe ByteString
290+ :: ColumnExpression db params grp from column -> Maybe ByteString
296− renderAliasPartMaybe = \case
291+ renderSQLPartMaybe = \case
297− DefaultAs _ -> Nothing
292+ DefaultAs _ -> Nothing
298− Specific (_ `As` name) -> Just $ renderAlias name
293+ Specific (_ `As` name) -> Just $ renderSQL name
299− renderValuePartMaybe = \case
294+ renderValuePartMaybe = \case
300− DefaultAs _ -> Nothing
295+ DefaultAs _ -> Nothing
301− Specific (value `As` _) -> Just $ renderExpression value
296+ Specific (value `As` _) -> Just $ renderExpression value
302− renderAliasPart, renderValuePart
297+ renderSQLPart, renderValuePart
303− :: ColumnExpression db from grp params column -> ByteString
298+ :: ColumnExpression db params grp from column -> ByteString
304− renderAliasPart = \case
299+ renderSQLPart = \case
305− DefaultAs name -> renderAlias name
300+ DefaultAs name -> renderSQL name
306− Specific (_ `As` name) -> renderAlias name
301+ Specific (_ `As` name) -> renderSQL name
307− renderValuePart = \case
302+ renderValuePart = \case
308− DefaultAs _ -> "DEFAULT"
303+ DefaultAs _ -> "DEFAULT"
309− Specific (value `As` _) -> renderExpression value
304+ Specific (value `As` _) -> renderExpression value
310
305
311pattern Values_
306pattern Values_
312 :: SOP.SListI columns
307 :: SOP.SListI columns
313− => NP (ColumnExpression db '[] 'Ungrouped params) columns
308+ => NP (ColumnExpression db params 'Ungrouped '[]) columns
314 -> QueryClause db params columns
309 -> QueryClause db params columns
315pattern Values_ vals = Values vals []
310pattern Values_ vals = Values vals []
316
311
317−data ColumnExpression db from grp params column where
312+data ColumnExpression db params grp from column where
318 DefaultAs
313 DefaultAs
319 :: KnownSymbol col
314 :: KnownSymbol col
320 => Alias col
315 => Alias col
321− -> ColumnExpression db from grp params (col ::: 'Def :=> ty)
316+ -> ColumnExpression db params grp from (col ::: 'Def :=> ty)
322 Specific
317 Specific
323− :: Aliased (Expression db from grp params) (col ::: ty)
318+ :: Aliased (Expression db params grp from) (col ::: ty)
324− -> ColumnExpression db from grp params (col ::: defness :=> ty)
319+ -> ColumnExpression db params grp from (col ::: defness :=> ty)
325
320
326instance (KnownSymbol col, column ~ (col ::: defness :=> ty))
321instance (KnownSymbol col, column ~ (col ::: defness :=> ty))
327 => Aliasable col
322 => Aliasable col
328− (Expression db from grp params ty)
323+ (Expression db params grp from ty)
329− (ColumnExpression db from grp params column) where
324+ (ColumnExpression db params grp from column) where
330 expression `as` col = Specific (expression `As` col)
325 expression `as` col = Specific (expression `As` col)
331instance (KnownSymbol col, columns ~ '[col ::: defness :=> ty])
326instance (KnownSymbol col, columns ~ '[col ::: defness :=> ty])
332 => Aliasable col
327 => Aliasable col
333− (Expression db from grp params ty)
328+ (Expression db params grp from ty)
334− (NP (ColumnExpression db from grp params) columns) where
329+ (NP (ColumnExpression db params grp from) columns) where
335 expression `as` col = expression `as` col :* Nil
330 expression `as` col = expression `as` col :* Nil
336instance (KnownSymbol col, column ~ (col ::: 'Def :=> ty))
331instance (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
338 defaultAs = DefaultAs
333 defaultAs = DefaultAs
339instance (KnownSymbol col, columns ~ '[col ::: 'Def :=> ty])
334instance (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
341 defaultAs col = defaultAs col :* Nil
336 defaultAs col = defaultAs col :* Nil
342
337
343−instance (HasUnique tab from row, Has col row ty, colty ~ (col ::: defness :=> ty))
338+instance (HasUnique tab from row, Has col row ty, column ~ (col ::: defness :=> ty))
344− => IsLabel col (ColumnExpression db from 'Ungrouped params colty) where
339+ => IsLabel col (ColumnExpression db params 'Ungrouped from column) where
345 fromLabel = fromLabel @col `as` Alias
340 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])
347 => IsLabel col
342 => IsLabel col
348− (NP (ColumnExpression db from 'Ungrouped params) coltys) where
343+ (NP (ColumnExpression db params 'Ungrouped from) columns) where
349 fromLabel = fromLabel @col `as` Alias
344 fromLabel = fromLabel @col `as` Alias
350
345
351−instance (Has tab from row, Has col row ty, colty ~ (col ::: defness :=> ty))
346+instance (Has tab from row, Has col row ty, column ~ (col ::: defness :=> ty))
352− => IsQualified tab col (ColumnExpression db from 'Ungrouped params colty) where
347+ => IsQualified tab col (ColumnExpression db params 'Ungrouped from column) where
353 tab ! col = tab ! col `as` col
348 tab ! col = tab ! col `as` col
354−instance (Has tab from row, Has col row ty, coltys ~ '[col ::: defness :=> ty])
349+instance (Has tab from row, Has col row ty, columns ~ '[col ::: defness :=> ty])
355− => IsQualified tab col (NP (ColumnExpression db from 'Ungrouped params) coltys) where
350+ => IsQualified tab col (NP (ColumnExpression db params 'Ungrouped from) columns) where
356 tab ! col = tab ! col `as` col
351 tab ! col = tab ! col `as` col
357
352
358instance
353instance
359 ( HasUnique tab from row
354 ( HasUnique tab from row
360 , Has col row ty
355 , Has col row ty
361 , GroupedBy tab col bys
356 , GroupedBy tab col bys
362− , colty ~ (col ::: defness :=> ty)
357+ , column ~ (col ::: defness :=> ty)
363 ) => IsLabel col
358 ) => IsLabel col
364− (ColumnExpression db from ('Grouped bys) params colty) where
359+ (ColumnExpression db params ('Grouped bys) from column) where
365 fromLabel = fromLabel @col `as` Alias
360 fromLabel = fromLabel @col `as` Alias
366instance
361instance
367 ( HasUnique tab from row
362 ( HasUnique tab from row
368 , Has col row ty
363 , Has col row ty
369 , GroupedBy tab col bys
364 , GroupedBy tab col bys
370− , coltys ~ '[col ::: defness :=> ty]
365+ , columns ~ '[col ::: defness :=> ty]
371 ) => IsLabel col
366 ) => IsLabel col
372− (NP (ColumnExpression db from ('Grouped bys) params) coltys) where
367+ (NP (ColumnExpression db params ('Grouped bys) from) columns) where
373 fromLabel = fromLabel @col `as` Alias
368 fromLabel = fromLabel @col `as` Alias
374
369
375instance
370instance
376 ( Has tab from row
371 ( Has tab from row
377 , Has col row ty
372 , Has col row ty
378 , GroupedBy tab col bys
373 , GroupedBy tab col bys
379− , colty ~ (col ::: defness :=> ty)
374+ , column ~ (col ::: defness :=> ty)
380 ) => IsQualified tab col
375 ) => IsQualified tab col
381− (ColumnExpression db from ('Grouped bys) params colty) where
376+ (ColumnExpression db params ('Grouped bys) from column) where
382 tab ! col = tab ! col `as` col
377 tab ! col = tab ! col `as` col
383instance
378instance
384 ( Has tab from row
379 ( Has tab from row
385 , Has col row ty
380 , Has col row ty
386 , GroupedBy tab col bys
381 , GroupedBy tab col bys
387− , coltys ~ '[col ::: defness :=> ty]
382+ , columns ~ '[col ::: defness :=> ty]
388 ) => IsQualified tab col
383 ) => IsQualified tab col
389− (NP (ColumnExpression db from ('Grouped bys) params) coltys) where
384+ (NP (ColumnExpression db params ('Grouped bys) from) columns) where
390 tab ! col = tab ! col :* Nil
385 tab ! col = tab ! col :* Nil
391
386
392−renderColumnExpression
393− :: ColumnExpression db from grp params column
387+instance RenderSQL (ColumnExpression db params grp from column) where
394− -> ByteString
388+ renderSQL = \case
395−renderColumnExpression = \case
396− DefaultAs col ->
389+ DefaultAs col ->
397− renderAlias col <+> "=" <+> "DEFAULT"
390+ renderSQL col <+> "=" <+> "DEFAULT"
398− Specific (expression `As` col) ->
391+ Specific (expression `As` col) ->
399− renderAlias col <+> "=" <+> renderExpression expression
392+ renderSQL col <+> "=" <+> renderSQL expression
400
393
401-- | A `ReturningClause` computes and return value(s) based
394-- | A `ReturningClause` computes and return value(s) based
402-- on each row actually inserted, updated or deleted. This is primarily
395-- on each row actually inserted, updated or deleted. This is primarily
@@ -408,28 +401,19 @@ renderColumnExpression = \case
408-- the row will not be returned. `ReturningStar` will return all columns
401-- the row will not be returned. `ReturningStar` will return all columns
409-- in the row. Use @Returning Nil@ in the common case where no return
402-- in the row. Use @Returning Nil@ in the common case where no return
410-- values are desired.
403-- values are desired.
411−data ReturningClause
404+newtype ReturningClause db params from row =
412− (db :: DBType)
405+ Returning (Selection db params 'Ungrouped from row)
413− (params :: [NullityType])
406+
414− (row0 :: RowType)
407+instance RenderSQL (ReturningClause db params from row) where
415− (row1 :: RowType)
408+ renderSQL = \case
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 -> ""
409+ Returning (List Nil) -> ""
431− Returning results -> " RETURNING"
410+ Returning selection -> " RETURNING" <+> renderSQL selection
432− <+> renderCommaSeparated (renderAliasedAs renderExpression) results
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)
433
417
434-- | A `ConflictClause` specifies an action to perform upon a constraint
418-- | A `ConflictClause` specifies an action to perform upon a constraint
435-- violation. `OnConflictDoRaise` will raise an error.
419-- violation. `OnConflictDoRaise` will raise an error.
@@ -444,14 +428,12 @@ data ConflictClause tab db params table where
444 -> ConflictClause tab db params (constraints :=> columns)
428 -> ConflictClause tab db params (constraints :=> columns)
445
429
446-- | Render a `ConflictClause`.
430-- | Render a `ConflictClause`.
447−renderConflictClause
448− :: SOP.SListI (TableToColumns table)
431+instance SOP.SListI (TableToColumns table)
449− => ConflictClause tab db params table
432+ => RenderSQL (ConflictClause tab db params table) where
450− -> ByteString
433+ renderSQL = \case
451−renderConflictClause = \case
452− OnConflictDoRaise -> ""
434+ OnConflictDoRaise -> ""
453− OnConflict target action -> " ON CONFLICT"
435+ OnConflict target action -> " ON CONFLICT"
454− <+> renderConflictTarget target <+> renderConflictAction action
436+ <+> renderSQL target <+> renderSQL action
455
437
456data ConflictAction tab db params columns where
438data ConflictAction tab db params columns where
457 DoNothing :: ConflictAction tab db params columns
439 DoNothing :: ConflictAction tab db params columns
@@ -461,21 +443,19 @@ data ConflictAction tab db params columns where
461 , columns ~ (col0 ': cols)
443 , columns ~ (col0 ': cols)
462 , SOP.All (HasIn columns) subcolumns
444 , SOP.All (HasIn columns) subcolumns
463 , AllUnique subcolumns )
445 , AllUnique subcolumns )
464− => NP (ColumnExpression db '[tab ::: row, "excluded" ::: row] 'Ungrouped params) subcolumns
446+ => NP (ColumnExpression db params 'Ungrouped '[tab ::: row, "excluded" ::: row]) subcolumns
465− -> [Condition db '[tab ::: row, "excluded" ::: row] 'Ungrouped params]
447+ -> [Condition db params 'Ungrouped '[tab ::: row, "excluded" ::: row]]
466 -> ConflictAction tab db params columns
448 -> ConflictAction tab db params columns
467
449
468−renderConflictAction
469− :: ConflictAction tab db params columns
450+instance RenderSQL (ConflictAction tab db params columns) where
470− -> ByteString
451+ renderSQL = \case
471−renderConflictAction = \case
472− DoNothing -> "DO NOTHING"
452+ DoNothing -> "DO NOTHING"
473− DoUpdate updates whs'
453+ DoUpdate updates whs'
474− -> "DO UPDATE SET"
454+ -> "DO UPDATE SET"
475− <+> renderCommaSeparated renderColumnExpression updates
455+ <+> renderCommaSeparated renderSQL updates
476− <> case whs' of
456+ <> case whs' of
477− [] -> ""
457+ [] -> ""
478− wh:whs -> " WHERE" <+> renderExpression (foldr (.&&) wh whs)
458+ wh:whs -> " WHERE" <+> renderSQL (foldr (.&&) wh whs)
479
459
480-- | A `ConflictTarget` specifies the constraint violation that triggers a
460-- | A `ConflictTarget` specifies the constraint violation that triggers a
481-- `ConflictAction`.
461-- `ConflictAction`.
@@ -486,11 +466,9 @@ data ConflictTarget constraints where
486 -> ConflictTarget constraints
466 -> ConflictTarget constraints
487
467
488-- | Render a `ConflictTarget`
468-- | Render a `ConflictTarget`
489−renderConflictTarget
490− :: ConflictTarget constraints
469+instance RenderSQL (ConflictTarget constraints) where
491− -> ByteString
492−renderConflictTarget (OnConstraint con) =
470+ renderSQL (OnConstraint con) =
493− "ON" <+> "CONSTRAINT" <+> renderAlias con
471+ "ON" <+> "CONSTRAINT" <+> renderSQL con
494
472
495{-----------------------------------------
473{-----------------------------------------
496UPDATE statements
474UPDATE statements
@@ -500,28 +478,28 @@ UPDATE statements
500-- in all rows that satisfy the condition.
478-- in all rows that satisfy the condition.
501update
479update
502 :: ( SOP.SListI columns
480 :: ( SOP.SListI columns
503− , SOP.SListI results
481+ , SOP.SListI row1
504 , db ~ (commons :=> schemas)
482 , db ~ (commons :=> schemas)
505 , Has sch schemas schema
483 , Has sch schemas schema
506 , Has tab schema ('Table table)
484 , Has tab schema ('Table table)
507− , row ~ TableToRow table
485+ , row0 ~ TableToRow table
508 , columns ~ TableToColumns table
486 , columns ~ TableToColumns table
509 , SOP.All (HasIn columns) subcolumns
487 , SOP.All (HasIn columns) subcolumns
510 , AllUnique subcolumns )
488 , AllUnique subcolumns )
511 => QualifiedAlias sch tab -- ^ table to update
489 => QualifiedAlias sch tab -- ^ table to update
512− -> NP (ColumnExpression db '[tab ::: row] 'Ungrouped params) subcolumns
490+ -> NP (ColumnExpression db params 'Ungrouped '[tab ::: row0]) subcolumns
513 -- ^ modified values to replace old values
491 -- ^ modified values to replace old values
514− -> Condition db '[tab ::: row] 'Ungrouped params
492+ -> Condition db params 'Ungrouped '[tab ::: row0]
515 -- ^ condition under which to perform update on a row
493 -- ^ condition under which to perform update on a row
516− -> ReturningClause db params row results -- ^ results to return
494+ -> ReturningClause db params '[tab ::: row0] row1 -- ^ results to return
517− -> Manipulation db params results
495+ -> Manipulation db params row1
518update tab columns wh returning = UnsafeManipulation $
496update tab columns wh returning = UnsafeManipulation $
519 "UPDATE"
497 "UPDATE"
520− <+> renderQualifiedAlias tab
498+ <+> renderSQL tab
521 <+> "SET"
499 <+> "SET"
522− <+> renderCommaSeparated renderColumnExpression columns
500+ <+> renderCommaSeparated renderSQL columns
523− <+> "WHERE" <+> renderExpression wh
501+ <+> "WHERE" <+> renderSQL wh
524− <> renderReturningClause returning
502+ <> renderSQL returning
525
503
526-- | Update a row returning `Nil`.
504-- | Update a row returning `Nil`.
527update_
505update_
@@ -534,12 +512,12 @@ update_
534 , SOP.All (HasIn columns) subcolumns
512 , SOP.All (HasIn columns) subcolumns
535 , AllUnique subcolumns )
513 , AllUnique subcolumns )
536 => QualifiedAlias sch tab -- ^ table to update
514 => QualifiedAlias sch tab -- ^ table to update
537− -> NP (ColumnExpression db '[tab ::: row] 'Ungrouped params) subcolumns
515+ -> NP (ColumnExpression db params 'Ungrouped '[tab ::: row]) subcolumns
538 -- ^ modified values to replace old values
516 -- ^ modified values to replace old values
539− -> Condition db '[tab ::: row] 'Ungrouped params
517+ -> Condition db params 'Ungrouped '[tab ::: row]
540 -- ^ condition under which to perform update on a row
518 -- ^ condition under which to perform update on a row
541 -> Manipulation db params '[]
519 -> 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)
543
521
544{-----------------------------------------
522{-----------------------------------------
545DELETE statements
523DELETE statements
@@ -553,26 +531,26 @@ data UsingClause db params from where
553
531
554-- | Delete rows from a table.
532-- | Delete rows from a table.
555deleteFrom
533deleteFrom
556− :: ( SOP.SListI results
534+ :: ( SOP.SListI row1
557 , db ~ (commons :=> schemas)
535 , db ~ (commons :=> schemas)
558 , Has sch schemas schema
536 , Has sch schemas schema
559 , Has tab schema ('Table table)
537 , Has tab schema ('Table table)
560− , row ~ TableToRow table
538+ , row0 ~ TableToRow table
561 , columns ~ TableToColumns table )
539 , columns ~ TableToColumns table )
562 => QualifiedAlias sch tab -- ^ table to delete from
540 => QualifiedAlias sch tab -- ^ table to delete from
563 -> UsingClause db params from
541 -> UsingClause db params from
564− -> Condition db (tab ::: row ': from) 'Ungrouped params
542+ -> Condition db params 'Ungrouped (tab ::: row0 ': from)
565 -- ^ condition under which to delete a row
543 -- ^ condition under which to delete a row
566− -> ReturningClause db params row results -- ^ results to return
544+ -> ReturningClause db params '[tab ::: row0] row1 -- ^ results to return
567− -> Manipulation db params results
545+ -> Manipulation db params row1
568deleteFrom tab using wh returning = UnsafeManipulation $
546deleteFrom tab using wh returning = UnsafeManipulation $
569 "DELETE FROM"
547 "DELETE FROM"
570− <+> renderQualifiedAlias tab
548+ <+> renderSQL tab
571 <> case using of
549 <> case using of
572 NoUsing -> ""
550 NoUsing -> ""
573− Using tables -> " USING" <+> renderFromClause tables
551+ Using tables -> " USING" <+> renderSQL tables
574− <+> "WHERE" <+> renderExpression wh
552+ <+> "WHERE" <+> renderSQL wh
575− <> renderReturningClause returning
553+ <> renderSQL returning
576
554
577-- | Delete rows returning `Nil`.
555-- | Delete rows returning `Nil`.
578deleteFrom_
556deleteFrom_
@@ -583,10 +561,10 @@ deleteFrom_
583 , columns ~ TableToColumns table )
561 , columns ~ TableToColumns table )
584 => QualifiedAlias sch tab -- ^ table to delete from
562 => QualifiedAlias sch tab -- ^ table to delete from
585 -> UsingClause db params from
563 -> UsingClause db params from
586− -> Condition db (tab ::: row ': from) 'Ungrouped params
564+ -> Condition db params 'Ungrouped (tab ::: row ': from)
587 -- ^ condition under which to delete a row
565 -- ^ condition under which to delete a row
588 -> Manipulation db params '[]
566 -> 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)
590
568
591-- | This has the behaviour of a cartesian product, taking all
569-- | This has the behaviour of a cartesian product, taking all
592-- possible combinations between @left@ and @right@ - exactly like a
570-- possible combinations between @left@ and @right@ - exactly like a
@@ -600,4 +578,4 @@ also
600 -- ^ left
578 -- ^ left
601 -> FromClause schema params (Join left right)
579 -> FromClause schema params (Join left right)
602also right left = UnsafeFromClause $
580also 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
71 :: Has "migrations" schemas MigrationsSchema
71 :: Has "migrations" schemas MigrationsSchema
72 => PQ schemas schemas IO ()
72 => PQ schemas schemas IO ()
73 numMigrations = do
73 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))))
75 num <- ntuples result
75 num <- ntuples result
76 liftBase $ print num
76 liftBase $ print num
77:}
77:}
@@ -291,7 +291,7 @@ selectMigration
291 :: Has "migrations" schemas MigrationsSchema
291 :: Has "migrations" schemas MigrationsSchema
292 => Query ('[] :=> schemas) '[ 'NotNull 'PGtext ]
292 => Query ('[] :=> schemas) '[ 'NotNull 'PGtext ]
293 '[ "executed_at" ::: 'NotNull 'PGtimestamptz ]
293 '[ "executed_at" ::: 'NotNull 'PGtimestamptz ]
294−selectMigration = select
294+selectMigration = select_
295 (#executed_at `as` #executed_at)
295 (#executed_at `as` #executed_at)
296 ( from (table ((#migrations ! #schema_migrations) `as` #m))
296 ( from (table ((#migrations ! #schema_migrations) `as` #m))
297 & where_ (#name .== param @1))
297 & where_ (#name .== param @1))
squeal-postgresql/src/Squeal/PostgreSQL/Query.hs+327−312
@@ -18,7 +18,9 @@ Squeal queries.
18 , LambdaCase
18 , LambdaCase
19 , MultiParamTypeClasses
19 , MultiParamTypeClasses
20 , OverloadedStrings
20 , OverloadedStrings
21+ , ScopedTypeVariables
21 , StandaloneDeriving
22 , StandaloneDeriving
23+ , TypeApplications
22 , TypeFamilies
24 , TypeFamilies
23 , TypeInType
25 , TypeInType
24 , TypeOperators
26 , TypeOperators
@@ -28,14 +30,13 @@ Squeal queries.
28
30
29module Squeal.PostgreSQL.Query
31module Squeal.PostgreSQL.Query
30 ( -- * Queries
32 ( -- * Queries
31− Query (UnsafeQuery, renderQuery)
33+ Query (..)
32 -- ** Select
34 -- ** Select
33 , select
35 , select
36+ , select_
34 , selectDistinct
37 , selectDistinct
35− , selectStar
38+ , selectDistinct_
36− , selectDistinctStar
39+ , Selection (..)
37− , selectDotStar
38− , selectDistinctDotStar
39 -- ** Values
40 -- ** Values
40 , values
41 , values
41 , values_
42 , values_
@@ -47,7 +48,7 @@ module Squeal.PostgreSQL.Query
47 , except
48 , except
48 , exceptAll
49 , exceptAll
49 -- ** With
50 -- ** With
50− , With (with)
51+ , With (..)
51 , CommonTableExpression (..)
52 , CommonTableExpression (..)
52 , renderCommonTableExpression
53 , renderCommonTableExpression
53 , renderCommonTableExpressions
54 , renderCommonTableExpressions
@@ -68,7 +69,6 @@ module Squeal.PostgreSQL.Query
68 , jsonbToRecordSet
69 , jsonbToRecordSet
69 -- * Table Expressions
70 -- * Table Expressions
70 , TableExpression (..)
71 , TableExpression (..)
71− , renderTableExpression
72 , from
72 , from
73 , where_
73 , where_
74 , groupBy
74 , groupBy
@@ -88,15 +88,11 @@ module Squeal.PostgreSQL.Query
88 , rightOuterJoin
88 , rightOuterJoin
89 , fullOuterJoin
89 , fullOuterJoin
90 -- * Grouping
90 -- * Grouping
91− , By (By1, By2)
91+ , By (..)
92− , renderBy
93− , GroupByClause (NoGroups, Group)
92+ , GroupByClause (..)
94− , renderGroupByClause
95− , HavingClause (NoHaving, Having)
93+ , HavingClause (..)
96− , renderHavingClause
97 -- * Sorting
94 -- * Sorting
98 , SortExpression (..)
95 , SortExpression (..)
99− , renderSortExpression
100 -- * Subquery Expressions
96 -- * Subquery Expressions
101 , in_
97 , in_
102 , rowIn
98 , rowIn
@@ -150,7 +146,7 @@ simple query:
150>>> :{
146>>> :{
151let
147let
152 query :: Query (DBof (Public Schema)) '[] '["col1" ::: 'NotNull 'PGint4, "col2" ::: 'NotNull 'PGint4]
148 query :: Query (DBof (Public Schema)) '[] '["col1" ::: 'NotNull 'PGint4, "col2" ::: 'NotNull 'PGint4]
153− query = selectStar (from (table #tab))
149+ query = select Star (from (table #tab))
154in printSQL query
150in printSQL query
155:}
151:}
156SELECT * FROM "tab" AS "tab"
152SELECT * FROM "tab" AS "tab"
@@ -161,7 +157,7 @@ restricted query:
161let
157let
162 query :: Query (DBof (Public Schema)) '[] '["sum" ::: 'NotNull 'PGint4, "col1" ::: 'NotNull 'PGint4]
158 query :: Query (DBof (Public Schema)) '[] '["sum" ::: 'NotNull 'PGint4, "col1" ::: 'NotNull 'PGint4]
163 query =
159 query =
164− select ((#col1 + #col2) `as` #sum :* #col1)
160+ select_ ((#col1 + #col2) `as` #sum :* #col1)
165 ( from (table #tab)
161 ( from (table #tab)
166 & where_ (#col1 .> #col2)
162 & where_ (#col1 .> #col2)
167 & where_ (#col2 .> 0) )
163 & where_ (#col2 .> 0) )
@@ -174,7 +170,7 @@ subquery:
174>>> :{
170>>> :{
175let
171let
176 query :: Query (DBof (Public Schema)) '[] '["col1" ::: 'NotNull 'PGint4, "col2" ::: 'NotNull 'PGint4]
172 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)))
178in printSQL query
174in printSQL query
179:}
175:}
180SELECT * FROM (SELECT * FROM "tab" AS "tab") AS "sub"
176SELECT * FROM (SELECT * FROM "tab" AS "tab") AS "sub"
@@ -184,7 +180,7 @@ limits and offsets:
184>>> :{
180>>> :{
185let
181let
186 query :: Query (DBof (Public Schema)) '[] '["col1" ::: 'NotNull 'PGint4, "col2" ::: 'NotNull 'PGint4]
182 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)
188in printSQL query
184in printSQL query
189:}
185:}
190SELECT * FROM "tab" AS "tab" LIMIT 50 OFFSET 4
186SELECT * FROM "tab" AS "tab" LIMIT 50 OFFSET 4
@@ -194,7 +190,7 @@ parameterized query:
194>>> :{
190>>> :{
195let
191let
196 query :: Query (DBof (Public Schema)) '[ 'NotNull 'PGint4] '["col1" ::: 'NotNull 'PGint4, "col2" ::: 'NotNull 'PGint4]
192 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))
198in printSQL query
194in printSQL query
199:}
195:}
200SELECT * FROM "tab" AS "tab" WHERE ("col1" > ($1 :: int4))
196SELECT * FROM "tab" AS "tab" WHERE ("col1" > ($1 :: int4))
@@ -205,7 +201,7 @@ aggregation query:
205let
201let
206 query :: Query (DBof (Public Schema)) '[] '["sum" ::: 'NotNull 'PGint4, "col1" ::: 'NotNull 'PGint4 ]
202 query :: Query (DBof (Public Schema)) '[] '["sum" ::: 'NotNull 'PGint4, "col1" ::: 'NotNull 'PGint4 ]
207 query =
203 query =
208− select (sum_ #col2 `as` #sum :* #col1)
204+ select_ (sum_ #col2 `as` #sum :* #col1)
209 ( from (table (#tab `as` #table1))
205 ( from (table (#tab `as` #table1))
210 & groupBy #col1
206 & groupBy #col1
211 & having (#col1 + sum_ #col2 .> 1) )
207 & having (#col1 + sum_ #col2 .> 1) )
@@ -218,7 +214,7 @@ sorted query:
218>>> :{
214>>> :{
219let
215let
220 query :: Query (DBof (Public Schema)) '[] '["col1" ::: 'NotNull 'PGint4, "col2" ::: 'NotNull 'PGint4]
216 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])
222in printSQL query
218in printSQL query
223:}
219:}
224SELECT * FROM "tab" AS "tab" ORDER BY "col1" ASC
220SELECT * FROM "tab" AS "tab" ORDER BY "col1" ASC
@@ -260,7 +256,7 @@ let
260 , "customer_name" ::: 'NotNull 'PGtext
256 , "customer_name" ::: 'NotNull 'PGtext
261 , "shipper_name" ::: 'NotNull 'PGtext
257 , "shipper_name" ::: 'NotNull 'PGtext
262 ]
258 ]
263− query = select
259+ query = select_
264 ( #o ! #price `as` #order_price :*
260 ( #o ! #price `as` #order_price :*
265 #c ! #name `as` #customer_name :*
261 #c ! #name `as` #customer_name :*
266 #s ! #name `as` #shipper_name )
262 #s ! #name `as` #shipper_name )
@@ -278,7 +274,7 @@ self-join:
278>>> :{
274>>> :{
279let
275let
280 query :: Query (DBof (Public Schema)) '[] '["col1" ::: 'NotNull 'PGint4, "col2" ::: 'NotNull 'PGint4]
276 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))))
282in printSQL query
278in printSQL query
283:}
279:}
284SELECT "t1".* FROM "tab" AS "t1" CROSS JOIN "tab" AS "t2"
280SELECT "t1".* FROM "tab" AS "t1" CROSS JOIN "tab" AS "t2"
@@ -298,7 +294,7 @@ set operations:
298>>> :{
294>>> :{
299let
295let
300 query :: Query (DBof (Public Schema)) '[] '["col1" ::: 'NotNull 'PGint4, "col2" ::: 'NotNull 'PGint4]
296 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))
302in printSQL query
298in printSQL query
303:}
299:}
304(SELECT * FROM "tab" AS "tab") UNION ALL (SELECT * FROM "tab" AS "tab")
300(SELECT * FROM "tab" AS "tab") UNION ALL (SELECT * FROM "tab" AS "tab")
@@ -309,9 +305,9 @@ with queries:
309let
305let
310 query :: Query (DBof (Public Schema)) '[] '["col1" ::: 'NotNull 'PGint4, "col2" ::: 'NotNull 'PGint4]
306 query :: Query (DBof (Public Schema)) '[] '["col1" ::: 'NotNull 'PGint4, "col2" ::: 'NotNull 'PGint4]
311 query = with (
307 query = with (
312− selectStar (from (table #tab)) `as` #cte1 :>>
308+ select Star (from (table #tab)) `as` #cte1 :>>
313− selectStar (from (common #cte1)) `as` #cte2
309+ select Star (from (common #cte1)) `as` #cte2
314− ) (selectStar (from (common #cte2)))
310+ ) (select Star (from (common #cte2)))
315in printSQL query
311in printSQL query
316:}
312:}
317WITH "cte1" AS (SELECT * FROM "tab" AS "tab"), "cte2" AS (SELECT * FROM "cte1" AS "cte1") SELECT * FROM "cte2" AS "cte2"
313WITH "cte1" AS (SELECT * FROM "tab" AS "tab"), "cte2" AS (SELECT * FROM "cte1" AS "cte1") SELECT * FROM "cte2" AS "cte2"
@@ -331,9 +327,9 @@ union
331 -> Query db params columns
327 -> Query db params columns
332 -> Query db params columns
328 -> Query db params columns
333q1 `union` q2 = UnsafeQuery $
329q1 `union` q2 = UnsafeQuery $
334− parenthesized (renderQuery q1)
330+ parenthesized (renderSQL q1)
335 <+> "UNION"
331 <+> "UNION"
336− <+> parenthesized (renderQuery q2)
332+ <+> parenthesized (renderSQL q2)
337
333
338-- | The results of two queries can be combined using the set operation
334-- | The results of two queries can be combined using the set operation
339-- `unionAll`, the disjoint union. Duplicate rows are retained.
335-- `unionAll`, the disjoint union. Duplicate rows are retained.
@@ -342,9 +338,9 @@ unionAll
342 -> Query db params columns
338 -> Query db params columns
343 -> Query db params columns
339 -> Query db params columns
344q1 `unionAll` q2 = UnsafeQuery $
340q1 `unionAll` q2 = UnsafeQuery $
345− parenthesized (renderQuery q1)
341+ parenthesized (renderSQL q1)
346 <+> "UNION" <+> "ALL"
342 <+> "UNION" <+> "ALL"
347− <+> parenthesized (renderQuery q2)
343+ <+> parenthesized (renderSQL q2)
348
344
349-- | The results of two queries can be combined using the set operation
345-- | The results of two queries can be combined using the set operation
350-- `intersect`, the intersection. Duplicate rows are eliminated.
346-- `intersect`, the intersection. Duplicate rows are eliminated.
@@ -353,9 +349,9 @@ intersect
353 -> Query db params columns
349 -> Query db params columns
354 -> Query db params columns
350 -> Query db params columns
355q1 `intersect` q2 = UnsafeQuery $
351q1 `intersect` q2 = UnsafeQuery $
356− parenthesized (renderQuery q1)
352+ parenthesized (renderSQL q1)
357 <+> "INTERSECT"
353 <+> "INTERSECT"
358− <+> parenthesized (renderQuery q2)
354+ <+> parenthesized (renderSQL q2)
359
355
360-- | The results of two queries can be combined using the set operation
356-- | The results of two queries can be combined using the set operation
361-- `intersectAll`, the intersection. Duplicate rows are retained.
357-- `intersectAll`, the intersection. Duplicate rows are retained.
@@ -364,9 +360,9 @@ intersectAll
364 -> Query db params columns
360 -> Query db params columns
365 -> Query db params columns
361 -> Query db params columns
366q1 `intersectAll` q2 = UnsafeQuery $
362q1 `intersectAll` q2 = UnsafeQuery $
367− parenthesized (renderQuery q1)
363+ parenthesized (renderSQL q1)
368 <+> "INTERSECT" <+> "ALL"
364 <+> "INTERSECT" <+> "ALL"
369− <+> parenthesized (renderQuery q2)
365+ <+> parenthesized (renderSQL q2)
370
366
371-- | The results of two queries can be combined using the set operation
367-- | The results of two queries can be combined using the set operation
372-- `except`, the set difference. Duplicate rows are eliminated.
368-- `except`, the set difference. Duplicate rows are eliminated.
@@ -375,9 +371,9 @@ except
375 -> Query db params columns
371 -> Query db params columns
376 -> Query db params columns
372 -> Query db params columns
377q1 `except` q2 = UnsafeQuery $
373q1 `except` q2 = UnsafeQuery $
378− parenthesized (renderQuery q1)
374+ parenthesized (renderSQL q1)
379 <+> "EXCEPT"
375 <+> "EXCEPT"
380− <+> parenthesized (renderQuery q2)
376+ <+> parenthesized (renderSQL q2)
381
377
382-- | The results of two queries can be combined using the set operation
378-- | The results of two queries can be combined using the set operation
383-- `exceptAll`, the set difference. Duplicate rows are retained.
379-- `exceptAll`, the set difference. Duplicate rows are retained.
@@ -386,88 +382,109 @@ exceptAll
386 -> Query db params columns
382 -> Query db params columns
387 -> Query db params columns
383 -> Query db params columns
388q1 `exceptAll` q2 = UnsafeQuery $
384q1 `exceptAll` q2 = UnsafeQuery $
389− parenthesized (renderQuery q1)
385+ parenthesized (renderSQL q1)
390 <+> "EXCEPT" <+> "ALL"
386 <+> "EXCEPT" <+> "ALL"
391− <+> parenthesized (renderQuery q2)
387+ <+> parenthesized (renderSQL q2)
392
388
393{-----------------------------------------
389{-----------------------------------------
394SELECT queries
390SELECT queries
395-----------------------------------------}
391-----------------------------------------}
396
392
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+
397-- | the `TableExpression` in the `select` command constructs an intermediate
442-- | the `TableExpression` in the `select` command constructs an intermediate
398-- virtual table by possibly combining tables, views, eliminating rows,
443-- virtual table by possibly combining tables, views, eliminating rows,
399-- grouping, etc. This table is finally passed on to processing by
444-- 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
401-- the intermediate table are actually output.
446-- the intermediate table are actually output.
402select
447select
403− :: (SListI columns, columns ~ (col ': cols))
448+ :: (SListI row, row ~ (x ': xs))
404− => NP (Aliased (Expression db from grouping params)) columns
449+ => Selection db params grp from row
405 -- ^ select list
450 -- ^ select list
406− -> TableExpression db params from grouping
451+ -> TableExpression db params grp from
407 -- ^ intermediate virtual table
452 -- ^ intermediate virtual table
408− -> Query db params columns
453+ -> Query db params row
409−select list rels = UnsafeQuery $
454+select selection tabexpr = UnsafeQuery $
410 "SELECT"
455 "SELECT"
411− <+> renderCommaSeparated (renderAliasedAs renderExpression) list
456+ <+> renderSQL selection
412− <+> renderTableExpression rels
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)
413
465
414-- | After the select list has been processed, the result table can
466-- | After the select list has been processed, the result table can
415-- be subject to the elimination of duplicate rows using `selectDistinct`.
467-- be subject to the elimination of duplicate rows using `selectDistinct`.
416selectDistinct
468selectDistinct
417 :: (SListI columns, columns ~ (col ': cols))
469 :: (SListI columns, columns ~ (col ': cols))
418− => NP (Aliased (Expression db from 'Ungrouped params)) columns
470+ => Selection db params 'Ungrouped from columns
419 -- ^ select list
471 -- ^ select list
420− -> TableExpression db params from 'Ungrouped
472+ -> TableExpression db params 'Ungrouped from
421 -- ^ intermediate virtual table
473 -- ^ intermediate virtual table
422 -> Query db params columns
474 -> Query db params columns
423−selectDistinct list rels = UnsafeQuery $
475+selectDistinct selection tabexpr = UnsafeQuery $
424 "SELECT DISTINCT"
476 "SELECT DISTINCT"
425− <+> renderCommaSeparated (renderAliasedAs renderExpression) list
477+ <+> renderSQL selection
426− <+> renderTableExpression rels
478+ <+> renderSQL tabexpr
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
436
479
437−-- | A `selectDistinctStar` emits all columns that the table expression
480+selectDistinct_
438−-- produces and eliminates duplicate rows.
481+ :: (SListI columns, columns ~ (col ': cols))
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
482+ => NP (Aliased (Expression db params 'Ungrouped from)) columns
454− -- ^ intermediate virtual table
483+ -- ^ select list
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
484+ -> TableExpression db params 'Ungrouped from
466 -- ^ intermediate virtual table
485 -- ^ intermediate virtual table
467 -> Query db params columns
486 -> Query db params columns
468−selectDistinctDotStar rel tab = UnsafeQuery $
487+selectDistinct_ list = select (List list)
469− "SELECT DISTINCT" <+> renderAlias rel <> ".*"
470− <+> renderTableExpression tab
471
488
472-- | `values` computes a row value or set of row values
489-- | `values` computes a row value or set of row values
473-- specified by value expressions. It is most commonly used
490-- specified by value expressions. It is most commonly used
@@ -480,8 +497,8 @@ selectDistinctDotStar rel tab = UnsafeQuery $
480-- SELECT * FROM (VALUES (1, E'one')) AS t ("a", "b")
497-- SELECT * FROM (VALUES (1, E'one')) AS t ("a", "b")
481values
498values
482 :: SListI cols
499 :: SListI cols
483− => NP (Aliased (Expression db '[] 'Ungrouped params)) cols
500+ => NP (Aliased (Expression db params 'Ungrouped '[] )) cols
484− -> [NP (Aliased (Expression db '[] 'Ungrouped params)) cols]
501+ -> [NP (Aliased (Expression db params 'Ungrouped '[] )) cols]
485 -- ^ When more than one row is specified, all the rows must
502 -- ^ When more than one row is specified, all the rows must
486 -- must have the same number of elements
503 -- must have the same number of elements
487 -> Query db params cols
504 -> Query db params cols
@@ -495,15 +512,15 @@ values rw rws = UnsafeQuery $ "SELECT * FROM"
495 <+> parenthesized (renderCommaSeparated renderAliasPart rw)
512 <+> parenthesized (renderCommaSeparated renderAliasPart rw)
496 where
513 where
497 renderAliasPart, renderValuePart
514 renderAliasPart, renderValuePart
498− :: Aliased (Expression db '[] 'Ungrouped params) ty -> ByteString
515+ :: Aliased (Expression db params 'Ungrouped '[] ) ty -> ByteString
499− renderAliasPart (_ `As` name) = renderAlias name
516+ renderAliasPart (_ `As` name) = renderSQL name
500− renderValuePart (value `As` _) = renderExpression value
517+ renderValuePart (value `As` _) = renderSQL value
501
518
502-- | `values_` computes a row value or set of row values
519-- | `values_` computes a row value or set of row values
503-- specified by value expressions.
520-- specified by value expressions.
504values_
521values_
505 :: SListI cols
522 :: SListI cols
506− => NP (Aliased (Expression db '[] 'Ungrouped params)) cols
523+ => NP (Aliased (Expression db params 'Ungrouped '[] )) cols
507 -- ^ one row of values
524 -- ^ one row of values
508 -> Query db params cols
525 -> Query db params cols
509values_ rw = values rw []
526values_ rw = values rw []
@@ -521,13 +538,13 @@ Table Expressions
521data TableExpression
538data TableExpression
522 (db :: DBType)
539 (db :: DBType)
523 (params :: [NullityType])
540 (params :: [NullityType])
541+ (grp :: Grouping)
524 (from :: FromType)
542 (from :: FromType)
525− (grouping :: Grouping)
526 = TableExpression
543 = TableExpression
527 { fromClause :: FromClause db params from
544 { fromClause :: FromClause db params from
528 -- ^ A table reference that can be a table name, or a derived table such
545 -- ^ A table reference that can be a table name, or a derived table such
529 -- as a subquery, a @JOIN@ construct, or complex combinations of these.
546 -- 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]
531 -- ^ optional search coditions, combined with `.&&`. After the processing
548 -- ^ optional search coditions, combined with `.&&`. After the processing
532 -- of the `fromClause` is done, each row of the derived virtual table
549 -- of the `fromClause` is done, each row of the derived virtual table
533 -- is checked against the search condition. If the result of the
550 -- is checked against the search condition. If the result of the
@@ -536,20 +553,20 @@ data TableExpression
536 -- at least one column of the table generated in the `fromClause`;
553 -- at least one column of the table generated in the `fromClause`;
537 -- this is not required, but otherwise the WHERE clause will
554 -- this is not required, but otherwise the WHERE clause will
538 -- be fairly useless.
555 -- be fairly useless.
539− , groupByClause :: GroupByClause from grouping
556+ , groupByClause :: GroupByClause grp from
540 -- ^ The `groupByClause` is used to group together those rows in a table
557 -- ^ The `groupByClause` is used to group together those rows in a table
541 -- that have the same values in all the columns listed. The order in which
558 -- that have the same values in all the columns listed. The order in which
542 -- the columns are listed does not matter. The effect is to combine each
559 -- the columns are listed does not matter. The effect is to combine each
543 -- set of rows having common values into one group row that represents all
560 -- set of rows having common values into one group row that represents all
544 -- rows in the group. This is done to eliminate redundancy in the output
561 -- rows in the group. This is done to eliminate redundancy in the output
545 -- and/or compute aggregates that apply to these groups.
562 -- and/or compute aggregates that apply to these groups.
546− , havingClause :: HavingClause db from grouping params
563+ , havingClause :: HavingClause db params grp from
547 -- ^ If a table has been grouped using `groupBy`, but only certain groups
564 -- ^ If a table has been grouped using `groupBy`, but only certain groups
548 -- are of interest, the `havingClause` can be used, much like a
565 -- are of interest, the `havingClause` can be used, much like a
549 -- `whereClause`, to eliminate groups from the result. Expressions in the
566 -- `whereClause`, to eliminate groups from the result. Expressions in the
550 -- `havingClause` can refer both to grouped expressions and to ungrouped
567 -- `havingClause` can refer both to grouped expressions and to ungrouped
551 -- expressions (which necessarily involve an aggregate function).
568 -- expressions (which necessarily involve an aggregate function).
552− , orderByClause :: [SortExpression db from grouping params]
569+ , orderByClause :: [SortExpression db params grp from]
553 -- ^ The `orderByClause` is for optional sorting. When more than one
570 -- ^ The `orderByClause` is for optional sorting. When more than one
554 -- `SortExpression` is specified, the later (right) values are used to sort
571 -- `SortExpression` is specified, the later (right) values are used to sort
555 -- rows that are equal according to the earlier (left) values.
572 -- rows that are equal according to the earlier (left) values.
@@ -566,34 +583,32 @@ data TableExpression
566 }
583 }
567
584
568-- | Render a `TableExpression`
585-- | Render a `TableExpression`
569−renderTableExpression
570− :: TableExpression db params from grouping
586+instance RenderSQL (TableExpression db params grp from) where
571− -> ByteString
587+ renderSQL
572−renderTableExpression
573− (TableExpression frm' whs' grps' hvs' srts' lims' offs') = mconcat
588+ (TableExpression frm' whs' grps' hvs' srts' lims' offs') = mconcat
574− [ "FROM ", renderFromClause frm'
589+ [ "FROM ", renderSQL frm'
575− , renderWheres whs'
590+ , renderWheres whs'
576− , renderGroupByClause grps'
591+ , renderSQL grps'
577− , renderHavingClause hvs'
592+ , renderSQL hvs'
578− , renderOrderByClause srts'
593+ , renderOrderByClause srts'
579− , renderLimits lims'
594+ , renderLimits lims'
580− , renderOffsets offs'
595+ , renderOffsets offs'
581− ]
596+ ]
582− where
597+ where
583− renderWheres = \case
598+ renderWheres = \case
584− [] -> ""
599+ [] -> ""
585− wh:[] -> " WHERE" <+> renderExpression wh
600+ wh:[] -> " WHERE" <+> renderSQL wh
586− wh:whs -> " WHERE" <+> renderExpression (foldr (.&&) wh whs)
601+ wh:whs -> " WHERE" <+> renderSQL (foldr (.&&) wh whs)
587− renderOrderByClause = \case
602+ renderOrderByClause = \case
588− [] -> ""
603+ [] -> ""
589− srts -> " ORDER BY"
604+ srts -> " ORDER BY"
590− <+> commaSeparated (renderSortExpression <$> srts)
605+ <+> commaSeparated (renderSQL <$> srts)
591− renderLimits = \case
606+ renderLimits = \case
592− [] -> ""
607+ [] -> ""
593− lims -> " LIMIT" <+> fromString (show (minimum lims))
608+ lims -> " LIMIT" <+> fromString (show (minimum lims))
594− renderOffsets = \case
609+ renderOffsets = \case
595− [] -> ""
610+ [] -> ""
596− offs -> " OFFSET" <+> fromString (show (sum offs))
611+ offs -> " OFFSET" <+> fromString (show (sum offs))
597
612
598-- | A `from` generates a `TableExpression` from a table reference that can be
613-- | A `from` generates a `TableExpression` from a table reference that can be
599-- a table name, or a derived table such as a subquery, a JOIN construct,
614-- a table name, or a derived table such as a subquery, a JOIN construct,
@@ -602,15 +617,15 @@ renderTableExpression
602-- to match the left-to-right sequencing of their placement in SQL.
617-- to match the left-to-right sequencing of their placement in SQL.
603from
618from
604 :: FromClause db params from -- ^ table reference
619 :: FromClause db params from -- ^ table reference
605− -> TableExpression db params from 'Ungrouped
620+ -> TableExpression db params 'Ungrouped from
606from rels = TableExpression rels [] NoGroups NoHaving [] [] []
621from rels = TableExpression rels [] NoGroups NoHaving [] [] []
607
622
608-- | A `where_` is an endomorphism of `TableExpression`s which adds a
623-- | A `where_` is an endomorphism of `TableExpression`s which adds a
609-- search condition to the `whereClause`.
624-- search condition to the `whereClause`.
610where_
625where_
611− :: Condition db from 'Ungrouped params -- ^ filtering condition
626+ :: Condition db params 'Ungrouped from -- ^ filtering condition
612− -> TableExpression db params from grouping
627+ -> TableExpression db params grp from
613− -> TableExpression db params from grouping
628+ -> TableExpression db params grp from
614where_ wh rels = rels {whereClause = wh : whereClause rels}
629where_ wh rels = rels {whereClause = wh : whereClause rels}
615
630
616-- | A `groupBy` is a transformation of `TableExpression`s which switches
631-- | A `groupBy` is a transformation of `TableExpression`s which switches
@@ -619,8 +634,8 @@ where_ wh rels = rels {whereClause = wh : whereClause rels}
619groupBy
634groupBy
620 :: SListI bys
635 :: SListI bys
621 => NP (By from) bys -- ^ grouped columns
636 => NP (By from) bys -- ^ grouped columns
622− -> TableExpression db params from 'Ungrouped
637+ -> TableExpression db params 'Ungrouped from
623− -> TableExpression db params from ('Grouped bys)
638+ -> TableExpression db params ('Grouped bys) from
624groupBy bys rels = TableExpression
639groupBy bys rels = TableExpression
625 { fromClause = fromClause rels
640 { fromClause = fromClause rels
626 , whereClause = whereClause rels
641 , whereClause = whereClause rels
@@ -634,34 +649,34 @@ groupBy bys rels = TableExpression
634-- | A `having` is an endomorphism of `TableExpression`s which adds a
649-- | A `having` is an endomorphism of `TableExpression`s which adds a
635-- search condition to the `havingClause`.
650-- search condition to the `havingClause`.
636having
651having
637− :: Condition db from ('Grouped bys) params -- ^ having condition
652+ :: Condition db params ('Grouped bys) from -- ^ having condition
638− -> TableExpression db params from ('Grouped bys)
653+ -> TableExpression db params ('Grouped bys) from
639− -> TableExpression db params from ('Grouped bys)
654+ -> TableExpression db params ('Grouped bys) from
640having hv rels = rels
655having hv rels = rels
641 { havingClause = case havingClause rels of Having hvs -> Having (hv:hvs) }
656 { havingClause = case havingClause rels of Having hvs -> Having (hv:hvs) }
642
657
643-- | An `orderBy` is an endomorphism of `TableExpression`s which appends an
658-- | An `orderBy` is an endomorphism of `TableExpression`s which appends an
644-- ordering to the right of the `orderByClause`.
659-- ordering to the right of the `orderByClause`.
645orderBy
660orderBy
646− :: [SortExpression db from grouping params] -- ^ sort expressions
661+ :: [SortExpression db params grp from] -- ^ sort expressions
647− -> TableExpression db params from grouping
662+ -> TableExpression db params grp from
648− -> TableExpression db params from grouping
663+ -> TableExpression db params grp from
649orderBy srts rels = rels {orderByClause = orderByClause rels ++ srts}
664orderBy srts rels = rels {orderByClause = orderByClause rels ++ srts}
650
665
651-- | A `limit` is an endomorphism of `TableExpression`s which adds to the
666-- | A `limit` is an endomorphism of `TableExpression`s which adds to the
652-- `limitClause`.
667-- `limitClause`.
653limit
668limit
654 :: Word64 -- ^ limit parameter
669 :: Word64 -- ^ limit parameter
655− -> TableExpression db params from grouping
670+ -> TableExpression db params grp from
656− -> TableExpression db params from grouping
671+ -> TableExpression db params grp from
657limit lim rels = rels {limitClause = lim : limitClause rels}
672limit lim rels = rels {limitClause = lim : limitClause rels}
658
673
659-- | An `offset` is an endomorphism of `TableExpression`s which adds to the
674-- | An `offset` is an endomorphism of `TableExpression`s which adds to the
660-- `offsetClause`.
675-- `offsetClause`.
661offset
676offset
662 :: Word64 -- ^ offset parameter
677 :: Word64 -- ^ offset parameter
663− -> TableExpression db params from grouping
678+ -> TableExpression db params grp from
664− -> TableExpression db params from grouping
679+ -> TableExpression db params grp from
665offset off rels = rels {offsetClause = off : offsetClause rels}
680offset off rels = rels {offsetClause = off : offsetClause rels}
666
681
667{-----------------------------------------
682{-----------------------------------------
@@ -670,66 +685,66 @@ JSON stuff
670
685
671unsafeSetOfFunction
686unsafeSetOfFunction
672 :: ByteString
687 :: ByteString
673− -> Expression db '[] 'Ungrouped params ty
688+ -> Expression db params 'Ungrouped '[] ty
674 -> Query db params row
689 -> Query db params row
675unsafeSetOfFunction fun expr = UnsafeQuery $
690unsafeSetOfFunction fun expr = UnsafeQuery $
676− "SELECT * FROM " <> fun <> "(" <> renderExpression expr <> ")"
691+ "SELECT * FROM " <> fun <> "(" <> renderSQL expr <> ")"
677
692
678-- | Expands the outermost JSON object into a set of key/value pairs.
693-- | Expands the outermost JSON object into a set of key/value pairs.
679jsonEach
694jsonEach
680− :: Expression db '[] 'Ungrouped params (nullity 'PGjson) -- ^ json object
695+ :: Expression db params 'Ungrouped '[] (nullity 'PGjson) -- ^ json object
681 -> Query db params
696 -> Query db params
682 '["key" ::: 'NotNull 'PGtext, "value" ::: 'NotNull 'PGjson]
697 '["key" ::: 'NotNull 'PGtext, "value" ::: 'NotNull 'PGjson]
683jsonEach = unsafeSetOfFunction "json_each"
698jsonEach = unsafeSetOfFunction "json_each"
684
699
685-- | Expands the outermost binary JSON object into a set of key/value pairs.
700-- | Expands the outermost binary JSON object into a set of key/value pairs.
686jsonbEach
701jsonbEach
687− :: Expression db '[] 'Ungrouped params (nullity 'PGjsonb) -- ^ jsonb object
702+ :: Expression db params 'Ungrouped '[] (nullity 'PGjsonb) -- ^ jsonb object
688 -> Query db params
703 -> Query db params
689 '["key" ::: 'NotNull 'PGtext, "value" ::: 'NotNull 'PGjsonb]
704 '["key" ::: 'NotNull 'PGtext, "value" ::: 'NotNull 'PGjsonb]
690jsonbEach = unsafeSetOfFunction "jsonb_each"
705jsonbEach = unsafeSetOfFunction "jsonb_each"
691
706
692-- | Expands the outermost JSON object into a set of key/value pairs.
707-- | Expands the outermost JSON object into a set of key/value pairs.
693jsonEachAsText
708jsonEachAsText
694− :: Expression db '[] 'Ungrouped params (nullity 'PGjson) -- ^ json object
709+ :: Expression db params 'Ungrouped '[] (nullity 'PGjson) -- ^ json object
695 -> Query db params
710 -> Query db params
696 '["key" ::: 'NotNull 'PGtext, "value" ::: 'NotNull 'PGtext]
711 '["key" ::: 'NotNull 'PGtext, "value" ::: 'NotNull 'PGtext]
697jsonEachAsText = unsafeSetOfFunction "json_each_text"
712jsonEachAsText = unsafeSetOfFunction "json_each_text"
698
713
699-- | Expands the outermost binary JSON object into a set of key/value pairs.
714-- | Expands the outermost binary JSON object into a set of key/value pairs.
700jsonbEachAsText
715jsonbEachAsText
701− :: Expression db '[] 'Ungrouped params (nullity 'PGjsonb) -- ^ jsonb object
716+ :: Expression db params 'Ungrouped '[] (nullity 'PGjsonb) -- ^ jsonb object
702 -> Query db params
717 -> Query db params
703 '["key" ::: 'NotNull 'PGtext, "value" ::: 'NotNull 'PGtext]
718 '["key" ::: 'NotNull 'PGtext, "value" ::: 'NotNull 'PGtext]
704jsonbEachAsText = unsafeSetOfFunction "jsonb_each_text"
719jsonbEachAsText = unsafeSetOfFunction "jsonb_each_text"
705
720
706-- | Returns set of keys in the outermost JSON object.
721-- | Returns set of keys in the outermost JSON object.
707jsonObjectKeys
722jsonObjectKeys
708− :: Expression db '[] 'Ungrouped params (nullity 'PGjson) -- ^ json object
723+ :: Expression db params 'Ungrouped '[] (nullity 'PGjson) -- ^ json object
709 -> Query db params '["json_object_keys" ::: 'NotNull 'PGtext]
724 -> Query db params '["json_object_keys" ::: 'NotNull 'PGtext]
710jsonObjectKeys = unsafeSetOfFunction "json_object_keys"
725jsonObjectKeys = unsafeSetOfFunction "json_object_keys"
711
726
712-- | Returns set of keys in the outermost JSON object.
727-- | Returns set of keys in the outermost JSON object.
713jsonbObjectKeys
728jsonbObjectKeys
714− :: Expression db '[] 'Ungrouped params (nullity 'PGjsonb) -- ^ jsonb object
729+ :: Expression db params 'Ungrouped '[] (nullity 'PGjsonb) -- ^ jsonb object
715 -> Query db params '["jsonb_object_keys" ::: 'NotNull 'PGtext]
730 -> Query db params '["jsonb_object_keys" ::: 'NotNull 'PGtext]
716jsonbObjectKeys = unsafeSetOfFunction "jsonb_object_keys"
731jsonbObjectKeys = unsafeSetOfFunction "jsonb_object_keys"
717
732
718unsafePopulateFunction
733unsafePopulateFunction
719 :: ByteString
734 :: ByteString
720 -> TypeExpression schemas (nullity ('PGcomposite row))
735 -> TypeExpression schemas (nullity ('PGcomposite row))
721− -> Expression (commons :=> schemas) '[] 'Ungrouped params ty
736+ -> Expression (commons :=> schemas) params 'Ungrouped '[] ty
722 -> Query (commons :=> schemas) params row
737 -> Query (commons :=> schemas) params row
723unsafePopulateFunction fun ty expr = UnsafeQuery $
738unsafePopulateFunction fun ty expr = UnsafeQuery $
724 "SELECT * FROM " <> fun <> "("
739 "SELECT * FROM " <> fun <> "("
725− <> "null::" <> renderTypeExpression ty <> ", "
740+ <> "null::" <> renderSQL ty <> ", "
726− <> renderExpression expr <> ")"
741+ <> renderSQL expr <> ")"
727
742
728-- | Expands the JSON expression to a row whose columns match the record
743-- | Expands the JSON expression to a row whose columns match the record
729-- type defined by the given table.
744-- type defined by the given table.
730jsonPopulateRecord
745jsonPopulateRecord
731 :: TypeExpression schemas (nullity ('PGcomposite row)) -- ^ row type
746 :: 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
733 -> Query (commons :=> schemas) params row
748 -> Query (commons :=> schemas) params row
734jsonPopulateRecord = unsafePopulateFunction "json_populate_record"
749jsonPopulateRecord = unsafePopulateFunction "json_populate_record"
735
750
@@ -737,7 +752,7 @@ jsonPopulateRecord = unsafePopulateFunction "json_populate_record"
737-- type defined by the given table.
752-- type defined by the given table.
738jsonbPopulateRecord
753jsonbPopulateRecord
739 :: TypeExpression schemas (nullity ('PGcomposite row)) -- ^ row type
754 :: 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
741 -> Query (commons :=> schemas) params row
756 -> Query (commons :=> schemas) params row
742jsonbPopulateRecord = unsafePopulateFunction "jsonb_populate_record"
757jsonbPopulateRecord = unsafePopulateFunction "jsonb_populate_record"
743
758
@@ -745,7 +760,7 @@ jsonbPopulateRecord = unsafePopulateFunction "jsonb_populate_record"
745-- set of rows whose columns match the record type defined by the given table.
760-- set of rows whose columns match the record type defined by the given table.
746jsonPopulateRecordSet
761jsonPopulateRecordSet
747 :: TypeExpression schemas (nullity ('PGcomposite row)) -- ^ row type
762 :: 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
749 -> Query (commons :=> schemas) params row
764 -> Query (commons :=> schemas) params row
750jsonPopulateRecordSet = unsafePopulateFunction "json_populate_record_set"
765jsonPopulateRecordSet = unsafePopulateFunction "json_populate_record_set"
751
766
@@ -754,29 +769,29 @@ jsonPopulateRecordSet = unsafePopulateFunction "json_populate_record_set"
754-- table.
769-- table.
755jsonbPopulateRecordSet
770jsonbPopulateRecordSet
756 :: TypeExpression schemas (nullity ('PGcomposite row)) -- ^ row type
771 :: 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
758 -> Query (commons :=> schemas) params row
773 -> Query (commons :=> schemas) params row
759jsonbPopulateRecordSet = unsafePopulateFunction "jsonb_populate_record_set"
774jsonbPopulateRecordSet = unsafePopulateFunction "jsonb_populate_record_set"
760
775
761unsafeRecordFunction
776unsafeRecordFunction
762 :: (SListI record, json `In` PGJsonType)
777 :: (SListI record, json `In` PGJsonType)
763 => ByteString
778 => ByteString
764− -> Expression (commons :=> schemas) '[] 'Ungrouped params (nullity json)
779+ -> Expression (commons :=> schemas) params 'Ungrouped '[] (nullity json)
765 -> NP (Aliased (TypeExpression schemas)) record
780 -> NP (Aliased (TypeExpression schemas)) record
766 -> Query (commons :=> schemas) params record
781 -> Query (commons :=> schemas) params record
767unsafeRecordFunction fun expr types = UnsafeQuery $
782unsafeRecordFunction fun expr types = UnsafeQuery $
768 "SELECT * FROM " <> fun <> "("
783 "SELECT * FROM " <> fun <> "("
769− <> renderExpression expr <> ")"
784+ <> renderSQL expr <> ")"
770 <+> "AS" <+> "x" <> parenthesized (renderCommaSeparated renderTy types)
785 <+> "AS" <+> "x" <> parenthesized (renderCommaSeparated renderTy types)
771 where
786 where
772 renderTy :: Aliased (TypeExpression db) ty -> ByteString
787 renderTy :: Aliased (TypeExpression db) ty -> ByteString
773 renderTy (ty `As` alias) =
788 renderTy (ty `As` alias) =
774− renderAlias alias <+> renderTypeExpression ty
789+ renderSQL alias <+> renderSQL ty
775
790
776-- | Builds an arbitrary record from a JSON object.
791-- | Builds an arbitrary record from a JSON object.
777jsonToRecord
792jsonToRecord
778 :: SListI record
793 :: SListI record
779− => Expression (commons :=> schemas) '[] 'Ungrouped params (nullity 'PGjson) -- ^ json object
794+ => Expression (commons :=> schemas) params 'Ungrouped '[] (nullity 'PGjson) -- ^ json object
780 -> NP (Aliased (TypeExpression schemas)) record -- ^ record types
795 -> NP (Aliased (TypeExpression schemas)) record -- ^ record types
781 -> Query (commons :=> schemas) params record
796 -> Query (commons :=> schemas) params record
782jsonToRecord = unsafeRecordFunction "json_to_record"
797jsonToRecord = unsafeRecordFunction "json_to_record"
@@ -784,7 +799,7 @@ jsonToRecord = unsafeRecordFunction "json_to_record"
784-- | Builds an arbitrary record from a binary JSON object.
799-- | Builds an arbitrary record from a binary JSON object.
785jsonbToRecord
800jsonbToRecord
786 :: SListI record
801 :: SListI record
787− => Expression (commons :=> schemas) '[] 'Ungrouped params (nullity 'PGjsonb) -- ^ jsonb object
802+ => Expression (commons :=> schemas) params 'Ungrouped '[] (nullity 'PGjsonb) -- ^ jsonb object
788 -> NP (Aliased (TypeExpression schemas)) record -- ^ record types
803 -> NP (Aliased (TypeExpression schemas)) record -- ^ record types
789 -> Query (commons :=> schemas) params record
804 -> Query (commons :=> schemas) params record
790jsonbToRecord = unsafeRecordFunction "jsonb_to_record"
805jsonbToRecord = unsafeRecordFunction "jsonb_to_record"
@@ -792,7 +807,7 @@ jsonbToRecord = unsafeRecordFunction "jsonb_to_record"
792-- | Builds an arbitrary set of records from a JSON array of objects.
807-- | Builds an arbitrary set of records from a JSON array of objects.
793jsonToRecordSet
808jsonToRecordSet
794 :: SListI record
809 :: SListI record
795− => Expression (commons :=> schemas) '[] 'Ungrouped params (nullity 'PGjson) -- ^ json array
810+ => Expression (commons :=> schemas) params 'Ungrouped '[] (nullity 'PGjson) -- ^ json array
796 -> NP (Aliased (TypeExpression schemas)) record -- ^ record types
811 -> NP (Aliased (TypeExpression schemas)) record -- ^ record types
797 -> Query (commons :=> schemas) params record
812 -> Query (commons :=> schemas) params record
798jsonToRecordSet = unsafeRecordFunction "json_to_record_set"
813jsonToRecordSet = unsafeRecordFunction "json_to_record_set"
@@ -800,7 +815,7 @@ jsonToRecordSet = unsafeRecordFunction "json_to_record_set"
800-- | Builds an arbitrary set of records from a binary JSON array of objects.
815-- | Builds an arbitrary set of records from a binary JSON array of objects.
801jsonbToRecordSet
816jsonbToRecordSet
802 :: SListI record
817 :: SListI record
803− => Expression (commons :=> schemas) '[] 'Ungrouped params (nullity 'PGjsonb) -- ^ jsonb array
818+ => Expression (commons :=> schemas) params 'Ungrouped '[] (nullity 'PGjsonb) -- ^ jsonb array
804 -> NP (Aliased (TypeExpression schemas)) record -- ^ record types
819 -> NP (Aliased (TypeExpression schemas)) record -- ^ record types
805 -> Query (commons :=> schemas) params record
820 -> Query (commons :=> schemas) params record
806jsonbToRecordSet = unsafeRecordFunction "jsonb_to_record_set"
821jsonbToRecordSet = unsafeRecordFunction "jsonb_to_record_set"
@@ -816,6 +831,8 @@ as a subquery, a @JOIN@ construct, or complex combinations of these.
816newtype FromClause db params from
831newtype FromClause db params from
817 = UnsafeFromClause { renderFromClause :: ByteString }
832 = UnsafeFromClause { renderFromClause :: ByteString }
818 deriving (GHC.Generic,Show,Eq,Ord,NFData)
833 deriving (GHC.Generic,Show,Eq,Ord,NFData)
834+instance RenderSQL (FromClause db params from) where
835+ renderSQL = renderFromClause
819
836
820-- | A real `table` is a table from the database.
837-- | A real `table` is a table from the database.
821table
838table
@@ -823,13 +840,13 @@ table
823 => Aliased (QualifiedAlias sch) (alias ::: tab)
840 => Aliased (QualifiedAlias sch) (alias ::: tab)
824 -> FromClause (commons :=> schemas) params '[alias ::: TableToRow table]
841 -> FromClause (commons :=> schemas) params '[alias ::: TableToRow table]
825table (tab `As` alias) = UnsafeFromClause $
842table (tab `As` alias) = UnsafeFromClause $
826− renderQualifiedAlias tab <+> "AS" <+> renderAlias alias
843+ renderSQL tab <+> "AS" <+> renderSQL alias
827
844
828-- | `subquery` derives a table from a `Query`.
845-- | `subquery` derives a table from a `Query`.
829subquery
846subquery
830 :: Aliased (Query db params) query
847 :: Aliased (Query db params) query
831 -> FromClause db params '[query]
848 -> FromClause db params '[query]
832−subquery = UnsafeFromClause . renderAliasedAs (parenthesized . renderQuery)
849+subquery = UnsafeFromClause . renderAliased (parenthesized . renderQuery)
833
850
834-- | `view` derives a table from a `View`.
851-- | `view` derives a table from a `View`.
835view
852view
@@ -837,14 +854,14 @@ view
837 => Aliased (QualifiedAlias sch) (alias ::: vw)
854 => Aliased (QualifiedAlias sch) (alias ::: vw)
838 -> FromClause (commons :=> schemas) params '[alias ::: view]
855 -> FromClause (commons :=> schemas) params '[alias ::: view]
839view (vw `As` alias) = UnsafeFromClause $
856view (vw `As` alias) = UnsafeFromClause $
840− renderQualifiedAlias vw <+> "AS" <+> renderAlias alias
857+ renderSQL vw <+> "AS" <+> renderSQL alias
841
858
842common
859common
843 :: Has cte commons common
860 :: Has cte commons common
844 => Aliased Alias (alias ::: cte)
861 => Aliased Alias (alias ::: cte)
845 -> FromClause (commons :=> schemas) params '[alias ::: common]
862 -> FromClause (commons :=> schemas) params '[alias ::: common]
846common (cte `As` alias) = UnsafeFromClause $
863common (cte `As` alias) = UnsafeFromClause $
847− renderAlias cte <+> "AS" <+> renderAlias alias
864+ renderSQL cte <+> "AS" <+> renderSQL alias
848
865
849{- | @left & crossJoin right@. For every possible combination of rows from
866{- | @left & crossJoin right@. For every possible combination of rows from
850 @left@ and @right@ (i.e., a Cartesian product), the joined table will contain
867 @left@ and @right@ (i.e., a Cartesian product), the joined table will contain
@@ -859,7 +876,7 @@ crossJoin
859 -- ^ left
876 -- ^ left
860 -> FromClause db params (Join left right)
877 -> FromClause db params (Join left right)
861crossJoin right left = UnsafeFromClause $
878crossJoin right left = UnsafeFromClause $
862− renderFromClause left <+> "CROSS JOIN" <+> renderFromClause right
879+ renderSQL left <+> "CROSS JOIN" <+> renderSQL right
863
880
864{- | @left & innerJoin right on@. The joined table is filtered by
881{- | @left & innerJoin right on@. The joined table is filtered by
865the @on@ condition.
882the @on@ condition.
@@ -867,14 +884,14 @@ the @on@ condition.
867innerJoin
884innerJoin
868 :: FromClause db params right
885 :: FromClause db params right
869 -- ^ right
886 -- ^ right
870− -> Condition db (Join left right) 'Ungrouped params
887+ -> Condition db params 'Ungrouped (Join left right)
871 -- ^ @on@ condition
888 -- ^ @on@ condition
872 -> FromClause db params left
889 -> FromClause db params left
873 -- ^ left
890 -- ^ left
874 -> FromClause db params (Join left right)
891 -> FromClause db params (Join left right)
875innerJoin right on left = UnsafeFromClause $
892innerJoin right on left = UnsafeFromClause $
876− renderFromClause left <+> "INNER JOIN" <+> renderFromClause right
893+ renderSQL left <+> "INNER JOIN" <+> renderSQL right
877− <+> "ON" <+> renderExpression on
894+ <+> "ON" <+> renderSQL on
878
895
879{- | @left & leftOuterJoin right on@. First, an inner join is performed.
896{- | @left & leftOuterJoin right on@. First, an inner join is performed.
880 Then, for each row in @left@ that does not satisfy the @on@ condition with
897 Then, for each row in @left@ that does not satisfy the @on@ condition with
@@ -884,14 +901,14 @@ innerJoin right on left = UnsafeFromClause $
884leftOuterJoin
901leftOuterJoin
885 :: FromClause db params right
902 :: FromClause db params right
886 -- ^ right
903 -- ^ right
887− -> Condition db (Join left right) 'Ungrouped params
904+ -> Condition db params 'Ungrouped (Join left right)
888 -- ^ @on@ condition
905 -- ^ @on@ condition
889 -> FromClause db params left
906 -> FromClause db params left
890 -- ^ left
907 -- ^ left
891 -> FromClause db params (Join left (NullifyFrom right))
908 -> FromClause db params (Join left (NullifyFrom right))
892leftOuterJoin right on left = UnsafeFromClause $
909leftOuterJoin right on left = UnsafeFromClause $
893− renderFromClause left <+> "LEFT OUTER JOIN" <+> renderFromClause right
910+ renderSQL left <+> "LEFT OUTER JOIN" <+> renderSQL right
894− <+> "ON" <+> renderExpression on
911+ <+> "ON" <+> renderSQL on
895
912
896{- | @left & rightOuterJoin right on@. First, an inner join is performed.
913{- | @left & rightOuterJoin right on@. First, an inner join is performed.
897 Then, for each row in @right@ that does not satisfy the @on@ condition with
914 Then, for each row in @right@ that does not satisfy the @on@ condition with
@@ -902,14 +919,14 @@ leftOuterJoin right on left = UnsafeFromClause $
902rightOuterJoin
919rightOuterJoin
903 :: FromClause db params right
920 :: FromClause db params right
904 -- ^ right
921 -- ^ right
905− -> Condition db (Join left right) 'Ungrouped params
922+ -> Condition db params 'Ungrouped (Join left right)
906 -- ^ @on@ condition
923 -- ^ @on@ condition
907 -> FromClause db params left
924 -> FromClause db params left
908 -- ^ left
925 -- ^ left
909 -> FromClause db params (Join (NullifyFrom left) right)
926 -> FromClause db params (Join (NullifyFrom left) right)
910rightOuterJoin right on left = UnsafeFromClause $
927rightOuterJoin right on left = UnsafeFromClause $
911− renderFromClause left <+> "RIGHT OUTER JOIN" <+> renderFromClause right
928+ renderSQL left <+> "RIGHT OUTER JOIN" <+> renderSQL right
912− <+> "ON" <+> renderExpression on
929+ <+> "ON" <+> renderSQL on
913
930
914{- | @left & fullOuterJoin right on@. First, an inner join is performed.
931{- | @left & fullOuterJoin right on@. First, an inner join is performed.
915 Then, for each row in @left@ that does not satisfy the @on@ condition with
932 Then, for each row in @left@ that does not satisfy the @on@ condition with
@@ -921,15 +938,15 @@ rightOuterJoin right on left = UnsafeFromClause $
921fullOuterJoin
938fullOuterJoin
922 :: FromClause db params right
939 :: FromClause db params right
923 -- ^ right
940 -- ^ right
924− -> Condition db (Join left right) 'Ungrouped params
941+ -> Condition db params 'Ungrouped (Join left right)
925 -- ^ @on@ condition
942 -- ^ @on@ condition
926 -> FromClause db params left
943 -> FromClause db params left
927 -- ^ left
944 -- ^ left
928 -> FromClause db params
945 -> FromClause db params
929 (Join (NullifyFrom left) (NullifyFrom right))
946 (Join (NullifyFrom left) (NullifyFrom right))
930fullOuterJoin right on left = UnsafeFromClause $
947fullOuterJoin right on left = UnsafeFromClause $
931− renderFromClause left <+> "FULL OUTER JOIN" <+> renderFromClause right
948+ renderSQL left <+> "FULL OUTER JOIN" <+> renderSQL right
932− <+> "ON" <+> renderExpression on
949+ <+> "ON" <+> renderSQL on
933
950
934{-----------------------------------------
951{-----------------------------------------
935Grouping
952Grouping
@@ -955,6 +972,10 @@ data By
955deriving instance Show (By from by)
972deriving instance Show (By from by)
956deriving instance Eq (By from by)
973deriving instance Eq (By from by)
957deriving instance Ord (By from by)
974deriving 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
958
979
959instance (HasUnique rel rels cols, Has col cols ty, by ~ '(rel, col))
980instance (HasUnique rel rels cols, Has col cols ty, by ~ '(rel, col))
960 => IsLabel col (By rels by) where fromLabel = By1 fromLabel
981 => 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)])
966 => IsQualified rel col (NP (By rels) bys) where
987 => IsQualified rel col (NP (By rels) bys) where
967 rel ! col = By2 rel col :* Nil
988 rel ! col = By2 rel col :* Nil
968
989
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−
975-- | A `GroupByClause` indicates the `Grouping` of a `TableExpression`.
990-- | A `GroupByClause` indicates the `Grouping` of a `TableExpression`.
976-- A `NoGroups` indicates `Ungrouped` while a `Group` indicates `Grouped`.
991-- A `NoGroups` indicates `Ungrouped` while a `Group` indicates `Grouped`.
977-- @NoGroups@ is distinguised from @Group Nil@ since no aggregation can be
992-- @NoGroups@ is distinguised from @Group Nil@ since no aggregation can be
978-- done on @NoGroups@ while all output `Expression`s must be aggregated
993-- done on @NoGroups@ while all output `Expression`s must be aggregated
979-- in @Group Nil@. In general, all output `Expression`s in the
994-- in @Group Nil@. In general, all output `Expression`s in the
980-- complement of @bys@ must be aggregated in @Group bys@.
995-- complement of @bys@ must be aggregated in @Group bys@.
981−data GroupByClause from grouping where
996+data GroupByClause grp from where
982− NoGroups :: GroupByClause from 'Ungrouped
997+ NoGroups :: GroupByClause 'Ungrouped from
983 Group
998 Group
984 :: SListI bys
999 :: SListI bys
985 => NP (By from) bys
1000 => NP (By from) bys
986− -> GroupByClause from ('Grouped bys)
1001+ -> GroupByClause ('Grouped bys) from
987
1002
988-- | Renders a `GroupByClause`.
1003-- | Renders a `GroupByClause`.
989−renderGroupByClause :: GroupByClause from grouping -> ByteString
1004+instance RenderSQL (GroupByClause grp from) where
990−renderGroupByClause = \case
1005+ renderSQL = \case
991− NoGroups -> ""
1006+ NoGroups -> ""
992− Group Nil -> ""
1007+ Group Nil -> ""
993− Group bys -> " GROUP BY" <+> renderCommaSeparated renderBy bys
1008+ Group bys -> " GROUP BY" <+> renderCommaSeparated renderSQL bys
994
1009
995-- | A `HavingClause` is used to eliminate groups that are not of interest.
1010-- | A `HavingClause` is used to eliminate groups that are not of interest.
996-- An `Ungrouped` `TableExpression` may only use `NoHaving` while a `Grouped`
1011-- An `Ungrouped` `TableExpression` may only use `NoHaving` while a `Grouped`
997-- `TableExpression` must use `Having` whose conditions are combined with
1012-- `TableExpression` must use `Having` whose conditions are combined with
998-- `.&&`.
1013-- `.&&`.
999−data HavingClause db from grouping params where
1014+data HavingClause db params grp from where
1000− NoHaving :: HavingClause db from 'Ungrouped params
1015+ NoHaving :: HavingClause db params 'Ungrouped from
1001 Having
1016 Having
1002− :: [Condition db from ('Grouped bys) params]
1017+ :: [Condition db params ('Grouped bys) from]
1003− -> HavingClause db from ('Grouped bys) params
1018+ -> HavingClause db params ('Grouped bys) from
1004−deriving instance Show (HavingClause db from grouping params)
1019+deriving instance Show (HavingClause db params grp from)
1005−deriving instance Eq (HavingClause db from grouping params)
1020+deriving instance Eq (HavingClause db params grp from)
1006−deriving instance Ord (HavingClause db from grouping params)
1021+deriving instance Ord (HavingClause db params grp from)
1007
1022
1008-- | Render a `HavingClause`.
1023-- | Render a `HavingClause`.
1009−renderHavingClause :: HavingClause db from grouping params -> ByteString
1024+instance RenderSQL (HavingClause db params grp from) where
1010−renderHavingClause = \case
1025+ renderSQL = \case
1011− NoHaving -> ""
1026+ NoHaving -> ""
1012− Having [] -> ""
1027+ Having [] -> ""
1013− Having conditions ->
1028+ Having conditions ->
1014− " HAVING" <+> commaSeparated (renderExpression <$> conditions)
1029+ " HAVING" <+> commaSeparated (renderSQL <$> conditions)
1015
1030
1016{-----------------------------------------
1031{-----------------------------------------
1017Sorting
1032Sorting
@@ -1025,55 +1040,55 @@ Sorting
1025-- `AscNullsLast`, `DescNullsFirst` and `DescNullsLast` options are used to
1040-- `AscNullsLast`, `DescNullsFirst` and `DescNullsLast` options are used to
1026-- determine whether nulls appear before or after non-null values in the sort
1041-- determine whether nulls appear before or after non-null values in the sort
1027-- ordering of a `Null` result column.
1042-- ordering of a `Null` result column.
1028−data SortExpression db from grouping params where
1043+data SortExpression db params grp from where
1029 Asc
1044 Asc
1030− :: Expression db from grouping params ('NotNull ty)
1045+ :: Expression db params grp from ('NotNull ty)
1031− -> SortExpression db from grouping params
1046+ -> SortExpression db params grp from
1032 Desc
1047 Desc
1033− :: Expression db from grouping params ('NotNull ty)
1048+ :: Expression db params grp from ('NotNull ty)
1034− -> SortExpression db from grouping params
1049+ -> SortExpression db params grp from
1035 AscNullsFirst
1050 AscNullsFirst
1036− :: Expression db from grouping params ('Null ty)
1051+ :: Expression db params grp from ('Null ty)
1037− -> SortExpression db from grouping params
1052+ -> SortExpression db params grp from
1038 AscNullsLast
1053 AscNullsLast
1039− :: Expression db from grouping params ('Null ty)
1054+ :: Expression db params grp from ('Null ty)
1040− -> SortExpression db from grouping params
1055+ -> SortExpression db params grp from
1041 DescNullsFirst
1056 DescNullsFirst
1042− :: Expression db from grouping params ('Null ty)
1057+ :: Expression db params grp from ('Null ty)
1043− -> SortExpression db from grouping params
1058+ -> SortExpression db params grp from
1044 DescNullsLast
1059 DescNullsLast
1045− :: Expression db from grouping params ('Null ty)
1060+ :: Expression db params grp from ('Null ty)
1046− -> SortExpression db from grouping params
1061+ -> SortExpression db params grp from
1047−deriving instance Show (SortExpression db from grouping params)
1062+deriving instance Show (SortExpression db params grp from)
1048
1063
1049-- | Render a `SortExpression`.
1064-- | Render a `SortExpression`.
1050−renderSortExpression :: SortExpression db from grouping params -> ByteString
1065+instance RenderSQL (SortExpression db params grp from) where
1051−renderSortExpression = \case
1066+ renderSQL = \case
1052− Asc expression -> renderExpression expression <+> "ASC"
1067+ Asc expression -> renderSQL expression <+> "ASC"
1053− Desc expression -> renderExpression expression <+> "DESC"
1068+ Desc expression -> renderSQL expression <+> "DESC"
1054− AscNullsFirst expression -> renderExpression expression
1069+ AscNullsFirst expression -> renderSQL expression
1055− <+> "ASC NULLS FIRST"
1070+ <+> "ASC NULLS FIRST"
1056− DescNullsFirst expression -> renderExpression expression
1071+ DescNullsFirst expression -> renderSQL expression
1057− <+> "DESC NULLS FIRST"
1072+ <+> "DESC NULLS FIRST"
1058− AscNullsLast expression -> renderExpression expression <+> "ASC NULLS LAST"
1073+ AscNullsLast expression -> renderSQL expression <+> "ASC NULLS LAST"
1059− DescNullsLast expression -> renderExpression expression <+> "DESC NULLS LAST"
1074+ DescNullsLast expression -> renderSQL expression <+> "DESC NULLS LAST"
1060
1075
1061unsafeSubqueryExpression
1076unsafeSubqueryExpression
1062 :: ByteString
1077 :: ByteString
1063− -> Expression db from grp params ty
1078+ -> Expression db params grp from ty
1064 -> Query db params '[alias ::: ty]
1079 -> Query db params '[alias ::: ty]
1065− -> Expression db from grp params (nullity 'PGbool)
1080+ -> Expression db params grp from (nullity 'PGbool)
1066unsafeSubqueryExpression op x q = UnsafeExpression $
1081unsafeSubqueryExpression op x q = UnsafeExpression $
1067− renderExpression x <+> op <+> parenthesized (renderQuery q)
1082+ renderSQL x <+> op <+> parenthesized (renderSQL q)
1068
1083
1069unsafeRowSubqueryExpression
1084unsafeRowSubqueryExpression
1070 :: SListI row
1085 :: SListI row
1071 => ByteString
1086 => ByteString
1072− -> NP (Aliased (Expression db from grp params)) row
1087+ -> NP (Aliased (Expression db params grp from)) row
1073 -> Query db params row
1088 -> Query db params row
1074− -> Expression db from grp params (nullity 'PGbool)
1089+ -> Expression db params grp from (nullity 'PGbool)
1075unsafeRowSubqueryExpression op xs q = UnsafeExpression $
1090unsafeRowSubqueryExpression op xs q = UnsafeExpression $
1076− renderExpression (row xs) <+> op <+> parenthesized (renderQuery q)
1091+ renderSQL (row xs) <+> op <+> parenthesized (renderSQL q)
1077
1092
1078-- | The right-hand side is a sub`Query`, which must return exactly one column.
1093-- | The right-hand side is a sub`Query`, which must return exactly one column.
1079-- The left-hand expression is evaluated and compared to each row of the
1094-- The left-hand expression is evaluated and compared to each row of the
@@ -1084,9 +1099,9 @@ unsafeRowSubqueryExpression op xs q = UnsafeExpression $
1084-- >>> printSQL $ true `in_` values_ (true `as` #foo)
1099-- >>> printSQL $ true `in_` values_ (true `as` #foo)
1085-- TRUE IN (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1100-- TRUE IN (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1086in_
1101in_
1087− :: Expression db from grp params ty -- ^ expression
1102+ :: Expression db params grp from ty -- ^ expression
1088 -> Query db params '[alias ::: ty] -- ^ subquery
1103 -> Query db params '[alias ::: ty] -- ^ subquery
1089− -> Expression db from grp params (nullity 'PGbool)
1104+ -> Expression db params grp from (nullity 'PGbool)
1090in_ = unsafeSubqueryExpression "IN"
1105in_ = unsafeSubqueryExpression "IN"
1091
1106
1092{- | The left-hand side of this form of `rowIn` is a row constructor.
1107{- | 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.
1099The result is `false` if no equal row is found
1114The result is `false` if no equal row is found
1100(including the case where the subquery returns no rows).
1115(including the case where the subquery returns no rows).
1101
1116
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]
1103>>> printSQL $ myRow `rowIn` values_ myRow
1118>>> printSQL $ myRow `rowIn` values_ myRow
1104ROW(1, FALSE) IN (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1119ROW(1, FALSE) IN (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1105-}
1120-}
1106rowIn
1121rowIn
1107 :: SListI row
1122 :: SListI row
1108− => NP (Aliased (Expression db from grp params)) row -- ^ row constructor
1123+ => NP (Aliased (Expression db params grp from)) row -- ^ row constructor
1109 -> Query db params row -- ^ subquery
1124 -> Query db params row -- ^ subquery
1110− -> Expression db from grp params (nullity 'PGbool)
1125+ -> Expression db params grp from (nullity 'PGbool)
1111rowIn = unsafeRowSubqueryExpression "IN"
1126rowIn = unsafeRowSubqueryExpression "IN"
1112
1127
1113-- | >>> printSQL $ true `eqAll` values_ (true `as` #foo)
1128-- | >>> printSQL $ true `eqAll` values_ (true `as` #foo)
1114-- TRUE = ALL (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1129-- TRUE = ALL (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1115eqAll
1130eqAll
1116− :: Expression db from grp params ty -- ^ expression
1131+ :: Expression db params grp from ty -- ^ expression
1117 -> Query db params '[alias ::: ty] -- ^ subquery
1132 -> Query db params '[alias ::: ty] -- ^ subquery
1118− -> Expression db from grp params (nullity 'PGbool)
1133+ -> Expression db params grp from (nullity 'PGbool)
1119eqAll = unsafeSubqueryExpression "= ALL"
1134eqAll = unsafeSubqueryExpression "= ALL"
1120
1135
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]
1122-- >>> printSQL $ myRow `rowEqAll` values_ myRow
1137-- >>> printSQL $ myRow `rowEqAll` values_ myRow
1123-- ROW(1, FALSE) = ALL (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1138-- ROW(1, FALSE) = ALL (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1124rowEqAll
1139rowEqAll
1125 :: SListI row
1140 :: SListI row
1126− => NP (Aliased (Expression db from grp params)) row -- ^ row constructor
1141+ => NP (Aliased (Expression db params grp from)) row -- ^ row constructor
1127 -> Query db params row -- ^ subquery
1142 -> Query db params row -- ^ subquery
1128− -> Expression db from grp params (nullity 'PGbool)
1143+ -> Expression db params grp from (nullity 'PGbool)
1129rowEqAll = unsafeRowSubqueryExpression "= ALL"
1144rowEqAll = unsafeRowSubqueryExpression "= ALL"
1130
1145
1131-- | >>> printSQL $ true `eqAny` values_ (true `as` #foo)
1146-- | >>> printSQL $ true `eqAny` values_ (true `as` #foo)
1132-- TRUE = ANY (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1147-- TRUE = ANY (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1133eqAny
1148eqAny
1134− :: Expression db from grp params ty -- ^ expression
1149+ :: Expression db params grp from ty -- ^ expression
1135 -> Query db params '[alias ::: ty] -- ^ subquery
1150 -> Query db params '[alias ::: ty] -- ^ subquery
1136− -> Expression db from grp params (nullity 'PGbool)
1151+ -> Expression db params grp from (nullity 'PGbool)
1137eqAny = unsafeSubqueryExpression "= ANY"
1152eqAny = unsafeSubqueryExpression "= ANY"
1138
1153
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]
1140-- >>> printSQL $ myRow `rowEqAny` values_ myRow
1155-- >>> printSQL $ myRow `rowEqAny` values_ myRow
1141-- ROW(1, FALSE) = ANY (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1156-- ROW(1, FALSE) = ANY (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1142rowEqAny
1157rowEqAny
1143 :: SListI row
1158 :: SListI row
1144− => NP (Aliased (Expression db from grp params)) row -- ^ row constructor
1159+ => NP (Aliased (Expression db params grp from)) row -- ^ row constructor
1145 -> Query db params row -- ^ subquery
1160 -> Query db params row -- ^ subquery
1146− -> Expression db from grp params (nullity 'PGbool)
1161+ -> Expression db params grp from (nullity 'PGbool)
1147rowEqAny = unsafeRowSubqueryExpression "= ANY"
1162rowEqAny = unsafeRowSubqueryExpression "= ANY"
1148
1163
1149-- | >>> printSQL $ true `neqAll` values_ (true `as` #foo)
1164-- | >>> printSQL $ true `neqAll` values_ (true `as` #foo)
1150-- TRUE <> ALL (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1165-- TRUE <> ALL (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1151neqAll
1166neqAll
1152− :: Expression db from grp params ty -- ^ expression
1167+ :: Expression db params grp from ty -- ^ expression
1153 -> Query db params '[alias ::: ty] -- ^ subquery
1168 -> Query db params '[alias ::: ty] -- ^ subquery
1154− -> Expression db from grp params (nullity 'PGbool)
1169+ -> Expression db params grp from (nullity 'PGbool)
1155neqAll = unsafeSubqueryExpression "<> ALL"
1170neqAll = unsafeSubqueryExpression "<> ALL"
1156
1171
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]
1158-- >>> printSQL $ myRow `rowNeqAll` values_ myRow
1173-- >>> printSQL $ myRow `rowNeqAll` values_ myRow
1159-- ROW(1, FALSE) <> ALL (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1174-- ROW(1, FALSE) <> ALL (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1160rowNeqAll
1175rowNeqAll
1161 :: SListI row
1176 :: SListI row
1162− => NP (Aliased (Expression db from grp params)) row -- ^ row constructor
1177+ => NP (Aliased (Expression db params grp from)) row -- ^ row constructor
1163 -> Query db params row -- ^ subquery
1178 -> Query db params row -- ^ subquery
1164− -> Expression db from grp params (nullity 'PGbool)
1179+ -> Expression db params grp from (nullity 'PGbool)
1165rowNeqAll = unsafeRowSubqueryExpression "<> ALL"
1180rowNeqAll = unsafeRowSubqueryExpression "<> ALL"
1166
1181
1167-- | >>> printSQL $ true `neqAny` values_ (true `as` #foo)
1182-- | >>> printSQL $ true `neqAny` values_ (true `as` #foo)
1168-- TRUE <> ANY (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1183-- TRUE <> ANY (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1169neqAny
1184neqAny
1170− :: Expression db from grp params ty -- ^ expression
1185+ :: Expression db params grp from ty -- ^ expression
1171 -> Query db params '[alias ::: ty] -- ^ subquery
1186 -> Query db params '[alias ::: ty] -- ^ subquery
1172− -> Expression db from grp params (nullity 'PGbool)
1187+ -> Expression db params grp from (nullity 'PGbool)
1173neqAny = unsafeSubqueryExpression "<> ANY"
1188neqAny = unsafeSubqueryExpression "<> ANY"
1174
1189
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]
1176-- >>> printSQL $ myRow `rowNeqAny` values_ myRow
1191-- >>> printSQL $ myRow `rowNeqAny` values_ myRow
1177-- ROW(1, FALSE) <> ANY (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1192-- ROW(1, FALSE) <> ANY (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1178rowNeqAny
1193rowNeqAny
1179 :: SListI row
1194 :: SListI row
1180− => NP (Aliased (Expression db from grp params)) row -- ^ row constructor
1195+ => NP (Aliased (Expression db params grp from)) row -- ^ row constructor
1181 -> Query db params row -- ^ subquery
1196 -> Query db params row -- ^ subquery
1182− -> Expression db from grp params (nullity 'PGbool)
1197+ -> Expression db params grp from (nullity 'PGbool)
1183rowNeqAny = unsafeRowSubqueryExpression "<> ANY"
1198rowNeqAny = unsafeRowSubqueryExpression "<> ANY"
1184
1199
1185-- | >>> printSQL $ true `allLt` values_ (true `as` #foo)
1200-- | >>> printSQL $ true `allLt` values_ (true `as` #foo)
1186-- TRUE ALL < (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1201-- TRUE ALL < (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1187allLt
1202allLt
1188− :: Expression db from grp params ty -- ^ expression
1203+ :: Expression db params grp from ty -- ^ expression
1189 -> Query db params '[alias ::: ty] -- ^ subquery
1204 -> Query db params '[alias ::: ty] -- ^ subquery
1190− -> Expression db from grp params (nullity 'PGbool)
1205+ -> Expression db params grp from (nullity 'PGbool)
1191allLt = unsafeSubqueryExpression "ALL <"
1206allLt = unsafeSubqueryExpression "ALL <"
1192
1207
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]
1194-- >>> printSQL $ myRow `rowLtAll` values_ myRow
1209-- >>> printSQL $ myRow `rowLtAll` values_ myRow
1195-- ROW(1, FALSE) ALL < (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1210-- ROW(1, FALSE) ALL < (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1196rowLtAll
1211rowLtAll
1197 :: SListI row
1212 :: SListI row
1198− => NP (Aliased (Expression db from grp params)) row -- ^ row constructor
1213+ => NP (Aliased (Expression db params grp from)) row -- ^ row constructor
1199 -> Query db params row -- ^ subquery
1214 -> Query db params row -- ^ subquery
1200− -> Expression db from grp params (nullity 'PGbool)
1215+ -> Expression db params grp from (nullity 'PGbool)
1201rowLtAll = unsafeRowSubqueryExpression "ALL <"
1216rowLtAll = unsafeRowSubqueryExpression "ALL <"
1202
1217
1203-- | >>> printSQL $ true `ltAny` values_ (true `as` #foo)
1218-- | >>> printSQL $ true `ltAny` values_ (true `as` #foo)
1204-- TRUE ANY < (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1219-- TRUE ANY < (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1205ltAny
1220ltAny
1206− :: Expression db from grp params ty -- ^ expression
1221+ :: Expression db params grp from ty -- ^ expression
1207 -> Query db params '[alias ::: ty] -- ^ subquery
1222 -> Query db params '[alias ::: ty] -- ^ subquery
1208− -> Expression db from grp params (nullity 'PGbool)
1223+ -> Expression db params grp from (nullity 'PGbool)
1209ltAny = unsafeSubqueryExpression "ANY <"
1224ltAny = unsafeSubqueryExpression "ANY <"
1210
1225
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]
1212-- >>> printSQL $ myRow `rowLtAll` values_ myRow
1227-- >>> printSQL $ myRow `rowLtAll` values_ myRow
1213-- ROW(1, FALSE) ALL < (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1228-- ROW(1, FALSE) ALL < (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1214rowLtAny
1229rowLtAny
1215 :: SListI row
1230 :: SListI row
1216− => NP (Aliased (Expression db from grp params)) row -- ^ row constructor
1231+ => NP (Aliased (Expression db params grp from)) row -- ^ row constructor
1217 -> Query db params row -- ^ subquery
1232 -> Query db params row -- ^ subquery
1218− -> Expression db from grp params (nullity 'PGbool)
1233+ -> Expression db params grp from (nullity 'PGbool)
1219rowLtAny = unsafeRowSubqueryExpression "ANY <"
1234rowLtAny = unsafeRowSubqueryExpression "ANY <"
1220
1235
1221-- | >>> printSQL $ true `lteAll` values_ (true `as` #foo)
1236-- | >>> printSQL $ true `lteAll` values_ (true `as` #foo)
1222-- TRUE <= ALL (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1237-- TRUE <= ALL (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1223lteAll
1238lteAll
1224− :: Expression db from grp params ty -- ^ expression
1239+ :: Expression db params grp from ty -- ^ expression
1225 -> Query db params '[alias ::: ty] -- ^ subquery
1240 -> Query db params '[alias ::: ty] -- ^ subquery
1226− -> Expression db from grp params (nullity 'PGbool)
1241+ -> Expression db params grp from (nullity 'PGbool)
1227lteAll = unsafeSubqueryExpression "<= ALL"
1242lteAll = unsafeSubqueryExpression "<= ALL"
1228
1243
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]
1230-- >>> printSQL $ myRow `rowLteAll` values_ myRow
1245-- >>> printSQL $ myRow `rowLteAll` values_ myRow
1231-- ROW(1, FALSE) <= ALL (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1246-- ROW(1, FALSE) <= ALL (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1232rowLteAll
1247rowLteAll
1233 :: SListI row
1248 :: SListI row
1234− => NP (Aliased (Expression db from grp params)) row -- ^ row constructor
1249+ => NP (Aliased (Expression db params grp from)) row -- ^ row constructor
1235 -> Query db params row -- ^ subquery
1250 -> Query db params row -- ^ subquery
1236− -> Expression db from grp params (nullity 'PGbool)
1251+ -> Expression db params grp from (nullity 'PGbool)
1237rowLteAll = unsafeRowSubqueryExpression "<= ALL"
1252rowLteAll = unsafeRowSubqueryExpression "<= ALL"
1238
1253
1239-- | >>> printSQL $ true `lteAny` values_ (true `as` #foo)
1254-- | >>> printSQL $ true `lteAny` values_ (true `as` #foo)
1240-- TRUE <= ANY (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1255-- TRUE <= ANY (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1241lteAny
1256lteAny
1242− :: Expression db from grp params ty -- ^ expression
1257+ :: Expression db params grp from ty -- ^ expression
1243 -> Query db params '[alias ::: ty] -- ^ subquery
1258 -> Query db params '[alias ::: ty] -- ^ subquery
1244− -> Expression db from grp params (nullity 'PGbool)
1259+ -> Expression db params grp from (nullity 'PGbool)
1245lteAny = unsafeSubqueryExpression "<= ANY"
1260lteAny = unsafeSubqueryExpression "<= ANY"
1246
1261
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]
1248-- >>> printSQL $ myRow `rowLteAny` values_ myRow
1263-- >>> printSQL $ myRow `rowLteAny` values_ myRow
1249-- ROW(1, FALSE) <= ANY (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1264-- ROW(1, FALSE) <= ANY (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1250rowLteAny
1265rowLteAny
1251 :: SListI row
1266 :: SListI row
1252− => NP (Aliased (Expression db from grp params)) row -- ^ row constructor
1267+ => NP (Aliased (Expression db params grp from)) row -- ^ row constructor
1253 -> Query db params row -- ^ subquery
1268 -> Query db params row -- ^ subquery
1254− -> Expression db from grp params (nullity 'PGbool)
1269+ -> Expression db params grp from (nullity 'PGbool)
1255rowLteAny = unsafeRowSubqueryExpression "<= ANY"
1270rowLteAny = unsafeRowSubqueryExpression "<= ANY"
1256
1271
1257-- | >>> printSQL $ true `gtAll` values_ (true `as` #foo)
1272-- | >>> printSQL $ true `gtAll` values_ (true `as` #foo)
1258-- TRUE > ALL (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1273-- TRUE > ALL (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1259gtAll
1274gtAll
1260− :: Expression db from grp params ty -- ^ expression
1275+ :: Expression db params grp from ty -- ^ expression
1261 -> Query db params '[alias ::: ty] -- ^ subquery
1276 -> Query db params '[alias ::: ty] -- ^ subquery
1262− -> Expression db from grp params (nullity 'PGbool)
1277+ -> Expression db params grp from (nullity 'PGbool)
1263gtAll = unsafeSubqueryExpression "> ALL"
1278gtAll = unsafeSubqueryExpression "> ALL"
1264
1279
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]
1266-- >>> printSQL $ myRow `rowGtAll` values_ myRow
1281-- >>> printSQL $ myRow `rowGtAll` values_ myRow
1267-- ROW(1, FALSE) > ALL (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1282-- ROW(1, FALSE) > ALL (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1268rowGtAll
1283rowGtAll
1269 :: SListI row
1284 :: SListI row
1270− => NP (Aliased (Expression db from grp params)) row -- ^ row constructor
1285+ => NP (Aliased (Expression db params grp from)) row -- ^ row constructor
1271 -> Query db params row -- ^ subquery
1286 -> Query db params row -- ^ subquery
1272− -> Expression db from grp params (nullity 'PGbool)
1287+ -> Expression db params grp from (nullity 'PGbool)
1273rowGtAll = unsafeRowSubqueryExpression "> ALL"
1288rowGtAll = unsafeRowSubqueryExpression "> ALL"
1274
1289
1275-- | >>> printSQL $ true `gtAny` values_ (true `as` #foo)
1290-- | >>> printSQL $ true `gtAny` values_ (true `as` #foo)
1276-- TRUE > ANY (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1291-- TRUE > ANY (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1277gtAny
1292gtAny
1278− :: Expression db from grp params ty -- ^ expression
1293+ :: Expression db params grp from ty -- ^ expression
1279 -> Query db params '[alias ::: ty] -- ^ subquery
1294 -> Query db params '[alias ::: ty] -- ^ subquery
1280− -> Expression db from grp params (nullity 'PGbool)
1295+ -> Expression db params grp from (nullity 'PGbool)
1281gtAny = unsafeSubqueryExpression "> ANY"
1296gtAny = unsafeSubqueryExpression "> ANY"
1282
1297
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]
1284-- >>> printSQL $ myRow `rowGtAny` values_ myRow
1299-- >>> printSQL $ myRow `rowGtAny` values_ myRow
1285-- ROW(1, FALSE) > ANY (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1300-- ROW(1, FALSE) > ANY (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1286rowGtAny
1301rowGtAny
1287 :: SListI row
1302 :: SListI row
1288− => NP (Aliased (Expression db from grp params)) row -- ^ row constructor
1303+ => NP (Aliased (Expression db params grp from)) row -- ^ row constructor
1289 -> Query db params row -- ^ subquery
1304 -> Query db params row -- ^ subquery
1290− -> Expression db from grp params (nullity 'PGbool)
1305+ -> Expression db params grp from (nullity 'PGbool)
1291rowGtAny = unsafeRowSubqueryExpression "> ANY"
1306rowGtAny = unsafeRowSubqueryExpression "> ANY"
1292
1307
1293-- | >>> printSQL $ true `gteAll` values_ (true `as` #foo)
1308-- | >>> printSQL $ true `gteAll` values_ (true `as` #foo)
1294-- TRUE >= ALL (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1309-- TRUE >= ALL (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1295gteAll
1310gteAll
1296− :: Expression db from grp params ty -- ^ expression
1311+ :: Expression db params grp from ty -- ^ expression
1297 -> Query db params '[alias ::: ty] -- ^ subquery
1312 -> Query db params '[alias ::: ty] -- ^ subquery
1298− -> Expression db from grp params (nullity 'PGbool)
1313+ -> Expression db params grp from (nullity 'PGbool)
1299gteAll = unsafeSubqueryExpression ">= ALL"
1314gteAll = unsafeSubqueryExpression ">= ALL"
1300
1315
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]
1302-- >>> printSQL $ myRow `rowGteAll` values_ myRow
1317-- >>> printSQL $ myRow `rowGteAll` values_ myRow
1303-- ROW(1, FALSE) >= ALL (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1318-- ROW(1, FALSE) >= ALL (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1304rowGteAll
1319rowGteAll
1305 :: SListI row
1320 :: SListI row
1306− => NP (Aliased (Expression db from grp params)) row -- ^ row constructor
1321+ => NP (Aliased (Expression db params grp from)) row -- ^ row constructor
1307 -> Query db params row -- ^ subquery
1322 -> Query db params row -- ^ subquery
1308− -> Expression db from grp params (nullity 'PGbool)
1323+ -> Expression db params grp from (nullity 'PGbool)
1309rowGteAll = unsafeRowSubqueryExpression ">= ALL"
1324rowGteAll = unsafeRowSubqueryExpression ">= ALL"
1310
1325
1311-- | >>> printSQL $ true `gteAny` values_ (true `as` #foo)
1326-- | >>> printSQL $ true `gteAny` values_ (true `as` #foo)
1312-- TRUE >= ANY (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1327-- TRUE >= ANY (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1313gteAny
1328gteAny
1314− :: Expression db from grp params ty -- ^ expression
1329+ :: Expression db params grp from ty -- ^ expression
1315 -> Query db params '[alias ::: ty] -- ^ subquery
1330 -> Query db params '[alias ::: ty] -- ^ subquery
1316− -> Expression db from grp params (nullity 'PGbool)
1331+ -> Expression db params grp from (nullity 'PGbool)
1317gteAny = unsafeSubqueryExpression ">= ANY"
1332gteAny = unsafeSubqueryExpression ">= ANY"
1318
1333
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]
1320-- >>> printSQL $ myRow `rowGteAny` values_ myRow
1335-- >>> printSQL $ myRow `rowGteAny` values_ myRow
1321-- ROW(1, FALSE) >= ANY (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1336-- ROW(1, FALSE) >= ANY (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1322rowGteAny
1337rowGteAny
1323 :: SListI row
1338 :: SListI row
1324− => NP (Aliased (Expression db from grp params)) row -- ^ row constructor
1339+ => NP (Aliased (Expression db params grp from)) row -- ^ row constructor
1325 -> Query db params row -- ^ subquery
1340 -> Query db params row -- ^ subquery
1326− -> Expression db from grp params (nullity 'PGbool)
1341+ -> Expression db params grp from (nullity 'PGbool)
1327rowGteAny = unsafeRowSubqueryExpression ">= ANY"
1342rowGteAny = unsafeRowSubqueryExpression ">= ANY"
1328
1343
1329-- | A `CommonTableExpression` is an auxiliary statement in a `with` clause.
1344-- | A `CommonTableExpression` is an auxiliary statement in a `with` clause.
@@ -1358,7 +1373,7 @@ renderCommonTableExpression
1358 -> CommonTableExpression statement params db0 db1 -> ByteString
1373 -> CommonTableExpression statement params db0 db1 -> ByteString
1359renderCommonTableExpression renderStatement
1374renderCommonTableExpression renderStatement
1360 (CommonTableExpression (statement `As` alias)) =
1375 (CommonTableExpression (statement `As` alias)) =
1361− renderAlias alias <+> "AS" <+> parenthesized (renderStatement statement)
1376+ renderSQL alias <+> "AS" <+> parenthesized (renderStatement statement)
1362
1377
1363-- | render a non-empty `AlignedList` of `CommonTableExpression`s.
1378-- | render a non-empty `AlignedList` of `CommonTableExpression`s.
1364renderCommonTableExpressions
1379renderCommonTableExpressions
@@ -1385,5 +1400,5 @@ class With statement where
1385instance With Query where
1400instance With Query where
1386 with Done query = query
1401 with Done query = query
1387 with (cte :>> ctes) query = UnsafeQuery $
1402 with (cte :>> ctes) query = UnsafeQuery $
1388− "WITH" <+> renderCommonTableExpressions renderQuery cte ctes
1403+ "WITH" <+> renderCommonTableExpressions renderSQL cte ctes
1389− <+> renderQuery query
1404+ <+> renderSQL query
squeal-postgresql/src/Squeal/PostgreSQL/Schema.hs+31−46
@@ -68,12 +68,9 @@ module Squeal.PostgreSQL.Schema
68 , (:::)
68 , (:::)
69 , Alias (..)
69 , Alias (..)
70 , IsLabel (..)
70 , IsLabel (..)
71− , renderAlias
72− , renderAliasString
73− , renderAliases
74 , Aliased (As)
71 , Aliased (As)
75 , Aliasable (as)
72 , Aliasable (as)
76− , renderAliasedAs
73+ , renderAliased
77 , Has
74 , Has
78 , HasUnique
75 , HasUnique
79 , HasAll
76 , HasAll
@@ -83,12 +80,9 @@ module Squeal.PostgreSQL.Schema
83 , IsNotElem
80 , IsNotElem
84 , AllUnique
81 , AllUnique
85 , DefaultAliasable (..)
82 , DefaultAliasable (..)
86− , renderQualifiedAlias
87 -- * Enumerated Labels
83 -- * Enumerated Labels
88 , IsPGlabel (..)
84 , IsPGlabel (..)
89 , PGlabel (..)
85 , PGlabel (..)
90− , renderLabel
91− , renderLabels
92 , LabelsPG
86 , LabelsPG
93 -- * Grouping
87 -- * Grouping
94 , Grouping (..)
88 , Grouping (..)
@@ -377,25 +371,19 @@ instance alias1 ~ alias2 => IsLabel alias1 (Alias alias2) where
377 fromLabel = Alias
371 fromLabel = Alias
378instance aliases ~ '[alias] => IsLabel alias (NP Alias aliases) where
372instance aliases ~ '[alias] => IsLabel alias (NP Alias aliases) where
379 fromLabel = fromLabel :* Nil
373 fromLabel = fromLabel :* Nil
374+-- | >>> printSQL (#jimbob :: Alias "jimbob")
375+-- "jimbob"
380−instance KnownSymbol alias => RenderSQL (Alias alias) where renderSQL = renderAlias
376+instance KnownSymbol alias => RenderSQL (Alias alias) where
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
377+ renderSQL = doubleQuoted . fromString . symbolVal
391
378
392-- | >>> import Generics.SOP (NP(..))
379-- | >>> import Generics.SOP (NP(..))
393−-- >>> renderAliases (#jimbob :* #kandi)
380+-- >>> printSQL (#jimbob :* #kandi :: NP Alias '["jimbob", "kandi"])
394−-- ["\"jimbob\"","\"kandi\""]
381+-- "jimbob", "kandi"
395−renderAliases
396− :: All KnownSymbol aliases => NP Alias aliases -> [ByteString]
382+instance All KnownSymbol aliases => RenderSQL (NP Alias aliases) where
383+ renderSQL
384+ = commaSeparated
397−renderAliases = hcollapse
385+ . hcollapse
398− . hcmap (Proxy @KnownSymbol) (K . renderAlias)
386+ . hcmap (Proxy @KnownSymbol) (K . renderSQL)
399
387
400-- | The `As` operator is used to name an expression. `As` is like a demoted
388-- | The `As` operator is used to name an expression. `As` is like a demoted
401-- version of `:::`.
389-- version of `:::`.
@@ -436,14 +424,14 @@ instance (KnownSymbol alias, tys ~ '[alias ::: ty]) => Aliasable alias
436 expression `as` alias = expression `As` alias :* Nil
424 expression `as` alias = expression `As` alias :* Nil
437
425
438-- | >>> let renderMaybe = fromString . maybe "Nothing" (const "Just")
426-- | >>> 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)
440-- "Just AS \"an_int\""
428-- "Just AS \"an_int\""
441−renderAliasedAs
429+renderAliased
442 :: (forall ty. expression ty -> ByteString)
430 :: (forall ty. expression ty -> ByteString)
443 -> Aliased expression aliased
431 -> Aliased expression aliased
444 -> ByteString
432 -> ByteString
445−renderAliasedAs render (expression `As` alias) =
433+renderAliased render (expression `As` alias) =
446− render expression <> " AS " <> renderAlias alias
434+ render expression <> " AS " <> renderSQL alias
447
435
448-- | @HasUnique alias fields field@ is a constraint that proves that
436-- | @HasUnique alias fields field@ is a constraint that proves that
449-- @fields@ is a singleton of @alias ::: field@.
437-- @fields@ is a singleton of @alias ::: field@.
@@ -514,15 +502,14 @@ instance (q ~ "public", a0 ~ a1, a1 ~ a2, KnownSymbol a2) =>
514 IsLabel a0 (Aliased (QualifiedAlias q) (a1 ::: a2)) where
502 IsLabel a0 (Aliased (QualifiedAlias q) (a1 ::: a2)) where
515 fromLabel = QualifiedAlias `As` Alias
503 fromLabel = QualifiedAlias `As` Alias
516
504
517−renderQualifiedAlias
518− :: forall q a. (KnownSymbol q, KnownSymbol a)
505+instance (KnownSymbol q, KnownSymbol a)
519− => QualifiedAlias q a -> ByteString
506+ => RenderSQL (QualifiedAlias q a) where
520−renderQualifiedAlias _ =
507+ renderSQL _ =
521− let
508+ let
522− qualifier = renderAlias (Alias @q)
509+ qualifier = renderSQL (Alias @q)
523− alias = renderAlias (Alias @a)
510+ alias = renderSQL (Alias @a)
524− in
511+ in
525− if qualifier == "\"public\"" then alias else qualifier <> "." <> alias
512+ if qualifier == "\"public\"" then alias else qualifier <> "." <> alias
526
513
527-- | @Elem@ is a promoted `Data.List.elem`.
514-- | @Elem@ is a promoted `Data.List.elem`.
528type family Elem x xs where
515type family Elem x xs where
@@ -730,15 +717,13 @@ instance labels ~ '[label]
730 => IsPGlabel label (NP PGlabel labels) where label = PGlabel :* Nil
717 => IsPGlabel label (NP PGlabel labels) where label = PGlabel :* Nil
731-- | A `PGlabel` unit type with an `IsPGlabel` instance
718-- | A `PGlabel` unit type with an `IsPGlabel` instance
732data PGlabel (label :: Symbol) = PGlabel
719data PGlabel (label :: Symbol) = PGlabel
733−-- | Renders a label
734−renderLabel :: KnownSymbol label => proxy label -> ByteString
720+instance KnownSymbol label => RenderSQL (PGlabel label) where
735−renderLabel (_ :: proxy label) =
736− "\'" <> renderSymbol @label <> "\'"
721+ renderSQL _ = "\'" <> renderSymbol @label <> "\'"
737−-- | Renders a list of labels
738−renderLabels
739− :: All KnownSymbol labels => NP PGlabel labels -> [ByteString]
722+instance All KnownSymbol labels => RenderSQL (NP PGlabel labels) where
723+ renderSQL
724+ = commaSeparated
740−renderLabels = hcollapse
725+ . hcollapse
741− . hcmap (Proxy @KnownSymbol) (K . renderLabel)
726+ . hcmap (Proxy @KnownSymbol) (K . renderSQL)
742
727
743{- | The `PG` type family embeds a subset of Haskell types
728{- | The `PG` type family embeds a subset of Haskell types
744as Postgres types. As an open type family, `PG` is extensible.
729as 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
30 , defaultMode
30 , defaultMode
31 , longRunningMode
31 , longRunningMode
32 , IsolationLevel (..)
32 , IsolationLevel (..)
33− , renderIsolationLevel
34 , AccessMode (..)
33 , AccessMode (..)
35− , renderAccessMode
36 , DeferrableMode (..)
34 , DeferrableMode (..)
37− , renderDeferrableMode
38 ) where
35 ) where
39
36
40import Control.Exception.Lifted
37import Control.Exception.Lifted
41import Control.Monad.Base
38import Control.Monad.Base
42import Control.Monad.Trans.Control
39import Control.Monad.Trans.Control
43−import Data.ByteString
44import Generics.SOP
40import Generics.SOP
45
41
46import qualified Database.PostgreSQL.LibPQ as LibPQ
42import qualified Database.PostgreSQL.LibPQ as LibPQ
@@ -72,7 +68,7 @@ transactionally_ = transactionally defaultMode
72-- | @BEGIN@ a transaction.
68-- | @BEGIN@ a transaction.
73begin :: MonadPQ schemas tx => TransactionMode -> tx (K Result ('[] :: RowType))
69begin :: MonadPQ schemas tx => TransactionMode -> tx (K Result ('[] :: RowType))
74begin mode = manipulate . UnsafeManipulation $
70begin mode = manipulate . UnsafeManipulation $
75− "BEGIN" <+> renderTransactionMode mode <> ";"
71+ "BEGIN" <+> renderSQL mode <> ";"
76
72
77-- | @COMMIT@ a schema invariant transaction.
73-- | @COMMIT@ a schema invariant transaction.
78commit :: MonadPQ schemas tx => tx (K Result ('[] :: RowType))
74commit :: MonadPQ schemas tx => tx (K Result ('[] :: RowType))
@@ -90,7 +86,7 @@ transactionallySchema
90 -> PQ schemas0 schemas1 io x
86 -> PQ schemas0 schemas1 io x
91transactionallySchema mode u = PQ $ \ conn -> mask $ \ restore -> do
87transactionallySchema mode u = PQ $ \ conn -> mask $ \ restore -> do
92 _ <- liftBase . LibPQ.exec (unK conn) $
88 _ <- liftBase . LibPQ.exec (unK conn) $
93− "BEGIN" <+> renderTransactionMode mode <> ";"
89+ "BEGIN" <+> renderSQL mode <> ";"
94 x <- restore (unPQ u conn)
90 x <- restore (unPQ u conn)
95 `onException` (liftBase (LibPQ.exec (unK conn) "ROLLBACK"))
91 `onException` (liftBase (LibPQ.exec (unK conn) "ROLLBACK"))
96 _ <- liftBase $ LibPQ.exec (unK conn) "COMMIT"
92 _ <- liftBase $ LibPQ.exec (unK conn) "COMMIT"
@@ -123,12 +119,12 @@ longRunningMode :: TransactionMode
123longRunningMode = TransactionMode Serializable ReadOnly Deferrable
119longRunningMode = TransactionMode Serializable ReadOnly Deferrable
124
120
125-- | Render a `TransactionMode`.
121-- | Render a `TransactionMode`.
126−renderTransactionMode :: TransactionMode -> ByteString
122+instance RenderSQL TransactionMode where
127−renderTransactionMode mode =
123+ renderSQL mode =
128− "ISOLATION LEVEL"
124+ "ISOLATION LEVEL"
129− <+> renderIsolationLevel (isolationLevel mode)
125+ <+> renderSQL (isolationLevel mode)
130− <+> renderAccessMode (accessMode mode)
126+ <+> renderSQL (accessMode mode)
131− <+> renderDeferrableMode (deferrableMode mode)
127+ <+> renderSQL (deferrableMode mode)
132
128
133-- | The SQL standard defines four levels of transaction isolation.
129-- | The SQL standard defines four levels of transaction isolation.
134-- The most strict is `Serializable`, which is defined by the standard in a paragraph
130-- The most strict is `Serializable`, which is defined by the standard in a paragraph
@@ -179,12 +175,12 @@ data IsolationLevel
179 deriving (Show, Eq)
175 deriving (Show, Eq)
180
176
181-- | Render an `IsolationLevel`.
177-- | Render an `IsolationLevel`.
182−renderIsolationLevel :: IsolationLevel -> ByteString
178+instance RenderSQL IsolationLevel where
183−renderIsolationLevel = \case
179+ renderSQL = \case
184− Serializable -> "SERIALIZABLE"
180+ Serializable -> "SERIALIZABLE"
185− ReadCommitted -> "READ COMMITTED"
181+ ReadCommitted -> "READ COMMITTED"
186− ReadUncommitted -> "READ UNCOMMITTED"
182+ ReadUncommitted -> "READ UNCOMMITTED"
187− RepeatableRead -> "REPEATABLE READ"
183+ RepeatableRead -> "REPEATABLE READ"
188
184
189-- | The transaction access mode determines whether the transaction is `ReadWrite` or `ReadOnly`.
185-- | The transaction access mode determines whether the transaction is `ReadWrite` or `ReadOnly`.
190-- `ReadWrite` is the default. When a transaction is `ReadOnly`,
186-- `ReadWrite` is the default. When a transaction is `ReadOnly`,
@@ -201,10 +197,10 @@ data AccessMode
201 deriving (Show, Eq)
197 deriving (Show, Eq)
202
198
203-- | Render an `AccessMode`.
199-- | Render an `AccessMode`.
204−renderAccessMode :: AccessMode -> ByteString
200+instance RenderSQL AccessMode where
205−renderAccessMode = \case
201+ renderSQL = \case
206− ReadWrite -> "READ WRITE"
202+ ReadWrite -> "READ WRITE"
207− ReadOnly -> "READ ONLY"
203+ ReadOnly -> "READ ONLY"
208
204
209-- | The `Deferrable` transaction property has no effect
205-- | The `Deferrable` transaction property has no effect
210-- unless the transaction is also `Serializable` and `ReadOnly`.
206-- unless the transaction is also `Serializable` and `ReadOnly`.
@@ -220,7 +216,7 @@ data DeferrableMode
220 deriving (Show, Eq)
216 deriving (Show, Eq)
221
217
222-- | Render a `DeferrableMode`.
218-- | Render a `DeferrableMode`.
223−renderDeferrableMode :: DeferrableMode -> ByteString
219+instance RenderSQL DeferrableMode where
224−renderDeferrableMode = \case
220+ renderSQL = \case
225− Deferrable -> "DEFERRABLE"
221+ Deferrable -> "DEFERRABLE"
226− NotDeferrable -> "NOT DEFERRABLE"
222+ NotDeferrable -> "NOT DEFERRABLE"