on dev help sign in
Merge pull request #75 from morphismtech/dev-commons-schemas

multi-schema support

commit33d155003598051c65fbb0aa6988d4ad809f4212 authorEitan Chatav <eitan.chatav@gmail.com> dateWed 5 Dec 2018, 09:56 (8 years ago) parent7ff3dbea82907e
14 files changed+1347−1288
squeal-postgresql/exe/Example.hs+10−6 squeal-postgresql/squeal-postgresql.cabal+1−1 squeal-postgresql/src/Squeal/PostgreSQL.hs+23−22 squeal-postgresql/src/Squeal/PostgreSQL/Binary.hs+5−5 squeal-postgresql/src/Squeal/PostgreSQL/Definition.hs+220−171 squeal-postgresql/src/Squeal/PostgreSQL/Expression.hs+386−383 squeal-postgresql/src/Squeal/PostgreSQL/Manipulation.hs+137−155 squeal-postgresql/src/Squeal/PostgreSQL/Migration.hs+48−45 squeal-postgresql/src/Squeal/PostgreSQL/PQ.hs+86−86 squeal-postgresql/src/Squeal/PostgreSQL/Pool.hs+18−18 squeal-postgresql/src/Squeal/PostgreSQL/Query.hs+352−378 squeal-postgresql/src/Squeal/PostgreSQL/Schema.hs+41−3 squeal-postgresql/src/Squeal/PostgreSQL/Transaction.hs+9−9 squeal-postgresql/test/Specs/ExceptionHandling.hs+11−6
squeal-postgresql/exe/Example.hs+10−6
@@ -41,7 +41,11 @@ type Schema =
4141 ])
4242 ]
4343
44−setup :: Definition '[] Schema
44+type Schemas = Public Schema
45+
46+type DB = DBof Schemas
47+
48+setup :: Definition (Public '[]) Schemas
4549setup =
4650 createTable #users
4751 ( serial `as` #id :*
@@ -57,23 +61,23 @@ setup =
5761 foreignKey #user_id #users #id
5862 OnDeleteCascade OnUpdateCascade `as` #fk_user_id )
5963
60−teardown :: Definition Schema '[]
64+teardown :: Definition Schemas (Public '[])
6165teardown = dropTable #emails >>> dropTable #users
6266
63−insertUser :: Manipulation Schema '[ 'NotNull 'PGtext, 'NotNull ('PGvararray ('Null 'PGint2))]
67+insertUser :: Manipulation DB '[ 'NotNull 'PGtext, 'NotNull ('PGvararray ('Null 'PGint2))]
6468 '[ "fromOnly" ::: 'NotNull 'PGint4 ]
6569insertUser = insertRows #users
6670 (Default `as` #id :* Set (param @1) `as` #name :* Set (param @2) `as` #vec) []
6771 OnConflictDoNothing (Returning (#id `as` #fromOnly))
6872
69−insertEmail :: Manipulation Schema '[ 'NotNull 'PGint4, 'Null 'PGtext] '[]
73+insertEmail :: Manipulation DB '[ 'NotNull 'PGint4, 'Null 'PGtext] '[]
7074insertEmail = insertRows #emails
7175 ( Default `as` #id :*
7276 Set (param @1) `as` #user_id :*
7377 Set (param @2) `as` #email ) []
7478 OnConflictDoNothing (Returning Nil)
7579
76−getUsers :: Query Schema '[]
80+getUsers :: Query DB '[]
7781 '[ "userName" ::: 'NotNull 'PGtext
7882 , "userEmail" ::: 'Null 'PGtext
7983 , "userVec" ::: 'NotNull ('PGvararray ('Null 'PGint2))]
@@ -95,7 +99,7 @@ users =
9599 , User "Carole" (Just "carole@hotmail.com") [Just 3]
96100 ]
97101
98−session :: (MonadBase IO pq, MonadPQ Schema pq) => pq ()
102+session :: (MonadBase IO pq, MonadPQ Schemas pq) => pq ()
99103session = do
100104 liftBase $ Char8.putStrLn "manipulating"
101105 idResults <- traversePrepared insertUser ([(userName user, userVec user) | user <- users])
squeal-postgresql/squeal-postgresql.cabal+1−1
@@ -1,5 +1,5 @@
11name: squeal-postgresql
2−version: 0.4.0.0
2+version: 0.4.9.0
33synopsis: Squeal PostgreSQL Library
44description: Squeal is a type-safe embedding of PostgreSQL in Haskell
55homepage: https://github.com/morphismtech/squeal
squeal-postgresql/src/Squeal/PostgreSQL.hs+23−22
@@ -32,26 +32,27 @@ The first step is to define the schema of our database. This is where
3232we use @DataKinds@ and @TypeOperators@.
3333
3434>>> :{
35+type UsersColumns =
36+ '[ "id" ::: 'Def :=> 'NotNull 'PGint4
37+ , "name" ::: 'NoDef :=> 'NotNull 'PGtext ]
38+type UsersConstraints = '[ "pk_users" ::: 'PrimaryKey '["id"] ]
39+type EmailsColumns =
40+ '[ "id" ::: 'Def :=> 'NotNull 'PGint4
41+ , "user_id" ::: 'NoDef :=> 'NotNull 'PGint4
42+ , "email" ::: 'NoDef :=> 'Null 'PGtext ]
43+type EmailsConstraints =
44+ '[ "pk_emails" ::: 'PrimaryKey '["id"]
45+ , "fk_user_id" ::: 'ForeignKey '["user_id"] "users" '["id"] ]
3546type Schema =
36− '[ "users" ::: 'Table (
37− '[ "pk_users" ::: 'PrimaryKey '["id"] ] :=>
38− '[ "id" ::: 'Def :=> 'NotNull 'PGint4
39− , "name" ::: 'NoDef :=> 'NotNull 'PGtext
40− ])
41− , "emails" ::: 'Table (
42− '[ "pk_emails" ::: 'PrimaryKey '["id"]
43− , "fk_user_id" ::: 'ForeignKey '["user_id"] "users" '["id"]
44− ] :=>
45− '[ "id" ::: 'Def :=> 'NotNull 'PGint4
46− , "user_id" ::: 'NoDef :=> 'NotNull 'PGint4
47− , "email" ::: 'NoDef :=> 'Null 'PGtext
48− ])
49− ]
47+ '[ "users" ::: 'Table (UsersConstraints :=> UsersColumns)
48+ , "emails" ::: 'Table (EmailsConstraints :=> EmailsColumns) ]
49+type Schemas = Public Schema
50+type DB = DBof Schemas
5051:}
5152
5253Notice the use of type operators.
5354
54−`:::` is used to pair an alias `GHC.TypeLits.Symbol` with a `SchemumType`,
55+`:::` is used to pair an alias `GHC.TypeLits.Symbol` with a `SchemasType`, a `SchemumType`,
5556a `TableConstraint` or a `ColumnType`. It is intended to connote Haskell's @::@
5657operator.
5758
@@ -68,7 +69,7 @@ labels to refer to named tables and columns in our schema.
6869
6970>>> :{
7071let
71− setup :: Definition '[] Schema
72+ setup :: Definition (Public '[]) Schemas
7273 setup =
7374 createTable #users
7475 ( serial `as` #id :*
@@ -89,14 +90,14 @@ We can easily see the generated SQL is unsurprising looking.
8990CREATE TABLE "users" ("id" serial, "name" text NOT NULL, CONSTRAINT "pk_users" PRIMARY KEY ("id"));
9091CREATE TABLE "emails" ("id" serial, "user_id" int NOT NULL, "email" text NULL, CONSTRAINT "pk_emails" PRIMARY KEY ("id"), CONSTRAINT "fk_user_id" FOREIGN KEY ("user_id") REFERENCES "users" ("id") ON DELETE CASCADE ON UPDATE CASCADE);
9192
92−Notice that @setup@ starts with an empty schema @'[]@ and produces @Schema@.
93+Notice that @setup@ starts with an empty public schema @(Public '[])@ and produces @Schemas@.
9394In our `createTable` commands we included `TableConstraint`s to define
9495primary and foreign keys, making them somewhat complex. Our @teardown@
9596`Definition` is simpler.
9697
9798>>> :{
9899let
99− teardown :: Definition Schema '[]
100+ teardown :: Definition Schemas (Public '[])
100101 teardown = dropTable #emails >>> dropTable #users
101102:}
102103
@@ -117,7 +118,7 @@ of our inserts.
117118
118119>>> :{
119120let
120− insertUser :: Manipulation Schema '[ 'NotNull 'PGtext ] '[ "fromOnly" ::: 'NotNull 'PGint4 ]
121+ insertUser :: Manipulation DB '[ 'NotNull 'PGtext ] '[ "fromOnly" ::: 'NotNull 'PGint4 ]
121122 insertUser = insertRow #users
122123 (Default `as` #id :* Set (param @1) `as` #name)
123124 OnConflictDoNothing (Returning (#id `as` #fromOnly))
@@ -125,7 +126,7 @@ let
125126
126127>>> :{
127128let
128− insertEmail :: Manipulation Schema '[ 'NotNull 'PGint4, 'Null 'PGtext] '[]
129+ insertEmail :: Manipulation DB '[ 'NotNull 'PGint4, 'Null 'PGtext] '[]
129130 insertEmail = insertRow #emails
130131 ( Default `as` #id :*
131132 Set (param @1) `as` #user_id :*
@@ -145,7 +146,7 @@ need to use an inner join to get the right result. A `Query` is like a
145146
146147>>> :{
147148let
148− getUsers :: Query Schema '[]
149+ getUsers :: Query DB '[]
149150 '[ "userName" ::: 'NotNull 'PGtext
150151 , "userEmail" ::: 'Null 'PGtext ]
151152 getUsers = select
@@ -190,7 +191,7 @@ transformer and when the schema doesn't change we can use `Monad` and
190191
191192>>> :{
192193let
193− session :: PQ Schema Schema IO ()
194+ session :: PQ Schemas Schemas IO ()
194195 session = do
195196 idResults <- traversePrepared insertUser (Only . userName <$> users)
196197 ids <- traverse (fmap fromOnly . getRow 0) idResults
squeal-postgresql/src/Squeal/PostgreSQL/Binary.hs+5−5
@@ -27,7 +27,7 @@ round trip query.
2727>>> instance HasDatatypeInfo Row
2828>>> :{
2929let
30− roundTrip :: Query '[] (TuplePG Row) (RowPG Row)
30+ roundTrip :: Query (DBof (Public '[])) (TuplePG Row) (RowPG Row)
3131 roundTrip = values_ $
3232 parameter @1 int2 `as` #col1 :*
3333 parameter @2 text `as` #col2 :*
@@ -68,7 +68,7 @@ Once again, we define a simple round trip query.
6868
6969>>> :{
7070let
71− roundTrip :: Query '[] (TuplePG Row) (RowPG Row)
71+ roundTrip :: Query (DBof (Public '[])) (TuplePG Row) (RowPG Row)
7272 roundTrip = values_ $
7373 parameter @1 (int2 & vararray) `as` #col1 :*
7474 parameter @2 (int2 & fixarray @2) `as` #col2 :*
@@ -114,7 +114,7 @@ type Schema =
114114
115115>>> :{
116116let
117− setup :: Definition '[] Schema
117+ setup :: Definition (Public '[]) (Public Schema)
118118 setup =
119119 createTypeEnumFrom @Schwarma #schwarma >>>
120120 createTypeCompositeFrom @Person #person
@@ -146,7 +146,7 @@ Once again, define a round trip query.
146146
147147>>> :{
148148let
149− roundTrip :: Query Schema (TuplePG Row) (RowPG Row)
149+ roundTrip :: Query (DBof (Public Schema)) (TuplePG Row) (RowPG Row)
150150 roundTrip = values_ $
151151 parameter @1 (typedef #schwarma) `as` #schwarma :*
152152 parameter @2 (typedef #person) `as` #person1 :*
@@ -157,7 +157,7 @@ Finally, we can drop our type definitions.
157157
158158>>> :{
159159let
160− teardown :: Definition Schema '[]
160+ teardown :: Definition (Public Schema) (Public '[])
161161 teardown = dropType #schwarma >>> dropType #person
162162:}
163163
squeal-postgresql/src/Squeal/PostgreSQL/Definition.hs+220−171
@@ -33,6 +33,8 @@ module Squeal.PostgreSQL.Definition
3333 , (>>>)
3434 -- * Tables
3535 -- ** Create
36+ , createSchema
37+ , createSchemaIfNotExists
3638 , createTable
3739 , createTableIfNotExists
3840 , TableConstraintExpression (..)
@@ -104,16 +106,16 @@ import Squeal.PostgreSQL.Schema
104106statements
105107-----------------------------------------}
106108
107−-- | A `Definition` is a statement that changes the schema of the
109+-- | A `Definition` is a statement that changes the schemas of the
108110-- database, like a `createTable`, `dropTable`, or `alterTable` command.
109111-- `Definition`s may be composed using the `>>>` operator.
110112newtype Definition
111− (schema0 :: SchemaType)
112− (schema1 :: SchemaType)
113+ (schemas0 :: SchemasType)
114+ (schemas1 :: SchemasType)
113115 = UnsafeDefinition { renderDefinition :: ByteString }
114116 deriving (GHC.Generic,Show,Eq,Ord,NFData)
115117
116−instance RenderSQL (Definition schema0 schema1) where
118+instance RenderSQL (Definition schemas0 schemas1) where
117119 renderSQL = renderDefinition
118120
119121instance Category Definition where
@@ -125,6 +127,21 @@ instance Category Definition where
125127CREATE statements
126128-----------------------------------------}
127129
130+createSchema
131+ :: KnownSymbol sch
132+ => Alias sch
133+ -> Definition schemas (Create sch '[] schemas)
134+createSchema sch = UnsafeDefinition $
135+ "CREATE" <+> "SCHEMA" <+> renderAlias sch <> ";"
136+
137+createSchemaIfNotExists
138+ :: (KnownSymbol sch, Has sch schemas schema)
139+ => Alias sch
140+ -> Definition schemas schemas
141+createSchemaIfNotExists sch = UnsafeDefinition $
142+ "CREATE" <+> "SCHEMA" <+> "IF" <+> "NOT" <+> "EXISTS"
143+ <+> renderAlias sch <> ";"
144+
128145{- | `createTable` adds a table to the schema.
129146
130147>>> :set -XOverloadedLabels
@@ -136,7 +153,7 @@ type Table = '[] :=>
136153
137154>>> :{
138155let
139− setup :: Definition '[] '["tab" ::: 'Table Table]
156+ setup :: Definition (Public '[]) (Public '["tab" ::: 'Table Table])
140157 setup = createTable #tab
141158 (nullable int `as` #a :* nullable real `as` #b) Nil
142159in printSQL setup
@@ -144,17 +161,19 @@ in printSQL setup
144161CREATE TABLE "tab" ("a" int NULL, "b" real NULL);
145162-}
146163createTable
147− :: ( KnownSymbol table
164+ :: ( KnownSymbol sch
165+ , KnownSymbol tab
148166 , columns ~ (col ': cols)
149167 , SOP.SListI columns
150168 , SOP.SListI constraints
151− , schema1 ~ Create table ('Table (constraints :=> columns)) schema0 )
152− => Alias table -- ^ the name of the table to add
153− -> NP (Aliased (ColumnTypeExpression schema0)) columns
169+ , Has sch schemas0 schema0
170+ , schemas1 ~ Alter sch (Create tab ('Table (constraints :=> columns)) schema0) schemas0 )
171+ => QualifiedAlias sch tab -- ^ the name of the table to add
172+ -> NP (Aliased (ColumnTypeExpression schemas0)) columns
154173 -- ^ the names and datatype of each column
155− -> NP (Aliased (TableConstraintExpression schema1 table)) constraints
174+ -> NP (Aliased (TableConstraintExpression sch tab schemas1)) constraints
156175 -- ^ constraints that must hold for the table
157− -> Definition schema0 schema1
176+ -> Definition schemas0 schemas1
158177createTable tab columns constraints = UnsafeDefinition $
159178 "CREATE TABLE" <+> renderCreation tab columns constraints
160179
@@ -170,11 +189,11 @@ type Table = '[] :=>
170189 , "b" ::: 'NoDef :=> 'Null 'PGfloat4 ]
171190:}
172191
173−>>> type Schema = '["tab" ::: 'Table Table]
192+>>> type Schemas = Public '["tab" ::: 'Table Table]
174193
175194>>> :{
176195let
177− setup :: Definition Schema Schema
196+ setup :: Definition Schemas Schemas
178197 setup = createTableIfNotExists #tab
179198 (nullable int `as` #a :* nullable real `as` #b) Nil
180199in printSQL setup
@@ -182,31 +201,33 @@ in printSQL setup
182201CREATE TABLE IF NOT EXISTS "tab" ("a" int NULL, "b" real NULL);
183202-}
184203createTableIfNotExists
185− :: ( Has table schema ('Table (constraints :=> columns))
204+ :: ( Has sch schemas schema
205+ , Has tab schema ('Table (constraints :=> columns))
186206 , SOP.SListI columns
187207 , SOP.SListI constraints )
188− => Alias table -- ^ the name of the table to add
189− -> NP (Aliased (ColumnTypeExpression schema)) columns
208+ => QualifiedAlias sch tab -- ^ the name of the table to add
209+ -> NP (Aliased (ColumnTypeExpression schemas)) columns
190210 -- ^ the names and datatype of each column
191− -> NP (Aliased (TableConstraintExpression schema table)) constraints
211+ -> NP (Aliased (TableConstraintExpression sch tab schemas)) constraints
192212 -- ^ constraints that must hold for the table
193− -> Definition schema schema
213+ -> Definition schemas schemas
194214createTableIfNotExists tab columns constraints = UnsafeDefinition $
195215 "CREATE TABLE IF NOT EXISTS"
196216 <+> renderCreation tab columns constraints
197217
198218-- helper function for `createTable` and `createTableIfNotExists`
199219renderCreation
200− :: ( KnownSymbol table
220+ :: ( KnownSymbol sch
221+ , KnownSymbol tab
201222 , SOP.SListI columns
202223 , SOP.SListI constraints )
203− => Alias table -- ^ the name of the table to add
204− -> NP (Aliased (ColumnTypeExpression schema0)) columns
224+ => QualifiedAlias sch tab -- ^ the name of the table to add
225+ -> NP (Aliased (ColumnTypeExpression schemas0)) columns
205226 -- ^ the names and datatype of each column
206− -> NP (Aliased (TableConstraintExpression schema1 table)) constraints
227+ -> NP (Aliased (TableConstraintExpression sch tab schemas1)) constraints
207228 -- ^ constraints that must hold for the table
208229 -> ByteString
209−renderCreation tab columns constraints = renderAlias tab
230+renderCreation tab columns constraints = renderQualifiedAlias tab
210231 <+> parenthesized
211232 ( renderCommaSeparated renderColumnDef columns
212233 <> ( case constraints of
@@ -215,11 +236,11 @@ renderCreation tab columns constraints = renderAlias tab
215236 renderCommaSeparated renderConstraint constraints ) )
216237 <> ";"
217238 where
218− renderColumnDef :: Aliased (ColumnTypeExpression schema) x -> ByteString
239+ renderColumnDef :: Aliased (ColumnTypeExpression schemas) x -> ByteString
219240 renderColumnDef (ty `As` column) =
220241 renderAlias column <+> renderColumnTypeExpression ty
221242 renderConstraint
222− :: Aliased (TableConstraintExpression schema columns) constraint
243+ :: Aliased (TableConstraintExpression sch tab schemas) constraint
223244 -> ByteString
224245 renderConstraint (constraint `As` alias) =
225246 "CONSTRAINT" <+> renderAlias alias <+> renderTableConstraintExpression constraint
@@ -237,9 +258,10 @@ renderCreation tab columns constraints = renderAlias tab
237258-- violate a constraint, an error is raised. This applies
238259-- even if the value came from the default value definition.
239260newtype TableConstraintExpression
240− (schema :: SchemaType)
241− (table :: Symbol)
242− (tableConstraint :: TableConstraint)
261+ (sch :: Symbol)
262+ (tab :: Symbol)
263+ (schemas :: SchemasType)
264+ (constraint :: TableConstraint)
243265 = UnsafeTableConstraintExpression
244266 { renderTableConstraintExpression :: ByteString }
245267 deriving (GHC.Generic,Show,Eq,Ord,NFData)
@@ -258,7 +280,7 @@ type Schema = '[
258280
259281>>> :{
260282let
261− definition :: Definition '[] Schema
283+ definition :: Definition (Public '[]) (Public Schema)
262284 definition = createTable #tab
263285 ( (int & notNullable) `as` #a :*
264286 (int & notNullable) `as` #b )
@@ -269,13 +291,14 @@ let
269291CREATE TABLE "tab" ("a" int NOT NULL, "b" int NOT NULL, CONSTRAINT "inequality" CHECK (("a" > "b")));
270292-}
271293check
272− :: ( Has alias schema ('Table table)
294+ :: ( Has sch schemas schema
295+ , Has tab schema ('Table table)
273296 , HasAll aliases (TableToRow table) subcolumns )
274297 => NP Alias aliases
275298 -- ^ specify the subcolumns which are getting checked
276− -> (forall tab. Condition schema '[tab ::: subcolumns] 'Ungrouped '[])
299+ -> (forall t. Condition ('[] :=> schemas) '[t ::: subcolumns] 'Ungrouped '[])
277300 -- ^ a closed `Condition` on those subcolumns
278− -> TableConstraintExpression schema alias ('Check aliases)
301+ -> TableConstraintExpression sch tab schemas ('Check aliases)
279302check _cols condition = UnsafeTableConstraintExpression $
280303 "CHECK" <+> parenthesized (renderExpression condition)
281304
@@ -292,7 +315,7 @@ type Schema = '[
292315
293316>>> :{
294317let
295− definition :: Definition '[] Schema
318+ definition :: Definition (Public '[]) (Public Schema)
296319 definition = createTable #tab
297320 ( (int & nullable) `as` #a :*
298321 (int & nullable) `as` #b )
@@ -303,11 +326,12 @@ let
303326CREATE TABLE "tab" ("a" int NULL, "b" int NULL, CONSTRAINT "uq_a_b" UNIQUE ("a", "b"));
304327-}
305328unique
306− :: ( Has alias schema ('Table table)
329+ :: ( Has sch schemas schema
330+ , Has tab schema('Table table)
307331 , HasAll aliases (TableToRow table) subcolumns )
308332 => NP Alias aliases
309333 -- ^ specify subcolumns which together are unique for each row
310− -> TableConstraintExpression schema alias ('Unique aliases)
334+ -> TableConstraintExpression sch tab schemas ('Unique aliases)
311335unique columns = UnsafeTableConstraintExpression $
312336 "UNIQUE" <+> parenthesized (commaSeparated (renderAliases columns))
313337
@@ -325,7 +349,7 @@ type Schema = '[
325349
326350>>> :{
327351let
328− definition :: Definition '[] Schema
352+ definition :: Definition (Public '[]) (Public Schema)
329353 definition = createTable #tab
330354 ( serial `as` #id :*
331355 (text & notNullable) `as` #name )
@@ -336,12 +360,13 @@ let
336360CREATE TABLE "tab" ("id" serial, "name" text NOT NULL, CONSTRAINT "pk_id" PRIMARY KEY ("id"));
337361-}
338362primaryKey
339− :: ( Has alias schema ('Table table)
363+ :: ( Has sch schemas schema
364+ , Has tab schema ('Table table)
340365 , HasAll aliases (TableToColumns table) subcolumns
341366 , AllNotNull subcolumns )
342367 => NP Alias aliases
343368 -- ^ specify the subcolumns which together form a primary key.
344− -> TableConstraintExpression schema alias ('PrimaryKey aliases)
369+ -> TableConstraintExpression sch tab schemas ('PrimaryKey aliases)
345370primaryKey columns = UnsafeTableConstraintExpression $
346371 "PRIMARY KEY" <+> parenthesized (commaSeparated (renderAliases columns))
347372
@@ -370,7 +395,7 @@ type Schema =
370395
371396>>> :{
372397let
373− setup :: Definition '[] Schema
398+ setup :: Definition (Public '[]) (Public Schema)
374399 setup =
375400 createTable #users
376401 ( serial `as` #id :*
@@ -405,7 +430,7 @@ type Schema =
405430
406431>>> :{
407432let
408− setup :: Definition '[] Schema
433+ setup :: Definition (Public '[]) (Public Schema)
409434 setup =
410435 createTable #employees
411436 ( serial `as` #id :*
@@ -419,7 +444,7 @@ in printSQL setup
419444CREATE TABLE "employees" ("id" serial, "name" text NOT NULL, "employer_id" integer NULL, CONSTRAINT "employees_pk" PRIMARY KEY ("id"), CONSTRAINT "employees_employer_fk" FOREIGN KEY ("employer_id") REFERENCES "employees" ("id") ON DELETE CASCADE ON UPDATE CASCADE);
420445-}
421446foreignKey
422− :: (ForeignKeyed schema child parent
447+ :: (ForeignKeyed schemas sch schema child parent
423448 table reftable
424449 columns refcolumns
425450 constraints cols
@@ -434,7 +459,7 @@ foreignKey
434459 -- ^ what to do when reference is deleted
435460 -> OnUpdateClause
436461 -- ^ what to do when reference is updated
437− -> TableConstraintExpression schema child
462+ -> TableConstraintExpression sch child schemas
438463 ('ForeignKey columns parent refcolumns)
439464foreignKey keys parent refs ondel onupd = UnsafeTableConstraintExpression $
440465 "FOREIGN KEY" <+> parenthesized (commaSeparated (renderAliases keys))
@@ -444,13 +469,16 @@ foreignKey keys parent refs ondel onupd = UnsafeTableConstraintExpression $
444469 <+> renderOnUpdateClause onupd
445470
446471-- | A constraint synonym between types involved in a foreign key constraint.
447−type ForeignKeyed schema
472+type ForeignKeyed schemas
473+ sch
474+ schema
448475 child parent
449476 table reftable
450477 columns refcolumns
451478 constraints cols
452479 reftys tys =
453− ( Has child schema ('Table table)
480+ ( Has sch schemas schema
481+ , Has child schema ('Table table)
454482 , Has parent schema ('Table reftable)
455483 , HasAll columns (TableToColumns table) tys
456484 , reftable ~ (constraints :=> cols)
@@ -505,17 +533,18 @@ DROP statements
505533--
506534-- >>> :{
507535-- let
508−-- definition :: Definition '["muh_table" ::: 'Table t] '[]
536+-- definition :: Definition '["public" ::: '["muh_table" ::: 'Table t]] (Public '[])
509537-- definition = dropTable #muh_table
510538-- :}
511539--
512540-- >>> printSQL definition
513541-- DROP TABLE "muh_table";
514542dropTable
515− :: Has table schema ('Table t)
516− => Alias table -- ^ table to remove
517− -> Definition schema (Drop table schema)
518−dropTable tab = UnsafeDefinition $ "DROP TABLE" <+> renderAlias tab <> ";"
543+ :: ( Has sch schemas schema
544+ , Has tab schema ('Table table))
545+ => QualifiedAlias sch tab -- ^ table to remove
546+ -> Definition schemas (Alter sch (Drop tab schema) schemas)
547+dropTable tab = UnsafeDefinition $ "DROP TABLE" <+> renderQualifiedAlias tab <> ";"
519548
520549{-----------------------------------------
521550ALTER statements
@@ -523,13 +552,13 @@ ALTER statements
523552
524553-- | `alterTable` changes the definition of a table from the schema.
525554alterTable
526− :: KnownSymbol alias
527− => Alias alias -- ^ table to alter
528− -> AlterTable alias table schema -- ^ alteration to perform
529− -> Definition schema (Alter alias ('Table table) schema)
555+ :: (Has sch schemas schema, Has tab schema ('Table table0))
556+ => QualifiedAlias sch tab -- ^ table to alter
557+ -> AlterTable sch tab schemas table1 -- ^ alteration to perform
558+ -> Definition schemas (Alter sch (Alter tab ('Table table1) schema) schemas)
530559alterTable tab alteration = UnsafeDefinition $
531560 "ALTER TABLE"
532− <+> renderAlias tab
561+ <+> renderQualifiedAlias tab
533562 <+> renderAlterTable alteration
534563 <> ";"
535564
@@ -549,9 +578,10 @@ alterTableRename table0 table1 = UnsafeDefinition $
549578-- | An `AlterTable` describes the alteration to perform on the columns
550579-- of a table.
551580newtype AlterTable
552− (alias :: Symbol)
553− (table :: TableType)
554− (schema :: SchemaType) =
581+ (sch :: Symbol)
582+ (tab :: Symbol)
583+ (schemas :: SchemasType)
584+ (table :: TableType) =
555585 UnsafeAlterTable {renderAlterTable :: ByteString}
556586 deriving (GHC.Generic,Show,Eq,Ord,NFData)
557587
@@ -560,21 +590,22 @@ newtype AlterTable
560590-- >>> :{
561591-- let
562592-- definition :: Definition
563−-- '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'NotNull 'PGint4])]
564−-- '["tab" ::: 'Table ('["positive" ::: Check '["col"]] :=> '["col" ::: 'NoDef :=> 'NotNull 'PGint4])]
593+-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'NotNull 'PGint4])]]
594+-- '["public" ::: '["tab" ::: 'Table ('["positive" ::: 'Check '["col"]] :=> '["col" ::: 'NoDef :=> 'NotNull 'PGint4])]]
565595-- definition = alterTable #tab (addConstraint #positive (check #col (#col .> 0)))
566596-- in printSQL definition
567597-- :}
568598-- ALTER TABLE "tab" ADD CONSTRAINT "positive" CHECK (("col" > 0));
569599addConstraint
570600 :: ( KnownSymbol alias
601+ , Has sch schemas schema
571602 , Has tab schema ('Table table0)
572603 , table0 ~ (constraints :=> columns)
573604 , table1 ~ (Create alias constraint constraints :=> columns) )
574605 => Alias alias
575− -> TableConstraintExpression schema tab constraint
606+ -> TableConstraintExpression sch tab schemas constraint
576607 -- ^ constraint to add
577− -> AlterTable tab table1 schema
608+ -> AlterTable sch tab schemas table1
578609addConstraint alias constraint = UnsafeAlterTable $
579610 "ADD" <+> "CONSTRAINT" <+> renderAlias alias
580611 <+> renderTableConstraintExpression constraint
@@ -584,20 +615,21 @@ addConstraint alias constraint = UnsafeAlterTable $
584615-- >>> :{
585616-- let
586617-- definition :: Definition
587−-- '["tab" ::: 'Table ('["positive" ::: Check '["col"]] :=> '["col" ::: 'NoDef :=> 'NotNull 'PGint4])]
588−-- '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'NotNull 'PGint4])]
618+-- '["public" ::: '["tab" ::: 'Table ('["positive" ::: Check '["col"]] :=> '["col" ::: 'NoDef :=> 'NotNull 'PGint4])]]
619+-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'NotNull 'PGint4])]]
589620-- definition = alterTable #tab (dropConstraint #positive)
590621-- in printSQL definition
591622-- :}
592623-- ALTER TABLE "tab" DROP CONSTRAINT "positive";
593624dropConstraint
594625 :: ( KnownSymbol constraint
626+ , Has sch schemas schema
595627 , Has tab schema ('Table table0)
596628 , table0 ~ (constraints :=> columns)
597629 , table1 ~ (Drop constraint constraints :=> columns) )
598630 => Alias constraint
599631 -- ^ constraint to drop
600− -> AlterTable tab table1 schema
632+ -> AlterTable sch tab schemas table1
601633dropConstraint constraint = UnsafeAlterTable $
602634 "DROP" <+> "CONSTRAINT" <+> renderAlias constraint
603635
@@ -609,10 +641,10 @@ class AddColumn ty where
609641 -- >>> :{
610642 -- let
611643 -- definition :: Definition
612− -- '["tab" ::: 'Table ('[] :=> '["col1" ::: 'NoDef :=> 'Null 'PGint4])]
613− -- '["tab" ::: 'Table ('[] :=>
644+ -- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col1" ::: 'NoDef :=> 'Null 'PGint4])]]
645+ -- '["public" ::: '["tab" ::: 'Table ('[] :=>
614646 -- '[ "col1" ::: 'NoDef :=> 'Null 'PGint4
615− -- , "col2" ::: 'Def :=> 'Null 'PGtext ])]
647+ -- , "col2" ::: 'Def :=> 'Null 'PGtext ])]]
616648 -- definition = alterTable #tab (addColumn #col2 (text & nullable & default_ "foo"))
617649 -- in printSQL definition
618650 -- :}
@@ -621,22 +653,22 @@ class AddColumn ty where
621653 -- >>> :{
622654 -- let
623655 -- definition :: Definition
624− -- '["tab" ::: 'Table ('[] :=> '["col1" ::: 'NoDef :=> 'Null 'PGint4])]
625− -- '["tab" ::: 'Table ('[] :=>
656+ -- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col1" ::: 'NoDef :=> 'Null 'PGint4])]]
657+ -- '["public" ::: '["tab" ::: 'Table ('[] :=>
626658 -- '[ "col1" ::: 'NoDef :=> 'Null 'PGint4
627− -- , "col2" ::: 'NoDef :=> 'Null 'PGtext ])]
659+ -- , "col2" ::: 'NoDef :=> 'Null 'PGtext ])]]
628660 -- definition = alterTable #tab (addColumn #col2 (text & nullable))
629661 -- in printSQL definition
630662 -- :}
631663 -- ALTER TABLE "tab" ADD COLUMN "col2" text NULL;
632664 addColumn
633665 :: ( KnownSymbol column
666+ , Has sch schemas schema
634667 , Has tab schema ('Table table0)
635− , table0 ~ (constraints :=> columns)
636− , table1 ~ (constraints :=> Create column ty columns) )
668+ , table0 ~ (constraints :=> columns) )
637669 => Alias column -- ^ column to add
638− -> ColumnTypeExpression schema ty -- ^ type of the new column
639− -> AlterTable tab table1 schema
670+ -> ColumnTypeExpression schemas ty -- ^ type of the new column
671+ -> AlterTable sch tab schemas (constraints :=> Create column ty columns)
640672 addColumn column ty = UnsafeAlterTable $
641673 "ADD COLUMN" <+> renderAlias column <+> renderColumnTypeExpression ty
642674instance {-# OVERLAPPING #-} AddColumn ('Def :=> ty)
@@ -650,21 +682,22 @@ instance {-# OVERLAPPABLE #-} AddColumn ('NoDef :=> 'Null ty)
650682-- >>> :{
651683-- let
652684-- definition :: Definition
653−-- '["tab" ::: 'Table ('[] :=>
685+-- '["public" ::: '["tab" ::: 'Table ('[] :=>
654686-- '[ "col1" ::: 'NoDef :=> 'Null 'PGint4
655−-- , "col2" ::: 'NoDef :=> 'Null 'PGtext ])]
656−-- '["tab" ::: 'Table ('[] :=> '["col1" ::: 'NoDef :=> 'Null 'PGint4])]
687+-- , "col2" ::: 'NoDef :=> 'Null 'PGtext ])]]
688+-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col1" ::: 'NoDef :=> 'Null 'PGint4])]]
657689-- definition = alterTable #tab (dropColumn #col2)
658690-- in printSQL definition
659691-- :}
660692-- ALTER TABLE "tab" DROP COLUMN "col2";
661693dropColumn
662694 :: ( KnownSymbol column
695+ , Has sch schemas schema
663696 , Has tab schema ('Table table0)
664697 , table0 ~ (constraints :=> columns)
665698 , table1 ~ (constraints :=> Drop column columns) )
666699 => Alias column -- ^ column to remove
667− -> AlterTable tab table1 schema
700+ -> AlterTable sch tab schemas table1
668701dropColumn column = UnsafeAlterTable $
669702 "DROP COLUMN" <+> renderAlias column
670703
@@ -673,8 +706,8 @@ dropColumn column = UnsafeAlterTable $
673706-- >>> :{
674707-- let
675708-- definition :: Definition
676−-- '["tab" ::: 'Table ('[] :=> '["foo" ::: 'NoDef :=> 'Null 'PGint4])]
677−-- '["tab" ::: 'Table ('[] :=> '["bar" ::: 'NoDef :=> 'Null 'PGint4])]
709+-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["foo" ::: 'NoDef :=> 'Null 'PGint4])]]
710+-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["bar" ::: 'NoDef :=> 'Null 'PGint4])]]
678711-- definition = alterTable #tab (renameColumn #foo #bar)
679712-- in printSQL definition
680713-- :}
@@ -682,30 +715,32 @@ dropColumn column = UnsafeAlterTable $
682715renameColumn
683716 :: ( KnownSymbol column0
684717 , KnownSymbol column1
718+ , Has sch schemas schema
685719 , Has tab schema ('Table table0)
686720 , table0 ~ (constraints :=> columns)
687721 , table1 ~ (constraints :=> Rename column0 column1 columns) )
688722 => Alias column0 -- ^ column to rename
689723 -> Alias column1 -- ^ what to rename the column
690− -> AlterTable tab table1 schema
724+ -> AlterTable sch tab schemas table1
691725renameColumn column0 column1 = UnsafeAlterTable $
692726 "RENAME COLUMN" <+> renderAlias column0 <+> "TO" <+> renderAlias column1
693727
694728-- | An `alterColumn` alters a single column.
695729alterColumn
696730 :: ( KnownSymbol column
731+ , Has sch schemas schema
697732 , Has tab schema ('Table table0)
698733 , table0 ~ (constraints :=> columns)
699734 , Has column columns ty0
700735 , tables1 ~ (constraints :=> Alter column ty1 columns))
701736 => Alias column -- ^ column to alter
702− -> AlterColumn schema ty0 ty1 -- ^ alteration to perform
703− -> AlterTable tab table1 schema
737+ -> AlterColumn schemas ty0 ty1 -- ^ alteration to perform
738+ -> AlterTable sch tab schemas table1
704739alterColumn column alteration = UnsafeAlterTable $
705740 "ALTER COLUMN" <+> renderAlias column <+> renderAlterColumn alteration
706741
707742-- | An `AlterColumn` describes the alteration to perform on a single column.
708−newtype AlterColumn (schema :: SchemaType) (ty0 :: ColumnType) (ty1 :: ColumnType) =
743+newtype AlterColumn (schemas :: SchemasType) (ty0 :: ColumnType) (ty1 :: ColumnType) =
709744 UnsafeAlterColumn {renderAlterColumn :: ByteString}
710745 deriving (GHC.Generic,Show,Eq,Ord,NFData)
711746
@@ -716,15 +751,15 @@ newtype AlterColumn (schema :: SchemaType) (ty0 :: ColumnType) (ty1 :: ColumnTyp
716751-- >>> :{
717752-- let
718753-- definition :: Definition
719−-- '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'Null 'PGint4])]
720−-- '["tab" ::: 'Table ('[] :=> '["col" ::: 'Def :=> 'Null 'PGint4])]
754+-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'Null 'PGint4])]]
755+-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col" ::: 'Def :=> 'Null 'PGint4])]]
721756-- definition = alterTable #tab (alterColumn #col (setDefault 5))
722757-- in printSQL definition
723758-- :}
724759-- ALTER TABLE "tab" ALTER COLUMN "col" SET DEFAULT 5;
725760setDefault
726− :: Expression schema '[] 'Ungrouped '[] ty -- ^ default value to set
727− -> AlterColumn schema (constraint :=> ty) ('Def :=> ty)
761+ :: Expression ('[] :=> schemas) '[] 'Ungrouped '[] ty -- ^ default value to set
762+ -> AlterColumn schemas (constraint :=> ty) ('Def :=> ty)
728763setDefault expression = UnsafeAlterColumn $
729764 "SET DEFAULT" <+> renderExpression expression
730765
@@ -733,13 +768,13 @@ setDefault expression = UnsafeAlterColumn $
733768-- >>> :{
734769-- let
735770-- definition :: Definition
736−-- '["tab" ::: 'Table ('[] :=> '["col" ::: 'Def :=> 'Null 'PGint4])]
737−-- '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'Null 'PGint4])]
771+-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col" ::: 'Def :=> 'Null 'PGint4])]]
772+-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'Null 'PGint4])]]
738773-- definition = alterTable #tab (alterColumn #col dropDefault)
739774-- in printSQL definition
740775-- :}
741776-- ALTER TABLE "tab" ALTER COLUMN "col" DROP DEFAULT;
742−dropDefault :: AlterColumn schema ('Def :=> ty) ('NoDef :=> ty)
777+dropDefault :: AlterColumn schemas ('Def :=> ty) ('NoDef :=> ty)
743778dropDefault = UnsafeAlterColumn $ "DROP DEFAULT"
744779
745780-- | A `setNotNull` adds a @NOT NULL@ constraint to a column.
@@ -749,14 +784,14 @@ dropDefault = UnsafeAlterColumn $ "DROP DEFAULT"
749784-- >>> :{
750785-- let
751786-- definition :: Definition
752−-- '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'Null 'PGint4])]
753−-- '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'NotNull 'PGint4])]
787+-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'Null 'PGint4])]]
788+-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'NotNull 'PGint4])]]
754789-- definition = alterTable #tab (alterColumn #col setNotNull)
755790-- in printSQL definition
756791-- :}
757792-- ALTER TABLE "tab" ALTER COLUMN "col" SET NOT NULL;
758793setNotNull
759− :: AlterColumn schema (constraint :=> 'Null ty) (constraint :=> 'NotNull ty)
794+ :: AlterColumn schemas (constraint :=> 'Null ty) (constraint :=> 'NotNull ty)
760795setNotNull = UnsafeAlterColumn $ "SET NOT NULL"
761796
762797-- | A `dropNotNull` drops a @NOT NULL@ constraint from a column.
@@ -764,14 +799,14 @@ setNotNull = UnsafeAlterColumn $ "SET NOT NULL"
764799-- >>> :{
765800-- let
766801-- definition :: Definition
767−-- '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'NotNull 'PGint4])]
768−-- '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'Null 'PGint4])]
802+-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'NotNull 'PGint4])]]
803+-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'Null 'PGint4])]]
769804-- definition = alterTable #tab (alterColumn #col dropNotNull)
770805-- in printSQL definition
771806-- :}
772807-- ALTER TABLE "tab" ALTER COLUMN "col" DROP NOT NULL;
773808dropNotNull
774− :: AlterColumn schema (constraint :=> 'NotNull ty) (constraint :=> 'Null ty)
809+ :: AlterColumn schemas (constraint :=> 'NotNull ty) (constraint :=> 'Null ty)
775810dropNotNull = UnsafeAlterColumn $ "DROP NOT NULL"
776811
777812-- | An `alterType` converts a column to a different data type.
@@ -781,37 +816,37 @@ dropNotNull = UnsafeAlterColumn $ "DROP NOT NULL"
781816-- >>> :{
782817-- let
783818-- definition :: Definition
784−-- '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'NotNull 'PGint4])]
785−-- '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'NotNull 'PGnumeric])]
819+-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'NotNull 'PGint4])]]
820+-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'NotNull 'PGnumeric])]]
786821-- definition =
787822-- alterTable #tab (alterColumn #col (alterType (numeric & notNullable)))
788823-- in printSQL definition
789824-- :}
790825-- ALTER TABLE "tab" ALTER COLUMN "col" TYPE numeric NOT NULL;
791−alterType :: ColumnTypeExpression schema ty -> AlterColumn schema ty0 ty
826+alterType :: ColumnTypeExpression schemas ty -> AlterColumn schemas ty0 ty
792827alterType ty = UnsafeAlterColumn $ "TYPE" <+> renderColumnTypeExpression ty
793828
794−-- | Create a view.
795−--
796−-- >>> :{
797−-- let
798−-- definition :: Definition
799−-- '[ "abc" ::: 'Table ('[] :=> '["a" ::: 'NoDef :=> 'Null 'PGint4, "b" ::: 'NoDef :=> 'Null 'PGint4, "c" ::: 'NoDef :=> 'Null 'PGint4])]
800−-- '[ "abc" ::: 'Table ('[] :=> '["a" ::: 'NoDef :=> 'Null 'PGint4, "b" ::: 'NoDef :=> 'Null 'PGint4, "c" ::: 'NoDef :=> 'Null 'PGint4])
801−-- , "bc" ::: 'View ('["b" ::: 'Null 'PGint4, "c" ::: 'Null 'PGint4])]
802−-- definition =
803−-- createView #bc (select (#b :* #c) (from (table #abc)))
804−-- in printSQL definition
805−-- :}
806−-- CREATE VIEW "bc" AS SELECT "b" AS "b", "c" AS "c" FROM "abc" AS "abc";
829+{- | Create a view.
830+>>> type ABC = '["a" ::: 'NoDef :=> 'Null 'PGint4, "b" ::: 'NoDef :=> 'Null 'PGint4, "c" ::: 'NoDef :=> 'Null 'PGint4]
831+>>> type BC = '["b" ::: 'Null 'PGint4, "c" ::: 'Null 'PGint4]
832+>>> :{
833+let
834+ definition :: Definition
835+ '[ "public" ::: '["abc" ::: 'Table ('[] :=> ABC)]]
836+ '[ "public" ::: '["abc" ::: 'Table ('[] :=> ABC), "bc" ::: 'View BC]]
837+ definition =
838+ createView #bc (select (#b :* #c) (from (table #abc)))
839+in printSQL definition
840+:}
841+CREATE VIEW "bc" AS SELECT "b" AS "b", "c" AS "c" FROM "abc" AS "abc";
842+-}
807843createView
808− :: KnownSymbol view
809− => Alias view -- ^ the name of the view to add
810− -> Query schema '[] row
811− -- ^ query
812− -> Definition schema (Create view ('View row) schema)
844+ :: (KnownSymbol sch, KnownSymbol vw, Has sch schemas schema)
845+ => QualifiedAlias sch vw -- ^ the name of the view to add
846+ -> Query ('[] :=> schemas) '[] view -- ^ query
847+ -> Definition schemas (Alter sch (Create vw ('View view) schema) schemas)
813848createView alias query = UnsafeDefinition $
814− "CREATE" <+> "VIEW" <+> renderAlias alias <+> "AS"
849+ "CREATE" <+> "VIEW" <+> renderQualifiedAlias alias <+> "AS"
815850 <+> renderQuery query <> ";"
816851
817852-- | Drop a view.
@@ -819,32 +854,32 @@ createView alias query = UnsafeDefinition $
819854-- >>> :{
820855-- let
821856-- definition :: Definition
822−-- '[ "abc" ::: 'Table ('[] :=> '["a" ::: 'NoDef :=> 'Null 'PGint4, "b" ::: 'NoDef :=> 'Null 'PGint4, "c" ::: 'NoDef :=> 'Null 'PGint4])
823−-- , "bc" ::: 'View ('["b" ::: 'Null 'PGint4, "c" ::: 'Null 'PGint4])]
824−-- '[ "abc" ::: 'Table ('[] :=> '["a" ::: 'NoDef :=> 'Null 'PGint4, "b" ::: 'NoDef :=> 'Null 'PGint4, "c" ::: 'NoDef :=> 'Null 'PGint4])]
857+-- '[ "public" ::: '["abc" ::: 'Table ('[] :=> '["a" ::: 'NoDef :=> 'Null 'PGint4, "b" ::: 'NoDef :=> 'Null 'PGint4, "c" ::: 'NoDef :=> 'Null 'PGint4])
858+-- , "bc" ::: 'View ('["b" ::: 'Null 'PGint4, "c" ::: 'Null 'PGint4])]]
859+-- '[ "public" ::: '["abc" ::: 'Table ('[] :=> '["a" ::: 'NoDef :=> 'Null 'PGint4, "b" ::: 'NoDef :=> 'Null 'PGint4, "c" ::: 'NoDef :=> 'Null 'PGint4])]]
825860-- definition = dropView #bc
826861-- in printSQL definition
827862-- :}
828863-- DROP VIEW "bc";
829864dropView
830− :: Has view schema ('View v)
831− => Alias view -- ^ view to remove
832− -> Definition schema (Drop view schema)
833−dropView v = UnsafeDefinition $ "DROP VIEW" <+> renderAlias v <> ";"
865+ :: (Has sch schemas schema, Has vw schema ('View view))
866+ => QualifiedAlias sch vw -- ^ view to remove
867+ -> Definition schemas (Alter sch (Drop vw schema) schemas)
868+dropView vw = UnsafeDefinition $ "DROP VIEW" <+> renderQualifiedAlias vw <> ";"
834869
835870-- | Enumerated types are created using the `createTypeEnum` command, for example
836871--
837−-- >>> printSQL $ createTypeEnum #mood (label @"sad" :* label @"ok" :* label @"happy")
872+-- >>> printSQL $ (createTypeEnum #mood (label @"sad" :* label @"ok" :* label @"happy") :: Definition (Public '[]) '["public" ::: '["mood" ::: 'Typedef ('PGenum '["sad","ok","happy"])]])
838873-- CREATE TYPE "mood" AS ENUM ('sad', 'ok', 'happy');
839874createTypeEnum
840− :: (KnownSymbol enum, SOP.All KnownSymbol labels)
841− => Alias enum
875+ :: (KnownSymbol enum, Has sch schemas schema, SOP.All KnownSymbol labels)
876+ => QualifiedAlias sch enum
842877 -- ^ name of the user defined enumerated type
843878 -> NP PGlabel labels
844879 -- ^ labels of the enumerated type
845− -> Definition schema (Create enum ('Typedef ('PGenum labels)) schema)
880+ -> Definition schemas (Alter sch (Create enum ('Typedef ('PGenum labels)) schema) schemas)
846881createTypeEnum enum labels = UnsafeDefinition $
847− "CREATE" <+> "TYPE" <+> renderAlias enum <+> "AS" <+> "ENUM" <+>
882+ "CREATE" <+> "TYPE" <+> renderQualifiedAlias enum <+> "AS" <+> "ENUM" <+>
848883 parenthesized (commaSeparated (renderLabels labels)) <> ";"
849884
850885-- | Enumerated types can also be generated from a Haskell type, for example
@@ -852,17 +887,23 @@ createTypeEnum enum labels = UnsafeDefinition $
852887-- >>> data Schwarma = Beef | Lamb | Chicken deriving GHC.Generic
853888-- >>> instance SOP.Generic Schwarma
854889-- >>> instance SOP.HasDatatypeInfo Schwarma
855−-- >>> printSQL $ createTypeEnumFrom @Schwarma #schwarma
890+-- >>> :{
891+-- let
892+-- createSchwarma :: Definition (Public '[]) '["public" ::: '["schwarma" ::: 'Typedef (PG (Enumerated Schwarma))]]
893+-- createSchwarma = createTypeEnumFrom @Schwarma #schwarma
894+-- in
895+-- printSQL createSchwarma
896+-- :}
856897-- CREATE TYPE "schwarma" AS ENUM ('Beef', 'Lamb', 'Chicken');
857898createTypeEnumFrom
858− :: forall hask enum schema.
899+ :: forall hask sch enum schemas schema.
859900 ( SOP.Generic hask
860901 , SOP.All KnownSymbol (LabelsPG hask)
861902 , KnownSymbol enum
862− )
863− => Alias enum
903+ , Has sch schemas schema )
904+ => QualifiedAlias sch enum
864905 -- ^ name of the user defined enumerated type
865− -> Definition schema (Create enum ('Typedef (PG (Enumerated hask))) schema)
906+ -> Definition schemas (Alter sch (Create enum ('Typedef (PG (Enumerated hask))) schema) schemas)
866907createTypeEnumFrom enum = createTypeEnum enum
867908 (SOP.hpure label :: NP PGlabel (LabelsPG hask))
868909
@@ -877,7 +918,7 @@ type PGcomplex = 'PGcomposite
877918
878919>>> :{
879920let
880− setup :: Definition '[] '["complex" ::: 'Typedef PGcomplex]
921+ setup :: Definition (Public '[]) '["public" ::: '["complex" ::: 'Typedef PGcomplex]]
881922 setup = createTypeComposite #complex
882923 (float8 `as` #real :* float8 `as` #imaginary)
883924in printSQL setup
@@ -885,17 +926,17 @@ in printSQL setup
885926CREATE TYPE "complex" AS ("real" float8, "imaginary" float8);
886927-}
887928createTypeComposite
888− :: (KnownSymbol ty, SOP.SListI fields)
889− => Alias ty
929+ :: (KnownSymbol ty, Has sch schemas schema, SOP.SListI fields)
930+ => QualifiedAlias sch ty
890931 -- ^ name of the user defined composite type
891− -> NP (Aliased (TypeExpression schema)) fields
932+ -> NP (Aliased (TypeExpression schemas)) fields
892933 -- ^ list of attribute names and data types
893− -> Definition schema (Create ty ('Typedef ('PGcomposite fields)) schema)
934+ -> Definition schemas (Alter sch (Create ty ('Typedef ('PGcomposite fields)) schema) schemas)
894935createTypeComposite ty fields = UnsafeDefinition $
895− "CREATE" <+> "TYPE" <+> renderAlias ty <+> "AS" <+> parenthesized
936+ "CREATE" <+> "TYPE" <+> renderQualifiedAlias ty <+> "AS" <+> parenthesized
896937 (renderCommaSeparated renderField fields) <> ";"
897938 where
898− renderField :: Aliased (TypeExpression schema) x -> ByteString
939+ renderField :: Aliased (TypeExpression schemas) x -> ByteString
899940 renderField (typ `As` alias) =
900941 renderAlias alias <+> renderTypeExpression typ
901942
@@ -904,23 +945,31 @@ createTypeComposite ty fields = UnsafeDefinition $
904945-- >>> data Complex = Complex {real :: Double, imaginary :: Double} deriving GHC.Generic
905946-- >>> instance SOP.Generic Complex
906947-- >>> instance SOP.HasDatatypeInfo Complex
907−-- >>> printSQL $ createTypeCompositeFrom @Complex #complex
948+-- >>> type Schema = '["complex" ::: 'Typedef (PG (Composite Complex))]
949+-- >>> :{
950+-- let
951+-- createComplex :: Definition (Public '[]) (Public Schema)
952+-- createComplex = createTypeCompositeFrom @Complex #complex
953+-- in
954+-- printSQL createComplex
955+-- :}
908956-- CREATE TYPE "complex" AS ("real" float8, "imaginary" float8);
909957createTypeCompositeFrom
910− :: forall hask ty schema.
911− ( SOP.All (FieldTyped schema) (RowPG hask)
912− , KnownSymbol ty )
913− => Alias ty
958+ :: forall hask sch ty schemas schema.
959+ ( SOP.All (FieldTyped schemas) (RowPG hask)
960+ , KnownSymbol ty
961+ , Has sch schemas schema )
962+ => QualifiedAlias sch ty
914963 -- ^ name of the user defined composite type
915− -> Definition schema (Create ty ( 'Typedef (PG (Composite hask))) schema)
964+ -> Definition schemas (Alter sch (Create ty ( 'Typedef (PG (Composite hask))) schema) schemas)
916965createTypeCompositeFrom ty = createTypeComposite ty
917− (SOP.hcpure (SOP.Proxy :: SOP.Proxy (FieldTyped schema)) fieldtype
918− :: NP (Aliased (TypeExpression schema)) (RowPG hask))
966+ (SOP.hcpure (SOP.Proxy :: SOP.Proxy (FieldTyped schemas)) fieldtype
967+ :: NP (Aliased (TypeExpression schemas)) (RowPG hask))
919968
920−class FieldTyped schema ty where
921− fieldtype :: Aliased (TypeExpression schema) ty
922−instance (KnownSymbol alias, PGTyped schema ty)
923− => FieldTyped schema (alias ::: ty) where
969+class FieldTyped schemas ty where
970+ fieldtype :: Aliased (TypeExpression schemas) ty
971+instance (KnownSymbol alias, PGTyped schemas ty)
972+ => FieldTyped schemas (alias ::: ty) where
924973 fieldtype = pgtype `As` Alias
925974
926975-- | Drop a type.
@@ -928,57 +977,57 @@ instance (KnownSymbol alias, PGTyped schema ty)
928977-- >>> data Schwarma = Beef | Lamb | Chicken deriving GHC.Generic
929978-- >>> instance SOP.Generic Schwarma
930979-- >>> instance SOP.HasDatatypeInfo Schwarma
931−-- >>> printSQL (dropType #schwarma :: Definition '["schwarma" ::: 'Typedef (PG (Enumerated Schwarma))] '[])
980+-- >>> printSQL (dropType #schwarma :: Definition '["public" ::: '["schwarma" ::: 'Typedef (PG (Enumerated Schwarma))]] (Public '[]))
932981-- DROP TYPE "schwarma";
933982dropType
934− :: Has tydef schema ('Typedef ty)
935− => Alias tydef
983+ :: (Has sch schemas schema, Has td schema ('Typedef ty))
984+ => QualifiedAlias sch td
936985 -- ^ name of the user defined type
937− -> Definition schema (Drop tydef schema)
938−dropType tydef = UnsafeDefinition $ "DROP" <+> "TYPE" <+> renderAlias tydef <> ";"
986+ -> Definition schemas (Alter sch (Drop td schema) schemas)
987+dropType tydef = UnsafeDefinition $ "DROP" <+> "TYPE" <+> renderQualifiedAlias tydef <> ";"
939988
940989-- | `ColumnTypeExpression`s are used in `createTable` commands.
941−newtype ColumnTypeExpression (schema :: SchemaType) (ty :: ColumnType)
990+newtype ColumnTypeExpression (schemas :: SchemasType) (ty :: ColumnType)
942991 = UnsafeColumnTypeExpression { renderColumnTypeExpression :: ByteString }
943992 deriving (GHC.Generic,Show,Eq,Ord,NFData)
944993
945994-- | used in `createTable` commands as a column constraint to note that
946995-- @NULL@ may be present in a column
947996nullable
948− :: TypeExpression schema (nullity ty)
949− -> ColumnTypeExpression schema ('NoDef :=> 'Null ty)
997+ :: TypeExpression schemas (nullity ty)
998+ -> ColumnTypeExpression schemas ('NoDef :=> 'Null ty)
950999nullable ty = UnsafeColumnTypeExpression $ renderTypeExpression ty <+> "NULL"
9511000
9521001-- | used in `createTable` commands as a column constraint to ensure
9531002-- @NULL@ is not present in a column
9541003notNullable
955− :: TypeExpression schema (nullity ty)
956− -> ColumnTypeExpression schema ('NoDef :=> 'NotNull ty)
1004+ :: TypeExpression schemas (nullity ty)
1005+ -> ColumnTypeExpression schemas ('NoDef :=> 'NotNull ty)
9571006notNullable ty = UnsafeColumnTypeExpression $ renderTypeExpression ty <+> "NOT NULL"
9581007
9591008-- | used in `createTable` commands as a column constraint to give a default
9601009default_
961− :: Expression schema '[] 'Ungrouped '[] ty
962− -> ColumnTypeExpression schema ('NoDef :=> ty)
963− -> ColumnTypeExpression schema ('Def :=> ty)
1010+ :: Expression ('[] :=> schemas) '[] 'Ungrouped '[] ty
1011+ -> ColumnTypeExpression schemas ('NoDef :=> ty)
1012+ -> ColumnTypeExpression schemas ('Def :=> ty)
9641013default_ x ty = UnsafeColumnTypeExpression $
9651014 renderColumnTypeExpression ty <+> "DEFAULT" <+> renderExpression x
9661015
9671016-- | not a true type, but merely a notational convenience for creating
9681017-- unique identifier columns with type `PGint2`
9691018serial2, smallserial
970− :: ColumnTypeExpression schema ('Def :=> 'NotNull 'PGint2)
1019+ :: ColumnTypeExpression schemas ('Def :=> 'NotNull 'PGint2)
9711020serial2 = UnsafeColumnTypeExpression "serial2"
9721021smallserial = UnsafeColumnTypeExpression "smallserial"
9731022-- | not a true type, but merely a notational convenience for creating
9741023-- unique identifier columns with type `PGint4`
9751024serial4, serial
976− :: ColumnTypeExpression schema ('Def :=> 'NotNull 'PGint4)
1025+ :: ColumnTypeExpression schemas ('Def :=> 'NotNull 'PGint4)
9771026serial4 = UnsafeColumnTypeExpression "serial4"
9781027serial = UnsafeColumnTypeExpression "serial"
9791028-- | not a true type, but merely a notational convenience for creating
9801029-- unique identifier columns with type `PGint8`
9811030serial8, bigserial
982− :: ColumnTypeExpression schema ('Def :=> 'NotNull 'PGint8)
1031+ :: ColumnTypeExpression schemas ('Def :=> 'NotNull 'PGint8)
9831032serial8 = UnsafeColumnTypeExpression "serial8"
9841033bigserial = UnsafeColumnTypeExpression "bigserial"
squeal-postgresql/src/Squeal/PostgreSQL/Expression.hs+386−383
@@ -218,7 +218,7 @@ values from primitive expression using arithmetic, logical,
218218and other operations.
219219-}
220220newtype Expression
221− (schema :: SchemaType)
221+ (db :: DBType)
222222 (from :: FromType)
223223 (grouping :: Grouping)
224224 (params :: [NullityType])
@@ -226,7 +226,7 @@ newtype Expression
226226 = UnsafeExpression { renderExpression :: ByteString }
227227 deriving (GHC.Generic,Show,Eq,Ord,NFData)
228228
229−instance RenderSQL (Expression schema from grouping params ty) where
229+instance RenderSQL (Expression db from grouping params ty) where
230230 renderSQL = renderExpression
231231
232232{- | A `HasParameter` constraint is used to indicate a value that is
@@ -239,60 +239,59 @@ refer to the out-of-line data values.
239239-}
240240class KnownNat n => HasParameter
241241 (n :: Nat)
242− (schema :: SchemaType)
243242 (params :: [NullityType])
244243 (ty :: NullityType)
245244 | n params -> ty where
246245 -- | `parameter` takes a `Nat` using type application and a `TypeExpression`.
247246 --
248− -- >>> let expr = parameter @1 int4 :: Expression sch rels grp '[ 'Null 'PGint4] ('Null 'PGint4)
247+ -- >>> let expr = parameter @1 int4 :: Expression (DBof schemas) from grp '[ 'Null 'PGint4] ('Null 'PGint4)
249248 -- >>> printSQL expr
250249 -- ($1 :: int4)
251250 parameter
252− :: TypeExpression schema ty
253− -> Expression schema from grouping params ty
251+ :: TypeExpression schemas ty
252+ -> Expression (commons :=> schemas) from grouping params ty
254253 parameter ty = UnsafeExpression $ parenthesized $
255254 "$" <> renderNat @n <+> "::"
256255 <+> renderTypeExpression ty
257−instance {-# OVERLAPPING #-} HasParameter 1 schema (ty1:tys) ty1
258−instance {-# OVERLAPPABLE #-} (KnownNat n, HasParameter (n-1) schema params ty)
259− => HasParameter n schema (ty' : params) ty
256+instance {-# OVERLAPPING #-} HasParameter 1 (ty1:tys) ty1
257+instance {-# OVERLAPPABLE #-} (KnownNat n, HasParameter (n-1) params ty)
258+ => HasParameter n (ty' : params) ty
260259
261260-- | `param` takes a `Nat` using type application and for basic types,
262261-- infers a `TypeExpression`.
263262--
264−-- >>> let expr = param @1 :: Expression sch rels grp '[ 'Null 'PGint4] ('Null 'PGint4)
263+-- >>> let expr = param @1 :: Expression (commons :=> schemas) from grp '[ 'Null 'PGint4] ('Null 'PGint4)
265264-- >>> printSQL expr
266265-- ($1 :: int4)
267266param
268− :: forall n schema params from grouping ty
269− . (PGTyped schema ty, HasParameter n schema params ty)
270− => Expression schema from grouping params ty -- ^ param
271−param = parameter @n pgtype
267+ :: forall n db commons schemas params from grouping ty
268+ . (db ~ (commons :=> schemas), PGTyped schemas ty, HasParameter n params ty)
269+ => Expression db from grouping params ty -- ^ param
270+param = parameter @n (pgtype @schemas)
272271
273272instance (HasUnique table from columns, Has column columns ty)
274− => IsLabel column (Expression schema from 'Ungrouped params ty) where
273+ => IsLabel column (Expression db from 'Ungrouped params ty) where
275274 fromLabel = UnsafeExpression $ renderAlias (Alias @column)
276275instance (HasUnique table from columns, Has column columns ty)
277276 => IsLabel column
278− (Aliased (Expression schema from 'Ungrouped params) (column ::: ty)) where
277+ (Aliased (Expression db from 'Ungrouped params) (column ::: ty)) where
279278 fromLabel = fromLabel @column `As` Alias @column
280279instance (HasUnique table from columns, Has column columns ty)
281280 => IsLabel column
282− (NP (Aliased (Expression schema from 'Ungrouped params)) '[column ::: ty]) where
281+ (NP (Aliased (Expression db from 'Ungrouped params)) '[column ::: ty]) where
283282 fromLabel = fromLabel @column :* Nil
284283
285284instance (Has table from columns, Has column columns ty)
286− => IsQualified table column (Expression schema from 'Ungrouped params ty) where
285+ => IsQualified table column (Expression db from 'Ungrouped params ty) where
287286 table ! column = UnsafeExpression $
288287 renderAlias table <> "." <> renderAlias column
289288instance (Has table from columns, Has column columns ty)
290289 => IsQualified table column
291− (Aliased (Expression schema from 'Ungrouped params) (column ::: ty)) where
290+ (Aliased (Expression db from 'Ungrouped params) (column ::: ty)) where
292291 table ! column = table ! column `As` column
293292instance (Has table from columns, Has column columns ty)
294293 => IsQualified table column
295− (NP (Aliased (Expression schema from 'Ungrouped params)) '[column ::: ty]) where
294+ (NP (Aliased (Expression db from 'Ungrouped params)) '[column ::: ty]) where
296295 table ! column = table ! column :* Nil
297296
298297instance
@@ -300,14 +299,14 @@ instance
300299 , Has column columns ty
301300 , GroupedBy table column bys
302301 ) => IsLabel column
303− (Expression schema from ('Grouped bys) params ty) where
302+ (Expression db from ('Grouped bys) params ty) where
304303 fromLabel = UnsafeExpression $ renderAlias (Alias @column)
305304instance
306305 ( HasUnique table from columns
307306 , Has column columns ty
308307 , GroupedBy table column bys
309308 ) => IsLabel column
310− ( Aliased (Expression schema from ('Grouped bys) params)
309+ ( Aliased (Expression db from ('Grouped bys) params)
311310 (column ::: ty) ) where
312311 fromLabel = fromLabel @column `As` Alias @column
313312instance
@@ -315,7 +314,7 @@ instance
315314 , Has column columns ty
316315 , GroupedBy table column bys
317316 ) => IsLabel column
318− ( NP (Aliased (Expression schema from ('Grouped bys) params))
317+ ( NP (Aliased (Expression db from ('Grouped bys) params))
319318 '[column ::: ty] ) where
320319 fromLabel = fromLabel @column :* Nil
321320
@@ -324,7 +323,7 @@ instance
324323 , Has column columns ty
325324 , GroupedBy table column bys
326325 ) => IsQualified table column
327− (Expression schema from ('Grouped bys) params ty) where
326+ (Expression db from ('Grouped bys) params ty) where
328327 table ! column = UnsafeExpression $
329328 renderAlias table <> "." <> renderAlias column
330329instance
@@ -332,7 +331,7 @@ instance
332331 , Has column columns ty
333332 , GroupedBy table column bys
334333 ) => IsQualified table column
335− (Aliased (Expression schema from ('Grouped bys) params)
334+ (Aliased (Expression db from ('Grouped bys) params)
336335 (column ::: ty)) where
337336 table ! column = table ! column `As` column
338337instance
@@ -340,7 +339,7 @@ instance
340339 , Has column columns ty
341340 , GroupedBy table column bys
342341 ) => IsQualified table column
343− ( NP (Aliased (Expression schema from ('Grouped bys) params))
342+ ( NP (Aliased (Expression db from ('Grouped bys) params))
344343 '[column ::: ty]) where
345344 table ! column = table ! column :* Nil
346345
@@ -348,7 +347,7 @@ instance
348347--
349348-- >>> printSQL null_
350349-- NULL
351−null_ :: Expression schema rels grouping params ('Null ty)
350+null_ :: Expression db rels grouping params ('Null ty)
352351null_ = UnsafeExpression "NULL"
353352
354353-- | analagous to `Just`
@@ -356,8 +355,8 @@ null_ = UnsafeExpression "NULL"
356355-- >>> printSQL $ notNull true
357356-- TRUE
358357notNull
359− :: Expression schema rels grouping params ('NotNull ty)
360− -> Expression schema rels grouping params ('Null ty)
358+ :: Expression db rels grouping params ('NotNull ty)
359+ -> Expression db rels grouping params ('Null ty)
361360notNull = UnsafeExpression . renderExpression
362361
363362-- | return the leftmost value which is not NULL
@@ -365,11 +364,11 @@ notNull = UnsafeExpression . renderExpression
365364-- >>> printSQL $ coalesce [null_, true] false
366365-- COALESCE(NULL, TRUE, FALSE)
367366coalesce
368− :: [Expression schema from grouping params ('Null ty)]
367+ :: [Expression db from grouping params ('Null ty)]
369368 -- ^ @NULL@s may be present
370− -> Expression schema from grouping params ('NotNull ty)
369+ -> Expression db from grouping params ('NotNull ty)
371370 -- ^ @NULL@ is absent
372− -> Expression schema from grouping params ('NotNull ty)
371+ -> Expression db from grouping params ('NotNull ty)
373372coalesce nullxs notNullx = UnsafeExpression $
374373 "COALESCE" <> parenthesized (commaSeparated
375374 ((renderExpression <$> nullxs) <> [renderExpression notNullx]))
@@ -379,26 +378,26 @@ coalesce nullxs notNullx = UnsafeExpression $
379378-- >>> printSQL $ fromNull true null_
380379-- COALESCE(NULL, TRUE)
381380fromNull
382− :: Expression schema from grouping params ('NotNull ty)
381+ :: Expression db from grouping params ('NotNull ty)
383382 -- ^ what to convert @NULL@ to
384− -> Expression schema from grouping params ('Null ty)
385− -> Expression schema from grouping params ('NotNull ty)
383+ -> Expression db from grouping params ('Null ty)
384+ -> Expression db from grouping params ('NotNull ty)
386385fromNull notNullx nullx = coalesce [nullx] notNullx
387386
388387-- | >>> printSQL $ null_ & isNull
389388-- NULL IS NULL
390389isNull
391− :: Expression schema from grouping params ('Null ty)
390+ :: Expression db from grouping params ('Null ty)
392391 -- ^ possibly @NULL@
393− -> Condition schema from grouping params
392+ -> Condition db from grouping params
394393isNull x = UnsafeExpression $ renderExpression x <+> "IS NULL"
395394
396395-- | >>> printSQL $ null_ & isNotNull
397396-- NULL IS NOT NULL
398397isNotNull
399− :: Expression schema from grouping params ('Null ty)
398+ :: Expression db from grouping params ('Null ty)
400399 -- ^ possibly @NULL@
401− -> Condition schema from grouping params
400+ -> Condition db from grouping params
402401isNotNull x = UnsafeExpression $ renderExpression x <+> "IS NOT NULL"
403402
404403-- | analagous to `maybe` using @IS NULL@
@@ -406,13 +405,13 @@ isNotNull x = UnsafeExpression $ renderExpression x <+> "IS NOT NULL"
406405-- >>> printSQL $ matchNull true not_ null_
407406-- CASE WHEN NULL IS NULL THEN TRUE ELSE (NOT NULL) END
408407matchNull
409− :: Expression schema from grouping params (nullty)
408+ :: Expression db from grouping params (nullty)
410409 -- ^ what to convert @NULL@ to
411− -> ( Expression schema from grouping params ('NotNull ty)
412− -> Expression schema from grouping params (nullty) )
410+ -> ( Expression db from grouping params ('NotNull ty)
411+ -> Expression db from grouping params (nullty) )
413412 -- ^ function to perform when @NULL@ is absent
414− -> Expression schema from grouping params ('Null ty)
415− -> Expression schema from grouping params (nullty)
413+ -> Expression db from grouping params ('Null ty)
414+ -> Expression db from grouping params (nullty)
416415matchNull y f x = ifThenElse (isNull x) y
417416 (f (UnsafeExpression (renderExpression x)))
418417
@@ -420,25 +419,25 @@ matchNull y f x = ifThenElse (isNull x) y
420419`nullIf` gives @NULL@.
421420
422421>>> :set -XTypeApplications -XDataKinds
423−>>> let expr = nullIf false (param @1) :: Expression schema rels grp '[ 'NotNull 'PGbool] ('Null 'PGbool)
422+>>> let expr = nullIf false (param @1) :: Expression (commons :=> schema) from grp '[ 'NotNull 'PGbool] ('Null 'PGbool)
424423>>> printSQL expr
425424NULL IF (FALSE, ($1 :: bool))
426425-}
427426nullIf
428− :: Expression schema from grouping params ('NotNull ty)
427+ :: Expression db from grouping params ('NotNull ty)
429428 -- ^ @NULL@ is absent
430− -> Expression schema from grouping params ('NotNull ty)
429+ -> Expression db from grouping params ('NotNull ty)
431430 -- ^ @NULL@ is absent
432− -> Expression schema from grouping params ('Null ty)
431+ -> Expression db from grouping params ('Null ty)
433432nullIf x y = UnsafeExpression $ "NULL IF" <+> parenthesized
434433 (renderExpression x <> ", " <> renderExpression y)
435434
436435-- | >>> printSQL $ array [null_, false, true]
437436-- ARRAY[NULL, FALSE, TRUE]
438437array
439− :: [Expression schema from grouping params ty]
438+ :: [Expression db from grouping params ty]
440439 -- ^ array elements
441− -> Expression schema from grouping params (nullity ('PGvararray ty))
440+ -> Expression db from grouping params (nullity ('PGvararray ty))
442441array xs = UnsafeExpression $
443442 "ARRAY[" <> commaSeparated (renderExpression <$> xs) <> "]"
444443
@@ -446,13 +445,13 @@ array xs = UnsafeExpression $
446445-- (ARRAY[NULL, FALSE, TRUE])[2]
447446index
448447 :: Word64 -- ^ index
449− -> Expression schema from grouping params (nullity ('PGvararray ty)) -- ^ array
450− -> Expression schema from grouping params (NullifyType ty)
448+ -> Expression db from grouping params (nullity ('PGvararray ty)) -- ^ array
449+ -> Expression db from grouping params (NullifyType ty)
451450index n expr = UnsafeExpression $
452451 parenthesized (renderExpression expr) <> "[" <> fromString (show n) <> "]"
453452
454453instance (KnownSymbol label, label `In` labels) => IsPGlabel label
455− (Expression schema from grouping params (nullity ('PGenum labels))) where
454+ (Expression db from grouping params (nullity ('PGenum labels))) where
456455 label = UnsafeExpression $ renderLabel (PGlabel @label)
457456
458457-- | A row constructor is an expression that builds a row value
@@ -464,14 +463,14 @@ instance (KnownSymbol label, label `In` labels) => IsPGlabel label
464463-- , "imaginary" ::: 'NotNull 'PGfloat8 ]
465464-- :}
466465--
467−-- >>> let i = row (0 `as` #real :* 1 `as` #imaginary) :: Expression '[] '[] 'Ungrouped '[] ('NotNull Complex)
466+-- >>> let i = row (0 `as` #real :* 1 `as` #imaginary) :: Expression db from grp params ('NotNull Complex)
468467-- >>> printSQL i
469468-- ROW(0, 1)
470469row
471470 :: SListI row
472− => NP (Aliased (Expression schema from grouping params)) row
471+ => NP (Aliased (Expression db from grouping params)) row
473472 -- ^ zero or more expressions for the row field values
474− -> Expression schema from grouping params (nullity ('PGcomposite row))
473+ -> Expression db from grouping params (nullity ('PGcomposite row))
475474row exprs = UnsafeExpression $ "ROW" <> parenthesized
476475 (renderCommaSeparated (\ (expr `As` _) -> renderExpression expr) exprs)
477476
@@ -479,50 +478,54 @@ row exprs = UnsafeExpression $ "ROW" <> parenthesized
479478-- type Complex = 'PGcomposite
480479-- '[ "real" ::: 'NotNull 'PGfloat8
481480-- , "imaginary" ::: 'NotNull 'PGfloat8 ]
481+-- type Schema = '["complex" ::: 'Typedef Complex]
482+-- type DB = DBof (Public Schema)
482483-- :}
483484--
484−-- >>> let i = row (0 `as` #real :* 1 `as` #imaginary) :: Expression '["complex" ::: 'Typedef Complex] '[] 'Ungrouped '[] ('NotNull Complex)
485+-- >>> let i = row (0 `as` #real :* 1 `as` #imaginary) :: Expression DB from grp params ('NotNull Complex)
485486-- >>> printSQL $ i & field #complex #imaginary
486487-- (ROW(0, 1)::"complex")."imaginary"
487488field
488− :: (Has tydef schema ('Typedef ('PGcomposite row)), Has field row ty)
489− => Alias tydef -- ^ row type
489+ :: ( Has sch schemas schema
490+ , Has tydef schema ('Typedef ('PGcomposite row))
491+ , Has field row ty)
492+ => QualifiedAlias sch tydef -- ^ row type
490493 -> Alias field -- ^ field name
491− -> Expression schema from grouping params ('NotNull ('PGcomposite row))
492− -> Expression schema from grouping params ty
494+ -> Expression (commons :=> schemas) from grouping params ('NotNull ('PGcomposite row))
495+ -> Expression (commons :=> schemas) from grouping params ty
493496field td fld expr = UnsafeExpression $
494− parenthesized (renderExpression expr <> "::" <> renderAlias td)
497+ parenthesized (renderExpression expr <> "::" <> renderQualifiedAlias td)
495498 <> "." <> renderAlias fld
496499
497500instance Semigroup
498− (Expression schema from grouping params (nullity ('PGvararray ty))) where
501+ (Expression db from grouping params (nullity ('PGvararray ty))) where
499502 (<>) = unsafeBinaryOp "||"
500503
501504instance Monoid
502− (Expression schema from grouping params (nullity ('PGvararray ty))) where
505+ (Expression db from grouping params (nullity ('PGvararray ty))) where
503506 mempty = array []
504507 mappend = (<>)
505508
506−-- | >>> let expr = greatest currentTimestamp [param @1] :: Expression sch rels grp '[ 'NotNull 'PGtimestamptz] ('NotNull 'PGtimestamptz)
509+-- | >>> let expr = greatest currentTimestamp [param @1] :: Expression (commons :=> schemas) rels grp '[ 'NotNull 'PGtimestamptz] ('NotNull 'PGtimestamptz)
507510-- >>> printSQL expr
508511-- GREATEST(CURRENT_TIMESTAMP, ($1 :: timestamp with time zone))
509512greatest
510− :: Expression schema from grouping params (nullty)
513+ :: Expression db from grouping params (nullty)
511514 -- ^ needs at least 1 argument
512− -> [Expression schema from grouping params (nullty)]
515+ -> [Expression db from grouping params (nullty)]
513516 -- ^ or more
514− -> Expression schema from grouping params (nullty)
517+ -> Expression db from grouping params (nullty)
515518greatest x xs = UnsafeExpression $ "GREATEST("
516519 <> commaSeparated (renderExpression <$> (x:xs)) <> ")"
517520
518521-- | >>> printSQL $ least currentTimestamp [null_]
519522-- LEAST(CURRENT_TIMESTAMP, NULL)
520523least
521− :: Expression schema from grouping params (nullty)
524+ :: Expression db from grouping params (nullty)
522525 -- ^ needs at least 1 argument
523− -> [Expression schema from grouping params (nullty)]
526+ -> [Expression db from grouping params (nullty)]
524527 -- ^ or more
525− -> Expression schema from grouping params (nullty)
528+ -> Expression db from grouping params (nullty)
526529least x xs = UnsafeExpression $ "LEAST("
527530 <> commaSeparated (renderExpression <$> (x:xs)) <> ")"
528531
@@ -531,9 +534,9 @@ least x xs = UnsafeExpression $ "LEAST("
531534unsafeBinaryOp
532535 :: ByteString
533536 -- ^ operator
534− -> Expression schema from grouping params (ty0)
535− -> Expression schema from grouping params (ty1)
536− -> Expression schema from grouping params (ty2)
537+ -> Expression db from grouping params (ty0)
538+ -> Expression db from grouping params (ty1)
539+ -> Expression db from grouping params (ty2)
537540unsafeBinaryOp op x y = UnsafeExpression $ parenthesized $
538541 renderExpression x <+> op <+> renderExpression y
539542
@@ -542,8 +545,8 @@ unsafeBinaryOp op x y = UnsafeExpression $ parenthesized $
542545unsafeUnaryOp
543546 :: ByteString
544547 -- ^ operator
545− -> Expression schema from grouping params (ty0)
546− -> Expression schema from grouping params (ty1)
548+ -> Expression db from grouping params (ty0)
549+ -> Expression db from grouping params (ty1)
547550unsafeUnaryOp op x = UnsafeExpression $ parenthesized $
548551 op <+> renderExpression x
549552
@@ -552,8 +555,8 @@ unsafeUnaryOp op x = UnsafeExpression $ parenthesized $
552555unsafeFunction
553556 :: ByteString
554557 -- ^ function
555− -> Expression schema from grouping params (xty)
556− -> Expression schema from grouping params (yty)
558+ -> Expression db from grouping params (xty)
559+ -> Expression db from grouping params (yty)
557560unsafeFunction fun x = UnsafeExpression $
558561 fun <> parenthesized (renderExpression x)
559562
@@ -562,13 +565,13 @@ unsafeVariadicFunction
562565 :: SListI elems
563566 => ByteString
564567 -- ^ function
565− -> NP (Expression schema from grouping params) elems
566− -> Expression schema from grouping params ret
568+ -> NP (Expression db from grouping params) elems
569+ -> Expression db from grouping params ret
567570unsafeVariadicFunction fun x = UnsafeExpression $
568571 fun <> parenthesized (commaSeparated (hcollapse (hmap (K . renderExpression) x)))
569572
570573instance ty `In` PGNum
571− => Num (Expression schema from grouping params (nullity ty)) where
574+ => Num (Expression db from grouping params (nullity ty)) where
572575 (+) = unsafeBinaryOp "+"
573576 (-) = unsafeBinaryOp "-"
574577 (*) = unsafeBinaryOp "*"
@@ -580,12 +583,12 @@ instance ty `In` PGNum
580583 . show
581584
582585instance (ty `In` PGNum, ty `In` PGFloating) => Fractional
583− (Expression schema from grouping params (nullity ty)) where
586+ (Expression db from grouping params (nullity ty)) where
584587 (/) = unsafeBinaryOp "/"
585588 fromRational x = fromInteger (numerator x) / fromInteger (denominator x)
586589
587590instance (ty `In` PGNum, ty `In` PGFloating) => Floating
588− (Expression schema from grouping params (nullity ty)) where
591+ (Expression db from grouping params (nullity ty)) where
589592 pi = UnsafeExpression "pi()"
590593 exp = unsafeFunction "exp"
591594 log = unsafeFunction "ln"
@@ -608,18 +611,18 @@ instance (ty `In` PGNum, ty `In` PGFloating) => Floating
608611
609612-- | >>> :{
610613-- let
611−-- expression :: Expression schema from grouping params (nullity 'PGfloat4)
614+-- expression :: Expression db from grouping params (nullity 'PGfloat4)
612615-- expression = atan2_ pi 2
613616-- in printSQL expression
614617-- :}
615618-- atan2(pi(), 2)
616619atan2_
617620 :: float `In` PGFloating
618− => Expression schema from grouping params (nullity float)
621+ => Expression db from grouping params (nullity float)
619622 -- ^ numerator
620− -> Expression schema from grouping params (nullity float)
623+ -> Expression db from grouping params (nullity float)
621624 -- ^ denominator
622− -> Expression schema from grouping params (nullity float)
625+ -> Expression db from grouping params (nullity float)
623626atan2_ y x = UnsafeExpression $
624627 "atan2(" <> renderExpression y <> ", " <> renderExpression x <> ")"
625628
@@ -630,11 +633,11 @@ atan2_ y x = UnsafeExpression $
630633-- | >>> printSQL $ true & cast int4
631634-- (TRUE :: int4)
632635cast
633− :: TypeExpression schema ty1
636+ :: TypeExpression schemas ty1
634637 -- ^ type to cast as
635− -> Expression schema from grouping params ty0
638+ -> Expression (commons :=> schemas) from grouping params ty0
636639 -- ^ value to convert
637− -> Expression schema from grouping params ty1
640+ -> Expression (commons :=> schemas) from grouping params ty1
638641cast ty x = UnsafeExpression $ parenthesized $
639642 renderExpression x <+> "::" <+> renderTypeExpression ty
640643
@@ -642,136 +645,136 @@ cast ty x = UnsafeExpression $ parenthesized $
642645--
643646-- >>> :{
644647-- let
645−-- expression :: Expression schema from grouping params (nullity 'PGint2)
648+-- expression :: Expression db from grouping params (nullity 'PGint2)
646649-- expression = 5 `quot_` 2
647650-- in printSQL expression
648651-- :}
649652-- (5 / 2)
650653quot_
651654 :: int `In` PGIntegral
652− => Expression schema from grouping params (nullity int)
655+ => Expression db from grouping params (nullity int)
653656 -- ^ numerator
654− -> Expression schema from grouping params (nullity int)
657+ -> Expression db from grouping params (nullity int)
655658 -- ^ denominator
656− -> Expression schema from grouping params (nullity int)
659+ -> Expression db from grouping params (nullity int)
657660quot_ = unsafeBinaryOp "/"
658661
659662-- | remainder upon integer division
660663--
661664-- >>> :{
662665-- let
663−-- expression :: Expression schema from grouping params (nullity 'PGint2)
666+-- expression :: Expression db from grouping params (nullity 'PGint2)
664667-- expression = 5 `rem_` 2
665668-- in printSQL expression
666669-- :}
667670-- (5 % 2)
668671rem_
669672 :: int `In` PGIntegral
670− => Expression schema from grouping params (nullity int)
673+ => Expression db from grouping params (nullity int)
671674 -- ^ numerator
672− -> Expression schema from grouping params (nullity int)
675+ -> Expression db from grouping params (nullity int)
673676 -- ^ denominator
674− -> Expression schema from grouping params (nullity int)
677+ -> Expression db from grouping params (nullity int)
675678rem_ = unsafeBinaryOp "%"
676679
677680-- | >>> :{
678681-- let
679−-- expression :: Expression schema from grouping params (nullity 'PGfloat4)
682+-- expression :: Expression db from grouping params (nullity 'PGfloat4)
680683-- expression = trunc pi
681684-- in printSQL expression
682685-- :}
683686-- trunc(pi())
684687trunc
685688 :: frac `In` PGFloating
686− => Expression schema from grouping params (nullity frac)
689+ => Expression db from grouping params (nullity frac)
687690 -- ^ fractional number
688− -> Expression schema from grouping params (nullity frac)
691+ -> Expression db from grouping params (nullity frac)
689692trunc = unsafeFunction "trunc"
690693
691694-- | >>> :{
692695-- let
693−-- expression :: Expression schema from grouping params (nullity 'PGfloat4)
696+-- expression :: Expression db from grouping params (nullity 'PGfloat4)
694697-- expression = round_ pi
695698-- in printSQL expression
696699-- :}
697700-- round(pi())
698701round_
699702 :: frac `In` PGFloating
700− => Expression schema from grouping params (nullity frac)
703+ => Expression db from grouping params (nullity frac)
701704 -- ^ fractional number
702− -> Expression schema from grouping params (nullity frac)
705+ -> Expression db from grouping params (nullity frac)
703706round_ = unsafeFunction "round"
704707
705708-- | >>> :{
706709-- let
707−-- expression :: Expression schema from grouping params (nullity 'PGfloat4)
710+-- expression :: Expression db from grouping params (nullity 'PGfloat4)
708711-- expression = ceiling_ pi
709712-- in printSQL expression
710713-- :}
711714-- ceiling(pi())
712715ceiling_
713716 :: frac `In` PGFloating
714− => Expression schema from grouping params (nullity frac)
717+ => Expression db from grouping params (nullity frac)
715718 -- ^ fractional number
716− -> Expression schema from grouping params (nullity frac)
719+ -> Expression db from grouping params (nullity frac)
717720ceiling_ = unsafeFunction "ceiling"
718721
719722-- | A `Condition` is an `Expression`, which can evaluate
720723-- to `true`, `false` or `null_`. This is because SQL uses
721724-- a three valued logic.
722−type Condition schema from grouping params =
723− Expression schema from grouping params ('Null 'PGbool)
725+type Condition db from grouping params =
726+ Expression db from grouping params ('Null 'PGbool)
724727
725728-- | >>> printSQL true
726729-- TRUE
727−true :: Expression schema from grouping params (nullity 'PGbool)
730+true :: Expression db from grouping params (nullity 'PGbool)
728731true = UnsafeExpression "TRUE"
729732
730733-- | >>> printSQL false
731734-- FALSE
732−false :: Expression schema from grouping params (nullity 'PGbool)
735+false :: Expression db from grouping params (nullity 'PGbool)
733736false = UnsafeExpression "FALSE"
734737
735738-- | >>> printSQL $ not_ true
736739-- (NOT TRUE)
737740not_
738− :: Expression schema from grouping params (nullity 'PGbool)
739− -> Expression schema from grouping params (nullity 'PGbool)
741+ :: Expression db from grouping params (nullity 'PGbool)
742+ -> Expression db from grouping params (nullity 'PGbool)
740743not_ = unsafeUnaryOp "NOT"
741744
742745-- | >>> printSQL $ true .&& false
743746-- (TRUE AND FALSE)
744747(.&&)
745− :: Expression schema from grouping params (nullity 'PGbool)
746− -> Expression schema from grouping params (nullity 'PGbool)
747− -> Expression schema from grouping params (nullity 'PGbool)
748+ :: Expression db from grouping params (nullity 'PGbool)
749+ -> Expression db from grouping params (nullity 'PGbool)
750+ -> Expression db from grouping params (nullity 'PGbool)
748751infixr 3 .&&
749752(.&&) = unsafeBinaryOp "AND"
750753
751754-- | >>> printSQL $ true .|| false
752755-- (TRUE OR FALSE)
753756(.||)
754− :: Expression schema from grouping params (nullity 'PGbool)
755− -> Expression schema from grouping params (nullity 'PGbool)
756− -> Expression schema from grouping params (nullity 'PGbool)
757+ :: Expression db from grouping params (nullity 'PGbool)
758+ -> Expression db from grouping params (nullity 'PGbool)
759+ -> Expression db from grouping params (nullity 'PGbool)
757760infixr 2 .||
758761(.||) = unsafeBinaryOp "OR"
759762
760763-- | >>> :{
761764-- let
762−-- expression :: Expression schema from grouping params (nullity 'PGint2)
765+-- expression :: Expression db from grouping params (nullity 'PGint2)
763766-- expression = caseWhenThenElse [(true, 1), (false, 2)] 3
764767-- in printSQL expression
765768-- :}
766769-- CASE WHEN TRUE THEN 1 WHEN FALSE THEN 2 ELSE 3 END
767770caseWhenThenElse
768− :: [ ( Condition schema from grouping params
769− , Expression schema from grouping params ty
771+ :: [ ( Condition db from grouping params
772+ , Expression db from grouping params ty
770773 ) ]
771774 -- ^ whens and thens
772− -> Expression schema from grouping params ty
775+ -> Expression db from grouping params ty
773776 -- ^ else
774− -> Expression schema from grouping params ty
777+ -> Expression db from grouping params ty
775778caseWhenThenElse whenThens else_ = UnsafeExpression $ mconcat
776779 [ "CASE"
777780 , mconcat
@@ -787,16 +790,16 @@ caseWhenThenElse whenThens else_ = UnsafeExpression $ mconcat
787790
788791-- | >>> :{
789792-- let
790−-- expression :: Expression schema from grouping params (nullity 'PGint2)
793+-- expression :: Expression db from grouping params (nullity 'PGint2)
791794-- expression = ifThenElse true 1 0
792795-- in printSQL expression
793796-- :}
794797-- CASE WHEN TRUE THEN 1 ELSE 0 END
795798ifThenElse
796− :: Condition schema from grouping params
797− -> Expression schema from grouping params ty -- ^ then
798− -> Expression schema from grouping params ty -- ^ else
799− -> Expression schema from grouping params ty
799+ :: Condition db from grouping params
800+ -> Expression db from grouping params ty -- ^ then
801+ -> Expression db from grouping params ty -- ^ else
802+ -> Expression db from grouping params ty
800803ifThenElse if_ then_ else_ = caseWhenThenElse [(if_,then_)] else_
801804
802805-- | Comparison operations like `.==`, `./=`, `.>`, `.>=`, `.<` and `.<=`
@@ -805,85 +808,85 @@ ifThenElse if_ then_ else_ = caseWhenThenElse [(if_,then_)] else_
805808-- >>> printSQL $ true .== null_
806809-- (TRUE = NULL)
807810(.==)
808− :: Expression schema from grouping params (nullity0 ty) -- ^ lhs
809− -> Expression schema from grouping params (nullity1 ty) -- ^ rhs
810− -> Condition schema from grouping params
811+ :: Expression db from grouping params (nullity0 ty) -- ^ lhs
812+ -> Expression db from grouping params (nullity1 ty) -- ^ rhs
813+ -> Condition db from grouping params
811814(.==) = unsafeBinaryOp "="
812815infix 4 .==
813816
814817-- | >>> printSQL $ true ./= null_
815818-- (TRUE <> NULL)
816819(./=)
817− :: Expression schema from grouping params (nullity0 ty) -- ^ lhs
818− -> Expression schema from grouping params (nullity1 ty) -- ^ rhs
819− -> Condition schema from grouping params
820+ :: Expression db from grouping params (nullity0 ty) -- ^ lhs
821+ -> Expression db from grouping params (nullity1 ty) -- ^ rhs
822+ -> Condition db from grouping params
820823(./=) = unsafeBinaryOp "<>"
821824infix 4 ./=
822825
823826-- | >>> printSQL $ true .>= null_
824827-- (TRUE >= NULL)
825828(.>=)
826− :: Expression schema from grouping params (nullity0 ty) -- ^ lhs
827− -> Expression schema from grouping params (nullity1 ty) -- ^ rhs
828− -> Condition schema from grouping params
829+ :: Expression db from grouping params (nullity0 ty) -- ^ lhs
830+ -> Expression db from grouping params (nullity1 ty) -- ^ rhs
831+ -> Condition db from grouping params
829832(.>=) = unsafeBinaryOp ">="
830833infix 4 .>=
831834
832835-- | >>> printSQL $ true .< null_
833836-- (TRUE < NULL)
834837(.<)
835− :: Expression schema from grouping params (nullity0 ty) -- ^ lhs
836− -> Expression schema from grouping params (nullity1 ty) -- ^ rhs
837− -> Condition schema from grouping params
838+ :: Expression db from grouping params (nullity0 ty) -- ^ lhs
839+ -> Expression db from grouping params (nullity1 ty) -- ^ rhs
840+ -> Condition db from grouping params
838841(.<) = unsafeBinaryOp "<"
839842infix 4 .<
840843
841844-- | >>> printSQL $ true .<= null_
842845-- (TRUE <= NULL)
843846(.<=)
844− :: Expression schema from grouping params (nullity0 ty) -- ^ lhs
845− -> Expression schema from grouping params (nullity1 ty) -- ^ rhs
846− -> Condition schema from grouping params
847+ :: Expression db from grouping params (nullity0 ty) -- ^ lhs
848+ -> Expression db from grouping params (nullity1 ty) -- ^ rhs
849+ -> Condition db from grouping params
847850(.<=) = unsafeBinaryOp "<="
848851infix 4 .<=
849852
850853-- | >>> printSQL $ true .> null_
851854-- (TRUE > NULL)
852855(.>)
853− :: Expression schema from grouping params (nullity0 ty) -- ^ lhs
854− -> Expression schema from grouping params (nullity1 ty) -- ^ rhs
855− -> Condition schema from grouping params
856+ :: Expression db from grouping params (nullity0 ty) -- ^ lhs
857+ -> Expression db from grouping params (nullity1 ty) -- ^ rhs
858+ -> Condition db from grouping params
856859(.>) = unsafeBinaryOp ">"
857860infix 4 .>
858861
859862-- | >>> printSQL currentDate
860863-- CURRENT_DATE
861864currentDate
862− :: Expression schema from grouping params (nullity 'PGdate)
865+ :: Expression db from grouping params (nullity 'PGdate)
863866currentDate = UnsafeExpression "CURRENT_DATE"
864867
865868-- | >>> printSQL currentTime
866869-- CURRENT_TIME
867870currentTime
868− :: Expression schema from grouping params (nullity 'PGtimetz)
871+ :: Expression db from grouping params (nullity 'PGtimetz)
869872currentTime = UnsafeExpression "CURRENT_TIME"
870873
871874-- | >>> printSQL currentTimestamp
872875-- CURRENT_TIMESTAMP
873876currentTimestamp
874− :: Expression schema from grouping params (nullity 'PGtimestamptz)
877+ :: Expression db from grouping params (nullity 'PGtimestamptz)
875878currentTimestamp = UnsafeExpression "CURRENT_TIMESTAMP"
876879
877880-- | >>> printSQL localTime
878881-- LOCALTIME
879882localTime
880− :: Expression schema from grouping params (nullity 'PGtime)
883+ :: Expression db from grouping params (nullity 'PGtime)
881884localTime = UnsafeExpression "LOCALTIME"
882885
883886-- | >>> printSQL localTimestamp
884887-- LOCALTIMESTAMP
885888localTimestamp
886− :: Expression schema from grouping params (nullity 'PGtimestamp)
889+ :: Expression db from grouping params (nullity 'PGtimestamp)
887890localTimestamp = UnsafeExpression "LOCALTIMESTAMP"
888891
889892{-----------------------------------------
@@ -891,7 +894,7 @@ text
891894-----------------------------------------}
892895
893896instance IsString
894− (Expression schema from grouping params (nullity 'PGtext)) where
897+ (Expression db from grouping params (nullity 'PGtext)) where
895898 fromString str = UnsafeExpression $
896899 "E\'" <> fromString (escape =<< str) <> "\'"
897900 where
@@ -907,36 +910,36 @@ instance IsString
907910 c -> [c]
908911
909912instance Semigroup
910− (Expression schema from grouping params (nullity 'PGtext)) where
913+ (Expression db from grouping params (nullity 'PGtext)) where
911914 (<>) = unsafeBinaryOp "||"
912915
913916instance Monoid
914− (Expression schema from grouping params (nullity 'PGtext)) where
917+ (Expression db from grouping params (nullity 'PGtext)) where
915918 mempty = fromString ""
916919 mappend = (<>)
917920
918921-- | >>> printSQL $ lower "ARRRGGG"
919922-- lower(E'ARRRGGG')
920923lower
921− :: Expression schema from grouping params (nullity 'PGtext)
924+ :: Expression db from grouping params (nullity 'PGtext)
922925 -- ^ string to lower case
923− -> Expression schema from grouping params (nullity 'PGtext)
926+ -> Expression db from grouping params (nullity 'PGtext)
924927lower = unsafeFunction "lower"
925928
926929-- | >>> printSQL $ upper "eeee"
927930-- upper(E'eeee')
928931upper
929− :: Expression schema from grouping params (nullity 'PGtext)
932+ :: Expression db from grouping params (nullity 'PGtext)
930933 -- ^ string to upper case
931− -> Expression schema from grouping params (nullity 'PGtext)
934+ -> Expression db from grouping params (nullity 'PGtext)
932935upper = unsafeFunction "upper"
933936
934937-- | >>> printSQL $ charLength "four"
935938-- char_length(E'four')
936939charLength
937− :: Expression schema from grouping params (nullity 'PGtext)
940+ :: Expression db from grouping params (nullity 'PGtext)
938941 -- ^ string to measure
939− -> Expression schema from grouping params (nullity 'PGint4)
942+ -> Expression db from grouping params (nullity 'PGint4)
940943charLength = unsafeFunction "char_length"
941944
942945-- | The `like` expression returns true if the @string@ matches
@@ -949,11 +952,11 @@ charLength = unsafeFunction "char_length"
949952-- >>> printSQL $ "abc" `like` "a%"
950953-- (E'abc' LIKE E'a%')
951954like
952− :: Expression schema from grouping params (nullity 'PGtext)
955+ :: Expression db from grouping params (nullity 'PGtext)
953956 -- ^ string
954− -> Expression schema from grouping params (nullity 'PGtext)
957+ -> Expression db from grouping params (nullity 'PGtext)
955958 -- ^ pattern
956− -> Expression schema from grouping params (nullity 'PGbool)
959+ -> Expression db from grouping params (nullity 'PGbool)
957960like = unsafeBinaryOp "LIKE"
958961
959962-- | The key word ILIKE can be used instead of LIKE to make the
@@ -981,36 +984,36 @@ Table 9.44: json and jsonb operators
981984-- | Get JSON value (object field or array element) at a key.
982985(.->)
983986 :: (json `In` PGJsonType, key `In` PGJsonKey)
984− => Expression schema from grouping params (nullity json)
985− -> Expression schema from grouping params (nullity key)
986− -> Expression schema from grouping params ('Null json)
987+ => Expression db from grouping params (nullity json)
988+ -> Expression db from grouping params (nullity key)
989+ -> Expression db from grouping params ('Null json)
987990infixl 8 .->
988991(.->) = unsafeBinaryOp "->"
989992
990993-- | Get JSON value (object field or array element) at a key, as text.
991994(.->>)
992995 :: (json `In` PGJsonType, key `In` PGJsonKey)
993− => Expression schema from grouping params (nullity json)
994− -> Expression schema from grouping params (nullity key)
995− -> Expression schema from grouping params ('Null 'PGtext)
996+ => Expression db from grouping params (nullity json)
997+ -> Expression db from grouping params (nullity key)
998+ -> Expression db from grouping params ('Null 'PGtext)
996999infixl 8 .->>
9971000(.->>) = unsafeBinaryOp "->>"
9981001
9991002-- | Get JSON value at a specified path.
10001003(.#>)
10011004 :: (json `In` PGJsonType, PGTextArray "(.#>)" path)
1002− => Expression schema from grouping params (nullity json)
1003− -> Expression schema from grouping params (nullity path)
1004− -> Expression schema from grouping params ('Null json)
1005+ => Expression db from grouping params (nullity json)
1006+ -> Expression db from grouping params (nullity path)
1007+ -> Expression db from grouping params ('Null json)
10051008infixl 8 .#>
10061009(.#>) = unsafeBinaryOp "#>"
10071010
10081011-- | Get JSON value at a specified path as text.
10091012(.#>>)
10101013 :: (json `In` PGJsonType, PGTextArray "(.#>>)" path)
1011− => Expression schema from grouping params (nullity json)
1012− -> Expression schema from grouping params (nullity path)
1013− -> Expression schema from grouping params ('Null 'PGtext)
1014+ => Expression db from grouping params (nullity json)
1015+ -> Expression db from grouping params (nullity path)
1016+ -> Expression db from grouping params ('Null 'PGtext)
10141017infixl 8 .#>>
10151018(.#>>) = unsafeBinaryOp "#>>"
10161019
@@ -1019,48 +1022,48 @@ infixl 8 .#>>
10191022-- | Does the left JSON value contain the right JSON path/value entries at the
10201023-- top level?
10211024(.@>)
1022− :: Expression schema from grouping params (nullity 'PGjsonb)
1023− -> Expression schema from grouping params (nullity 'PGjsonb)
1024− -> Condition schema from grouping params
1025+ :: Expression db from grouping params (nullity 'PGjsonb)
1026+ -> Expression db from grouping params (nullity 'PGjsonb)
1027+ -> Condition db from grouping params
10251028infixl 9 .@>
10261029(.@>) = unsafeBinaryOp "@>"
10271030
10281031-- | Are the left JSON path/value entries contained at the top level within the
10291032-- right JSON value?
10301033(.<@)
1031− :: Expression schema from grouping params (nullity 'PGjsonb)
1032− -> Expression schema from grouping params (nullity 'PGjsonb)
1033− -> Condition schema from grouping params
1034+ :: Expression db from grouping params (nullity 'PGjsonb)
1035+ -> Expression db from grouping params (nullity 'PGjsonb)
1036+ -> Condition db from grouping params
10341037infixl 9 .<@
10351038(.<@) = unsafeBinaryOp "<@"
10361039
10371040-- | Does the string exist as a top-level key within the JSON value?
10381041(.?)
1039− :: Expression schema from grouping params (nullity 'PGjsonb)
1040− -> Expression schema from grouping params (nullity 'PGtext)
1041− -> Condition schema from grouping params
1042+ :: Expression db from grouping params (nullity 'PGjsonb)
1043+ -> Expression db from grouping params (nullity 'PGtext)
1044+ -> Condition db from grouping params
10421045infixl 9 .?
10431046(.?) = unsafeBinaryOp "?"
10441047
10451048-- | Do any of these array strings exist as top-level keys?
10461049(.?|)
1047− :: Expression schema from grouping params (nullity 'PGjsonb)
1048− -> Expression schema from grouping params (nullity ('PGvararray ('NotNull 'PGtext)))
1049− -> Condition schema from grouping params
1050+ :: Expression db from grouping params (nullity 'PGjsonb)
1051+ -> Expression db from grouping params (nullity ('PGvararray ('NotNull 'PGtext)))
1052+ -> Condition db from grouping params
10501053infixl 9 .?|
10511054(.?|) = unsafeBinaryOp "?|"
10521055
10531056-- | Do all of these array strings exist as top-level keys?
10541057(.?&)
1055− :: Expression schema from grouping params (nullity 'PGjsonb)
1056− -> Expression schema from grouping params (nullity ('PGvararray ('NotNull 'PGtext)))
1057− -> Condition schema from grouping params
1058+ :: Expression db from grouping params (nullity 'PGjsonb)
1059+ -> Expression db from grouping params (nullity ('PGvararray ('NotNull 'PGtext)))
1060+ -> Condition db from grouping params
10581061infixl 9 .?&
10591062(.?&) = unsafeBinaryOp "?&"
10601063
10611064-- | Concatenate two jsonb values into a new jsonb value.
10621065instance
1063− Semigroup (Expression schema from grouping param (nullity 'PGjsonb)) where
1066+ Semigroup (Expression db from grouping param (nullity 'PGjsonb)) where
10641067 (<>) = unsafeBinaryOp "||"
10651068
10661069-- | Delete a key or keys from a JSON object, or remove an array element.
@@ -1077,9 +1080,9 @@ instance
10771080-- count from the end). Throws an error if top level container is not an array.
10781081(.-.)
10791082 :: (key `In` '[ 'PGtext, 'PGvararray ('NotNull 'PGtext), 'PGint4, 'PGint2 ]) -- hlint error without parens here
1080− => Expression schema from grouping params (nullity 'PGjsonb)
1081− -> Expression schema from grouping params (nullity key)
1082− -> Expression schema from grouping params (nullity 'PGjsonb)
1083+ => Expression db from grouping params (nullity 'PGjsonb)
1084+ -> Expression db from grouping params (nullity key)
1085+ -> Expression db from grouping params (nullity 'PGjsonb)
10831086infixl 6 .-.
10841087(.-.) = unsafeBinaryOp "-"
10851088
@@ -1087,9 +1090,9 @@ infixl 6 .-.
10871090-- integers count from the end)
10881091(#-.)
10891092 :: PGTextArray "(#-.)" arrayty
1090− => Expression schema from grouping params (nullity 'PGjsonb)
1091− -> Expression schema from grouping params (nullity arrayty)
1092− -> Expression schema from grouping params (nullity 'PGjsonb)
1093+ => Expression db from grouping params (nullity 'PGjsonb)
1094+ -> Expression db from grouping params (nullity arrayty)
1095+ -> Expression db from grouping params (nullity 'PGjsonb)
10931096infixl 6 #-.
10941097(#-.) = unsafeBinaryOp "#-"
10951098
@@ -1100,14 +1103,14 @@ Table 9.45: JSON creation functions
11001103-- | Literal binary JSON
11011104jsonbLit
11021105 :: JSON.ToJSON x
1103− => x -> Expression schema from grouping params (nullity 'PGjsonb)
1106+ => x -> Expression (commons :=> schemas) from grouping params (nullity 'PGjsonb)
11041107jsonbLit = cast jsonb . UnsafeExpression
11051108 . singleQuotedUtf8 . toStrict . JSON.encode
11061109
11071110-- | Literal JSON
11081111jsonLit
11091112 :: JSON.ToJSON x
1110− => x -> Expression schema from grouping params (nullity 'PGjson)
1113+ => x -> Expression (commons :=> schemas) from grouping params (nullity 'PGjson)
11111114jsonLit = cast json . UnsafeExpression
11121115 . singleQuotedUtf8 . toStrict . JSON.encode
11131116
@@ -1118,8 +1121,8 @@ jsonLit = cast json . UnsafeExpression
11181121-- number, a Boolean, or a null value, the text representation will be used, in
11191122-- such a fashion that it is a valid json value.
11201123toJson
1121− :: Expression schema from grouping params (nullity ty)
1122− -> Expression schema from grouping params (nullity 'PGjson)
1124+ :: Expression db from grouping params (nullity ty)
1125+ -> Expression db from grouping params (nullity 'PGjson)
11231126toJson = unsafeFunction "to_json"
11241127
11251128-- | Returns the value as jsonb. Arrays and composites are converted
@@ -1129,43 +1132,43 @@ toJson = unsafeFunction "to_json"
11291132-- number, a Boolean, or a null value, the text representation will be used, in
11301133-- such a fashion that it is a valid jsonb value.
11311134toJsonb
1132− :: Expression schema from grouping params (nullity ty)
1133− -> Expression schema from grouping params (nullity 'PGjsonb)
1135+ :: Expression db from grouping params (nullity ty)
1136+ -> Expression db from grouping params (nullity 'PGjsonb)
11341137toJsonb = unsafeFunction "to_jsonb"
11351138
11361139-- | Returns the array as a JSON array. A PostgreSQL multidimensional array
11371140-- becomes a JSON array of arrays.
11381141arrayToJson
11391142 :: PGArray "arrayToJson" arr
1140− => Expression schema from grouping params (nullity arr)
1141− -> Expression schema from grouping params (nullity 'PGjson)
1143+ => Expression db from grouping params (nullity arr)
1144+ -> Expression db from grouping params (nullity 'PGjson)
11421145arrayToJson = unsafeFunction "array_to_json"
11431146
11441147-- | Returns the row as a JSON object.
11451148rowToJson
1146− :: Expression schema from grouping params (nullity ('PGcomposite ty))
1147− -> Expression schema from grouping params (nullity 'PGjson)
1149+ :: Expression db from grouping params (nullity ('PGcomposite ty))
1150+ -> Expression db from grouping params (nullity 'PGjson)
11481151rowToJson = unsafeFunction "row_to_json"
11491152
11501153-- | Builds a possibly-heterogeneously-typed JSON array out of a variadic
11511154-- argument list.
11521155jsonBuildArray
11531156 :: SListI elems
1154− => NP (Expression schema from grouping params) elems
1155− -> Expression schema from grouping params (nullity 'PGjson)
1157+ => NP (Expression db from grouping params) elems
1158+ -> Expression db from grouping params (nullity 'PGjson)
11561159jsonBuildArray = unsafeVariadicFunction "json_build_array"
11571160
11581161-- | Builds a possibly-heterogeneously-typed (binary) JSON array out of a
11591162-- variadic argument list.
11601163jsonbBuildArray
11611164 :: SListI elems
1162− => NP (Expression schema from grouping params) elems
1163− -> Expression schema from grouping params (nullity 'PGjsonb)
1165+ => NP (Expression db from grouping params) elems
1166+ -> Expression db from grouping params (nullity 'PGjsonb)
11641167jsonbBuildArray = unsafeVariadicFunction "jsonb_build_array"
11651168
11661169unsafeRowFunction
11671170 :: All Top elems
1168− => NP (Aliased (Expression schema from grouping params)) elems
1171+ => NP (Aliased (Expression db from grouping params)) elems
11691172 -> [ByteString]
11701173unsafeRowFunction =
11711174 (`appEndo` []) . hcfoldMap (Proxy :: Proxy Top)
@@ -1177,8 +1180,8 @@ unsafeRowFunction =
11771180-- and values.
11781181jsonBuildObject
11791182 :: All Top elems
1180− => NP (Aliased (Expression schema from grouping params)) elems
1181− -> Expression schema from grouping params (nullity 'PGjson)
1183+ => NP (Aliased (Expression db from grouping params)) elems
1184+ -> Expression db from grouping params (nullity 'PGjson)
11821185jsonBuildObject
11831186 = unsafeFunction "json_build_object"
11841187 . UnsafeExpression
@@ -1190,8 +1193,8 @@ jsonBuildObject
11901193-- between text and values.
11911194jsonbBuildObject
11921195 :: All Top elems
1193− => NP (Aliased (Expression schema from grouping params)) elems
1194− -> Expression schema from grouping params (nullity 'PGjsonb)
1196+ => NP (Aliased (Expression db from grouping params)) elems
1197+ -> Expression db from grouping params (nullity 'PGjsonb)
11951198jsonbBuildObject
11961199 = unsafeFunction "jsonb_build_object"
11971200 . UnsafeExpression
@@ -1204,8 +1207,8 @@ jsonbBuildObject
12041207-- array has exactly two elements, which are taken as a key/value pair.
12051208jsonObject
12061209 :: PGArrayOf "jsonObject" arr ('NotNull 'PGtext)
1207− => Expression schema from grouping params (nullity arr)
1208− -> Expression schema from grouping params (nullity 'PGjson)
1210+ => Expression db from grouping params (nullity arr)
1211+ -> Expression db from grouping params (nullity 'PGjson)
12091212jsonObject = unsafeFunction "json_object"
12101213
12111214-- | Builds a binary JSON object out of a text array. The array must have either
@@ -1214,8 +1217,8 @@ jsonObject = unsafeFunction "json_object"
12141217-- array has exactly two elements, which are taken as a key/value pair.
12151218jsonbObject
12161219 :: PGArrayOf "jsonbObject" arr ('NotNull 'PGtext)
1217− => Expression schema from grouping params (nullity arr)
1218− -> Expression schema from grouping params (nullity 'PGjsonb)
1220+ => Expression db from grouping params (nullity arr)
1221+ -> Expression db from grouping params (nullity 'PGjsonb)
12191222jsonbObject = unsafeFunction "jsonb_object"
12201223
12211224-- | This is an alternate form of 'jsonObject' that takes two arrays; one for
@@ -1223,9 +1226,9 @@ jsonbObject = unsafeFunction "jsonb_object"
12231226jsonZipObject
12241227 :: ( PGArrayOf "jsonZipObject" keysArray ('NotNull 'PGtext)
12251228 , PGArrayOf "jsonZipObject" valuesArray ('NotNull 'PGtext))
1226− => Expression schema from grouping params (nullity keysArray)
1227− -> Expression schema from grouping params (nullity valuesArray)
1228− -> Expression schema from grouping params (nullity 'PGjson)
1229+ => Expression db from grouping params (nullity keysArray)
1230+ -> Expression db from grouping params (nullity valuesArray)
1231+ -> Expression db from grouping params (nullity 'PGjson)
12291232jsonZipObject ks vs =
12301233 unsafeVariadicFunction "json_object" (ks :* vs :* Nil)
12311234
@@ -1235,9 +1238,9 @@ jsonZipObject ks vs =
12351238jsonbZipObject
12361239 :: ( PGArrayOf "jsonbZipObject" keysArray ('NotNull 'PGtext)
12371240 , PGArrayOf "jsonbZipObject" valuesArray ('NotNull 'PGtext))
1238− => Expression schema from grouping params (nullity keysArray)
1239− -> Expression schema from grouping params (nullity valuesArray)
1240− -> Expression schema from grouping params (nullity 'PGjsonb)
1241+ => Expression db from grouping params (nullity keysArray)
1242+ -> Expression db from grouping params (nullity valuesArray)
1243+ -> Expression db from grouping params (nullity 'PGjsonb)
12411244jsonbZipObject ks vs =
12421245 unsafeVariadicFunction "jsonb_object" (ks :* vs :* Nil)
12431246
@@ -1247,23 +1250,23 @@ Table 9.46: JSON processing functions
12471250
12481251-- | Returns the number of elements in the outermost JSON array.
12491252jsonArrayLength
1250− :: Expression schema from grouping params (nullity 'PGjson)
1251− -> Expression schema from grouping params (nullity 'PGint4)
1253+ :: Expression db from grouping params (nullity 'PGjson)
1254+ -> Expression db from grouping params (nullity 'PGint4)
12521255jsonArrayLength = unsafeFunction "json_array_length"
12531256
12541257-- | Returns the number of elements in the outermost binary JSON array.
12551258jsonbArrayLength
1256− :: Expression schema from grouping params (nullity 'PGjsonb)
1257− -> Expression schema from grouping params (nullity 'PGint4)
1259+ :: Expression db from grouping params (nullity 'PGjsonb)
1260+ -> Expression db from grouping params (nullity 'PGint4)
12581261jsonbArrayLength = unsafeFunction "jsonb_array_length"
12591262
12601263-- | Returns JSON value pointed to by the given path (equivalent to #>
12611264-- operator).
12621265jsonExtractPath
12631266 :: SListI elems
1264− => Expression schema from grouping params (nullity 'PGjson)
1265− -> NP (Expression schema from grouping params) elems
1266− -> Expression schema from grouping params (nullity 'PGjsonb)
1267+ => Expression db from grouping params (nullity 'PGjson)
1268+ -> NP (Expression db from grouping params) elems
1269+ -> Expression db from grouping params (nullity 'PGjsonb)
12671270jsonExtractPath x xs =
12681271 unsafeVariadicFunction "json_extract_path" (x :* xs)
12691272
@@ -1271,9 +1274,9 @@ jsonExtractPath x xs =
12711274-- operator).
12721275jsonbExtractPath
12731276 :: SListI elems
1274− => Expression schema from grouping params (nullity 'PGjsonb)
1275− -> NP (Expression schema from grouping params) elems
1276− -> Expression schema from grouping params (nullity 'PGjsonb)
1277+ => Expression db from grouping params (nullity 'PGjsonb)
1278+ -> NP (Expression db from grouping params) elems
1279+ -> Expression db from grouping params (nullity 'PGjsonb)
12771280jsonbExtractPath x xs =
12781281 unsafeVariadicFunction "jsonb_extract_path" (x :* xs)
12791282
@@ -1281,9 +1284,9 @@ jsonbExtractPath x xs =
12811284-- operator), as text.
12821285jsonExtractPathAsText
12831286 :: SListI elems
1284− => Expression schema from grouping params (nullity 'PGjson)
1285− -> NP (Expression schema from grouping params) elems
1286− -> Expression schema from grouping params (nullity 'PGjson)
1287+ => Expression db from grouping params (nullity 'PGjson)
1288+ -> NP (Expression db from grouping params) elems
1289+ -> Expression db from grouping params (nullity 'PGjson)
12871290jsonExtractPathAsText x xs =
12881291 unsafeVariadicFunction "json_extract_path_text" (x :* xs)
12891292
@@ -1291,38 +1294,38 @@ jsonExtractPathAsText x xs =
12911294-- operator), as text.
12921295jsonbExtractPathAsText
12931296 :: SListI elems
1294− => Expression schema from grouping params (nullity 'PGjsonb)
1295− -> NP (Expression schema from grouping params) elems
1296− -> Expression schema from grouping params (nullity 'PGjsonb)
1297+ => Expression db from grouping params (nullity 'PGjsonb)
1298+ -> NP (Expression db from grouping params) elems
1299+ -> Expression db from grouping params (nullity 'PGjsonb)
12971300jsonbExtractPathAsText x xs =
12981301 unsafeVariadicFunction "jsonb_extract_path_text" (x :* xs)
12991302
13001303-- | Returns the type of the outermost JSON value as a text string. Possible
13011304-- types are object, array, string, number, boolean, and null.
13021305jsonTypeof
1303− :: Expression schema from grouping params (nullity 'PGjson)
1304− -> Expression schema from grouping params (nullity 'PGtext)
1306+ :: Expression db from grouping params (nullity 'PGjson)
1307+ -> Expression db from grouping params (nullity 'PGtext)
13051308jsonTypeof = unsafeFunction "json_typeof"
13061309
13071310-- | Returns the type of the outermost binary JSON value as a text string.
13081311-- Possible types are object, array, string, number, boolean, and null.
13091312jsonbTypeof
1310− :: Expression schema from grouping params (nullity 'PGjsonb)
1311− -> Expression schema from grouping params (nullity 'PGtext)
1313+ :: Expression db from grouping params (nullity 'PGjsonb)
1314+ -> Expression db from grouping params (nullity 'PGtext)
13121315jsonbTypeof = unsafeFunction "jsonb_typeof"
13131316
13141317-- | Returns its argument with all object fields that have null values omitted.
13151318-- Other null values are untouched.
13161319jsonStripNulls
1317− :: Expression schema from grouping params (nullity 'PGjson)
1318− -> Expression schema from grouping params (nullity 'PGjson)
1320+ :: Expression db from grouping params (nullity 'PGjson)
1321+ -> Expression db from grouping params (nullity 'PGjson)
13191322jsonStripNulls = unsafeFunction "json_strip_nulls"
13201323
13211324-- | Returns its argument with all object fields that have null values omitted.
13221325-- Other null values are untouched.
13231326jsonbStripNulls
1324− :: Expression schema from grouping params (nullity 'PGjsonb)
1325− -> Expression schema from grouping params (nullity 'PGjsonb)
1327+ :: Expression db from grouping params (nullity 'PGjsonb)
1328+ -> Expression db from grouping params (nullity 'PGjsonb)
13261329jsonbStripNulls = unsafeFunction "jsonb_strip_nulls"
13271330
13281331-- | @ jsonbSet target path new_value create_missing @
@@ -1334,11 +1337,11 @@ jsonbStripNulls = unsafeFunction "jsonb_strip_nulls"
13341337-- arrays.
13351338jsonbSet
13361339 :: PGTextArray "jsonbSet" arr
1337− => Expression schema from grouping params (nullity 'PGjsonb)
1338− -> Expression schema from grouping params (nullity arr)
1339− -> Expression schema from grouping params (nullity 'PGjsonb)
1340− -> Maybe (Expression schema from grouping params (nullity 'PGbool))
1341− -> Expression schema from grouping params (nullity 'PGjsonb)
1340+ => Expression db from grouping params (nullity 'PGjsonb)
1341+ -> Expression db from grouping params (nullity arr)
1342+ -> Expression db from grouping params (nullity 'PGjsonb)
1343+ -> Maybe (Expression db from grouping params (nullity 'PGbool))
1344+ -> Expression db from grouping params (nullity 'PGjsonb)
13421345jsonbSet tgt path val createMissing = case createMissing of
13431346 Just m -> unsafeVariadicFunction "jsonb_set" (tgt :* path :* val :* m :* Nil)
13441347 Nothing -> unsafeVariadicFunction "jsonb_set" (tgt :* path :* val :* Nil)
@@ -1353,19 +1356,19 @@ jsonbSet tgt path val createMissing = case createMissing of
13531356-- in path count from the end of JSON arrays.
13541357jsonbInsert
13551358 :: PGTextArray "jsonbInsert" arr
1356− => Expression schema from grouping params (nullity 'PGjsonb)
1357− -> Expression schema from grouping params (nullity arr)
1358− -> Expression schema from grouping params (nullity 'PGjsonb)
1359− -> Maybe (Expression schema from grouping params (nullity 'PGbool))
1360− -> Expression schema from grouping params (nullity 'PGjsonb)
1359+ => Expression db from grouping params (nullity 'PGjsonb)
1360+ -> Expression db from grouping params (nullity arr)
1361+ -> Expression db from grouping params (nullity 'PGjsonb)
1362+ -> Maybe (Expression db from grouping params (nullity 'PGbool))
1363+ -> Expression db from grouping params (nullity 'PGjsonb)
13611364jsonbInsert tgt path val insertAfter = case insertAfter of
13621365 Just i -> unsafeVariadicFunction "jsonb_insert" (tgt :* path :* val :* i :* Nil)
13631366 Nothing -> unsafeVariadicFunction "jsonb_insert" (tgt :* path :* val :* Nil)
13641367
13651368-- | Returns its argument as indented JSON text.
13661369jsonbPretty
1367− :: Expression schema from grouping params (nullity 'PGjsonb)
1368− -> Expression schema from grouping params (nullity 'PGtext)
1370+ :: Expression db from grouping params (nullity 'PGjsonb)
1371+ -> Expression db from grouping params (nullity 'PGtext)
13691372jsonbPretty = unsafeFunction "jsonb_pretty"
13701373
13711374{-----------------------------------------
@@ -1375,54 +1378,54 @@ aggregation
13751378-- | escape hatch to define aggregate functions
13761379unsafeAggregate
13771380 :: ByteString -- ^ aggregate function
1378− -> Expression schema from 'Ungrouped params (xty)
1379− -> Expression schema from ('Grouped bys) params (yty)
1381+ -> Expression db from 'Ungrouped params (xty)
1382+ -> Expression db from ('Grouped bys) params (yty)
13801383unsafeAggregate fun x = UnsafeExpression $ mconcat
13811384 [fun, "(", renderExpression x, ")"]
13821385
13831386-- | escape hatch to define aggregate functions over distinct values
13841387unsafeAggregateDistinct
13851388 :: ByteString -- ^ aggregate function
1386− -> Expression schema from 'Ungrouped params (xty)
1387− -> Expression schema from ('Grouped bys) params (yty)
1389+ -> Expression db from 'Ungrouped params (xty)
1390+ -> Expression db from ('Grouped bys) params (yty)
13881391unsafeAggregateDistinct fun x = UnsafeExpression $ mconcat
13891392 [fun, "(DISTINCT ", renderExpression x, ")"]
13901393
13911394-- | >>> :{
13921395-- let
1393−-- expression :: Expression schema '[tab ::: '["col" ::: 'Null 'PGnumeric]] ('Grouped bys) params ('Null 'PGnumeric)
1396+-- expression :: Expression db '[tab ::: '["col" ::: 'Null 'PGnumeric]] ('Grouped bys) params ('Null 'PGnumeric)
13941397-- expression = sum_ #col
13951398-- in printSQL expression
13961399-- :}
13971400-- sum("col")
13981401sum_
13991402 :: ty `In` PGNum
1400− => Expression schema from 'Ungrouped params (nullity ty)
1403+ => Expression db from 'Ungrouped params (nullity ty)
14011404 -- ^ what to sum
1402− -> Expression schema from ('Grouped bys) params (nullity ty)
1405+ -> Expression db from ('Grouped bys) params (nullity ty)
14031406sum_ = unsafeAggregate "sum"
14041407
14051408-- | >>> :{
14061409-- let
1407−-- expression :: Expression schema '[tab ::: '["col" ::: nullity 'PGnumeric]] ('Grouped bys) params (nullity 'PGnumeric)
1410+-- expression :: Expression db '[tab ::: '["col" ::: nullity 'PGnumeric]] ('Grouped bys) params (nullity 'PGnumeric)
14081411-- expression = sumDistinct #col
14091412-- in printSQL expression
14101413-- :}
14111414-- sum(DISTINCT "col")
14121415sumDistinct
14131416 :: ty `In` PGNum
1414− => Expression schema from 'Ungrouped params (nullity ty)
1417+ => Expression db from 'Ungrouped params (nullity ty)
14151418 -- ^ what to sum
1416− -> Expression schema from ('Grouped bys) params (nullity ty)
1419+ -> Expression db from ('Grouped bys) params (nullity ty)
14171420sumDistinct = unsafeAggregateDistinct "sum"
14181421
14191422-- | A constraint for `PGType`s that you can take averages of and the resulting
14201423-- `PGType`.
14211424class PGAvg ty avg | ty -> avg where
14221425 avg, avgDistinct
1423− :: Expression schema from 'Ungrouped params (nullity ty)
1426+ :: Expression db from 'Ungrouped params (nullity ty)
14241427 -- ^ what to average
1425− -> Expression schema from ('Grouped bys) params (nullity avg)
1428+ -> Expression db from ('Grouped bys) params (nullity avg)
14261429 avg = unsafeAggregate "avg"
14271430 avgDistinct = unsafeAggregateDistinct "avg"
14281431instance PGAvg 'PGint2 'PGnumeric
@@ -1435,110 +1438,110 @@ instance PGAvg 'PGinterval 'PGinterval
14351438
14361439-- | >>> :{
14371440-- let
1438−-- expression :: Expression schema '[tab ::: '["col" ::: nullity 'PGint4]] (Grouped bys) params (nullity 'PGint4)
1441+-- expression :: Expression db '[tab ::: '["col" ::: nullity 'PGint4]] (Grouped bys) params (nullity 'PGint4)
14391442-- expression = bitAnd #col
14401443-- in printSQL expression
14411444-- :}
14421445-- bit_and("col")
14431446bitAnd
14441447 :: int `In` PGIntegral
1445− => Expression schema from 'Ungrouped params (nullity int)
1448+ => Expression db from 'Ungrouped params (nullity int)
14461449 -- ^ what to aggregate
1447− -> Expression schema from ('Grouped bys) params (nullity int)
1450+ -> Expression db from ('Grouped bys) params (nullity int)
14481451bitAnd = unsafeAggregate "bit_and"
14491452
14501453-- | >>> :{
14511454-- let
1452−-- expression :: Expression schema '[tab ::: '["col" ::: nullity 'PGint4]] (Grouped bys) params (nullity 'PGint4)
1455+-- expression :: Expression db '[tab ::: '["col" ::: nullity 'PGint4]] (Grouped bys) params (nullity 'PGint4)
14531456-- expression = bitOr #col
14541457-- in printSQL expression
14551458-- :}
14561459-- bit_or("col")
14571460bitOr
14581461 :: int `In` PGIntegral
1459− => Expression schema from 'Ungrouped params (nullity int)
1462+ => Expression db from 'Ungrouped params (nullity int)
14601463 -- ^ what to aggregate
1461− -> Expression schema from ('Grouped bys) params (nullity int)
1464+ -> Expression db from ('Grouped bys) params (nullity int)
14621465bitOr = unsafeAggregate "bit_or"
14631466
14641467-- | >>> :{
14651468-- let
1466−-- expression :: Expression schema '[tab ::: '["col" ::: nullity 'PGint4]] (Grouped bys) params (nullity 'PGint4)
1469+-- expression :: Expression db '[tab ::: '["col" ::: nullity 'PGint4]] (Grouped bys) params (nullity 'PGint4)
14671470-- expression = bitAndDistinct #col
14681471-- in printSQL expression
14691472-- :}
14701473-- bit_and(DISTINCT "col")
14711474bitAndDistinct
14721475 :: int `In` PGIntegral
1473− => Expression schema from 'Ungrouped params (nullity int)
1476+ => Expression db from 'Ungrouped params (nullity int)
14741477 -- ^ what to aggregate
1475− -> Expression schema from ('Grouped bys) params (nullity int)
1478+ -> Expression db from ('Grouped bys) params (nullity int)
14761479bitAndDistinct = unsafeAggregateDistinct "bit_and"
14771480
14781481-- | >>> :{
14791482-- let
1480−-- expression :: Expression schema '[tab ::: '["col" ::: nullity 'PGint4]] (Grouped bys) params (nullity 'PGint4)
1483+-- expression :: Expression db '[tab ::: '["col" ::: nullity 'PGint4]] (Grouped bys) params (nullity 'PGint4)
14811484-- expression = bitOrDistinct #col
14821485-- in printSQL expression
14831486-- :}
14841487-- bit_or(DISTINCT "col")
14851488bitOrDistinct
14861489 :: int `In` PGIntegral
1487− => Expression schema from 'Ungrouped params (nullity int)
1490+ => Expression db from 'Ungrouped params (nullity int)
14881491 -- ^ what to aggregate
1489− -> Expression schema from ('Grouped bys) params (nullity int)
1492+ -> Expression db from ('Grouped bys) params (nullity int)
14901493bitOrDistinct = unsafeAggregateDistinct "bit_or"
14911494
14921495-- | >>> :{
14931496-- let
1494−-- expression :: Expression schema '[tab ::: '["col" ::: nullity 'PGbool]] (Grouped bys) params (nullity 'PGbool)
1497+-- expression :: Expression db '[tab ::: '["col" ::: nullity 'PGbool]] (Grouped bys) params (nullity 'PGbool)
14951498-- expression = boolAnd #col
14961499-- in printSQL expression
14971500-- :}
14981501-- bool_and("col")
14991502boolAnd
1500− :: Expression schema from 'Ungrouped params (nullity 'PGbool)
1503+ :: Expression db from 'Ungrouped params (nullity 'PGbool)
15011504 -- ^ what to aggregate
1502− -> Expression schema from ('Grouped bys) params (nullity 'PGbool)
1505+ -> Expression db from ('Grouped bys) params (nullity 'PGbool)
15031506boolAnd = unsafeAggregate "bool_and"
15041507
15051508-- | >>> :{
15061509-- let
1507−-- expression :: Expression schema '[tab ::: '["col" ::: nullity 'PGbool]] (Grouped bys) params (nullity 'PGbool)
1510+-- expression :: Expression db '[tab ::: '["col" ::: nullity 'PGbool]] (Grouped bys) params (nullity 'PGbool)
15081511-- expression = boolOr #col
15091512-- in printSQL expression
15101513-- :}
15111514-- bool_or("col")
15121515boolOr
1513− :: Expression schema from 'Ungrouped params (nullity 'PGbool)
1516+ :: Expression db from 'Ungrouped params (nullity 'PGbool)
15141517 -- ^ what to aggregate
1515− -> Expression schema from ('Grouped bys) params (nullity 'PGbool)
1518+ -> Expression db from ('Grouped bys) params (nullity 'PGbool)
15161519boolOr = unsafeAggregate "bool_or"
15171520
15181521-- | >>> :{
15191522-- let
1520−-- expression :: Expression schema '[tab ::: '["col" ::: nullity 'PGbool]] (Grouped bys) params (nullity 'PGbool)
1523+-- expression :: Expression db '[tab ::: '["col" ::: nullity 'PGbool]] (Grouped bys) params (nullity 'PGbool)
15211524-- expression = boolAndDistinct #col
15221525-- in printSQL expression
15231526-- :}
15241527-- bool_and(DISTINCT "col")
15251528boolAndDistinct
1526− :: Expression schema from 'Ungrouped params (nullity 'PGbool)
1529+ :: Expression db from 'Ungrouped params (nullity 'PGbool)
15271530 -- ^ what to aggregate
1528− -> Expression schema from ('Grouped bys) params (nullity 'PGbool)
1531+ -> Expression db from ('Grouped bys) params (nullity 'PGbool)
15291532boolAndDistinct = unsafeAggregateDistinct "bool_and"
15301533
15311534-- | >>> :{
15321535-- let
1533−-- expression :: Expression schema '[tab ::: '["col" ::: nullity 'PGbool]] (Grouped bys) params (nullity 'PGbool)
1536+-- expression :: Expression db '[tab ::: '["col" ::: nullity 'PGbool]] (Grouped bys) params (nullity 'PGbool)
15341537-- expression = boolOrDistinct #col
15351538-- in printSQL expression
15361539-- :}
15371540-- bool_or(DISTINCT "col")
15381541boolOrDistinct
1539− :: Expression schema from 'Ungrouped params (nullity 'PGbool)
1542+ :: Expression db from 'Ungrouped params (nullity 'PGbool)
15401543 -- ^ what to aggregate
1541− -> Expression schema from ('Grouped bys) params (nullity 'PGbool)
1544+ -> Expression db from ('Grouped bys) params (nullity 'PGbool)
15421545boolOrDistinct = unsafeAggregateDistinct "bool_or"
15431546
15441547-- | A special aggregation that does not require an input
@@ -1546,70 +1549,70 @@ boolOrDistinct = unsafeAggregateDistinct "bool_or"
15461549-- >>> printSQL countStar
15471550-- count(*)
15481551countStar
1549− :: Expression schema from ('Grouped bys) params ('NotNull 'PGint8)
1552+ :: Expression db from ('Grouped bys) params ('NotNull 'PGint8)
15501553countStar = UnsafeExpression $ "count(*)"
15511554
15521555-- | >>> :{
15531556-- let
1554−-- expression :: Expression schema '[tab ::: '["col" ::: nullity ty]] (Grouped bys) params ('NotNull 'PGint8)
1557+-- expression :: Expression db '[tab ::: '["col" ::: nullity ty]] (Grouped bys) params ('NotNull 'PGint8)
15551558-- expression = count #col
15561559-- in printSQL expression
15571560-- :}
15581561-- count("col")
15591562count
1560− :: Expression schema from 'Ungrouped params ty
1563+ :: Expression db from 'Ungrouped params ty
15611564 -- ^ what to count
1562− -> Expression schema from ('Grouped bys) params ('NotNull 'PGint8)
1565+ -> Expression db from ('Grouped bys) params ('NotNull 'PGint8)
15631566count = unsafeAggregate "count"
15641567
15651568-- | >>> :{
15661569-- let
1567−-- expression :: Expression schema '[tab ::: '["col" ::: nullity ty]] (Grouped bys) params ('NotNull 'PGint8)
1570+-- expression :: Expression db '[tab ::: '["col" ::: nullity ty]] (Grouped bys) params ('NotNull 'PGint8)
15681571-- expression = countDistinct #col
15691572-- in printSQL expression
15701573-- :}
15711574-- count(DISTINCT "col")
15721575countDistinct
1573− :: Expression schema from 'Ungrouped params ty
1576+ :: Expression db from 'Ungrouped params ty
15741577 -- ^ what to count
1575− -> Expression schema from ('Grouped bys) params ('NotNull 'PGint8)
1578+ -> Expression db from ('Grouped bys) params ('NotNull 'PGint8)
15761579countDistinct = unsafeAggregateDistinct "count"
15771580
15781581-- | synonym for `boolAnd`
15791582--
15801583-- >>> :{
15811584-- let
1582−-- expression :: Expression schema '[tab ::: '["col" ::: nullity 'PGbool]] (Grouped bys) params (nullity 'PGbool)
1585+-- expression :: Expression db '[tab ::: '["col" ::: nullity 'PGbool]] (Grouped bys) params (nullity 'PGbool)
15831586-- expression = every #col
15841587-- in printSQL expression
15851588-- :}
15861589-- every("col")
15871590every
1588− :: Expression schema from 'Ungrouped params (nullity 'PGbool)
1591+ :: Expression db from 'Ungrouped params (nullity 'PGbool)
15891592 -- ^ what to aggregate
1590− -> Expression schema from ('Grouped bys) params (nullity 'PGbool)
1593+ -> Expression db from ('Grouped bys) params (nullity 'PGbool)
15911594every = unsafeAggregate "every"
15921595
15931596-- | synonym for `boolAndDistinct`
15941597--
15951598-- >>> :{
15961599-- let
1597−-- expression :: Expression schema '[tab ::: '["col" ::: nullity 'PGbool]] (Grouped bys) params (nullity 'PGbool)
1600+-- expression :: Expression db '[tab ::: '["col" ::: nullity 'PGbool]] (Grouped bys) params (nullity 'PGbool)
15981601-- expression = everyDistinct #col
15991602-- in printSQL expression
16001603-- :}
16011604-- every(DISTINCT "col")
16021605everyDistinct
1603− :: Expression schema from 'Ungrouped params (nullity 'PGbool)
1606+ :: Expression db from 'Ungrouped params (nullity 'PGbool)
16041607 -- ^ what to aggregate
1605− -> Expression schema from ('Grouped bys) params (nullity 'PGbool)
1608+ -> Expression db from ('Grouped bys) params (nullity 'PGbool)
16061609everyDistinct = unsafeAggregateDistinct "every"
16071610
16081611-- | minimum and maximum aggregation
16091612max_, min_, maxDistinct, minDistinct
1610− :: Expression schema from 'Ungrouped params (nullity ty)
1613+ :: Expression db from 'Ungrouped params (nullity ty)
16111614 -- ^ what to aggregate
1612− -> Expression schema from ('Grouped bys) params (nullity ty)
1615+ -> Expression db from ('Grouped bys) params (nullity ty)
16131616max_ = unsafeAggregate "max"
16141617min_ = unsafeAggregate "min"
16151618maxDistinct = unsafeAggregateDistinct "max"
@@ -1620,153 +1623,153 @@ type expressions
16201623-----------------------------------------}
16211624
16221625-- | `TypeExpression`s are used in `cast`s and `createTable` commands.
1623−newtype TypeExpression (schema :: SchemaType) (ty :: NullityType)
1626+newtype TypeExpression (schemas :: SchemasType) (ty :: NullityType)
16241627 = UnsafeTypeExpression { renderTypeExpression :: ByteString }
16251628 deriving (GHC.Generic,Show,Eq,Ord,NFData)
16261629
16271630-- | The enum or composite type in a `Typedef` can be expressed by its alias.
16281631typedef
1629− :: Has alias schema ('Typedef ty)
1630− => Alias alias
1631− -> TypeExpression schema (nullity ty)
1632−typedef = UnsafeTypeExpression . renderAlias
1632+ :: (Has sch schemas schema, Has td schema ('Typedef ty))
1633+ => QualifiedAlias sch td
1634+ -> TypeExpression schemas (nullity ty)
1635+typedef = UnsafeTypeExpression . renderQualifiedAlias
16331636
16341637-- | The composite type corresponding to a `Table` definition can be expressed
16351638-- by its alias.
16361639typetable
1637− :: Has alias schema ('Table tab)
1638− => Alias alias
1639− -> TypeExpression schema (nullity ('PGcomposite (TableToRow tab)))
1640−typetable = UnsafeTypeExpression . renderAlias
1640+ :: (Has sch schemas schema, Has tab schema ('Table table))
1641+ => QualifiedAlias sch tab
1642+ -> TypeExpression schemas (nullity ('PGcomposite (TableToRow table)))
1643+typetable = UnsafeTypeExpression . renderQualifiedAlias
16411644
16421645-- | The composite type corresponding to a `View` definition can be expressed
16431646-- by its alias.
16441647typeview
1645− :: Has alias schema ('View view)
1646− => Alias alias
1647− -> TypeExpression schema (nullity ('PGcomposite view))
1648−typeview = UnsafeTypeExpression . renderAlias
1648+ :: (Has sch schemas schema, Has vw schema ('View view))
1649+ => QualifiedAlias sch vw
1650+ -> TypeExpression schemas (nullity ('PGcomposite view))
1651+typeview = UnsafeTypeExpression . renderQualifiedAlias
16491652
16501653-- | logical Boolean (true/false)
1651−bool :: TypeExpression schema (nullity 'PGbool)
1654+bool :: TypeExpression schemas (nullity 'PGbool)
16521655bool = UnsafeTypeExpression "bool"
16531656-- | signed two-byte integer
1654−int2, smallint :: TypeExpression schema (nullity 'PGint2)
1657+int2, smallint :: TypeExpression schemas (nullity 'PGint2)
16551658int2 = UnsafeTypeExpression "int2"
16561659smallint = UnsafeTypeExpression "smallint"
16571660-- | signed four-byte integer
1658−int4, int, integer :: TypeExpression schema (nullity 'PGint4)
1661+int4, int, integer :: TypeExpression schemas (nullity 'PGint4)
16591662int4 = UnsafeTypeExpression "int4"
16601663int = UnsafeTypeExpression "int"
16611664integer = UnsafeTypeExpression "integer"
16621665-- | signed eight-byte integer
1663−int8, bigint :: TypeExpression schema (nullity 'PGint8)
1666+int8, bigint :: TypeExpression schemas (nullity 'PGint8)
16641667int8 = UnsafeTypeExpression "int8"
16651668bigint = UnsafeTypeExpression "bigint"
16661669-- | arbitrary precision numeric type
1667−numeric :: TypeExpression schema (nullity 'PGnumeric)
1670+numeric :: TypeExpression schemas (nullity 'PGnumeric)
16681671numeric = UnsafeTypeExpression "numeric"
16691672-- | single precision floating-point number (4 bytes)
1670−float4, real :: TypeExpression schema (nullity 'PGfloat4)
1673+float4, real :: TypeExpression schemas (nullity 'PGfloat4)
16711674float4 = UnsafeTypeExpression "float4"
16721675real = UnsafeTypeExpression "real"
16731676-- | double precision floating-point number (8 bytes)
1674−float8, doublePrecision :: TypeExpression schema (nullity 'PGfloat8)
1677+float8, doublePrecision :: TypeExpression schemas (nullity 'PGfloat8)
16751678float8 = UnsafeTypeExpression "float8"
16761679doublePrecision = UnsafeTypeExpression "double precision"
16771680-- | variable-length character string
1678−text :: TypeExpression schema (nullity 'PGtext)
1681+text :: TypeExpression schemas (nullity 'PGtext)
16791682text = UnsafeTypeExpression "text"
16801683-- | fixed-length character string
16811684char, character
1682− :: forall n schema nullity. (KnownNat n, 1 <= n)
1683− => TypeExpression schema (nullity ('PGchar n))
1685+ :: forall n schemas nullity. (KnownNat n, 1 <= n)
1686+ => TypeExpression schemas (nullity ('PGchar n))
16841687char = UnsafeTypeExpression $ "char(" <> renderNat @n <> ")"
16851688character = UnsafeTypeExpression $ "character(" <> renderNat @n <> ")"
16861689-- | variable-length character string
16871690varchar, characterVarying
1688− :: forall n schema nullity. (KnownNat n, 1 <= n)
1689− => TypeExpression schema (nullity ('PGvarchar n))
1691+ :: forall n schemas nullity. (KnownNat n, 1 <= n)
1692+ => TypeExpression schemas (nullity ('PGvarchar n))
16901693varchar = UnsafeTypeExpression $ "varchar(" <> renderNat @n <> ")"
16911694characterVarying = UnsafeTypeExpression $
16921695 "character varying(" <> renderNat @n <> ")"
16931696-- | binary data ("byte array")
1694−bytea :: TypeExpression schema (nullity 'PGbytea)
1697+bytea :: TypeExpression schemas (nullity 'PGbytea)
16951698bytea = UnsafeTypeExpression "bytea"
16961699-- | date and time (no time zone)
1697−timestamp :: TypeExpression schema (nullity 'PGtimestamp)
1700+timestamp :: TypeExpression schemas (nullity 'PGtimestamp)
16981701timestamp = UnsafeTypeExpression "timestamp"
16991702-- | date and time, including time zone
1700−timestampWithTimeZone :: TypeExpression schema (nullity 'PGtimestamptz)
1703+timestampWithTimeZone :: TypeExpression schemas (nullity 'PGtimestamptz)
17011704timestampWithTimeZone = UnsafeTypeExpression "timestamp with time zone"
17021705-- | calendar date (year, month, day)
1703−date :: TypeExpression schema (nullity 'PGdate)
1706+date :: TypeExpression schemas (nullity 'PGdate)
17041707date = UnsafeTypeExpression "date"
17051708-- | time of day (no time zone)
1706−time :: TypeExpression schema (nullity 'PGtime)
1709+time :: TypeExpression schemas (nullity 'PGtime)
17071710time = UnsafeTypeExpression "time"
17081711-- | time of day, including time zone
1709−timeWithTimeZone :: TypeExpression schema (nullity 'PGtimetz)
1712+timeWithTimeZone :: TypeExpression schemas (nullity 'PGtimetz)
17101713timeWithTimeZone = UnsafeTypeExpression "time with time zone"
17111714-- | time span
1712−interval :: TypeExpression schema (nullity 'PGinterval)
1715+interval :: TypeExpression schemas (nullity 'PGinterval)
17131716interval = UnsafeTypeExpression "interval"
17141717-- | universally unique identifier
1715−uuid :: TypeExpression schema (nullity 'PGuuid)
1718+uuid :: TypeExpression schemas (nullity 'PGuuid)
17161719uuid = UnsafeTypeExpression "uuid"
17171720-- | IPv4 or IPv6 host address
1718−inet :: TypeExpression schema (nullity 'PGinet)
1721+inet :: TypeExpression schemas (nullity 'PGinet)
17191722inet = UnsafeTypeExpression "inet"
17201723-- | textual JSON data
1721−json :: TypeExpression schema (nullity 'PGjson)
1724+json :: TypeExpression schemas (nullity 'PGjson)
17221725json = UnsafeTypeExpression "json"
17231726-- | binary JSON data, decomposed
1724−jsonb :: TypeExpression schema (nullity 'PGjsonb)
1727+jsonb :: TypeExpression schemas (nullity 'PGjsonb)
17251728jsonb = UnsafeTypeExpression "jsonb"
17261729-- | variable length array
17271730vararray
1728− :: TypeExpression schema pg
1729− -> TypeExpression schema (nullity ('PGvararray pg))
1731+ :: TypeExpression schemas pg
1732+ -> TypeExpression schemas (nullity ('PGvararray pg))
17301733vararray ty = UnsafeTypeExpression $ renderTypeExpression ty <> "[]"
17311734-- | fixed length array
17321735--
17331736-- >>> renderTypeExpression (fixarray @2 json)
17341737-- "json[2]"
17351738fixarray
1736− :: forall n schema nullity pg. KnownNat n
1737− => TypeExpression schema pg
1738− -> TypeExpression schema (nullity ('PGfixarray n pg))
1739+ :: forall n schemas nullity pg. KnownNat n
1740+ => TypeExpression schemas pg
1741+ -> TypeExpression schemas (nullity ('PGfixarray n pg))
17391742fixarray ty = UnsafeTypeExpression $
17401743 renderTypeExpression ty <> "[" <> renderNat @n <> "]"
17411744
17421745-- | `pgtype` is a demoted version of a `PGType`
1743−class PGTyped schema (ty :: NullityType) where
1744− pgtype :: TypeExpression schema ty
1745−instance PGTyped schema (nullity 'PGbool) where pgtype = bool
1746−instance PGTyped schema (nullity 'PGint2) where pgtype = int2
1747−instance PGTyped schema (nullity 'PGint4) where pgtype = int4
1748−instance PGTyped schema (nullity 'PGint8) where pgtype = int8
1749−instance PGTyped schema (nullity 'PGnumeric) where pgtype = numeric
1750−instance PGTyped schema (nullity 'PGfloat4) where pgtype = float4
1751−instance PGTyped schema (nullity 'PGfloat8) where pgtype = float8
1752−instance PGTyped schema (nullity 'PGtext) where pgtype = text
1746+class PGTyped schemas (ty :: NullityType) where
1747+ pgtype :: TypeExpression schemas ty
1748+instance PGTyped schemas (nullity 'PGbool) where pgtype = bool
1749+instance PGTyped schemas (nullity 'PGint2) where pgtype = int2
1750+instance PGTyped schemas (nullity 'PGint4) where pgtype = int4
1751+instance PGTyped schemas (nullity 'PGint8) where pgtype = int8
1752+instance PGTyped schemas (nullity 'PGnumeric) where pgtype = numeric
1753+instance PGTyped schemas (nullity 'PGfloat4) where pgtype = float4
1754+instance PGTyped schemas (nullity 'PGfloat8) where pgtype = float8
1755+instance PGTyped schemas (nullity 'PGtext) where pgtype = text
17531756instance (KnownNat n, 1 <= n)
1754− => PGTyped schema (nullity ('PGchar n)) where pgtype = char @n
1757+ => PGTyped schemas (nullity ('PGchar n)) where pgtype = char @n
17551758instance (KnownNat n, 1 <= n)
1756− => PGTyped schema (nullity ('PGvarchar n)) where pgtype = varchar @n
1757−instance PGTyped schema (nullity 'PGbytea) where pgtype = bytea
1758−instance PGTyped schema (nullity 'PGtimestamp) where pgtype = timestamp
1759−instance PGTyped schema (nullity 'PGtimestamptz) where pgtype = timestampWithTimeZone
1760−instance PGTyped schema (nullity 'PGdate) where pgtype = date
1761−instance PGTyped schema (nullity 'PGtime) where pgtype = time
1762−instance PGTyped schema (nullity 'PGtimetz) where pgtype = timeWithTimeZone
1763−instance PGTyped schema (nullity 'PGinterval) where pgtype = interval
1764−instance PGTyped schema (nullity 'PGuuid) where pgtype = uuid
1765−instance PGTyped schema (nullity 'PGjson) where pgtype = json
1766−instance PGTyped schema (nullity 'PGjsonb) where pgtype = jsonb
1767−instance PGTyped schema ty
1768− => PGTyped schema (nullity ('PGvararray ty)) where
1769− pgtype = vararray (pgtype @schema @ty)
1770−instance (KnownNat n, PGTyped schema ty)
1771− => PGTyped schema (nullity ('PGfixarray n ty)) where
1772− pgtype = fixarray @n (pgtype @schema @ty)
1759+ => PGTyped schemas (nullity ('PGvarchar n)) where pgtype = varchar @n
1760+instance PGTyped schemas (nullity 'PGbytea) where pgtype = bytea
1761+instance PGTyped schemas (nullity 'PGtimestamp) where pgtype = timestamp
1762+instance PGTyped schemas (nullity 'PGtimestamptz) where pgtype = timestampWithTimeZone
1763+instance PGTyped schemas (nullity 'PGdate) where pgtype = date
1764+instance PGTyped schemas (nullity 'PGtime) where pgtype = time
1765+instance PGTyped schemas (nullity 'PGtimetz) where pgtype = timeWithTimeZone
1766+instance PGTyped schemas (nullity 'PGinterval) where pgtype = interval
1767+instance PGTyped schemas (nullity 'PGuuid) where pgtype = uuid
1768+instance PGTyped schemas (nullity 'PGjson) where pgtype = json
1769+instance PGTyped schemas (nullity 'PGjsonb) where pgtype = jsonb
1770+instance PGTyped schemas ty
1771+ => PGTyped schemas (nullity ('PGvararray ty)) where
1772+ pgtype = vararray (pgtype @schemas @ty)
1773+instance (KnownNat n, PGTyped schemas ty)
1774+ => PGTyped schemas (nullity ('PGfixarray n ty)) where
1775+ pgtype = fixarray @n (pgtype @schemas @ty)
squeal-postgresql/src/Squeal/PostgreSQL/Manipulation.hs+137−155
@@ -59,17 +59,16 @@ import Squeal.PostgreSQL.Schema
5959
6060{- |
6161A `Manipulation` is a statement which may modify data in the database,
62−but does not alter the schema. Examples are inserts, updates and deletes.
62+but does not alter its schemas. Examples are inserts, updates and deletes.
6363A `Query` is also considered a `Manipulation` even though it does not modify data.
6464
6565simple insert:
6666
67+>>> type Columns = '["col1" ::: 'NoDef :=> 'Null 'PGint4, "col2" ::: 'Def :=> 'NotNull 'PGint4]
68+>>> type Schema = '["tab" ::: 'Table ('[] :=> Columns)]
6769>>> :{
6870let
69− manipulation :: Manipulation
70− '[ "tab" ::: 'Table ('[] :=>
71− '[ "col1" ::: 'NoDef :=> 'NotNull 'PGint4
72− , "col2" ::: 'Def :=> 'NotNull 'PGint4 ])] '[] '[]
71+ manipulation :: Manipulation (DBof (Public Schema)) '[] '[]
7372 manipulation =
7473 insertRow_ #tab (Set 2 `as` #col1 :* Default `as` #col2)
7574in printSQL manipulation
@@ -78,13 +77,11 @@ INSERT INTO "tab" ("col1", "col2") VALUES (2, DEFAULT)
7877
7978parameterized insert:
8079
80+>>> type Columns = '["col1" ::: 'NoDef :=> 'NotNull 'PGint4, "col2" ::: 'NoDef :=> 'NotNull 'PGint4]
81+>>> type Schema = '["tab" ::: 'Table ('[] :=> Columns)]
8182>>> :{
8283let
83− manipulation :: Manipulation
84− '[ "tab" ::: 'Table ('[] :=>
85− '[ "col1" ::: 'NoDef :=> 'NotNull 'PGint4
86− , "col2" ::: 'NoDef :=> 'NotNull 'PGint4 ])]
87− '[ 'NotNull 'PGint4, 'NotNull 'PGint4 ] '[]
84+ manipulation :: Manipulation (DBof (Public Schema)) '[ 'NotNull 'PGint4, 'NotNull 'PGint4 ] '[]
8885 manipulation =
8986 insertRow_ #tab
9087 (Set (param @1) `as` #col1 :* Set (param @2) `as` #col2)
@@ -96,27 +93,21 @@ returning insert:
9693
9794>>> :{
9895let
99− manipulation :: Manipulation
100− '[ "tab" ::: 'Table ('[] :=>
101− '[ "col1" ::: 'NoDef :=> 'NotNull 'PGint4
102− , "col2" ::: 'Def :=> 'NotNull 'PGint4 ])] '[]
103− '["fromOnly" ::: 'NotNull 'PGint4]
96+ manipulation :: Manipulation (DBof (Public Schema)) '[] '["fromOnly" ::: 'NotNull 'PGint4]
10497 manipulation =
105− insertRow #tab (Set 2 `as` #col1 :* Default `as` #col2)
98+ insertRow #tab (Set 2 `as` #col1 :* Set 3 `as` #col2)
10699 OnConflictDoRaise (Returning (#col1 `as` #fromOnly))
107100in printSQL manipulation
108101:}
109−INSERT INTO "tab" ("col1", "col2") VALUES (2, DEFAULT) RETURNING "col1" AS "fromOnly"
102+INSERT INTO "tab" ("col1", "col2") VALUES (2, 3) RETURNING "col1" AS "fromOnly"
110103
111104upsert:
112105
106+>>> type Columns = '["col1" ::: 'NoDef :=> 'NotNull 'PGint4, "col2" ::: 'NoDef :=> 'NotNull 'PGint4]
107+>>> type Schema = '["tab" ::: 'Table ('[] :=> Columns)]
113108>>> :{
114109let
115− manipulation :: Manipulation
116− '[ "tab" ::: 'Table ('[] :=>
117− '[ "col1" ::: 'NoDef :=> 'NotNull 'PGint4
118− , "col2" ::: 'NoDef :=> 'NotNull 'PGint4 ])]
119− '[] '[ "sum" ::: 'NotNull 'PGint4]
110+ manipulation :: Manipulation (DBof (Public Schema)) '[] '[ "sum" ::: 'NotNull 'PGint4]
120111 manipulation =
121112 insertRows #tab
122113 (Set 2 `as` #col1 :* Set 4 `as` #col2)
@@ -133,31 +124,17 @@ query insert:
133124
134125>>> :{
135126let
136− manipulation :: Manipulation
137− '[ "tab" ::: 'Table ('[] :=>
138− '[ "col1" ::: 'NoDef :=> 'NotNull 'PGint4
139− , "col2" ::: 'NoDef :=> 'NotNull 'PGint4
140− ])
141− , "other_tab" ::: 'Table ('[] :=>
142− '[ "col1" ::: 'NoDef :=> 'NotNull 'PGint4
143− , "col2" ::: 'NoDef :=> 'NotNull 'PGint4
144− ])
145− ] '[] '[]
146− manipulation =
147− insertQuery_ #tab
148− (selectStar (from (table (#other_tab `as` #t))))
127+ manipulation :: Manipulation (DBof (Public Schema)) '[] '[]
128+ manipulation = insertQuery_ #tab (selectStar (from (table #tab)))
149129in printSQL manipulation
150130:}
151−INSERT INTO "tab" SELECT * FROM "other_tab" AS "t"
131+INSERT INTO "tab" SELECT * FROM "tab" AS "tab"
152132
153133update:
154134
155135>>> :{
156136let
157− manipulation :: Manipulation
158− '[ "tab" ::: 'Table ('[] :=>
159− '[ "col1" ::: 'NoDef :=> 'NotNull 'PGint4
160− , "col2" ::: 'NoDef :=> 'NotNull 'PGint4 ])] '[] '[]
137+ manipulation :: Manipulation (DBof (Public Schema)) '[] '[]
161138 manipulation =
162139 update_ #tab (Set 2 `as` #col1 :* Same `as` #col2)
163140 (#col1 ./= #col2)
@@ -169,10 +146,7 @@ delete:
169146
170147>>> :{
171148let
172− manipulation :: Manipulation
173− '[ "tab" ::: 'Table ('[] :=>
174− '[ "col1" ::: 'NoDef :=> 'NotNull 'PGint4
175− , "col2" ::: 'NoDef :=> 'NotNull 'PGint4 ])] '[]
149+ manipulation :: Manipulation (DBof (Public Schema)) '[]
176150 '[ "col1" ::: 'NotNull 'PGint4
177151 , "col2" ::: 'NotNull 'PGint4 ]
178152 manipulation = deleteFrom #tab NoUsing (#col1 .== #col2) ReturningStar
@@ -182,56 +156,46 @@ DELETE FROM "tab" WHERE ("col1" = "col2") RETURNING *
182156
183157delete and using clause:
184158
159+>>> :{
160+type Schema3 =
161+ '[ "tab" ::: 'Table ('[] :=> Columns)
162+ , "other_tab" ::: 'Table ('[] :=> Columns)
163+ , "third_tab" ::: 'Table ('[] :=> Columns) ]
164+:}
165+
185166>>> :{
186167let
187− manipulation :: Manipulation
188− '[ "tab" ::: 'Table ('[] :=>
189− '[ "col1" ::: 'NoDef :=> 'NotNull 'PGint4
190− , "col2" ::: 'NoDef :=> 'NotNull 'PGint4
191− ])
192− , "other_tab" ::: 'Table ('[] :=>
193− '[ "col1" ::: 'NoDef :=> 'NotNull 'PGint4
194− , "col2" ::: 'NoDef :=> 'NotNull 'PGint4
195− ])
196− , "third_tab" ::: 'Table ('[] :=>
197− '[ "col1" ::: 'NoDef :=> 'NotNull 'PGint4
198− , "col2" ::: 'NoDef :=> 'NotNull 'PGint4
199− ])
200− ] '[] '[]
168+ manipulation :: Manipulation (DBof (Public Schema3)) '[] '[]
201169 manipulation =
202− deleteFrom #tab (Using (table #other_tab & also (table #third_tab)))
170+ deleteFrom_ #tab (Using (table #other_tab & also (table #third_tab)))
203171 ( (#tab ! #col2 .== #other_tab ! #col2)
204172 .&& (#tab ! #col2 .== #third_tab ! #col2) )
205− (Returning Nil)
206173in printSQL manipulation
207174:}
208175DELETE FROM "tab" USING "other_tab" AS "other_tab", "third_tab" AS "third_tab" WHERE (("tab"."col2" = "other_tab"."col2") AND ("tab"."col2" = "third_tab"."col2"))
209176
210177with manipulation:
211178
212−>>> type ProductsTable = '[] :=> '["product" ::: 'NoDef :=> 'NotNull 'PGtext, "date" ::: 'Def :=> 'NotNull 'PGdate]
213−
179+>>> type ProductsColumns = '["product" ::: 'NoDef :=> 'NotNull 'PGtext, "date" ::: 'Def :=> 'NotNull 'PGdate]
180+>>> type ProductsSchema = '["products" ::: 'Table ('[] :=> ProductsColumns), "products_deleted" ::: 'Table ('[] :=> ProductsColumns)]
214181>>> :{
215182let
216− manipulation :: Manipulation
217− '[ "products" ::: 'Table ProductsTable
218− , "products_deleted" ::: 'Table ProductsTable
219− ] '[ 'NotNull 'PGdate] '[]
183+ manipulation :: Manipulation (DBof (Public ProductsSchema)) '[ 'NotNull 'PGdate] '[]
220184 manipulation = with
221− (deleteFrom #products NoUsing (#date .< param @1) ReturningStar `as` #deleted_rows)
222− (insertQuery_ #products_deleted (selectStar (from (view (#deleted_rows `as` #t)))))
185+ (deleteFrom #products NoUsing (#date .< param @1) ReturningStar `as` #del)
186+ (insertQuery_ #products_deleted (selectStar (from (common (#del)))))
223187in printSQL manipulation
224188:}
225−WITH "deleted_rows" AS (DELETE FROM "products" WHERE ("date" < ($1 :: date)) RETURNING *) INSERT INTO "products_deleted" SELECT * FROM "deleted_rows" AS "t"
189+WITH "del" AS (DELETE FROM "products" WHERE ("date" < ($1 :: date)) RETURNING *) INSERT INTO "products_deleted" SELECT * FROM "del" AS "del"
226190-}
227191
228192newtype Manipulation
229− (schema :: SchemaType)
193+ (db :: DBType)
230194 (params :: [NullityType])
231195 (columns :: RowType)
232196 = UnsafeManipulation { renderManipulation :: ByteString }
233197 deriving (GHC.Generic,Show,Eq,Ord,NFData)
234−instance RenderSQL (Manipulation schema params columns) where
198+instance RenderSQL (Manipulation db params columns) where
235199 renderSQL = renderManipulation
236200instance With Manipulation where
237201 with Done manip = manip
@@ -241,8 +205,8 @@ instance With Manipulation where
241205
242206-- | Convert a `Query` into a `Manipulation`.
243207queryStatement
244− :: Query schema params columns
245− -> Manipulation schema params columns
208+ :: Query db params columns
209+ -> Manipulation db params columns
246210queryStatement q = UnsafeManipulation $ renderQuery q
247211
248212{-----------------------------------------
@@ -259,18 +223,20 @@ INSERT statements
259223insertRows
260224 :: ( SOP.SListI columns
261225 , SOP.SListI results
226+ , db ~ (commons :=> schemas)
227+ , Has sch schemas schema
262228 , Has tab schema ('Table table)
263229 , row ~ TableToRow table
264230 , columns ~ TableToColumns table )
265− => Alias tab -- ^ table to insert into
266− -> NP (Aliased (ColumnValue schema '[] params)) columns -- ^ row to insert
267− -> [NP (Aliased (ColumnValue schema '[] params)) columns] -- ^ more rows to insert
268− -> ConflictClause schema table params
231+ => QualifiedAlias sch tab -- ^ table to insert into
232+ -> NP (Aliased (ColumnValue db '[] params)) columns -- ^ row to insert
233+ -> [NP (Aliased (ColumnValue db '[] params)) columns] -- ^ more rows to insert
234+ -> ConflictClause db table params
269235 -- ^ what to do in case of constraint conflict
270− -> ReturningClause schema params row results -- ^ results to return
271− -> Manipulation schema params results
236+ -> ReturningClause db params row results -- ^ results to return
237+ -> Manipulation db params results
272238insertRows tab rw rws conflict returning = UnsafeManipulation $
273− "INSERT" <+> "INTO" <+> renderAlias tab
239+ "INSERT" <+> "INTO" <+> renderQualifiedAlias tab
274240 <+> parenthesized (renderCommaSeparated renderAliasPart rw)
275241 <+> "VALUES"
276242 <+> commaSeparated
@@ -280,7 +246,7 @@ insertRows tab rw rws conflict returning = UnsafeManipulation $
280246 <> renderReturningClause returning
281247 where
282248 renderAliasPart, renderColumnValuePart
283− :: Aliased (ColumnValue schema '[] params) ty -> ByteString
249+ :: Aliased (ColumnValue db '[] params) ty -> ByteString
284250 renderAliasPart (_ `As` name) = renderAlias name
285251 renderColumnValuePart (value `As` _) = case value of
286252 Default -> "DEFAULT"
@@ -290,54 +256,62 @@ insertRows tab rw rws conflict returning = UnsafeManipulation $
290256insertRow
291257 :: ( SOP.SListI columns
292258 , SOP.SListI results
259+ , db ~ (commons :=> schemas)
260+ , Has sch schemas schema
293261 , Has tab schema ('Table table)
294262 , row ~ TableToRow table
295263 , columns ~ TableToColumns table )
296− => Alias tab -- ^ table to insert into
297− -> NP (Aliased (ColumnValue schema '[] params)) columns -- ^ row to insert
298− -> ConflictClause schema table params
264+ => QualifiedAlias sch tab -- ^ table to insert into
265+ -> NP (Aliased (ColumnValue db '[] params)) columns -- ^ row to insert
266+ -> ConflictClause db table params
299267 -- ^ what to do in case of constraint conflict
300− -> ReturningClause schema params row results -- ^ results to return
301− -> Manipulation schema params results
268+ -> ReturningClause db params row results -- ^ results to return
269+ -> Manipulation db params results
302270insertRow tab rw = insertRows tab rw []
303271
304272-- | Insert multiple rows returning `Nil` and raising an error on conflicts.
305273insertRows_
306274 :: ( SOP.SListI columns
275+ , db ~ (commons :=> schemas)
276+ , Has sch schemas schema
307277 , Has tab schema ('Table table)
308278 , columns ~ TableToColumns table )
309− => Alias tab -- ^ table to insert into
310− -> NP (Aliased (ColumnValue schema '[] params)) columns -- ^ row to insert
311− -> [NP (Aliased (ColumnValue schema '[] params)) columns] -- ^ more rows to insert
312− -> Manipulation schema params '[]
279+ => QualifiedAlias sch tab -- ^ table to insert into
280+ -> NP (Aliased (ColumnValue db '[] params)) columns -- ^ row to insert
281+ -> [NP (Aliased (ColumnValue db '[] params)) columns] -- ^ more rows to insert
282+ -> Manipulation db params '[]
313283insertRows_ tab rw rws =
314284 insertRows tab rw rws OnConflictDoRaise (Returning Nil)
315285
316286-- | Insert a single row returning `Nil` and raising an error on conflicts.
317287insertRow_
318288 :: ( SOP.SListI columns
289+ , db ~ (commons :=> schemas)
290+ , Has sch schemas schema
319291 , Has tab schema ('Table table)
320292 , columns ~ TableToColumns table )
321− => Alias tab -- ^ table to insert into
322− -> NP (Aliased (ColumnValue schema '[] params)) columns -- ^ row to insert
323− -> Manipulation schema params '[]
293+ => QualifiedAlias sch tab -- ^ table to insert into
294+ -> NP (Aliased (ColumnValue db '[] params)) columns -- ^ row to insert
295+ -> Manipulation db params '[]
324296insertRow_ tab rw = insertRow tab rw OnConflictDoRaise (Returning Nil)
325297
326298-- | Insert a `Query`.
327299insertQuery
328300 :: ( SOP.SListI columns
329301 , SOP.SListI results
302+ , db ~ (commons :=> schemas)
303+ , Has sch schemas schema
330304 , Has tab schema ('Table table)
331305 , row ~ TableToRow table
332306 , columns ~ TableToColumns table )
333− => Alias tab -- ^ table to insert into
334− -> Query schema params (TableToRow table)
335− -> ConflictClause schema table params
307+ => QualifiedAlias sch tab -- ^ table to insert into
308+ -> Query db params (TableToRow table)
309+ -> ConflictClause db table params
336310 -- ^ what to do in case of constraint conflict
337− -> ReturningClause schema params row results -- ^ results to return
338− -> Manipulation schema params results
311+ -> ReturningClause db params row results -- ^ results to return
312+ -> Manipulation db params results
339313insertQuery tab query conflict returning = UnsafeManipulation $
340− "INSERT" <+> "INTO" <+> renderAlias tab
314+ "INSERT" <+> "INTO" <+> renderQualifiedAlias tab
341315 <+> renderQuery query
342316 <> renderConflictClause conflict
343317 <> renderReturningClause returning
@@ -345,11 +319,13 @@ insertQuery tab query conflict returning = UnsafeManipulation $
345319-- | Insert a `Query` returning `Nil` and raising an error on conflicts.
346320insertQuery_
347321 :: ( SOP.SListI columns
322+ , db ~ (commons :=> schemas)
323+ , Has sch schemas schema
348324 , Has tab schema ('Table table)
349325 , columns ~ TableToColumns table )
350− => Alias tab -- ^ table to insert into
351− -> Query schema params (TableToRow table)
352− -> Manipulation schema params '[]
326+ => QualifiedAlias sch tab -- ^ table to insert into
327+ -> Query db params (TableToRow table)
328+ -> Manipulation db params '[]
353329insertQuery_ tab query =
354330 insertQuery tab query OnConflictDoRaise (Returning Nil)
355331
@@ -359,16 +335,16 @@ insertQuery_ tab query =
359335-- `Set` sets a value to be an `Expression`, which can refer to
360336-- existing value in the row for an update.
361337data ColumnValue
362− (schema :: SchemaType)
338+ (db :: DBType)
363339 (columns :: RowType)
364340 (params :: [NullityType])
365341 (ty :: ColumnType)
366342 where
367− Same :: ColumnValue schema (column ': columns) params ty
368− Default :: ColumnValue schema columns params ('Def :=> ty)
343+ Same :: ColumnValue db (column ': columns) params ty
344+ Default :: ColumnValue db columns params ('Def :=> ty)
369345 Set
370− :: (forall table. Expression schema '[table ::: columns] 'Ungrouped params ty)
371− -> ColumnValue schema columns params (constraint :=> ty)
346+ :: (forall table. Expression db '[table ::: columns] 'Ungrouped params ty)
347+ -> ColumnValue db columns params (constraint :=> ty)
372348
373349-- | A `ReturningClause` computes and return value(s) based
374350-- on each row actually inserted, updated or deleted. This is primarily
@@ -381,21 +357,21 @@ data ColumnValue
381357-- in the row. Use @Returning Nil@ in the common case where no return
382358-- values are desired.
383359data ReturningClause
384− (schema :: SchemaType)
360+ (db :: DBType)
385361 (params :: [NullityType])
386362 (row0 :: RowType)
387363 (row1 :: RowType)
388364 where
389365 ReturningStar
390− :: ReturningClause schema params row row
366+ :: ReturningClause db params row row
391367 Returning
392− :: NP (Aliased (Expression schema '[table ::: row0] 'Ungrouped params)) row1
393− -> ReturningClause schema params row0 row1
368+ :: NP (Aliased (Expression db '[table ::: row0] 'Ungrouped params)) row1
369+ -> ReturningClause db params row0 row1
394370
395371-- | Render a `ReturningClause`.
396372renderReturningClause
397373 :: SOP.SListI results
398− => ReturningClause schema params columns results
374+ => ReturningClause db params columns results
399375 -> ByteString
400376renderReturningClause = \case
401377 ReturningStar -> " RETURNING *"
@@ -409,21 +385,21 @@ renderReturningClause = \case
409385-- `OnConflictDoUpdate` updates the existing row that conflicts with the row
410386-- proposed for insertion.
411387data ConflictClause
412− (schema :: SchemaType)
388+ (db :: DBType)
413389 (table :: TableType)
414390 (params :: [NullityType]) where
415− OnConflictDoRaise :: ConflictClause schema table params
416− OnConflictDoNothing :: ConflictClause schema table params
391+ OnConflictDoRaise :: ConflictClause db table params
392+ OnConflictDoNothing :: ConflictClause db table params
417393 OnConflictDoUpdate
418394 :: (row ~ TableToRow table, columns ~ TableToColumns table)
419− => NP (Aliased (ColumnValue schema row params)) columns
420− -> [Condition schema '[t ::: row] 'Ungrouped params]
421− -> ConflictClause schema table params
395+ => NP (Aliased (ColumnValue db row params)) columns
396+ -> [Condition db '[t ::: row] 'Ungrouped params]
397+ -> ConflictClause db table params
422398
423399-- | Render a `ConflictClause`.
424400renderConflictClause
425401 :: SOP.SListI (TableToColumns table)
426− => ConflictClause schema table params
402+ => ConflictClause db table params
427403 -> ByteString
428404renderConflictClause = \case
429405 OnConflictDoRaise -> ""
@@ -436,7 +412,7 @@ renderConflictClause = \case
436412 wh:whs -> " WHERE" <+> renderExpression (foldr (.&&) wh whs)
437413 where
438414 renderUpdate
439− :: Aliased (ColumnValue schema columns params) column
415+ :: Aliased (ColumnValue db columns params) column
440416 -> Maybe ByteString
441417 renderUpdate = \case
442418 Same `As` _ -> Nothing
@@ -454,26 +430,28 @@ UPDATE statements
454430update
455431 :: ( SOP.SListI columns
456432 , SOP.SListI results
433+ , db ~ (commons :=> schemas)
434+ , Has sch schemas schema
457435 , Has tab schema ('Table table)
458436 , row ~ TableToRow table
459437 , columns ~ TableToColumns table )
460− => Alias tab -- ^ table to update
461− -> NP (Aliased (ColumnValue schema row params)) columns
438+ => QualifiedAlias sch tab -- ^ table to update
439+ -> NP (Aliased (ColumnValue db row params)) columns
462440 -- ^ modified values to replace old values
463− -> (forall t. Condition schema '[t ::: row] 'Ungrouped params)
441+ -> (forall t. Condition db '[t ::: row] 'Ungrouped params)
464442 -- ^ condition under which to perform update on a row
465− -> ReturningClause schema params row results -- ^ results to return
466− -> Manipulation schema params results
443+ -> ReturningClause db params row results -- ^ results to return
444+ -> Manipulation db params results
467445update tab columns wh returning = UnsafeManipulation $
468446 "UPDATE"
469− <+> renderAlias tab
447+ <+> renderQualifiedAlias tab
470448 <+> "SET"
471449 <+> renderCommaSeparatedMaybe renderUpdate columns
472450 <+> "WHERE" <+> renderExpression wh
473451 <> renderReturningClause returning
474452 where
475453 renderUpdate
476− :: Aliased (ColumnValue schema columns params) column
454+ :: Aliased (ColumnValue db columns params) column
477455 -> Maybe ByteString
478456 renderUpdate = \case
479457 Same `As` _ -> Nothing
@@ -485,60 +463,64 @@ update tab columns wh returning = UnsafeManipulation $
485463-- | Update a row returning `Nil`.
486464update_
487465 :: ( SOP.SListI columns
466+ , db ~ (commons :=> schemas)
467+ , Has sch schemas schema
488468 , Has tab schema ('Table table)
489469 , row ~ TableToRow table
490470 , columns ~ TableToColumns table )
491− => Alias tab -- ^ table to update
492− -> NP (Aliased (ColumnValue schema row params)) columns
471+ => QualifiedAlias sch tab -- ^ table to update
472+ -> NP (Aliased (ColumnValue db row params)) columns
493473 -- ^ modified values to replace old values
494− -> (forall t. Condition schema '[t ::: row] 'Ungrouped params)
474+ -> (forall t. Condition db '[t ::: row] 'Ungrouped params)
495475 -- ^ condition under which to perform update on a row
496− -> Manipulation schema params '[]
476+ -> Manipulation db params '[]
497477update_ tab columns wh = update tab columns wh (Returning Nil)
498478
499479{-----------------------------------------
500480DELETE statements
501481-----------------------------------------}
502482
503−data UsingClause schema params from where
504− NoUsing :: UsingClause schema params '[]
483+data UsingClause db params from where
484+ NoUsing :: UsingClause db params '[]
505485 Using
506− :: FromClause schema params from
507− -> UsingClause schema params from
486+ :: FromClause db params from
487+ -> UsingClause db params from
508488
509489-- | Delete rows from a table.
510490deleteFrom
511491 :: ( SOP.SListI results
492+ , db ~ (commons :=> schemas)
493+ , Has sch schemas schema
512494 , Has tab schema ('Table table)
513495 , row ~ TableToRow table
514496 , columns ~ TableToColumns table )
515− => Alias tab -- ^ table to delete from
516− -> UsingClause schema params from
517− -- ^-- tables to add to the scope - more tables can be added through `also`.
518− -> Condition schema (tab ::: row ': from) 'Ungrouped params
497+ => QualifiedAlias sch tab -- ^ table to delete from
498+ -> UsingClause db params from
499+ -> Condition db (tab ::: row ': from) 'Ungrouped params
519500 -- ^ condition under which to delete a row
520− -> ReturningClause schema params row results -- ^ results to return
521− -> Manipulation schema params results
522−deleteFrom tgt uses cond returning =
523− let renderUsing NoUsing = mempty
524− renderUsing (Using fc) = "USING" <+> renderFromClause fc <> " "
525− in UnsafeManipulation $
526− "DELETE FROM" <+> renderAlias tgt
527− <+> renderUsing uses
528− <> "WHERE" <+> renderExpression cond
529− <> renderReturningClause returning
501+ -> ReturningClause db params row results -- ^ results to return
502+ -> Manipulation db params results
503+deleteFrom tab using wh returning = UnsafeManipulation $
504+ "DELETE FROM"
505+ <+> renderQualifiedAlias tab
506+ <> case using of
507+ NoUsing -> ""
508+ Using tables -> " USING" <+> renderFromClause tables
509+ <+> "WHERE" <+> renderExpression wh
510+ <> renderReturningClause returning
530511
531512-- | Delete rows returning `Nil`.
532513deleteFrom_
533− :: ( Has tab schema ('Table table)
514+ :: ( db ~ (commons :=> schemas)
515+ , Has sch schemas schema
516+ , Has tab schema ('Table table)
534517 , row ~ TableToRow table
535518 , columns ~ TableToColumns table )
536− => Alias tab -- ^ table to delete from
537− -> UsingClause schema params from
538− -- ^-- tables to add to the scope - more tables can be added through `also`.
539− -> Condition schema (tab ::: row ': from) 'Ungrouped params
519+ => QualifiedAlias sch tab -- ^ table to delete from
520+ -> UsingClause db params from
521+ -> Condition db (tab ::: row ': from) 'Ungrouped params
540522 -- ^ condition under which to delete a row
541− -> Manipulation schema params '[]
523+ -> Manipulation db params '[]
542524deleteFrom_ tab uses wh = deleteFrom tab uses wh (Returning Nil)
543525
544526-- | This has the behaviour of a cartesian product, taking all
squeal-postgresql/src/Squeal/PostgreSQL/Migration.hs+48−45
@@ -31,7 +31,7 @@ type EmailsTable =
3131
3232>>> :{
3333let
34− makeUsers :: Migration IO '[] '["users" ::: 'Table UsersTable]
34+ makeUsers :: Migration IO (Public '[]) '["public" ::: '["users" ::: 'Table UsersTable]]
3535 makeUsers = Migration
3636 { name = "make users table"
3737 , up = void . define $
@@ -45,8 +45,8 @@ let
4545
4646>>> :{
4747let
48− makeEmails :: Migration IO '["users" ::: 'Table UsersTable]
49− '["users" ::: 'Table UsersTable, "emails" ::: 'Table EmailsTable]
48+ makeEmails :: Migration IO '["public" ::: '["users" ::: 'Table UsersTable]]
49+ '["public" ::: '["users" ::: 'Table UsersTable, "emails" ::: 'Table EmailsTable]]
5050 makeEmails = Migration
5151 { name = "make emails table"
5252 , up = void . define $
@@ -68,10 +68,10 @@ Now that we have a couple migrations we can chain them together.
6868>>> :{
6969let
7070 numMigrations
71− :: Has "schema_migrations" schema ('Table MigrationsTable)
72− => PQ schema schema IO ()
71+ :: Has "migrations" schemas MigrationsSchema
72+ => PQ schemas schemas IO ()
7373 numMigrations = do
74− result <- runQuery (selectStar (from (table (#schema_migrations `as` #m))))
74+ result <- runQuery (selectStar (from (table (#migrations ! #schema_migrations `as` #m))))
7575 num <- ntuples result
7676 liftBase $ print num
7777:}
@@ -124,11 +124,11 @@ import Squeal.PostgreSQL
124124
125125-- | A `Migration` should contain an inverse pair of
126126-- `up` and `down` instructions and a unique `name`.
127−data Migration io schema0 schema1 = Migration
127+data Migration io schemas0 schemas1 = Migration
128128 { name :: Text -- ^ The `name` of a `Migration`.
129129 -- Each `name` in a `Migration` should be unique.
130− , up :: PQ schema0 schema1 io () -- ^ The `up` instruction of a `Migration`.
131− , down :: PQ schema1 schema0 io () -- ^ The `down` instruction of a `Migration`.
130+ , up :: PQ schemas0 schemas1 io () -- ^ The `up` instruction of a `Migration`.
131+ , down :: PQ schemas1 schemas0 io () -- ^ The `down` instruction of a `Migration`.
132132 }
133133
134134-- | Run `Migration`s by creating the `MigrationsTable`
@@ -137,10 +137,10 @@ data Migration io schema0 schema1 = Migration
137137-- execute the `Migration` and insert its row in the `MigrationsTable`.
138138migrateUp
139139 :: MonadBaseControl IO io
140− => AlignedList (Migration io) schema0 schema1 -- ^ migrations to run
140+ => AlignedList (Migration io) schemas0 schemas1 -- ^ migrations to run
141141 -> PQ
142− ("schema_migrations" ::: 'Table MigrationsTable ': schema0)
143− ("schema_migrations" ::: 'Table MigrationsTable ': schema1)
142+ ("migrations" ::: MigrationsSchema ': schemas0)
143+ ("migrations" ::: MigrationsSchema ': schemas1)
144144 io ()
145145migrateUp migration =
146146 define createMigrations
@@ -150,10 +150,10 @@ migrateUp migration =
150150
151151 upMigrations
152152 :: MonadBaseControl IO io
153− => AlignedList (Migration io) schema0 schema1
153+ => AlignedList (Migration io) schemas0 schemas1
154154 -> PQ
155− ("schema_migrations" ::: 'Table MigrationsTable ': schema0)
156− ("schema_migrations" ::: 'Table MigrationsTable ': schema1)
155+ ("migrations" ::: MigrationsSchema ': schemas0)
156+ ("migrations" ::: MigrationsSchema ': schemas1)
157157 io ()
158158 upMigrations = \case
159159 Done -> return ()
@@ -161,9 +161,9 @@ migrateUp migration =
161161
162162 upMigration
163163 :: MonadBase IO io
164− => Migration io schema0 schema1 -> PQ
165− ("schema_migrations" ::: 'Table MigrationsTable ': schema0)
166− ("schema_migrations" ::: 'Table MigrationsTable ': schema1)
164+ => Migration io schemas0 schemas1 -> PQ
165+ ("migrations" ::: MigrationsSchema ': schemas0)
166+ ("migrations" ::: MigrationsSchema ': schemas1)
167167 io ()
168168 upMigration step =
169169 queryExecuted step
@@ -178,9 +178,9 @@ migrateUp migration =
178178
179179 queryExecuted
180180 :: MonadBase IO io
181− => Migration io schema0 schema1 -> PQ
182− ("schema_migrations" ::: 'Table MigrationsTable ': schema0)
183− ("schema_migrations" ::: 'Table MigrationsTable ': schema0)
181+ => Migration io schemas0 schemas1 -> PQ
182+ ("migrations" ::: MigrationsSchema ': schemas0)
183+ ("migrations" ::: MigrationsSchema ': schemas0)
184184 io Row
185185 queryExecuted step = do
186186 result <- runQueryParams selectMigration (Only (name step))
@@ -193,10 +193,10 @@ migrateUp migration =
193193-- rewind the `Migration` and delete its row in the `MigrationsTable`.
194194migrateDown
195195 :: MonadBaseControl IO io
196− => AlignedList (Migration io) schema0 schema1 -- ^ migrations to rewind
196+ => AlignedList (Migration io) schemas0 schemas1 -- ^ migrations to rewind
197197 -> PQ
198− ("schema_migrations" ::: 'Table MigrationsTable ': schema1)
199− ("schema_migrations" ::: 'Table MigrationsTable ': schema0)
198+ ("migrations" ::: MigrationsSchema ': schemas1)
199+ ("migrations" ::: MigrationsSchema ': schemas0)
200200 io ()
201201migrateDown migrations =
202202 define createMigrations
@@ -206,9 +206,9 @@ migrateDown migrations =
206206
207207 downMigrations
208208 :: MonadBaseControl IO io
209− => AlignedList (Migration io) schema0 schema1 -> PQ
210− ("schema_migrations" ::: 'Table MigrationsTable ': schema1)
211− ("schema_migrations" ::: 'Table MigrationsTable ': schema0)
209+ => AlignedList (Migration io) schemas0 schemas1 -> PQ
210+ ("migrations" ::: MigrationsSchema ': schemas1)
211+ ("migrations" ::: MigrationsSchema ': schemas0)
212212 io ()
213213 downMigrations = \case
214214 Done -> return ()
@@ -216,9 +216,9 @@ migrateDown migrations =
216216
217217 downMigration
218218 :: MonadBase IO io
219− => Migration io schema0 schema1 -> PQ
220− ("schema_migrations" ::: 'Table MigrationsTable ': schema1)
221− ("schema_migrations" ::: 'Table MigrationsTable ': schema0)
219+ => Migration io schemas0 schemas1 -> PQ
220+ ("migrations" ::: MigrationsSchema ': schemas1)
221+ ("migrations" ::: MigrationsSchema ': schemas0)
222222 io ()
223223 downMigration step =
224224 queryExecuted step
@@ -233,9 +233,9 @@ migrateDown migrations =
233233
234234 queryExecuted
235235 :: MonadBase IO io
236− => Migration io schema0 schema1 -> PQ
237− ("schema_migrations" ::: 'Table MigrationsTable ': schema1)
238− ("schema_migrations" ::: 'Table MigrationsTable ': schema1)
236+ => Migration io schemas0 schemas1 -> PQ
237+ ("migrations" ::: MigrationsSchema ': schemas1)
238+ ("migrations" ::: MigrationsSchema ': schemas1)
239239 io Row
240240 queryExecuted step = do
241241 result <- runQueryParams selectMigration (Only (name step))
@@ -258,12 +258,15 @@ type MigrationsTable =
258258 , "executed_at" ::: 'Def :=> 'NotNull 'PGtimestamptz
259259 ]
260260
261+type MigrationsSchema = '["schema_migrations" ::: 'Table MigrationsTable]
262+
261263-- | Creates a `MigrationsTable` if it does not already exist.
262264createMigrations
263− :: Has "schema_migrations" schema ('Table MigrationsTable)
264− => Definition schema schema
265+ :: Has "migrations" schemas MigrationsSchema
266+ => Definition schemas schemas
265267createMigrations =
266− createTableIfNotExists #schema_migrations
268+ createSchemaIfNotExists #migrations >>>
269+ createTableIfNotExists (#migrations ! #schema_migrations)
267270 ( (text & notNullable) `as` #name :*
268271 (timestampWithTimeZone & notNullable & default_ currentTimestamp)
269272 `as` #executed_at )
@@ -271,25 +274,25 @@ createMigrations =
271274
272275-- | Inserts a `Migration` into the `MigrationsTable`
273276insertMigration
274− :: Has "schema_migrations" schema ('Table MigrationsTable)
275− => Manipulation schema '[ 'NotNull 'PGtext] '[]
276−insertMigration = insertRow_ #schema_migrations
277+ :: Has "migrations" schemas MigrationsSchema
278+ => Manipulation ('[] :=> schemas) '[ 'NotNull 'PGtext] '[]
279+insertMigration = insertRow_ (#migrations ! #schema_migrations)
277280 ( Set (param @1) `as` #name :*
278281 Default `as` #executed_at )
279282
280283-- | Deletes a `Migration` from the `MigrationsTable`
281284deleteMigration
282− :: Has "schema_migrations" schema ('Table MigrationsTable)
283− => Manipulation schema '[ 'NotNull 'PGtext ] '[]
284−deleteMigration = deleteFrom_ #schema_migrations NoUsing (#name .== param @1)
285+ :: Has "migrations" schemas MigrationsSchema
286+ => Manipulation ('[] :=> schemas) '[ 'NotNull 'PGtext ] '[]
287+deleteMigration = deleteFrom_ (#migrations ! #schema_migrations) NoUsing (#name .== param @1)
285288
286289-- | Selects a `Migration` from the `MigrationsTable`, returning
287290-- the time at which it was executed.
288291selectMigration
289− :: Has "schema_migrations" schema ('Table MigrationsTable)
290− => Query schema '[ 'NotNull 'PGtext ]
292+ :: Has "migrations" schemas MigrationsSchema
293+ => Query ('[] :=> schemas) '[ 'NotNull 'PGtext ]
291294 '[ "executed_at" ::: 'NotNull 'PGtimestamptz ]
292295selectMigration = select
293296 (#executed_at `as` #executed_at)
294− ( from (table (#schema_migrations `as` #m))
297+ ( from (table ((#migrations ! #schema_migrations) `as` #m))
295298 & where_ (#name .== param @1))
squeal-postgresql/src/Squeal/PostgreSQL/PQ.hs+86−86
@@ -11,7 +11,7 @@ a `Definition` and `MonadPQ` for executing a `Manipulation` or `Query`,
1111and a `PQ` type with instances for them.
1212
1313Using Squeal in your application will come down to defining
14−the @schema@ of your database and including @PQ schema schema@ in your
14+the @schemas@ of your database and including @PQ schemas schemas@ in your
1515application's monad transformer stack, giving it an instance of `MonadPQ`.
1616
1717This module also provides functions for retrieving rows from the `LibPQ.Result`
@@ -130,22 +130,22 @@ Note that, for now, squeal doesn't offer any protection from connecting
130130with the wrong schema!
131131-}
132132connectdb
133− :: forall schema io
133+ :: forall schemas io
134134 . MonadBase IO io
135135 => ByteString -- ^ conninfo
136− -> io (K LibPQ.Connection schema)
136+ -> io (K LibPQ.Connection schemas)
137137connectdb = fmap K . liftBase . LibPQ.connectdb
138138
139139-- | Closes the connection to the server.
140−finish :: MonadBase IO io => K LibPQ.Connection schema -> io ()
140+finish :: MonadBase IO io => K LibPQ.Connection schemas -> io ()
141141finish = liftBase . LibPQ.finish . unK
142142
143143-- | Do `connectdb` and `finish` before and after a computation.
144144withConnection
145− :: forall schema0 schema1 io x
145+ :: forall schemas0 schemas1 io x
146146 . MonadBaseControl IO io
147147 => ByteString
148− -> PQ schema0 schema1 io x
148+ -> PQ schemas0 schemas1 io x
149149 -> io x
150150withConnection connString action = do
151151 K x <- bracket (connectdb connString) finish (unPQ action)
@@ -153,20 +153,20 @@ withConnection connString action = do
153153
154154-- | Safely `lowerConnection` to a smaller schema.
155155lowerConnection
156− :: K LibPQ.Connection (table ': schema)
157− -> K LibPQ.Connection schema
156+ :: K LibPQ.Connection (schema ': schemas)
157+ -> K LibPQ.Connection schemas
158158lowerConnection (K conn) = K conn
159159
160160-- | We keep track of the schema via an Atkey indexed state monad transformer,
161161-- `PQ`.
162162newtype PQ
163− (schema0 :: SchemaType)
164− (schema1 :: SchemaType)
163+ (schemas0 :: SchemasType)
164+ (schemas1 :: SchemasType)
165165 (m :: Type -> Type)
166166 (x :: Type) =
167− PQ { unPQ :: K LibPQ.Connection schema0 -> m (K x schema1) }
167+ PQ { unPQ :: K LibPQ.Connection schemas0 -> m (K x schemas1) }
168168
169−instance Monad m => Functor (PQ schema0 schema1 m) where
169+instance Monad m => Functor (PQ schemas0 schemas1 m) where
170170 fmap f (PQ pq) = PQ $ \ conn -> do
171171 K x <- pq conn
172172 return $ K (f x)
@@ -174,9 +174,9 @@ instance Monad m => Functor (PQ schema0 schema1 m) where
174174-- | Run a `PQ` and keep the result and the `Connection`.
175175runPQ
176176 :: Functor m
177− => PQ schema0 schema1 m x
178− -> K LibPQ.Connection schema0
179− -> m (x, K LibPQ.Connection schema1)
177+ => PQ schemas0 schemas1 m x
178+ -> K LibPQ.Connection schemas0
179+ -> m (x, K LibPQ.Connection schemas1)
180180runPQ (PQ pq) conn = (\ x -> (unK x, K (unK conn))) <$> pq conn
181181 -- K x <- pq conn
182182 -- return (x, K (unK conn))
@@ -184,16 +184,16 @@ runPQ (PQ pq) conn = (\ x -> (unK x, K (unK conn))) <$> pq conn
184184-- | Execute a `PQ` and discard the result but keep the `Connection`.
185185execPQ
186186 :: Functor m
187− => PQ schema0 schema1 m x
188− -> K LibPQ.Connection schema0
189− -> m (K LibPQ.Connection schema1)
187+ => PQ schemas0 schemas1 m x
188+ -> K LibPQ.Connection schemas0
189+ -> m (K LibPQ.Connection schemas1)
190190execPQ (PQ pq) conn = mapKK (\ _ -> unK conn) <$> pq conn
191191
192192-- | Evaluate a `PQ` and discard the `Connection` but keep the result.
193193evalPQ
194194 :: Functor m
195− => PQ schema0 schema1 m x
196− -> K LibPQ.Connection schema0
195+ => PQ schemas0 schemas1 m x
196+ -> K LibPQ.Connection schemas0
197197 -> m x
198198evalPQ (PQ pq) conn = unK <$> pq conn
199199
@@ -208,53 +208,53 @@ class IndexedMonadTransPQ pq where
208208 -- | indexed analog of `<*>`
209209 pqAp
210210 :: Monad m
211− => pq schema0 schema1 m (x -> y)
212− -> pq schema1 schema2 m x
213− -> pq schema0 schema2 m y
211+ => pq schemas0 schemas1 m (x -> y)
212+ -> pq schemas1 schemas2 m x
213+ -> pq schemas0 schemas2 m y
214214
215215 -- | indexed analog of `join`
216216 pqJoin
217217 :: Monad m
218− => pq schema0 schema1 m (pq schema1 schema2 m y)
219− -> pq schema0 schema2 m y
218+ => pq schemas0 schemas1 m (pq schemas1 schemas2 m y)
219+ -> pq schemas0 schemas2 m y
220220 pqJoin pq = pq & pqBind id
221221
222222 -- | indexed analog of `=<<`
223223 pqBind
224224 :: Monad m
225− => (x -> pq schema1 schema2 m y)
226− -> pq schema0 schema1 m x
227− -> pq schema0 schema2 m y
225+ => (x -> pq schemas1 schemas2 m y)
226+ -> pq schemas0 schemas1 m x
227+ -> pq schemas0 schemas2 m y
228228
229229 -- | indexed analog of flipped `>>`
230230 pqThen
231231 :: Monad m
232− => pq schema1 schema2 m y
233− -> pq schema0 schema1 m x
234− -> pq schema0 schema2 m y
232+ => pq schemas1 schemas2 m y
233+ -> pq schemas0 schemas1 m x
234+ -> pq schemas0 schemas2 m y
235235 pqThen pq2 pq1 = pq1 & pqBind (\ _ -> pq2)
236236
237237 -- | indexed analog of `<=<`
238238 pqAndThen
239239 :: Monad m
240− => (y -> pq schema1 schema2 m z)
241− -> (x -> pq schema0 schema1 m y)
242− -> x -> pq schema0 schema2 m z
240+ => (y -> pq schemas1 schemas2 m z)
241+ -> (x -> pq schemas0 schemas1 m y)
242+ -> x -> pq schemas0 schemas2 m z
243243 pqAndThen g f x = pqBind g (f x)
244244
245245 -- | Safely embed a computation in a larger schema.
246246 pqEmbed
247247 :: Monad m
248− => pq schema0 schema1 m x
249− -> pq (table ': schema0) (table : schema1) m x
248+ => pq schemas0 schemas1 m x
249+ -> pq (schema ': schemas0) (schema : schemas1) m x
250250
251251 -- | Run a `Definition` with `LibPQ.exec`, we expect that libpq obeys the law
252252 --
253253 -- @define statement1 & pqThen (define statement2) = define (statement1 >>> statement2)@
254254 define
255255 :: MonadBase IO io
256− => Definition schema0 schema1
257− -> pq schema0 schema1 io (K LibPQ.Result '[])
256+ => Definition schemas0 schemas1
257+ -> pq schemas0 schemas1 io (K LibPQ.Result '[])
258258
259259instance IndexedMonadTransPQ PQ where
260260
@@ -312,66 +312,66 @@ To define an instance, you can minimally define only `manipulateParams`,
312312a default instance.
313313
314314-}
315−class Monad pq => MonadPQ schema pq | pq -> schema where
315+class Monad pq => MonadPQ schemas pq | pq -> schemas where
316316 manipulateParams
317317 :: ToParams x params
318− => Manipulation schema params ys
318+ => Manipulation ('[] :=> schemas) params ys
319319 -- ^ `insertRows`, `update` or `deleteFrom`
320320 -> x -> pq (K LibPQ.Result ys)
321321 default manipulateParams
322− :: (MonadTrans t, MonadPQ schema pq1, pq ~ t pq1)
322+ :: (MonadTrans t, MonadPQ schemas pq1, pq ~ t pq1)
323323 => ToParams x params
324− => Manipulation schema params ys
324+ => Manipulation ('[] :=> schemas) params ys
325325 -- ^ `insertRows`, `update` or `deleteFrom`
326326 -> x -> pq (K LibPQ.Result ys)
327327 manipulateParams manipulation params = lift $
328328 manipulateParams manipulation params
329329
330− manipulate :: Manipulation schema '[] ys -> pq (K LibPQ.Result ys)
330+ manipulate :: Manipulation ('[] :=> schemas) '[] ys -> pq (K LibPQ.Result ys)
331331 manipulate statement = manipulateParams statement ()
332332
333333 runQueryParams
334334 :: ToParams x params
335− => Query schema params ys
335+ => Query ('[] :=> schemas) params ys
336336 -- ^ `select` and friends
337337 -> x -> pq (K LibPQ.Result ys)
338338 runQueryParams = manipulateParams . queryStatement
339339
340340 runQuery
341− :: Query schema '[] ys
341+ :: Query ('[] :=> schemas) '[] ys
342342 -- ^ `select` and friends
343343 -> pq (K LibPQ.Result ys)
344344 runQuery q = runQueryParams q ()
345345
346346 traversePrepared
347347 :: (ToParams x params, Traversable list)
348− => Manipulation schema params ys
348+ => Manipulation ('[] :=> schemas) params ys
349349 -- ^ `insertRows`, `update`, or `deleteFrom`, and friends
350350 -> list x -> pq (list (K LibPQ.Result ys))
351351 default traversePrepared
352− :: (MonadTrans t, MonadPQ schema pq1, pq ~ t pq1)
352+ :: (MonadTrans t, MonadPQ schemas pq1, pq ~ t pq1)
353353 => (ToParams x params, Traversable list)
354− => Manipulation schema params ys -> list x -> pq (list (K LibPQ.Result ys))
354+ => Manipulation ('[] :=> schemas) params ys -> list x -> pq (list (K LibPQ.Result ys))
355355 traversePrepared manipulation params = lift $
356356 traversePrepared manipulation params
357357
358358 forPrepared
359359 :: (ToParams x params, Traversable list)
360360 => list x
361− -> Manipulation schema params ys
361+ -> Manipulation ('[] :=> schemas) params ys
362362 -- ^ `insertRows`, `update` or `deleteFrom`
363363 -> pq (list (K LibPQ.Result ys))
364364 forPrepared = flip traversePrepared
365365
366366 traversePrepared_
367367 :: (ToParams x params, Foldable list)
368− => Manipulation schema params '[]
368+ => Manipulation ('[] :=> schemas) params '[]
369369 -- ^ `insertRows`, `update` or `deleteFrom`
370370 -> list x -> pq ()
371371 default traversePrepared_
372− :: (MonadTrans t, MonadPQ schema pq1, pq ~ t pq1)
372+ :: (MonadTrans t, MonadPQ schemas pq1, pq ~ t pq1)
373373 => (ToParams x params, Foldable list)
374− => Manipulation schema params '[]
374+ => Manipulation ('[] :=> schemas) params '[]
375375 -- ^ `insertRows`, `update` or `deleteFrom`
376376 -> list x -> pq ()
377377 traversePrepared_ manipulation params = lift $
@@ -380,22 +380,22 @@ class Monad pq => MonadPQ schema pq | pq -> schema where
380380 forPrepared_
381381 :: (ToParams x params, Foldable list)
382382 => list x
383− -> Manipulation schema params '[]
383+ -> Manipulation ('[] :=> schemas) params '[]
384384 -- ^ `insertRows`, `update` or `deleteFrom`
385385 -> pq ()
386386 forPrepared_ = flip traversePrepared_
387387
388388 liftPQ :: (LibPQ.Connection -> IO a) -> pq a
389389 default liftPQ
390− :: (MonadTrans t, MonadPQ schema pq1, pq ~ t pq1)
390+ :: (MonadTrans t, MonadPQ schemas pq1, pq ~ t pq1)
391391 => (LibPQ.Connection -> IO a) -> pq a
392392 liftPQ = lift . liftPQ
393393
394−instance (MonadBase IO io, schema0 ~ schema, schema1 ~ schema)
395− => MonadPQ schema (PQ schema0 schema1 io) where
394+instance (MonadBase IO io, schemas0 ~ schemas, schemas1 ~ schemas)
395+ => MonadPQ schemas (PQ schemas0 schemas1 io) where
396396
397397 manipulateParams
398− (UnsafeManipulation q :: Manipulation schema ps ys) (params :: x) =
398+ (UnsafeManipulation q :: Manipulation ('[] :=> schemas) ps ys) (params :: x) =
399399 PQ $ \ (K conn) -> do
400400 let
401401 toParam' encoding =
@@ -411,7 +411,7 @@ instance (MonadBase IO io, schema0 ~ schema, schema1 ~ schema)
411411 return $ K (K result)
412412
413413 traversePrepared
414− (UnsafeManipulation q :: Manipulation schema xs ys) (list :: list x) =
414+ (UnsafeManipulation q :: Manipulation ('[] :=> schemas) xs ys) (list :: list x) =
415415 PQ $ \ (K conn) -> liftBase $ do
416416 let temp = "temporary_statement"
417417 prepResultMaybe <- LibPQ.prepare conn temp q Nothing
@@ -438,7 +438,7 @@ instance (MonadBase IO io, schema0 ~ schema, schema1 ~ schema)
438438 return (K results)
439439
440440 traversePrepared_
441− (UnsafeManipulation q :: Manipulation schema xs '[]) (list :: list x) =
441+ (UnsafeManipulation q :: Manipulation ('[] :=> schemas) xs '[]) (list :: list x) =
442442 PQ $ \ (K conn) -> liftBase $ do
443443 let temp = "temporary_statement"
444444 prepResultMaybe <- LibPQ.prepare conn temp q Nothing
@@ -466,56 +466,56 @@ instance (MonadBase IO io, schema0 ~ schema, schema1 ~ schema)
466466 y <- liftBase $ pq conn
467467 return (K y)
468468
469−instance MonadPQ schema m => MonadPQ schema (IdentityT m)
470−instance MonadPQ schema m => MonadPQ schema (ReaderT r m)
471−instance MonadPQ schema m => MonadPQ schema (Strict.StateT s m)
472−instance MonadPQ schema m => MonadPQ schema (Lazy.StateT s m)
473−instance (Monoid w, MonadPQ schema m) => MonadPQ schema (Strict.WriterT w m)
474−instance (Monoid w, MonadPQ schema m) => MonadPQ schema (Lazy.WriterT w m)
475−instance MonadPQ schema m => MonadPQ schema (MaybeT m)
476−instance MonadPQ schema m => MonadPQ schema (ExceptT e m)
477−instance (Monoid w, MonadPQ schema m) => MonadPQ schema (Strict.RWST r w s m)
478−instance (Monoid w, MonadPQ schema m) => MonadPQ schema (Lazy.RWST r w s m)
479−instance MonadPQ schema m => MonadPQ schema (ContT r m)
480−
481−instance (Monad m, schema0 ~ schema1)
482− => Applicative (PQ schema0 schema1 m) where
469+instance MonadPQ schemas m => MonadPQ schemas (IdentityT m)
470+instance MonadPQ schemas m => MonadPQ schemas (ReaderT r m)
471+instance MonadPQ schemas m => MonadPQ schemas (Strict.StateT s m)
472+instance MonadPQ schemas m => MonadPQ schemas (Lazy.StateT s m)
473+instance (Monoid w, MonadPQ schemas m) => MonadPQ schemas (Strict.WriterT w m)
474+instance (Monoid w, MonadPQ schemas m) => MonadPQ schemas (Lazy.WriterT w m)
475+instance MonadPQ schemas m => MonadPQ schemas (MaybeT m)
476+instance MonadPQ schemas m => MonadPQ schemas (ExceptT e m)
477+instance (Monoid w, MonadPQ schemas m) => MonadPQ schemas (Strict.RWST r w s m)
478+instance (Monoid w, MonadPQ schemas m) => MonadPQ schemas (Lazy.RWST r w s m)
479+instance MonadPQ schemas m => MonadPQ schemas (ContT r m)
480+
481+instance (Monad m, schemas0 ~ schemas1)
482+ => Applicative (PQ schemas0 schemas1 m) where
483483 pure x = PQ $ \ _conn -> pure (K x)
484484 (<*>) = pqAp
485485
486−instance (Monad m, schema0 ~ schema1)
487− => Monad (PQ schema0 schema1 m) where
486+instance (Monad m, schemas0 ~ schemas1)
487+ => Monad (PQ schemas0 schemas1 m) where
488488 return = pure
489489 (>>=) = flip pqBind
490490
491−instance schema0 ~ schema1 => MFunctor (PQ schema0 schema1) where
491+instance schemas0 ~ schemas1 => MFunctor (PQ schemas0 schemas1) where
492492 hoist f (PQ pq) = PQ (f . pq)
493493
494−instance schema0 ~ schema1 => MonadTrans (PQ schema0 schema1) where
494+instance schemas0 ~ schemas1 => MonadTrans (PQ schemas0 schemas1) where
495495 lift m = PQ $ \ _conn -> do
496496 x <- m
497497 return (K x)
498498
499−instance schema0 ~ schema1 => MMonad (PQ schema0 schema1) where
499+instance schemas0 ~ schemas1 => MMonad (PQ schemas0 schemas1) where
500500 embed f (PQ pq) = PQ $ \ conn -> do
501501 evalPQ (f (pq conn)) conn
502502
503−instance (MonadBase b m, schema0 ~ schema1)
504− => MonadBase b (PQ schema0 schema1 m) where
503+instance (MonadBase b m, schemas0 ~ schemas1)
504+ => MonadBase b (PQ schemas0 schemas1 m) where
505505 liftBase = lift . liftBase
506506
507507-- | A snapshot of the state of a `PQ` computation.
508−type PQRun schema =
509− forall m x. Monad m => PQ schema schema m x -> m (K x schema)
508+type PQRun schemas =
509+ forall m x. Monad m => PQ schemas schemas m x -> m (K x schemas)
510510
511511-- | Helper function in defining `MonadBaseControl` instance for `PQ`.
512−pqliftWith :: Functor m => (PQRun schema -> m a) -> PQ schema schema m a
512+pqliftWith :: Functor m => (PQRun schemas -> m a) -> PQ schemas schemas m a
513513pqliftWith f = PQ $ \ conn ->
514514 fmap K (f $ \ pq -> unPQ pq conn)
515515
516−instance (MonadBaseControl b m, schema0 ~ schema1)
517− => MonadBaseControl b (PQ schema0 schema1 m) where
518− type StM (PQ schema0 schema1 m) x = StM m (K x schema0)
516+instance (MonadBaseControl b m, schemas0 ~ schemas1)
517+ => MonadBaseControl b (PQ schemas0 schemas1 m) where
518+ type StM (PQ schemas0 schemas1 m) x = StM m (K x schemas0)
519519 liftBaseWith f =
520520 pqliftWith $ \ run -> liftBaseWith $ \ runInBase -> f $ runInBase . run
521521 restoreM = PQ . const . restoreM
squeal-postgresql/src/Squeal/PostgreSQL/Pool.hs+18−18
@@ -41,7 +41,7 @@ import Generics.SOP (K(..))
4141import Squeal.PostgreSQL.PQ
4242import Squeal.PostgreSQL.Schema
4343
44−{- | `PoolPQ` @schema@ should be a drop-in replacement for `PQ` @schema schema@.
44+{- | `PoolPQ` @schemas@ should be a drop-in replacement for `PQ` @schemas schemas@.
4545
4646Typical use case would be to create your pool using `createConnectionPool` and run anything that requires the pool connection with it.
4747
@@ -63,8 +63,8 @@ Here's a simplified example:
6363> liftIO $ runPoolPQ (insertOne) pool
6464
6565-}
66−newtype PoolPQ (schema :: SchemaType) m x =
67− PoolPQ { runPoolPQ :: Pool (K Connection schema) -> m x }
66+newtype PoolPQ (schemas :: SchemasType) m x =
67+ PoolPQ { runPoolPQ :: Pool (K Connection schemas) -> m x }
6868 deriving Functor
6969
7070-- | Create a striped pool of connections.
@@ -86,12 +86,12 @@ createConnectionPool
8686 -> Int
8787 -- ^ Maximum number of connections to keep open per stripe. The smallest acceptable value is 1.
8888 -- Requests for connections will block if this limit is reached on a single stripe, even if other stripes have idle connections available.
89− -> io (Pool (K Connection schema))
89+ -> io (Pool (K Connection schemas))
9090createConnectionPool conninfo stripes idle maxResrc = liftBase $
9191 createPool (connectdb conninfo) finish stripes idle maxResrc
9292
9393-- | `Applicative` instance for `PoolPQ`.
94−instance Monad m => Applicative (PoolPQ schema m) where
94+instance Monad m => Applicative (PoolPQ schemas m) where
9595 pure x = PoolPQ $ \ _ -> pure x
9696 PoolPQ f <*> PoolPQ x = PoolPQ $ \ pool -> do
9797 f' <- f pool
@@ -99,55 +99,55 @@ instance Monad m => Applicative (PoolPQ schema m) where
9999 return $ f' x'
100100
101101-- | `Monad` instance for `PoolPQ`.
102−instance Monad m => Monad (PoolPQ schema m) where
102+instance Monad m => Monad (PoolPQ schemas m) where
103103 return = pure
104104 PoolPQ x >>= f = PoolPQ $ \ pool -> do
105105 x' <- x pool
106106 runPoolPQ (f x') pool
107107
108108-- | `MonadTrans` instance for `PoolPQ`.
109−instance MonadTrans (PoolPQ schema) where
109+instance MonadTrans (PoolPQ schemas) where
110110 lift m = PoolPQ $ \ _pool -> m
111111
112112-- | `MonadBase` instance for `PoolPQ`.
113−instance MonadBase b m => MonadBase b (PoolPQ schema m) where
113+instance MonadBase b m => MonadBase b (PoolPQ schemas m) where
114114 liftBase = lift . liftBase
115115
116116-- | `MonadPQ` instance for `PoolPQ`.
117−instance MonadBaseControl IO io => MonadPQ schema (PoolPQ schema io) where
117+instance MonadBaseControl IO io => MonadPQ schemas (PoolPQ schemas io) where
118118 manipulateParams manipulation params = PoolPQ $ \ pool -> do
119119 withResource pool $ \ conn -> do
120− (K result :: K (K Result ys) schema) <- flip unPQ conn $
120+ (K result :: K (K Result ys) schemas) <- flip unPQ conn $
121121 manipulateParams manipulation params
122122 return result
123123 traversePrepared manipulation params = PoolPQ $ \ pool ->
124124 withResource pool $ \ conn -> do
125− (K result :: K (list (K Result ys)) schema) <- flip unPQ conn $
125+ (K result :: K (list (K Result ys)) schemas) <- flip unPQ conn $
126126 traversePrepared manipulation params
127127 return result
128128 traversePrepared_ manipulation params = PoolPQ $ \ pool -> do
129129 withResource pool $ \ conn -> do
130− (_ :: K () schema) <- flip unPQ conn $
130+ (_ :: K () schemas) <- flip unPQ conn $
131131 traversePrepared_ manipulation params
132132 return ()
133133 liftPQ m = PoolPQ $ \ pool ->
134134 withResource pool $ \ conn -> do
135− (K result :: K result schema) <- flip unPQ conn $
135+ (K result :: K result schemas) <- flip unPQ conn $
136136 liftPQ m
137137 return result
138138
139139-- | A snapshot of the state of a `PoolPQ` computation.
140−type PoolPQRun schema =
141− forall m x. Monad m => PoolPQ schema m x -> m x
140+type PoolPQRun schemas =
141+ forall m x. Monad m => PoolPQ schemas m x -> m x
142142
143143-- | Helper function in defining `MonadBaseControl` instance for `PoolPQ`.
144−poolpqliftWith :: Functor m => (PoolPQRun schema -> m a) -> PoolPQ schema m a
144+poolpqliftWith :: Functor m => (PoolPQRun schemas -> m a) -> PoolPQ schemas m a
145145poolpqliftWith f = PoolPQ $ \ pool ->
146146 (f $ \ pq -> runPoolPQ pq pool)
147147
148148-- | `MonadBaseControl` instance for `PoolPQ`.
149−instance MonadBaseControl b m => MonadBaseControl b (PoolPQ schema m) where
150− type StM (PoolPQ schema m) x = StM m x
149+instance MonadBaseControl b m => MonadBaseControl b (PoolPQ schemas m) where
150+ type StM (PoolPQ schemas m) x = StM m x
151151 liftBaseWith f =
152152 poolpqliftWith $ \ run -> liftBaseWith $ \ runInBase -> f $ runInBase . run
153153 restoreM = PoolPQ . const . restoreM
squeal-postgresql/src/Squeal/PostgreSQL/Query.hs+352−378
@@ -81,6 +81,7 @@ module Squeal.PostgreSQL.Query
8181 , table
8282 , subquery
8383 , view
84+ , common
8485 , crossJoin
8586 , innerJoin
8687 , leftOuterJoin
@@ -144,12 +145,11 @@ is called a `Query`. Let's see some examples of queries.
144145
145146simple query:
146147
148+>>> type Columns = '["col1" ::: 'NoDef :=> 'NotNull 'PGint4, "col2" ::: 'NoDef :=> 'NotNull 'PGint4]
149+>>> type Schema = '["tab" ::: 'Table ('[] :=> Columns)]
147150>>> :{
148151let
149− query :: Query
150− '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'Null 'PGint4])]
151− '[]
152− '["col" ::: 'Null 'PGint4]
152+ query :: Query (DBof (Public Schema)) '[] '["col1" ::: 'NotNull 'PGint4, "col2" ::: 'NotNull 'PGint4]
153153 query = selectStar (from (table #tab))
154154in printSQL query
155155:}
@@ -159,16 +159,9 @@ restricted query:
159159
160160>>> :{
161161let
162− query :: Query
163− '[ "tab" ::: 'Table ('[] :=>
164− '[ "col1" ::: 'NoDef :=> 'NotNull 'PGint4
165− , "col2" ::: 'NoDef :=> 'NotNull 'PGint4 ])]
166− '[]
167− '[ "sum" ::: 'NotNull 'PGint4
168− , "col1" ::: 'NotNull 'PGint4 ]
162+ query :: Query (DBof (Public Schema)) '[] '["sum" ::: 'NotNull 'PGint4, "col1" ::: 'NotNull 'PGint4]
169163 query =
170− select
171− ((#col1 + #col2) `as` #sum :* #col1)
164+ select ((#col1 + #col2) `as` #sum :* #col1)
172165 ( from (table #tab)
173166 & where_ (#col1 .> #col2)
174167 & where_ (#col2 .> 0) )
@@ -180,13 +173,8 @@ subquery:
180173
181174>>> :{
182175let
183− query :: Query
184− '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'Null 'PGint4])]
185− '[]
186− '["col" ::: 'Null 'PGint4]
187− query =
188− selectStar
189− (from (subquery (selectStar (from (table #tab)) `as` #sub)))
176+ query :: Query (DBof (Public Schema)) '[] '["col1" ::: 'NotNull 'PGint4, "col2" ::: 'NotNull 'PGint4]
177+ query = selectStar (from (subquery (selectStar (from (table #tab)) `as` #sub)))
190178in printSQL query
191179:}
192180SELECT * FROM (SELECT * FROM "tab" AS "tab") AS "sub"
@@ -195,12 +183,8 @@ limits and offsets:
195183
196184>>> :{
197185let
198− query :: Query
199− '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'Null 'PGint4])]
200− '[]
201− '["col" ::: 'Null 'PGint4]
202− query = selectStar
203− (from (table #tab) & limit 100 & offset 2 & limit 50 & offset 2)
186+ 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)
204188in printSQL query
205189:}
206190SELECT * FROM "tab" AS "tab" LIMIT 50 OFFSET 4
@@ -209,27 +193,17 @@ parameterized query:
209193
210194>>> :{
211195let
212− query :: Query
213− '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'NotNull 'PGfloat8])]
214− '[ 'NotNull 'PGfloat8]
215− '["col" ::: 'NotNull 'PGfloat8]
216− query = selectStar
217− (from (table #tab) & where_ (#col .> param @1))
196+ query :: Query (DBof (Public Schema)) '[ 'NotNull 'PGint4] '["col1" ::: 'NotNull 'PGint4, "col2" ::: 'NotNull 'PGint4]
197+ query = selectStar (from (table #tab) & where_ (#col1 .> param @1))
218198in printSQL query
219199:}
220−SELECT * FROM "tab" AS "tab" WHERE ("col" > ($1 :: float8))
200+SELECT * FROM "tab" AS "tab" WHERE ("col1" > ($1 :: int4))
221201
222202aggregation query:
223203
224204>>> :{
225205let
226− query :: Query
227− '[ "tab" ::: 'Table ('[] :=>
228− '[ "col1" ::: 'NoDef :=> 'NotNull 'PGint4
229− , "col2" ::: 'NoDef :=> 'NotNull 'PGint4 ])]
230− '[]
231− '[ "sum" ::: 'NotNull 'PGint4
232− , "col1" ::: 'NotNull 'PGint4 ]
206+ query :: Query (DBof (Public Schema)) '[] '["sum" ::: 'NotNull 'PGint4, "col1" ::: 'NotNull 'PGint4 ]
233207 query =
234208 select (sum_ #col2 `as` #sum :* #col1)
235209 ( from (table (#tab `as` #table1))
@@ -243,42 +217,44 @@ sorted query:
243217
244218>>> :{
245219let
246− query :: Query
247− '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'Null 'PGint4])]
248− '[]
249− '["col" ::: 'Null 'PGint4]
250− query = selectStar
251− (from (table #tab) & orderBy [#col & AscNullsFirst])
220+ query :: Query (DBof (Public Schema)) '[] '["col1" ::: 'NotNull 'PGint4, "col2" ::: 'NotNull 'PGint4]
221+ query = selectStar (from (table #tab) & orderBy [#col1 & Asc])
252222in printSQL query
253223:}
254−SELECT * FROM "tab" AS "tab" ORDER BY "col" ASC NULLS FIRST
224+SELECT * FROM "tab" AS "tab" ORDER BY "col1" ASC
255225
256226joins:
257227
258228>>> :set -XFlexibleContexts
229+>>> :{
230+type OrdersColumns =
231+ '[ "id" ::: 'NoDef :=> 'NotNull 'PGint4
232+ , "price" ::: 'NoDef :=> 'NotNull 'PGfloat4
233+ , "customer_id" ::: 'NoDef :=> 'NotNull 'PGint4
234+ , "shipper_id" ::: 'NoDef :=> 'NotNull 'PGint4
235+ ]
236+:}
237+
238+>>> :{
239+type OrdersConstraints =
240+ '["pk_orders" ::: PrimaryKey '["id"]
241+ ,"fk_customers" ::: ForeignKey '["customer_id"] "customers" '["id"]
242+ ,"fk_shippers" ::: ForeignKey '["shipper_id"] "shippers" '["id"] ]
243+:}
244+
245+>>> type NamesColumns = '["id" ::: 'NoDef :=> 'NotNull 'PGint4, "name" ::: 'NoDef :=> 'NotNull 'PGtext]
246+>>> type CustomersConstraints = '["pk_customers" ::: PrimaryKey '["id"]]
247+>>> type ShippersConstraints = '["pk_shippers" ::: PrimaryKey '["id"]]
248+>>> :{
249+type OrdersSchema =
250+ '[ "orders" ::: 'Table (OrdersConstraints :=> OrdersColumns)
251+ , "customers" ::: 'Table (CustomersConstraints :=> NamesColumns)
252+ , "shippers" ::: 'Table (ShippersConstraints :=> NamesColumns) ]
253+:}
254+
259255>>> :{
260256let
261− query :: Query
262− '[ "orders" ::: 'Table (
263− '["pk_orders" ::: PrimaryKey '["id"]
264− ,"fk_customers" ::: ForeignKey '["customer_id"] "customers" '["id"]
265− ,"fk_shippers" ::: ForeignKey '["shipper_id"] "shippers" '["id"]] :=>
266− '[ "id" ::: 'NoDef :=> 'NotNull 'PGint4
267− , "price" ::: 'NoDef :=> 'NotNull 'PGfloat4
268− , "customer_id" ::: 'NoDef :=> 'NotNull 'PGint4
269− , "shipper_id" ::: 'NoDef :=> 'NotNull 'PGint4
270− ])
271− , "customers" ::: 'Table (
272− '["pk_customers" ::: PrimaryKey '["id"]] :=>
273− '[ "id" ::: 'NoDef :=> 'NotNull 'PGint4
274− , "name" ::: 'NoDef :=> 'NotNull 'PGtext
275− ])
276− , "shippers" ::: 'Table (
277− '["pk_shippers" ::: PrimaryKey '["id"]] :=>
278− '[ "id" ::: 'NoDef :=> 'NotNull 'PGint4
279− , "name" ::: 'NoDef :=> 'NotNull 'PGtext
280− ])
281− ]
257+ query :: Query (DBof (Public OrdersSchema))
282258 '[]
283259 '[ "order_price" ::: 'NotNull 'PGfloat4
284260 , "customer_name" ::: 'NotNull 'PGtext
@@ -301,12 +277,8 @@ self-join:
301277
302278>>> :{
303279let
304− query :: Query
305− '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'Null 'PGint4])]
306− '[]
307− '["col" ::: 'Null 'PGint4]
308− query = selectDotStar #t1
309− (from (table (#tab `as` #t1) & crossJoin (table (#tab `as` #t2))))
280+ 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))))
310282in printSQL query
311283:}
312284SELECT "t1".* FROM "tab" AS "t1" CROSS JOIN "tab" AS "t2"
@@ -315,7 +287,7 @@ value queries:
315287
316288>>> :{
317289let
318− query :: Query '[] '[] '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
290+ query :: Query db '[] '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
319291 query = values (1 `as` #foo :* true `as` #bar) [2 `as` #foo :* false `as` #bar]
320292in printSQL query
321293:}
@@ -325,14 +297,8 @@ set operations:
325297
326298>>> :{
327299let
328− query :: Query
329− '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'Null 'PGint4])]
330− '[]
331− '["col" ::: 'Null 'PGint4]
332− query =
333− selectStar (from (table #tab))
334− `unionAll`
335− selectStar (from (table #tab))
300+ query :: Query (DBof (Public Schema)) '[] '["col1" ::: 'NotNull 'PGint4, "col2" ::: 'NotNull 'PGint4]
301+ query = selectStar (from (table #tab)) `unionAll` selectStar (from (table #tab))
336302in printSQL query
337303:}
338304(SELECT * FROM "tab" AS "tab") UNION ALL (SELECT * FROM "tab" AS "tab")
@@ -341,35 +307,29 @@ with queries:
341307
342308>>> :{
343309let
344− query :: Query
345− '[ "t1" ::: 'View
346− '[ "c1" ::: 'NotNull 'PGtext
347− , "c2" ::: 'NotNull 'PGtext] ]
348− '[]
349− '[ "c1" ::: 'NotNull 'PGtext
350− , "c2" ::: 'NotNull 'PGtext ]
310+ query :: Query (DBof (Public Schema)) '[] '["col1" ::: 'NotNull 'PGint4, "col2" ::: 'NotNull 'PGint4]
351311 query = with (
352− selectStar (from (view #t1)) `as` #t2 :>>
353− selectStar (from (view #t2)) `as` #t3
354− ) (selectStar (from (view #t3)))
312+ selectStar (from (table #tab)) `as` #cte1 :>>
313+ selectStar (from (common #cte1)) `as` #cte2
314+ ) (selectStar (from (common #cte2)))
355315in printSQL query
356316:}
357−WITH "t2" AS (SELECT * FROM "t1" AS "t1"), "t3" AS (SELECT * FROM "t2" AS "t2") SELECT * FROM "t3" AS "t3"
317+WITH "cte1" AS (SELECT * FROM "tab" AS "tab"), "cte2" AS (SELECT * FROM "cte1" AS "cte1") SELECT * FROM "cte2" AS "cte2"
358318-}
359319newtype Query
360− (schema :: SchemaType)
320+ (db :: DBType)
361321 (params :: [NullityType])
362322 (columns :: RowType)
363323 = UnsafeQuery { renderQuery :: ByteString }
364324 deriving (GHC.Generic,Show,Eq,Ord,NFData)
365−instance RenderSQL (Query schema params columns) where renderSQL = renderQuery
325+instance RenderSQL (Query db params columns) where renderSQL = renderQuery
366326
367327-- | The results of two queries can be combined using the set operation
368328-- `union`. Duplicate rows are eliminated.
369329union
370− :: Query schema params columns
371− -> Query schema params columns
372− -> Query schema params columns
330+ :: Query db params columns
331+ -> Query db params columns
332+ -> Query db params columns
373333q1 `union` q2 = UnsafeQuery $
374334 parenthesized (renderQuery q1)
375335 <+> "UNION"
@@ -378,9 +338,9 @@ q1 `union` q2 = UnsafeQuery $
378338-- | The results of two queries can be combined using the set operation
379339-- `unionAll`, the disjoint union. Duplicate rows are retained.
380340unionAll
381− :: Query schema params columns
382− -> Query schema params columns
383− -> Query schema params columns
341+ :: Query db params columns
342+ -> Query db params columns
343+ -> Query db params columns
384344q1 `unionAll` q2 = UnsafeQuery $
385345 parenthesized (renderQuery q1)
386346 <+> "UNION" <+> "ALL"
@@ -389,9 +349,9 @@ q1 `unionAll` q2 = UnsafeQuery $
389349-- | The results of two queries can be combined using the set operation
390350-- `intersect`, the intersection. Duplicate rows are eliminated.
391351intersect
392− :: Query schema params columns
393− -> Query schema params columns
394− -> Query schema params columns
352+ :: Query db params columns
353+ -> Query db params columns
354+ -> Query db params columns
395355q1 `intersect` q2 = UnsafeQuery $
396356 parenthesized (renderQuery q1)
397357 <+> "INTERSECT"
@@ -400,9 +360,9 @@ q1 `intersect` q2 = UnsafeQuery $
400360-- | The results of two queries can be combined using the set operation
401361-- `intersectAll`, the intersection. Duplicate rows are retained.
402362intersectAll
403− :: Query schema params columns
404− -> Query schema params columns
405− -> Query schema params columns
363+ :: Query db params columns
364+ -> Query db params columns
365+ -> Query db params columns
406366q1 `intersectAll` q2 = UnsafeQuery $
407367 parenthesized (renderQuery q1)
408368 <+> "INTERSECT" <+> "ALL"
@@ -411,9 +371,9 @@ q1 `intersectAll` q2 = UnsafeQuery $
411371-- | The results of two queries can be combined using the set operation
412372-- `except`, the set difference. Duplicate rows are eliminated.
413373except
414− :: Query schema params columns
415− -> Query schema params columns
416− -> Query schema params columns
374+ :: Query db params columns
375+ -> Query db params columns
376+ -> Query db params columns
417377q1 `except` q2 = UnsafeQuery $
418378 parenthesized (renderQuery q1)
419379 <+> "EXCEPT"
@@ -422,9 +382,9 @@ q1 `except` q2 = UnsafeQuery $
422382-- | The results of two queries can be combined using the set operation
423383-- `exceptAll`, the set difference. Duplicate rows are retained.
424384exceptAll
425− :: Query schema params columns
426− -> Query schema params columns
427− -> Query schema params columns
385+ :: Query db params columns
386+ -> Query db params columns
387+ -> Query db params columns
428388q1 `exceptAll` q2 = UnsafeQuery $
429389 parenthesized (renderQuery q1)
430390 <+> "EXCEPT" <+> "ALL"
@@ -440,12 +400,12 @@ SELECT queries
440400-- the select list. The select list determines which columns of
441401-- the intermediate table are actually output.
442402select
443− :: SListI columns
444− => NP (Aliased (Expression schema from grouping params)) (column ': columns)
403+ :: (SListI columns, columns ~ (col ': cols))
404+ => NP (Aliased (Expression db from grouping params)) columns
445405 -- ^ select list
446− -> TableExpression schema params from grouping
406+ -> TableExpression db params from grouping
447407 -- ^ intermediate virtual table
448− -> Query schema params (column ': columns)
408+ -> Query db params columns
449409select list rels = UnsafeQuery $
450410 "SELECT"
451411 <+> renderCommaSeparated (renderAliasedAs renderExpression) list
@@ -454,12 +414,12 @@ select list rels = UnsafeQuery $
454414-- | After the select list has been processed, the result table can
455415-- be subject to the elimination of duplicate rows using `selectDistinct`.
456416selectDistinct
457− :: SListI columns
458− => NP (Aliased (Expression schema from 'Ungrouped params)) (column ': columns)
417+ :: (SListI columns, columns ~ (col ': cols))
418+ => NP (Aliased (Expression db from 'Ungrouped params)) columns
459419 -- ^ select list
460− -> TableExpression schema params from 'Ungrouped
420+ -> TableExpression db params from 'Ungrouped
461421 -- ^ intermediate virtual table
462− -> Query schema params (column ': columns)
422+ -> Query db params columns
463423selectDistinct list rels = UnsafeQuery $
464424 "SELECT DISTINCT"
465425 <+> renderCommaSeparated (renderAliasedAs renderExpression) list
@@ -469,18 +429,18 @@ selectDistinct list rels = UnsafeQuery $
469429-- that the table expression produces.
470430selectStar
471431 :: HasUnique table from columns
472− => TableExpression schema params from 'Ungrouped
432+ => TableExpression db params from 'Ungrouped
473433 -- ^ intermediate virtual table
474− -> Query schema params columns
434+ -> Query db params columns
475435selectStar rels = UnsafeQuery $ "SELECT" <+> "*" <+> renderTableExpression rels
476436
477437-- | A `selectDistinctStar` emits all columns that the table expression
478438-- produces and eliminates duplicate rows.
479439selectDistinctStar
480440 :: HasUnique table from columns
481− => TableExpression schema params from 'Ungrouped
441+ => TableExpression db params from 'Ungrouped
482442 -- ^ intermediate virtual table
483− -> Query schema params columns
443+ -> Query db params columns
484444selectDistinctStar rels = UnsafeQuery $
485445 "SELECT DISTINCT" <+> "*" <+> renderTableExpression rels
486446
@@ -490,9 +450,9 @@ selectDotStar
490450 :: Has table from columns
491451 => Alias table
492452 -- ^ particular virtual subtable
493− -> TableExpression schema params from 'Ungrouped
453+ -> TableExpression db params from 'Ungrouped
494454 -- ^ intermediate virtual table
495− -> Query schema params columns
455+ -> Query db params columns
496456selectDotStar rel tab = UnsafeQuery $
497457 "SELECT" <+> renderAlias rel <> ".*" <+> renderTableExpression tab
498458
@@ -502,9 +462,9 @@ selectDistinctDotStar
502462 :: Has table from columns
503463 => Alias table
504464 -- ^ particular virtual table
505− -> TableExpression schema params from 'Ungrouped
465+ -> TableExpression db params from 'Ungrouped
506466 -- ^ intermediate virtual table
507− -> Query schema params columns
467+ -> Query db params columns
508468selectDistinctDotStar rel tab = UnsafeQuery $
509469 "SELECT DISTINCT" <+> renderAlias rel <> ".*"
510470 <+> renderTableExpression tab
@@ -515,16 +475,16 @@ selectDistinctDotStar rel tab = UnsafeQuery $
515475-- but it can be used on its own.
516476--
517477-- >>> type Row = '["a" ::: 'NotNull 'PGint4, "b" ::: 'NotNull 'PGtext]
518−-- >>> let query = values (1 `as` #a :* "one" `as` #b) [] :: Query '[] '[] Row
478+-- >>> let query = values (1 `as` #a :* "one" `as` #b) [] :: Query db '[] Row
519479-- >>> printSQL query
520480-- SELECT * FROM (VALUES (1, E'one')) AS t ("a", "b")
521481values
522482 :: SListI cols
523− => NP (Aliased (Expression schema '[] 'Ungrouped params)) cols
524− -> [NP (Aliased (Expression schema '[] 'Ungrouped params)) cols]
483+ => NP (Aliased (Expression db '[] 'Ungrouped params)) cols
484+ -> [NP (Aliased (Expression db '[] 'Ungrouped params)) cols]
525485 -- ^ When more than one row is specified, all the rows must
526486 -- must have the same number of elements
527− -> Query schema params cols
487+ -> Query db params cols
528488values rw rws = UnsafeQuery $ "SELECT * FROM"
529489 <+> parenthesized (
530490 "VALUES"
@@ -535,7 +495,7 @@ values rw rws = UnsafeQuery $ "SELECT * FROM"
535495 <+> parenthesized (renderCommaSeparated renderAliasPart rw)
536496 where
537497 renderAliasPart, renderValuePart
538− :: Aliased (Expression schema '[] 'Ungrouped params) ty -> ByteString
498+ :: Aliased (Expression db '[] 'Ungrouped params) ty -> ByteString
539499 renderAliasPart (_ `As` name) = renderAlias name
540500 renderValuePart (value `As` _) = renderExpression value
541501
@@ -543,9 +503,9 @@ values rw rws = UnsafeQuery $ "SELECT * FROM"
543503-- specified by value expressions.
544504values_
545505 :: SListI cols
546− => NP (Aliased (Expression schema '[] 'Ungrouped params)) cols
506+ => NP (Aliased (Expression db '[] 'Ungrouped params)) cols
547507 -- ^ one row of values
548− -> Query schema params cols
508+ -> Query db params cols
549509values_ rw = values rw []
550510
551511{-----------------------------------------
@@ -559,15 +519,15 @@ Table Expressions
559519-- to a table on disk, a so-called base table, but more complex expressions
560520-- can be used to modify or combine base tables in various ways.
561521data TableExpression
562− (schema :: SchemaType)
522+ (db :: DBType)
563523 (params :: [NullityType])
564524 (from :: FromType)
565525 (grouping :: Grouping)
566526 = TableExpression
567− { fromClause :: FromClause schema params from
527+ { fromClause :: FromClause db params from
568528 -- ^ A table reference that can be a table name, or a derived table such
569529 -- as a subquery, a @JOIN@ construct, or complex combinations of these.
570− , whereClause :: [Condition schema from 'Ungrouped params]
530+ , whereClause :: [Condition db from 'Ungrouped params]
571531 -- ^ optional search coditions, combined with `.&&`. After the processing
572532 -- of the `fromClause` is done, each row of the derived virtual table
573533 -- is checked against the search condition. If the result of the
@@ -583,13 +543,13 @@ data TableExpression
583543 -- set of rows having common values into one group row that represents all
584544 -- rows in the group. This is done to eliminate redundancy in the output
585545 -- and/or compute aggregates that apply to these groups.
586− , havingClause :: HavingClause schema from grouping params
546+ , havingClause :: HavingClause db from grouping params
587547 -- ^ If a table has been grouped using `groupBy`, but only certain groups
588548 -- are of interest, the `havingClause` can be used, much like a
589549 -- `whereClause`, to eliminate groups from the result. Expressions in the
590550 -- `havingClause` can refer both to grouped expressions and to ungrouped
591551 -- expressions (which necessarily involve an aggregate function).
592− , orderByClause :: [SortExpression schema from grouping params]
552+ , orderByClause :: [SortExpression db from grouping params]
593553 -- ^ The `orderByClause` is for optional sorting. When more than one
594554 -- `SortExpression` is specified, the later (right) values are used to sort
595555 -- rows that are equal according to the earlier (left) values.
@@ -607,7 +567,7 @@ data TableExpression
607567
608568-- | Render a `TableExpression`
609569renderTableExpression
610− :: TableExpression schema params from grouping
570+ :: TableExpression db params from grouping
611571 -> ByteString
612572renderTableExpression
613573 (TableExpression frm' whs' grps' hvs' srts' lims' offs') = mconcat
@@ -641,16 +601,16 @@ renderTableExpression
641601-- `group`, `having`, `orderBy`, `limit` and `offset`, using the `&` operator
642602-- to match the left-to-right sequencing of their placement in SQL.
643603from
644− :: FromClause schema params from -- ^ table reference
645− -> TableExpression schema params from 'Ungrouped
604+ :: FromClause db params from -- ^ table reference
605+ -> TableExpression db params from 'Ungrouped
646606from rels = TableExpression rels [] NoGroups NoHaving [] [] []
647607
648608-- | A `where_` is an endomorphism of `TableExpression`s which adds a
649609-- search condition to the `whereClause`.
650610where_
651− :: Condition schema from 'Ungrouped params -- ^ filtering condition
652− -> TableExpression schema params from grouping
653− -> TableExpression schema params from grouping
611+ :: Condition db from 'Ungrouped params -- ^ filtering condition
612+ -> TableExpression db params from grouping
613+ -> TableExpression db params from grouping
654614where_ wh rels = rels {whereClause = wh : whereClause rels}
655615
656616-- | A `groupBy` is a transformation of `TableExpression`s which switches
@@ -659,8 +619,8 @@ where_ wh rels = rels {whereClause = wh : whereClause rels}
659619groupBy
660620 :: SListI bys
661621 => NP (By from) bys -- ^ grouped columns
662− -> TableExpression schema params from 'Ungrouped
663− -> TableExpression schema params from ('Grouped bys)
622+ -> TableExpression db params from 'Ungrouped
623+ -> TableExpression db params from ('Grouped bys)
664624groupBy bys rels = TableExpression
665625 { fromClause = fromClause rels
666626 , whereClause = whereClause rels
@@ -674,34 +634,34 @@ groupBy bys rels = TableExpression
674634-- | A `having` is an endomorphism of `TableExpression`s which adds a
675635-- search condition to the `havingClause`.
676636having
677− :: Condition schema from ('Grouped bys) params -- ^ having condition
678− -> TableExpression schema params from ('Grouped bys)
679− -> TableExpression schema params from ('Grouped bys)
637+ :: Condition db from ('Grouped bys) params -- ^ having condition
638+ -> TableExpression db params from ('Grouped bys)
639+ -> TableExpression db params from ('Grouped bys)
680640having hv rels = rels
681641 { havingClause = case havingClause rels of Having hvs -> Having (hv:hvs) }
682642
683643-- | An `orderBy` is an endomorphism of `TableExpression`s which appends an
684644-- ordering to the right of the `orderByClause`.
685645orderBy
686− :: [SortExpression schema from grouping params] -- ^ sort expressions
687− -> TableExpression schema params from grouping
688− -> TableExpression schema params from grouping
646+ :: [SortExpression db from grouping params] -- ^ sort expressions
647+ -> TableExpression db params from grouping
648+ -> TableExpression db params from grouping
689649orderBy srts rels = rels {orderByClause = orderByClause rels ++ srts}
690650
691651-- | A `limit` is an endomorphism of `TableExpression`s which adds to the
692652-- `limitClause`.
693653limit
694654 :: Word64 -- ^ limit parameter
695− -> TableExpression schema params from grouping
696− -> TableExpression schema params from grouping
655+ -> TableExpression db params from grouping
656+ -> TableExpression db params from grouping
697657limit lim rels = rels {limitClause = lim : limitClause rels}
698658
699659-- | An `offset` is an endomorphism of `TableExpression`s which adds to the
700660-- `offsetClause`.
701661offset
702662 :: Word64 -- ^ offset parameter
703− -> TableExpression schema params from grouping
704− -> TableExpression schema params from grouping
663+ -> TableExpression db params from grouping
664+ -> TableExpression db params from grouping
705665offset off rels = rels {offsetClause = off : offsetClause rels}
706666
707667{-----------------------------------------
@@ -710,56 +670,56 @@ JSON stuff
710670
711671unsafeSetOfFunction
712672 :: ByteString
713− -> Expression schema '[] 'Ungrouped params ty
714− -> Query schema params row
673+ -> Expression db '[] 'Ungrouped params ty
674+ -> Query db params row
715675unsafeSetOfFunction fun expr = UnsafeQuery $
716676 "SELECT * FROM " <> fun <> "(" <> renderExpression expr <> ")"
717677
718678-- | Expands the outermost JSON object into a set of key/value pairs.
719679jsonEach
720− :: Expression schema '[] 'Ungrouped params (nullity 'PGjson) -- ^ json object
721− -> Query schema params
680+ :: Expression db '[] 'Ungrouped params (nullity 'PGjson) -- ^ json object
681+ -> Query db params
722682 '["key" ::: 'NotNull 'PGtext, "value" ::: 'NotNull 'PGjson]
723683jsonEach = unsafeSetOfFunction "json_each"
724684
725685-- | Expands the outermost binary JSON object into a set of key/value pairs.
726686jsonbEach
727− :: Expression schema '[] 'Ungrouped params (nullity 'PGjsonb) -- ^ jsonb object
728− -> Query schema params
687+ :: Expression db '[] 'Ungrouped params (nullity 'PGjsonb) -- ^ jsonb object
688+ -> Query db params
729689 '["key" ::: 'NotNull 'PGtext, "value" ::: 'NotNull 'PGjsonb]
730690jsonbEach = unsafeSetOfFunction "jsonb_each"
731691
732692-- | Expands the outermost JSON object into a set of key/value pairs.
733693jsonEachAsText
734− :: Expression schema '[] 'Ungrouped params (nullity 'PGjson) -- ^ json object
735− -> Query schema params
694+ :: Expression db '[] 'Ungrouped params (nullity 'PGjson) -- ^ json object
695+ -> Query db params
736696 '["key" ::: 'NotNull 'PGtext, "value" ::: 'NotNull 'PGtext]
737697jsonEachAsText = unsafeSetOfFunction "json_each_text"
738698
739699-- | Expands the outermost binary JSON object into a set of key/value pairs.
740700jsonbEachAsText
741− :: Expression schema '[] 'Ungrouped params (nullity 'PGjsonb) -- ^ jsonb object
742− -> Query schema params
701+ :: Expression db '[] 'Ungrouped params (nullity 'PGjsonb) -- ^ jsonb object
702+ -> Query db params
743703 '["key" ::: 'NotNull 'PGtext, "value" ::: 'NotNull 'PGtext]
744704jsonbEachAsText = unsafeSetOfFunction "jsonb_each_text"
745705
746706-- | Returns set of keys in the outermost JSON object.
747707jsonObjectKeys
748− :: Expression schema '[] 'Ungrouped params (nullity 'PGjson) -- ^ json object
749− -> Query schema params '["json_object_keys" ::: 'NotNull 'PGtext]
708+ :: Expression db '[] 'Ungrouped params (nullity 'PGjson) -- ^ json object
709+ -> Query db params '["json_object_keys" ::: 'NotNull 'PGtext]
750710jsonObjectKeys = unsafeSetOfFunction "json_object_keys"
751711
752712-- | Returns set of keys in the outermost JSON object.
753713jsonbObjectKeys
754− :: Expression schema '[] 'Ungrouped params (nullity 'PGjsonb) -- ^ jsonb object
755− -> Query schema params '["jsonb_object_keys" ::: 'NotNull 'PGtext]
714+ :: Expression db '[] 'Ungrouped params (nullity 'PGjsonb) -- ^ jsonb object
715+ -> Query db params '["jsonb_object_keys" ::: 'NotNull 'PGtext]
756716jsonbObjectKeys = unsafeSetOfFunction "jsonb_object_keys"
757717
758718unsafePopulateFunction
759719 :: ByteString
760− -> TypeExpression schema (nullity ('PGcomposite row))
761− -> Expression schema '[] 'Ungrouped params ty
762− -> Query schema params row
720+ -> TypeExpression schemas (nullity ('PGcomposite row))
721+ -> Expression (commons :=> schemas) '[] 'Ungrouped params ty
722+ -> Query (commons :=> schemas) params row
763723unsafePopulateFunction fun ty expr = UnsafeQuery $
764724 "SELECT * FROM " <> fun <> "("
765725 <> "null::" <> renderTypeExpression ty <> ", "
@@ -768,81 +728,81 @@ unsafePopulateFunction fun ty expr = UnsafeQuery $
768728-- | Expands the JSON expression to a row whose columns match the record
769729-- type defined by the given table.
770730jsonPopulateRecord
771− :: TypeExpression schema (nullity ('PGcomposite row)) -- ^ row type
772− -> Expression schema '[] 'Ungrouped params (nullity 'PGjson) -- ^ json object
773− -> Query schema params row
731+ :: TypeExpression schemas (nullity ('PGcomposite row)) -- ^ row type
732+ -> Expression (commons :=> schemas) '[] 'Ungrouped params (nullity 'PGjson) -- ^ json object
733+ -> Query (commons :=> schemas) params row
774734jsonPopulateRecord = unsafePopulateFunction "json_populate_record"
775735
776736-- | Expands the binary JSON expression to a row whose columns match the record
777737-- type defined by the given table.
778738jsonbPopulateRecord
779− :: TypeExpression schema (nullity ('PGcomposite row)) -- ^ row type
780− -> Expression schema '[] 'Ungrouped params (nullity 'PGjsonb) -- ^ jsonb object
781− -> Query schema params row
739+ :: TypeExpression schemas (nullity ('PGcomposite row)) -- ^ row type
740+ -> Expression (commons :=> schemas) '[] 'Ungrouped params (nullity 'PGjsonb) -- ^ jsonb object
741+ -> Query (commons :=> schemas) params row
782742jsonbPopulateRecord = unsafePopulateFunction "jsonb_populate_record"
783743
784744-- | Expands the outermost array of objects in the given JSON expression to a
785745-- set of rows whose columns match the record type defined by the given table.
786746jsonPopulateRecordSet
787− :: TypeExpression schema (nullity ('PGcomposite row)) -- ^ row type
788− -> Expression schema '[] 'Ungrouped params (nullity 'PGjson) -- ^ json array
789− -> Query schema params row
747+ :: TypeExpression schemas (nullity ('PGcomposite row)) -- ^ row type
748+ -> Expression (commons :=> schemas) '[] 'Ungrouped params (nullity 'PGjson) -- ^ json array
749+ -> Query (commons :=> schemas) params row
790750jsonPopulateRecordSet = unsafePopulateFunction "json_populate_record_set"
791751
792752-- | Expands the outermost array of objects in the given binary JSON expression
793753-- to a set of rows whose columns match the record type defined by the given
794754-- table.
795755jsonbPopulateRecordSet
796− :: TypeExpression schema (nullity ('PGcomposite row)) -- ^ row type
797− -> Expression schema '[] 'Ungrouped params (nullity 'PGjsonb) -- ^ jsonb array
798− -> Query schema params row
756+ :: TypeExpression schemas (nullity ('PGcomposite row)) -- ^ row type
757+ -> Expression (commons :=> schemas) '[] 'Ungrouped params (nullity 'PGjsonb) -- ^ jsonb array
758+ -> Query (commons :=> schemas) params row
799759jsonbPopulateRecordSet = unsafePopulateFunction "jsonb_populate_record_set"
800760
801761unsafeRecordFunction
802762 :: (SListI record, json `In` PGJsonType)
803763 => ByteString
804− -> Expression schema '[] 'Ungrouped params (nullity json)
805− -> NP (Aliased (TypeExpression schema)) record
806− -> Query schema params record
764+ -> Expression (commons :=> schemas) '[] 'Ungrouped params (nullity json)
765+ -> NP (Aliased (TypeExpression schemas)) record
766+ -> Query (commons :=> schemas) params record
807767unsafeRecordFunction fun expr types = UnsafeQuery $
808768 "SELECT * FROM " <> fun <> "("
809769 <> renderExpression expr <> ")"
810770 <+> "AS" <+> "x" <> parenthesized (renderCommaSeparated renderTy types)
811771 where
812− renderTy :: Aliased (TypeExpression schema) ty -> ByteString
772+ renderTy :: Aliased (TypeExpression db) ty -> ByteString
813773 renderTy (ty `As` alias) =
814774 renderAlias alias <+> renderTypeExpression ty
815775
816776-- | Builds an arbitrary record from a JSON object.
817777jsonToRecord
818778 :: SListI record
819− => Expression schema '[] 'Ungrouped params (nullity 'PGjson) -- ^ json object
820− -> NP (Aliased (TypeExpression schema)) record -- ^ record types
821− -> Query schema params record
779+ => Expression (commons :=> schemas) '[] 'Ungrouped params (nullity 'PGjson) -- ^ json object
780+ -> NP (Aliased (TypeExpression schemas)) record -- ^ record types
781+ -> Query (commons :=> schemas) params record
822782jsonToRecord = unsafeRecordFunction "json_to_record"
823783
824784-- | Builds an arbitrary record from a binary JSON object.
825785jsonbToRecord
826786 :: SListI record
827− => Expression schema '[] 'Ungrouped params (nullity 'PGjsonb) -- ^ jsonb object
828− -> NP (Aliased (TypeExpression schema)) record -- ^ record types
829− -> Query schema params record
787+ => Expression (commons :=> schemas) '[] 'Ungrouped params (nullity 'PGjsonb) -- ^ jsonb object
788+ -> NP (Aliased (TypeExpression schemas)) record -- ^ record types
789+ -> Query (commons :=> schemas) params record
830790jsonbToRecord = unsafeRecordFunction "jsonb_to_record"
831791
832792-- | Builds an arbitrary set of records from a JSON array of objects.
833793jsonToRecordSet
834794 :: SListI record
835− => Expression schema '[] 'Ungrouped params (nullity 'PGjson) -- ^ json array
836− -> NP (Aliased (TypeExpression schema)) record -- ^ record types
837− -> Query schema params record
795+ => Expression (commons :=> schemas) '[] 'Ungrouped params (nullity 'PGjson) -- ^ json array
796+ -> NP (Aliased (TypeExpression schemas)) record -- ^ record types
797+ -> Query (commons :=> schemas) params record
838798jsonToRecordSet = unsafeRecordFunction "json_to_record_set"
839799
840800-- | Builds an arbitrary set of records from a binary JSON array of objects.
841801jsonbToRecordSet
842802 :: SListI record
843− => Expression schema '[] 'Ungrouped params (nullity 'PGjsonb) -- ^ jsonb array
844− -> NP (Aliased (TypeExpression schema)) record -- ^ record types
845− -> Query schema params record
803+ => Expression (commons :=> schemas) '[] 'Ungrouped params (nullity 'PGjsonb) -- ^ jsonb array
804+ -> NP (Aliased (TypeExpression schemas)) record -- ^ record types
805+ -> Query (commons :=> schemas) params record
846806jsonbToRecordSet = unsafeRecordFunction "jsonb_to_record_set"
847807
848808{-----------------------------------------
@@ -853,31 +813,38 @@ FROM clauses
853813A `FromClause` can be a table name, or a derived table such
854814as a subquery, a @JOIN@ construct, or complex combinations of these.
855815-}
856−newtype FromClause schema params from
816+newtype FromClause db params from
857817 = UnsafeFromClause { renderFromClause :: ByteString }
858818 deriving (GHC.Generic,Show,Eq,Ord,NFData)
859819
860−-- | A real `table` is a table from the schema.
820+-- | A real `table` is a table from the database.
861821table
862− :: Has tab schema ('Table table)
863− => Aliased Alias (alias ::: tab)
864− -> FromClause schema params '[alias ::: TableToRow table]
822+ :: (Has sch schemas schema, Has tab schema ('Table table))
823+ => Aliased (QualifiedAlias sch) (alias ::: tab)
824+ -> FromClause (commons :=> schemas) params '[alias ::: TableToRow table]
865825table (tab `As` alias) = UnsafeFromClause $
866− renderAlias tab <+> "AS" <+> renderAlias alias
826+ renderQualifiedAlias tab <+> "AS" <+> renderAlias alias
867827
868828-- | `subquery` derives a table from a `Query`.
869829subquery
870− :: Aliased (Query schema params) rel
871− -> FromClause schema params '[rel]
830+ :: Aliased (Query db params) query
831+ -> FromClause db params '[query]
872832subquery = UnsafeFromClause . renderAliasedAs (parenthesized . renderQuery)
873833
874834-- | `view` derives a table from a `View`.
875835view
876− :: Has view schema ('View row)
877− => Aliased Alias (alias ::: view)
878− -> FromClause schema params '[alias ::: row]
836+ :: (Has sch schemas schema, Has vw schema ('View view))
837+ => Aliased (QualifiedAlias sch) (alias ::: vw)
838+ -> FromClause (commons :=> schemas) params '[alias ::: view]
879839view (vw `As` alias) = UnsafeFromClause $
880− renderAlias vw <+> "AS" <+> renderAlias alias
840+ renderQualifiedAlias vw <+> "AS" <+> renderAlias alias
841+
842+common
843+ :: Has cte commons common
844+ => Aliased Alias (alias ::: cte)
845+ -> FromClause (commons :=> schemas) params '[alias ::: common]
846+common (cte `As` alias) = UnsafeFromClause $
847+ renderAlias cte <+> "AS" <+> renderAlias alias
881848
882849{- | @left & crossJoin right@. For every possible combination of rows from
883850 @left@ and @right@ (i.e., a Cartesian product), the joined table will contain
@@ -886,11 +853,11 @@ view (vw `As` alias) = UnsafeFromClause $
886853 have @n * m@ rows.
887854-}
888855crossJoin
889− :: FromClause schema params right
856+ :: FromClause db params right
890857 -- ^ right
891− -> FromClause schema params left
858+ -> FromClause db params left
892859 -- ^ left
893− -> FromClause schema params (Join left right)
860+ -> FromClause db params (Join left right)
894861crossJoin right left = UnsafeFromClause $
895862 renderFromClause left <+> "CROSS JOIN" <+> renderFromClause right
896863
@@ -898,13 +865,13 @@ crossJoin right left = UnsafeFromClause $
898865the @on@ condition.
899866-}
900867innerJoin
901− :: FromClause schema params right
868+ :: FromClause db params right
902869 -- ^ right
903− -> Condition schema (Join left right) 'Ungrouped params
870+ -> Condition db (Join left right) 'Ungrouped params
904871 -- ^ @on@ condition
905− -> FromClause schema params left
872+ -> FromClause db params left
906873 -- ^ left
907− -> FromClause schema params (Join left right)
874+ -> FromClause db params (Join left right)
908875innerJoin right on left = UnsafeFromClause $
909876 renderFromClause left <+> "INNER JOIN" <+> renderFromClause right
910877 <+> "ON" <+> renderExpression on
@@ -915,13 +882,13 @@ innerJoin right on left = UnsafeFromClause $
915882 Thus, the joined table always has at least one row for each row in @left@.
916883-}
917884leftOuterJoin
918− :: FromClause schema params right
885+ :: FromClause db params right
919886 -- ^ right
920− -> Condition schema (Join left right) 'Ungrouped params
887+ -> Condition db (Join left right) 'Ungrouped params
921888 -- ^ @on@ condition
922− -> FromClause schema params left
889+ -> FromClause db params left
923890 -- ^ left
924− -> FromClause schema params (Join left (NullifyFrom right))
891+ -> FromClause db params (Join left (NullifyFrom right))
925892leftOuterJoin right on left = UnsafeFromClause $
926893 renderFromClause left <+> "LEFT OUTER JOIN" <+> renderFromClause right
927894 <+> "ON" <+> renderExpression on
@@ -933,13 +900,13 @@ leftOuterJoin right on left = UnsafeFromClause $
933900 have a row for each row in @right@.
934901-}
935902rightOuterJoin
936− :: FromClause schema params right
903+ :: FromClause db params right
937904 -- ^ right
938− -> Condition schema (Join left right) 'Ungrouped params
905+ -> Condition db (Join left right) 'Ungrouped params
939906 -- ^ @on@ condition
940− -> FromClause schema params left
907+ -> FromClause db params left
941908 -- ^ left
942− -> FromClause schema params (Join (NullifyFrom left) right)
909+ -> FromClause db params (Join (NullifyFrom left) right)
943910rightOuterJoin right on left = UnsafeFromClause $
944911 renderFromClause left <+> "RIGHT OUTER JOIN" <+> renderFromClause right
945912 <+> "ON" <+> renderExpression on
@@ -952,13 +919,13 @@ rightOuterJoin right on left = UnsafeFromClause $
952919 is added.
953920-}
954921fullOuterJoin
955− :: FromClause schema params right
922+ :: FromClause db params right
956923 -- ^ right
957− -> Condition schema (Join left right) 'Ungrouped params
924+ -> Condition db (Join left right) 'Ungrouped params
958925 -- ^ @on@ condition
959− -> FromClause schema params left
926+ -> FromClause db params left
960927 -- ^ left
961− -> FromClause schema params
928+ -> FromClause db params
962929 (Join (NullifyFrom left) (NullifyFrom right))
963930fullOuterJoin right on left = UnsafeFromClause $
964931 renderFromClause left <+> "FULL OUTER JOIN" <+> renderFromClause right
@@ -1029,17 +996,17 @@ renderGroupByClause = \case
1029996-- An `Ungrouped` `TableExpression` may only use `NoHaving` while a `Grouped`
1030997-- `TableExpression` must use `Having` whose conditions are combined with
1031998-- `.&&`.
1032−data HavingClause schema from grouping params where
1033− NoHaving :: HavingClause schema from 'Ungrouped params
999+data HavingClause db from grouping params where
1000+ NoHaving :: HavingClause db from 'Ungrouped params
10341001 Having
1035− :: [Condition schema from ('Grouped bys) params]
1036− -> HavingClause schema from ('Grouped bys) params
1037−deriving instance Show (HavingClause schema from grouping params)
1038−deriving instance Eq (HavingClause schema from grouping params)
1039−deriving instance Ord (HavingClause schema from grouping params)
1002+ :: [Condition db from ('Grouped bys) params]
1003+ -> HavingClause db from ('Grouped bys) params
1004+deriving instance Show (HavingClause db from grouping params)
1005+deriving instance Eq (HavingClause db from grouping params)
1006+deriving instance Ord (HavingClause db from grouping params)
10401007
10411008-- | Render a `HavingClause`.
1042−renderHavingClause :: HavingClause schema from grouping params -> ByteString
1009+renderHavingClause :: HavingClause db from grouping params -> ByteString
10431010renderHavingClause = \case
10441011 NoHaving -> ""
10451012 Having [] -> ""
@@ -1058,29 +1025,29 @@ Sorting
10581025-- `AscNullsLast`, `DescNullsFirst` and `DescNullsLast` options are used to
10591026-- determine whether nulls appear before or after non-null values in the sort
10601027-- ordering of a `Null` result column.
1061−data SortExpression schema from grouping params where
1028+data SortExpression db from grouping params where
10621029 Asc
1063− :: Expression schema from grouping params ('NotNull ty)
1064− -> SortExpression schema from grouping params
1030+ :: Expression db from grouping params ('NotNull ty)
1031+ -> SortExpression db from grouping params
10651032 Desc
1066− :: Expression schema from grouping params ('NotNull ty)
1067− -> SortExpression schema from grouping params
1033+ :: Expression db from grouping params ('NotNull ty)
1034+ -> SortExpression db from grouping params
10681035 AscNullsFirst
1069− :: Expression schema from grouping params ('Null ty)
1070− -> SortExpression schema from grouping params
1036+ :: Expression db from grouping params ('Null ty)
1037+ -> SortExpression db from grouping params
10711038 AscNullsLast
1072− :: Expression schema from grouping params ('Null ty)
1073− -> SortExpression schema from grouping params
1039+ :: Expression db from grouping params ('Null ty)
1040+ -> SortExpression db from grouping params
10741041 DescNullsFirst
1075− :: Expression schema from grouping params ('Null ty)
1076− -> SortExpression schema from grouping params
1042+ :: Expression db from grouping params ('Null ty)
1043+ -> SortExpression db from grouping params
10771044 DescNullsLast
1078− :: Expression schema from grouping params ('Null ty)
1079− -> SortExpression schema from grouping params
1080−deriving instance Show (SortExpression schema from grouping params)
1045+ :: Expression db from grouping params ('Null ty)
1046+ -> SortExpression db from grouping params
1047+deriving instance Show (SortExpression db from grouping params)
10811048
10821049-- | Render a `SortExpression`.
1083−renderSortExpression :: SortExpression schema from grouping params -> ByteString
1050+renderSortExpression :: SortExpression db from grouping params -> ByteString
10841051renderSortExpression = \case
10851052 Asc expression -> renderExpression expression <+> "ASC"
10861053 Desc expression -> renderExpression expression <+> "DESC"
@@ -1093,18 +1060,18 @@ renderSortExpression = \case
10931060
10941061unsafeSubqueryExpression
10951062 :: ByteString
1096− -> Expression schema from grp params ty
1097− -> Query schema params '[alias ::: ty]
1098− -> Expression schema from grp params (nullity 'PGbool)
1063+ -> Expression db from grp params ty
1064+ -> Query db params '[alias ::: ty]
1065+ -> Expression db from grp params (nullity 'PGbool)
10991066unsafeSubqueryExpression op x q = UnsafeExpression $
11001067 renderExpression x <+> op <+> parenthesized (renderQuery q)
11011068
11021069unsafeRowSubqueryExpression
11031070 :: SListI row
11041071 => ByteString
1105− -> NP (Aliased (Expression schema from grp params)) row
1106− -> Query schema params row
1107− -> Expression schema from grp params (nullity 'PGbool)
1072+ -> NP (Aliased (Expression db from grp params)) row
1073+ -> Query db params row
1074+ -> Expression db from grp params (nullity 'PGbool)
11081075unsafeRowSubqueryExpression op xs q = UnsafeExpression $
11091076 renderExpression (row xs) <+> op <+> parenthesized (renderQuery q)
11101077
@@ -1117,9 +1084,9 @@ unsafeRowSubqueryExpression op xs q = UnsafeExpression $
11171084-- >>> printSQL $ true `in_` values_ (true `as` #foo)
11181085-- TRUE IN (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
11191086in_
1120− :: Expression schema from grp params ty -- ^ expression
1121− -> Query schema params '[alias ::: ty] -- ^ subquery
1122− -> Expression schema from grp params (nullity 'PGbool)
1087+ :: Expression db from grp params ty -- ^ expression
1088+ -> Query db params '[alias ::: ty] -- ^ subquery
1089+ -> Expression db from grp params (nullity 'PGbool)
11231090in_ = unsafeSubqueryExpression "IN"
11241091
11251092{- | The left-hand side of this form of `rowIn` is a row constructor.
@@ -1132,265 +1099,272 @@ is `true` if any equal subquery row is found.
11321099The result is `false` if no equal row is found
11331100(including the case where the subquery returns no rows).
11341101
1135−>>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression '[] '[] 'Ungrouped '[])) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1102+>>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db from grp params)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
11361103>>> printSQL $ myRow `rowIn` values_ myRow
11371104ROW(1, FALSE) IN (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
11381105-}
11391106rowIn
11401107 :: SListI row
1141− => NP (Aliased (Expression schema from grp params)) row -- ^ row constructor
1142− -> Query schema params row -- ^ subquery
1143− -> Expression schema from grp params (nullity 'PGbool)
1108+ => NP (Aliased (Expression db from grp params)) row -- ^ row constructor
1109+ -> Query db params row -- ^ subquery
1110+ -> Expression db from grp params (nullity 'PGbool)
11441111rowIn = unsafeRowSubqueryExpression "IN"
11451112
11461113-- | >>> printSQL $ true `eqAll` values_ (true `as` #foo)
11471114-- TRUE = ALL (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
11481115eqAll
1149− :: Expression schema from grp params ty -- ^ expression
1150− -> Query schema params '[alias ::: ty] -- ^ subquery
1151− -> Expression schema from grp params (nullity 'PGbool)
1116+ :: Expression db from grp params ty -- ^ expression
1117+ -> Query db params '[alias ::: ty] -- ^ subquery
1118+ -> Expression db from grp params (nullity 'PGbool)
11521119eqAll = unsafeSubqueryExpression "= ALL"
11531120
1154−-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression '[] '[] 'Ungrouped '[])) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1121+-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db from grp params)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
11551122-- >>> printSQL $ myRow `rowEqAll` values_ myRow
11561123-- ROW(1, FALSE) = ALL (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
11571124rowEqAll
11581125 :: SListI row
1159− => NP (Aliased (Expression schema from grp params)) row -- ^ row constructor
1160− -> Query schema params row -- ^ subquery
1161− -> Expression schema from grp params (nullity 'PGbool)
1126+ => NP (Aliased (Expression db from grp params)) row -- ^ row constructor
1127+ -> Query db params row -- ^ subquery
1128+ -> Expression db from grp params (nullity 'PGbool)
11621129rowEqAll = unsafeRowSubqueryExpression "= ALL"
11631130
11641131-- | >>> printSQL $ true `eqAny` values_ (true `as` #foo)
11651132-- TRUE = ANY (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
11661133eqAny
1167− :: Expression schema from grp params ty -- ^ expression
1168− -> Query schema params '[alias ::: ty] -- ^ subquery
1169− -> Expression schema from grp params (nullity 'PGbool)
1134+ :: Expression db from grp params ty -- ^ expression
1135+ -> Query db params '[alias ::: ty] -- ^ subquery
1136+ -> Expression db from grp params (nullity 'PGbool)
11701137eqAny = unsafeSubqueryExpression "= ANY"
11711138
1172−-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression '[] '[] 'Ungrouped '[])) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1139+-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db from grp params)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
11731140-- >>> printSQL $ myRow `rowEqAny` values_ myRow
11741141-- ROW(1, FALSE) = ANY (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
11751142rowEqAny
11761143 :: SListI row
1177− => NP (Aliased (Expression schema from grp params)) row -- ^ row constructor
1178− -> Query schema params row -- ^ subquery
1179− -> Expression schema from grp params (nullity 'PGbool)
1144+ => NP (Aliased (Expression db from grp params)) row -- ^ row constructor
1145+ -> Query db params row -- ^ subquery
1146+ -> Expression db from grp params (nullity 'PGbool)
11801147rowEqAny = unsafeRowSubqueryExpression "= ANY"
11811148
11821149-- | >>> printSQL $ true `neqAll` values_ (true `as` #foo)
11831150-- TRUE <> ALL (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
11841151neqAll
1185− :: Expression schema from grp params ty -- ^ expression
1186− -> Query schema params '[alias ::: ty] -- ^ subquery
1187− -> Expression schema from grp params (nullity 'PGbool)
1152+ :: Expression db from grp params ty -- ^ expression
1153+ -> Query db params '[alias ::: ty] -- ^ subquery
1154+ -> Expression db from grp params (nullity 'PGbool)
11881155neqAll = unsafeSubqueryExpression "<> ALL"
11891156
1190−-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression '[] '[] 'Ungrouped '[])) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1157+-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db from grp params)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
11911158-- >>> printSQL $ myRow `rowNeqAll` values_ myRow
11921159-- ROW(1, FALSE) <> ALL (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
11931160rowNeqAll
11941161 :: SListI row
1195− => NP (Aliased (Expression schema from grp params)) row -- ^ row constructor
1196− -> Query schema params row -- ^ subquery
1197− -> Expression schema from grp params (nullity 'PGbool)
1162+ => NP (Aliased (Expression db from grp params)) row -- ^ row constructor
1163+ -> Query db params row -- ^ subquery
1164+ -> Expression db from grp params (nullity 'PGbool)
11981165rowNeqAll = unsafeRowSubqueryExpression "<> ALL"
11991166
12001167-- | >>> printSQL $ true `neqAny` values_ (true `as` #foo)
12011168-- TRUE <> ANY (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
12021169neqAny
1203− :: Expression schema from grp params ty -- ^ expression
1204− -> Query schema params '[alias ::: ty] -- ^ subquery
1205− -> Expression schema from grp params (nullity 'PGbool)
1170+ :: Expression db from grp params ty -- ^ expression
1171+ -> Query db params '[alias ::: ty] -- ^ subquery
1172+ -> Expression db from grp params (nullity 'PGbool)
12061173neqAny = unsafeSubqueryExpression "<> ANY"
12071174
1208−-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression '[] '[] 'Ungrouped '[])) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1175+-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db from grp params)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
12091176-- >>> printSQL $ myRow `rowNeqAny` values_ myRow
12101177-- ROW(1, FALSE) <> ANY (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
12111178rowNeqAny
12121179 :: SListI row
1213− => NP (Aliased (Expression schema from grp params)) row -- ^ row constructor
1214− -> Query schema params row -- ^ subquery
1215− -> Expression schema from grp params (nullity 'PGbool)
1180+ => NP (Aliased (Expression db from grp params)) row -- ^ row constructor
1181+ -> Query db params row -- ^ subquery
1182+ -> Expression db from grp params (nullity 'PGbool)
12161183rowNeqAny = unsafeRowSubqueryExpression "<> ANY"
12171184
12181185-- | >>> printSQL $ true `allLt` values_ (true `as` #foo)
12191186-- TRUE ALL < (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
12201187allLt
1221− :: Expression schema from grp params ty -- ^ expression
1222− -> Query schema params '[alias ::: ty] -- ^ subquery
1223− -> Expression schema from grp params (nullity 'PGbool)
1188+ :: Expression db from grp params ty -- ^ expression
1189+ -> Query db params '[alias ::: ty] -- ^ subquery
1190+ -> Expression db from grp params (nullity 'PGbool)
12241191allLt = unsafeSubqueryExpression "ALL <"
12251192
1226−-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression '[] '[] 'Ungrouped '[])) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1193+-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db from grp params)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
12271194-- >>> printSQL $ myRow `rowLtAll` values_ myRow
12281195-- ROW(1, FALSE) ALL < (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
12291196rowLtAll
12301197 :: SListI row
1231− => NP (Aliased (Expression schema from grp params)) row -- ^ row constructor
1232− -> Query schema params row -- ^ subquery
1233− -> Expression schema from grp params (nullity 'PGbool)
1198+ => NP (Aliased (Expression db from grp params)) row -- ^ row constructor
1199+ -> Query db params row -- ^ subquery
1200+ -> Expression db from grp params (nullity 'PGbool)
12341201rowLtAll = unsafeRowSubqueryExpression "ALL <"
12351202
12361203-- | >>> printSQL $ true `ltAny` values_ (true `as` #foo)
12371204-- TRUE ANY < (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
12381205ltAny
1239− :: Expression schema from grp params ty -- ^ expression
1240− -> Query schema params '[alias ::: ty] -- ^ subquery
1241− -> Expression schema from grp params (nullity 'PGbool)
1206+ :: Expression db from grp params ty -- ^ expression
1207+ -> Query db params '[alias ::: ty] -- ^ subquery
1208+ -> Expression db from grp params (nullity 'PGbool)
12421209ltAny = unsafeSubqueryExpression "ANY <"
12431210
1244−-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression '[] '[] 'Ungrouped '[])) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1211+-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db from grp params)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
12451212-- >>> printSQL $ myRow `rowLtAll` values_ myRow
12461213-- ROW(1, FALSE) ALL < (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
12471214rowLtAny
12481215 :: SListI row
1249− => NP (Aliased (Expression schema from grp params)) row -- ^ row constructor
1250− -> Query schema params row -- ^ subquery
1251− -> Expression schema from grp params (nullity 'PGbool)
1216+ => NP (Aliased (Expression db from grp params)) row -- ^ row constructor
1217+ -> Query db params row -- ^ subquery
1218+ -> Expression db from grp params (nullity 'PGbool)
12521219rowLtAny = unsafeRowSubqueryExpression "ANY <"
12531220
12541221-- | >>> printSQL $ true `lteAll` values_ (true `as` #foo)
12551222-- TRUE <= ALL (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
12561223lteAll
1257− :: Expression schema from grp params ty -- ^ expression
1258− -> Query schema params '[alias ::: ty] -- ^ subquery
1259− -> Expression schema from grp params (nullity 'PGbool)
1224+ :: Expression db from grp params ty -- ^ expression
1225+ -> Query db params '[alias ::: ty] -- ^ subquery
1226+ -> Expression db from grp params (nullity 'PGbool)
12601227lteAll = unsafeSubqueryExpression "<= ALL"
12611228
1262−-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression '[] '[] 'Ungrouped '[])) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1229+-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db from grp params)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
12631230-- >>> printSQL $ myRow `rowLteAll` values_ myRow
12641231-- ROW(1, FALSE) <= ALL (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
12651232rowLteAll
12661233 :: SListI row
1267− => NP (Aliased (Expression schema from grp params)) row -- ^ row constructor
1268− -> Query schema params row -- ^ subquery
1269− -> Expression schema from grp params (nullity 'PGbool)
1234+ => NP (Aliased (Expression db from grp params)) row -- ^ row constructor
1235+ -> Query db params row -- ^ subquery
1236+ -> Expression db from grp params (nullity 'PGbool)
12701237rowLteAll = unsafeRowSubqueryExpression "<= ALL"
12711238
12721239-- | >>> printSQL $ true `lteAny` values_ (true `as` #foo)
12731240-- TRUE <= ANY (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
12741241lteAny
1275− :: Expression schema from grp params ty -- ^ expression
1276− -> Query schema params '[alias ::: ty] -- ^ subquery
1277− -> Expression schema from grp params (nullity 'PGbool)
1242+ :: Expression db from grp params ty -- ^ expression
1243+ -> Query db params '[alias ::: ty] -- ^ subquery
1244+ -> Expression db from grp params (nullity 'PGbool)
12781245lteAny = unsafeSubqueryExpression "<= ANY"
12791246
1280−-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression '[] '[] 'Ungrouped '[])) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1247+-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db from grp params)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
12811248-- >>> printSQL $ myRow `rowLteAny` values_ myRow
12821249-- ROW(1, FALSE) <= ANY (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
12831250rowLteAny
12841251 :: SListI row
1285− => NP (Aliased (Expression schema from grp params)) row -- ^ row constructor
1286− -> Query schema params row -- ^ subquery
1287− -> Expression schema from grp params (nullity 'PGbool)
1252+ => NP (Aliased (Expression db from grp params)) row -- ^ row constructor
1253+ -> Query db params row -- ^ subquery
1254+ -> Expression db from grp params (nullity 'PGbool)
12881255rowLteAny = unsafeRowSubqueryExpression "<= ANY"
12891256
12901257-- | >>> printSQL $ true `gtAll` values_ (true `as` #foo)
12911258-- TRUE > ALL (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
12921259gtAll
1293− :: Expression schema from grp params ty -- ^ expression
1294− -> Query schema params '[alias ::: ty] -- ^ subquery
1295− -> Expression schema from grp params (nullity 'PGbool)
1260+ :: Expression db from grp params ty -- ^ expression
1261+ -> Query db params '[alias ::: ty] -- ^ subquery
1262+ -> Expression db from grp params (nullity 'PGbool)
12961263gtAll = unsafeSubqueryExpression "> ALL"
12971264
1298−-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression '[] '[] 'Ungrouped '[])) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1265+-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db from grp params)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
12991266-- >>> printSQL $ myRow `rowGtAll` values_ myRow
13001267-- ROW(1, FALSE) > ALL (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
13011268rowGtAll
13021269 :: SListI row
1303− => NP (Aliased (Expression schema from grp params)) row -- ^ row constructor
1304− -> Query schema params row -- ^ subquery
1305− -> Expression schema from grp params (nullity 'PGbool)
1270+ => NP (Aliased (Expression db from grp params)) row -- ^ row constructor
1271+ -> Query db params row -- ^ subquery
1272+ -> Expression db from grp params (nullity 'PGbool)
13061273rowGtAll = unsafeRowSubqueryExpression "> ALL"
13071274
13081275-- | >>> printSQL $ true `gtAny` values_ (true `as` #foo)
13091276-- TRUE > ANY (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
13101277gtAny
1311− :: Expression schema from grp params ty -- ^ expression
1312− -> Query schema params '[alias ::: ty] -- ^ subquery
1313− -> Expression schema from grp params (nullity 'PGbool)
1278+ :: Expression db from grp params ty -- ^ expression
1279+ -> Query db params '[alias ::: ty] -- ^ subquery
1280+ -> Expression db from grp params (nullity 'PGbool)
13141281gtAny = unsafeSubqueryExpression "> ANY"
13151282
1316−-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression '[] '[] 'Ungrouped '[])) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1283+-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db from grp params)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
13171284-- >>> printSQL $ myRow `rowGtAny` values_ myRow
13181285-- ROW(1, FALSE) > ANY (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
13191286rowGtAny
13201287 :: SListI row
1321− => NP (Aliased (Expression schema from grp params)) row -- ^ row constructor
1322− -> Query schema params row -- ^ subquery
1323− -> Expression schema from grp params (nullity 'PGbool)
1288+ => NP (Aliased (Expression db from grp params)) row -- ^ row constructor
1289+ -> Query db params row -- ^ subquery
1290+ -> Expression db from grp params (nullity 'PGbool)
13241291rowGtAny = unsafeRowSubqueryExpression "> ANY"
13251292
13261293-- | >>> printSQL $ true `gteAll` values_ (true `as` #foo)
13271294-- TRUE >= ALL (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
13281295gteAll
1329− :: Expression schema from grp params ty -- ^ expression
1330− -> Query schema params '[alias ::: ty] -- ^ subquery
1331− -> Expression schema from grp params (nullity 'PGbool)
1296+ :: Expression db from grp params ty -- ^ expression
1297+ -> Query db params '[alias ::: ty] -- ^ subquery
1298+ -> Expression db from grp params (nullity 'PGbool)
13321299gteAll = unsafeSubqueryExpression ">= ALL"
13331300
1334−-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression '[] '[] 'Ungrouped '[])) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1301+-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db from grp params)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
13351302-- >>> printSQL $ myRow `rowGteAll` values_ myRow
13361303-- ROW(1, FALSE) >= ALL (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
13371304rowGteAll
13381305 :: SListI row
1339− => NP (Aliased (Expression schema from grp params)) row -- ^ row constructor
1340− -> Query schema params row -- ^ subquery
1341− -> Expression schema from grp params (nullity 'PGbool)
1306+ => NP (Aliased (Expression db from grp params)) row -- ^ row constructor
1307+ -> Query db params row -- ^ subquery
1308+ -> Expression db from grp params (nullity 'PGbool)
13421309rowGteAll = unsafeRowSubqueryExpression ">= ALL"
13431310
13441311-- | >>> printSQL $ true `gteAny` values_ (true `as` #foo)
13451312-- TRUE >= ANY (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
13461313gteAny
1347− :: Expression schema from grp params ty -- ^ expression
1348− -> Query schema params '[alias ::: ty] -- ^ subquery
1349− -> Expression schema from grp params (nullity 'PGbool)
1314+ :: Expression db from grp params ty -- ^ expression
1315+ -> Query db params '[alias ::: ty] -- ^ subquery
1316+ -> Expression db from grp params (nullity 'PGbool)
13501317gteAny = unsafeSubqueryExpression ">= ANY"
13511318
1352−-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression '[] '[] 'Ungrouped '[])) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1319+-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db from grp params)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
13531320-- >>> printSQL $ myRow `rowGteAny` values_ myRow
13541321-- ROW(1, FALSE) >= ANY (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
13551322rowGteAny
13561323 :: SListI row
1357− => NP (Aliased (Expression schema from grp params)) row -- ^ row constructor
1358− -> Query schema params row -- ^ subquery
1359− -> Expression schema from grp params (nullity 'PGbool)
1324+ => NP (Aliased (Expression db from grp params)) row -- ^ row constructor
1325+ -> Query db params row -- ^ subquery
1326+ -> Expression db from grp params (nullity 'PGbool)
13601327rowGteAny = unsafeRowSubqueryExpression ">= ANY"
13611328
13621329-- | A `CommonTableExpression` is an auxiliary statement in a `with` clause.
13631330data CommonTableExpression statement
13641331 (params :: [NullityType])
1365− (schema0 :: SchemaType)
1366− (schema1 :: SchemaType) where
1332+ (db0 :: DBType)
1333+ (db1 :: DBType) where
13671334 CommonTableExpression
1368− :: Aliased (statement schema params) (alias ::: cte)
1369− -> CommonTableExpression
1370− statement params schema (alias ::: 'View cte ': schema)
1371−instance (KnownSymbol alias, schema1 ~ (alias ::: 'View cte ': schema))
1372− => Aliasable alias
1373− (statement schema params cte)
1374− (CommonTableExpression statement params schema schema1) where
1375− statement `as` alias = CommonTableExpression (statement `as` alias)
1376−instance (KnownSymbol alias, schema1 ~ (alias ::: 'View cte ': schema))
1377− => Aliasable alias (statement schema params cte)
1378− (AlignedList (CommonTableExpression statement params) schema schema1) where
1379− statement `as` alias = single (statement `as` alias)
1335+ :: Aliased (statement (commons :=> schemas) params) (cte ::: common)
1336+ -> CommonTableExpression statement params
1337+ (commons :=> schemas) ((cte ::: common ': commons) :=> schemas)
1338+instance
1339+ ( KnownSymbol cte
1340+ , db0 ~ (commons :=> schemas)
1341+ , db1 ~ ((cte ::: common ': commons) :=> schemas)
1342+ ) => Aliasable cte
1343+ (statement db0 params common)
1344+ (CommonTableExpression statement params db0 db1) where
1345+ statement `as` cte = CommonTableExpression (statement `as` cte)
1346+instance
1347+ ( KnownSymbol cte
1348+ , db0 ~ (commons :=> schemas)
1349+ , db1 ~ ((cte ::: common ': commons) :=> schemas)
1350+ ) => Aliasable cte
1351+ (statement db0 params common)
1352+ (AlignedList (CommonTableExpression statement params) db0 db1) where
1353+ statement `as` cte = single (statement `as` cte)
13801354
13811355-- | render a `CommonTableExpression`.
13821356renderCommonTableExpression
1383− :: (forall sch ps row. statement ps sch row -> ByteString) -- ^ render statement
1384− -> CommonTableExpression statement params schema0 schema1 -> ByteString
1357+ :: (forall db ps row. statement db ps row -> ByteString) -- ^ render statement
1358+ -> CommonTableExpression statement params db0 db1 -> ByteString
13851359renderCommonTableExpression renderStatement
13861360 (CommonTableExpression (statement `As` alias)) =
13871361 renderAlias alias <+> "AS" <+> parenthesized (renderStatement statement)
13881362
13891363-- | render a non-empty `AlignedList` of `CommonTableExpression`s.
13901364renderCommonTableExpressions
1391− :: (forall sch ps row. statement ps sch row -> ByteString) -- ^ render statement
1392− -> CommonTableExpression statement params schema0 schema1
1393− -> AlignedList (CommonTableExpression statement params) schema1 schema2
1365+ :: (forall db ps row. statement db ps row -> ByteString) -- ^ render statement
1366+ -> CommonTableExpression statement params db0 db1
1367+ -> AlignedList (CommonTableExpression statement params) db1 db2
13941368 -> ByteString
13951369renderCommonTableExpressions renderStatement cte ctes =
13961370 renderCommonTableExpression renderStatement cte <> case ctes of
@@ -1403,11 +1377,11 @@ renderCommonTableExpressions renderStatement cte ctes =
14031377-- defining temporary tables that exist just for one query.
14041378class With statement where
14051379 with
1406− :: AlignedList (CommonTableExpression statement params) schema0 schema1
1380+ :: AlignedList (CommonTableExpression statement params) db0 db1
14071381 -- ^ common table expressions
1408− -> statement schema1 params row
1382+ -> statement db1 params row
14091383 -- ^ larger query
1410− -> statement schema0 params row
1384+ -> statement db0 params row
14111385instance With Query where
14121386 with Done query = query
14131387 with (cte :>> ctes) query = UnsafeQuery $
squeal-postgresql/src/Squeal/PostgreSQL/Schema.hs+41−3
@@ -54,6 +54,10 @@ module Squeal.PostgreSQL.Schema
5454 , TableType
5555 , SchemumType (..)
5656 , SchemaType
57+ , SchemasType
58+ , Public
59+ , DBType
60+ , DBof
5761 -- * Constraints
5862 , (:=>)
5963 , ColumnConstraint (..)
@@ -62,8 +66,10 @@ module Squeal.PostgreSQL.Schema
6266 , Uniquely
6367 -- * Aliases
6468 , (:::)
65− , Alias (Alias)
69+ , Alias (..)
70+ , IsLabel (..)
6671 , renderAlias
72+ , renderAliasString
6773 , renderAliases
6874 , Aliased (As)
6975 , Aliasable (as)
@@ -71,9 +77,9 @@ module Squeal.PostgreSQL.Schema
7177 , Has
7278 , HasUnique
7379 , HasAll
74− , IsLabel (..)
80+ , QualifiedAlias (..)
7581 , IsQualified (..)
76− , renderAliasString
82+ , renderQualifiedAlias
7783 -- * Enumerated Labels
7884 , IsPGlabel (..)
7985 , PGlabel (..)
@@ -471,6 +477,29 @@ class IsQualified table column expression where
471477 infixl 9 !
472478instance IsQualified table column (Alias table, Alias column) where (!) = (,)
473479
480+data QualifiedAlias (qualifier :: Symbol) (alias :: Symbol) = QualifiedAlias
481+ deriving (Eq,GHC.Generic,Ord,Show,NFData)
482+instance (q ~ q', a ~ a') => IsQualified q a (QualifiedAlias q' a') where
483+ _!_ = QualifiedAlias
484+instance (q' ~ "public", a ~ a') => IsLabel a (QualifiedAlias q' a') where
485+ fromLabel = QualifiedAlias
486+instance (q0 ~ q1, a0 ~ a1, a1 ~ a2, KnownSymbol a2) =>
487+ IsQualified q0 a0 (Aliased (QualifiedAlias q1) (a1 ::: a2)) where
488+ _!_ = QualifiedAlias `As` Alias
489+instance (q ~ "public", a0 ~ a1, a1 ~ a2, KnownSymbol a2) =>
490+ IsLabel a0 (Aliased (QualifiedAlias q) (a1 ::: a2)) where
491+ fromLabel = QualifiedAlias `As` Alias
492+
493+renderQualifiedAlias
494+ :: forall q a. (KnownSymbol q, KnownSymbol a)
495+ => QualifiedAlias q a -> ByteString
496+renderQualifiedAlias _ =
497+ let
498+ qualifier = renderAlias (Alias @q)
499+ alias = renderAlias (Alias @a)
500+ in
501+ if qualifier == "\"public\"" then alias else qualifier <> "." <> alias
502+
474503-- | @Elem@ is a promoted `Data.List.elem`.
475504type family Elem x xs where
476505 Elem x '[] = 'False
@@ -657,6 +686,15 @@ type family Schema :: SchemaType where
657686-}
658687type SchemaType = [(Symbol,SchemumType)]
659688
689+type SchemasType = [(Symbol,SchemaType)]
690+
691+type family Public (schema :: SchemaType) :: SchemasType
692+ where Public schema = '["public" ::: schema]
693+
694+type DBType = (FromType,SchemasType)
695+
696+type family DBof :: SchemasType -> DBType where DBof = '(,) '[]
697+
660698-- | `IsPGlabel` looks very much like the `IsLabel` class. Whereas
661699-- the overloaded label, `fromLabel` is used for column references,
662700-- `label`s are used for enum terms. A `label` is called with
squeal-postgresql/src/Squeal/PostgreSQL/Transaction.hs+9−9
@@ -52,7 +52,7 @@ import Squeal.PostgreSQL.Schema
5252
5353-- | Run a schema invariant computation `transactionally`.
5454transactionally
55− :: (MonadBaseControl IO tx, MonadPQ schema tx)
55+ :: (MonadBaseControl IO tx, MonadPQ schemas tx)
5656 => TransactionMode
5757 -> tx x -- ^ run inside a transaction
5858 -> tx x
@@ -64,30 +64,30 @@ transactionally mode tx = mask $ \restore -> do
6464
6565-- | Run a schema invariant computation `transactionally_` in `defaultMode`.
6666transactionally_
67− :: (MonadBaseControl IO tx, MonadPQ schema tx)
67+ :: (MonadBaseControl IO tx, MonadPQ schemas tx)
6868 => tx x -- ^ run inside a transaction
6969 -> tx x
7070transactionally_ = transactionally defaultMode
7171
7272-- | @BEGIN@ a transaction.
73−begin :: MonadPQ schema tx => TransactionMode -> tx (K Result ('[] :: RowType))
73+begin :: MonadPQ schemas tx => TransactionMode -> tx (K Result ('[] :: RowType))
7474begin mode = manipulate . UnsafeManipulation $
7575 "BEGIN" <+> renderTransactionMode mode <> ";"
7676
7777-- | @COMMIT@ a schema invariant transaction.
78−commit :: MonadPQ schema tx => tx (K Result ('[] :: RowType))
78+commit :: MonadPQ schemas tx => tx (K Result ('[] :: RowType))
7979commit = manipulate $ UnsafeManipulation "COMMIT;"
8080
8181-- | @ROLLBACK@ a schema invariant transaction.
82−rollback :: MonadPQ schema tx => tx (K Result ('[] :: RowType))
82+rollback :: MonadPQ schemas tx => tx (K Result ('[] :: RowType))
8383rollback = manipulate $ UnsafeManipulation "ROLLBACK;"
8484
8585-- | Run a schema changing computation `transactionallySchema`.
8686transactionallySchema
8787 :: MonadBaseControl IO io
8888 => TransactionMode
89− -> PQ schema0 schema1 io x
90− -> PQ schema0 schema1 io x
89+ -> PQ schemas0 schemas1 io x
90+ -> PQ schemas0 schemas1 io x
9191transactionallySchema mode u = PQ $ \ conn -> mask $ \ restore -> do
9292 _ <- liftBase . LibPQ.exec (unK conn) $
9393 "BEGIN" <+> renderTransactionMode mode <> ";"
@@ -99,8 +99,8 @@ transactionallySchema mode u = PQ $ \ conn -> mask $ \ restore -> do
9999-- | Run a schema changing computation `transactionallySchema_` in `DefaultMode`.
100100transactionallySchema_
101101 :: MonadBaseControl IO io
102− => PQ schema0 schema1 io x
103− -> PQ schema0 schema1 io x
102+ => PQ schemas0 schemas1 io x
103+ -> PQ schemas0 schemas1 io x
104104transactionallySchema_ = transactionallySchema defaultMode
105105
106106-- | The available transaction characteristics are the transaction `IsolationLevel`,
squeal-postgresql/test/Specs/ExceptionHandling.hs+11−6
@@ -7,6 +7,7 @@
77{-# LANGUAGE OverloadedStrings #-}
88{-# LANGUAGE TypeApplications #-}
99{-# LANGUAGE TypeFamilies #-}
10+{-# LANGUAGE TypeInType #-}
1011{-# LANGUAGE TypeOperators #-}
1112module ExceptionHandling
1213 ( specs
@@ -45,6 +46,10 @@ type Schema =
4546 ])
4647 ]
4748
49+type Schemas = Public Schema
50+
51+type DB = DBof Schemas
52+
4853data User =
4954 User { userName :: Text
5055 , userEmail :: Maybe Text
@@ -53,13 +58,13 @@ data User =
5358instance SOP.Generic User
5459instance SOP.HasDatatypeInfo User
5560
56−insertUser :: Manipulation Schema '[ 'NotNull 'PGtext, 'NotNull ('PGvararray ('Null 'PGint2))]
61+insertUser :: Manipulation DB '[ 'NotNull 'PGtext, 'NotNull ('PGvararray ('Null 'PGint2))]
5762 '[ "fromOnly" ::: 'NotNull 'PGint4 ]
5863insertUser = insertRows #users
5964 (Default `as` #id :* Set (param @1) `as` #name :* Set (param @2) `as` #vec) []
6065 OnConflictDoRaise (Returning (#id `as` #fromOnly))
6166
62−setup :: Definition '[] Schema
67+setup :: Definition (Public '[]) Schemas
6368setup =
6469 createTable #users
6570 ( serial `as` #id :*
@@ -76,10 +81,10 @@ setup =
7681 foreignKey #user_id #users #id
7782 OnDeleteCascade OnUpdateCascade `as` #fk_user_id )
7883
79−teardown :: Definition Schema '[]
84+teardown :: Definition Schemas (Public '[])
8085teardown = dropTable #emails >>> dropTable #users
8186
82−migration :: Migration IO '[] Schema
87+migration :: Migration IO (Public '[]) Schemas
8388migration = Migration { name = "test"
8489 , up = void $ define setup
8590 , down = void $ define teardown }
@@ -98,10 +103,10 @@ connectionString = "host=localhost port=5432 dbname=exampledb"
98103testUser :: User
99104testUser = User "TestUser" Nothing []
100105
101−newUser :: (MonadBase IO m, MonadPQ Schema m) => User -> m ()
106+newUser :: (MonadBase IO m, MonadPQ Schemas m) => User -> m ()
102107newUser u = void $ manipulateParams insertUser (userName u, userVec u)
103108
104−insertUserTwice :: (MonadBase IO m, MonadPQ Schema m) => m ()
109+insertUserTwice :: (MonadBase IO m, MonadPQ Schemas m) => m ()
105110insertUserTwice = newUser testUser >> newUser testUser
106111
107112specs :: SpecWith ()