@@ -11,13 +11,15 @@ Squeal data definition language.
11{-# LANGUAGE
11{-# LANGUAGE
12 AllowAmbiguousTypes
12 AllowAmbiguousTypes
13 , ConstraintKinds
13 , ConstraintKinds
14 , DeriveGeneric
15 , DeriveGeneric
15 , FlexibleContexts
17 , FlexibleContexts
16 , FlexibleInstances
18 , FlexibleInstances
18− , GeneralizedNewtypeDeriving
19 , LambdaCase
20 , LambdaCase
20 , MultiParamTypeClasses
21 , MultiParamTypeClasses
21 , OverloadedStrings
23 , OverloadedStrings
22 , RankNTypes
24 , RankNTypes
23 , ScopedTypeVariables
25 , ScopedTypeVariables
@@ -25,83 +27,25 @@ Squeal data definition language.
25 , TypeInType
27 , TypeInType
26 , TypeOperators
28 , TypeOperators
27 , UndecidableSuperClasses
29 , UndecidableSuperClasses
30+ , UndecidableInstances
30module Squeal.PostgreSQL.Definition
33module Squeal.PostgreSQL.Definition
31 ( -- * Definition
34 ( -- * Definition
32 Definition (..)
35 Definition (..)
34− -- * Tables
37+ , manipDefinition
37− , createSchemaIfNotExists
39− , createTableIfNotExists
43− , createTypeComposite
44− , createTypeCompositeFrom
46− , TableConstraintExpression (..)
52− , OnDeleteClause (..)
53− , OnUpdateClause (..)
76− , ColumnTypeExpression (..)
88import Control.Category
40import Control.Category
89import Control.DeepSeq
41import Control.DeepSeq
90import Data.ByteString
42import Data.ByteString
91import Data.Monoid
43import Data.Monoid
93import Prelude hiding ((.), id)
44import Prelude hiding ((.), id)
95−import qualified Generics.SOP as SOP
96import qualified GHC.Generics as GHC
46import qualified GHC.Generics as GHC
98−import Squeal.PostgreSQL.Alias
48+import Squeal.PostgreSQL.Manipulation
99−import Squeal.PostgreSQL.Expression
100−import Squeal.PostgreSQL.Expression.Logic
101−import Squeal.PostgreSQL.Expression.Type
102−import Squeal.PostgreSQL.List
103−import Squeal.PostgreSQL.PG
104−import Squeal.PostgreSQL.Query
105import Squeal.PostgreSQL.Render
49import Squeal.PostgreSQL.Render
106import Squeal.PostgreSQL.Schema
50import Squeal.PostgreSQL.Schema
@@ -129,958 +73,10 @@ instance Category Definition where
129 ddl1 . ddl0 = UnsafeDefinition $
73 ddl1 . ddl0 = UnsafeDefinition $
130 renderSQL ddl0 <> "\n" <> renderSQL ddl1
74 renderSQL ddl0 <> "\n" <> renderSQL ddl1
132−{-----------------------------------------
76+-- | A `Manipulation` without input or output can be run as a statement
133−CREATE statements
77+-- along with other `Definition`s, by embedding it using `manipDefinition`.
134−-----------------------------------------}
78+manipDefinition
135−
79+ :: Manipulation '[] schemas '[] '[]
136−createSchema
80+ -- ^ no input or output
139− -> Definition schemas (Create sch '[] schemas)
140−createSchema sch = UnsafeDefinition $
141− "CREATE" <+> "SCHEMA" <+> renderSQL sch <> ";"
143−createSchemaIfNotExists
144− :: (KnownSymbol sch, Has sch schemas schema)
146 -> Definition schemas schemas
81 -> Definition schemas schemas
147−createSchemaIfNotExists sch = UnsafeDefinition $
82+manipDefinition = UnsafeDefinition . (<> ";") . renderSQL
148− "CREATE" <+> "SCHEMA" <+> "IF" <+> "NOT" <+> "EXISTS"
149− <+> renderSQL sch <> ";"
151−{- | `createTable` adds a table to the schema.
153−>>> :set -XOverloadedLabels
156− '[ "a" ::: 'NoDef :=> 'Null 'PGint4
157− , "b" ::: 'NoDef :=> 'Null 'PGfloat4 ]
162− setup :: Definition (Public '[]) (Public '["tab" ::: 'Table Table])
163− setup = createTable #tab
164− (nullable int `as` #a :* nullable real `as` #b) Nil
167−CREATE TABLE "tab" ("a" int NULL, "b" real NULL);
170− :: ( KnownSymbol sch
172− , columns ~ (col ': cols)
173− , SOP.SListI columns
174− , SOP.SListI constraints
175− , Has sch schemas0 schema0
176− , schemas1 ~ Alter sch (Create tab ('Table (constraints :=> columns)) schema0) schemas0 )
177− => QualifiedAlias sch tab -- ^ the name of the table to add
178− -> NP (Aliased (ColumnTypeExpression schemas0)) columns
179− -- ^ the names and datatype of each column
180− -> NP (Aliased (TableConstraintExpression sch tab schemas1)) constraints
181− -- ^ constraints that must hold for the table
182− -> Definition schemas0 schemas1
183−createTable tab columns constraints = UnsafeDefinition $
184− "CREATE TABLE" <+> renderCreation tab columns constraints
186−{-| `createTableIfNotExists` creates a table if it doesn't exist, but does not add it to the schema.
187−Instead, the schema already has the table so if the table did not yet exist, the schema was wrong.
188−`createTableIfNotExists` fixes this. Interestingly, this property makes it an idempotent in
189−the `Category` of `Definition`s.
191−>>> :set -XOverloadedLabels -XTypeApplications
194− '[ "a" ::: 'NoDef :=> 'Null 'PGint4
195− , "b" ::: 'NoDef :=> 'Null 'PGfloat4 ]
198−>>> type Schemas = Public '["tab" ::: 'Table Table]
202− setup :: Definition Schemas Schemas
203− setup = createTableIfNotExists #tab
204− (nullable int `as` #a :* nullable real `as` #b) Nil
207−CREATE TABLE IF NOT EXISTS "tab" ("a" int NULL, "b" real NULL);
209−createTableIfNotExists
210− :: ( Has sch schemas schema
211− , Has tab schema ('Table (constraints :=> columns))
212− , SOP.SListI columns
213− , SOP.SListI constraints )
214− => QualifiedAlias sch tab -- ^ the name of the table to add
215− -> NP (Aliased (ColumnTypeExpression schemas)) columns
216− -- ^ the names and datatype of each column
217− -> NP (Aliased (TableConstraintExpression sch tab schemas)) constraints
218− -- ^ constraints that must hold for the table
219− -> Definition schemas schemas
220−createTableIfNotExists tab columns constraints = UnsafeDefinition $
221− "CREATE TABLE IF NOT EXISTS"
222− <+> renderCreation tab columns constraints
224−-- helper function for `createTable` and `createTableIfNotExists`
226− :: ( KnownSymbol sch
228− , SOP.SListI columns
229− , SOP.SListI constraints )
230− => QualifiedAlias sch tab -- ^ the name of the table to add
231− -> NP (Aliased (ColumnTypeExpression schemas0)) columns
232− -- ^ the names and datatype of each column
233− -> NP (Aliased (TableConstraintExpression sch tab schemas1)) constraints
234− -- ^ constraints that must hold for the table
236−renderCreation tab columns constraints = renderSQL tab
238− ( renderCommaSeparated renderColumnDef columns
239− <> ( case constraints of
242− renderCommaSeparated renderConstraint constraints ) )
245− renderColumnDef :: Aliased (ColumnTypeExpression schemas) x -> ByteString
246− renderColumnDef (ty `As` column) =
247− renderSQL column <+> renderColumnTypeExpression ty
249− :: Aliased (TableConstraintExpression sch tab schemas) constraint
251− renderConstraint (constraint `As` alias) =
252− "CONSTRAINT" <+> renderSQL alias <+> renderSQL constraint
254−-- | Data types are a way to limit the kind of data that can be stored in a
255−-- table. For many applications, however, the constraint they provide is
256−-- too coarse. For example, a column containing a product price should
257−-- probably only accept positive values. But there is no standard data type
258−-- that accepts only positive numbers. Another issue is that you might want
259−-- to constrain column data with respect to other columns or rows.
260−-- For example, in a table containing product information,
261−-- there should be only one row for each product number.
262−-- `TableConstraint`s give you as much control over the data in your tables
263−-- as you wish. If a user attempts to store data in a column that would
264−-- violate a constraint, an error is raised. This applies
265−-- even if the value came from the default value definition.
266−newtype TableConstraintExpression
269− (schemas :: SchemasType)
270− (constraint :: TableConstraint)
271− = UnsafeTableConstraintExpression
272− { renderTableConstraintExpression :: ByteString }
273− deriving (GHC.Generic,Show,Eq,Ord,NFData)
275− (TableConstraintExpression sch tab schemas constraint) where
276− renderSQL = renderTableConstraintExpression
278−{-| A `check` constraint is the most generic `TableConstraint` type.
279−It allows you to specify that the value in a certain column must satisfy
280−a Boolean (truth-value) expression.
284− "tab" ::: 'Table ('[ "inequality" ::: 'Check '["a","b"]] :=> '[
285− "a" ::: 'NoDef :=> 'NotNull 'PGint4,
286− "b" ::: 'NoDef :=> 'NotNull 'PGint4
292− definition :: Definition (Public '[]) (Public Schema)
293− definition = createTable #tab
294− ( (int & notNullable) `as` #a :*
295− (int & notNullable) `as` #b )
296− ( check (#a :* #b) (#a .> #b) `as` #inequality )
299−>>> printSQL definition
300−CREATE TABLE "tab" ("a" int NOT NULL, "b" int NOT NULL, CONSTRAINT "inequality" CHECK (("a" > "b")));
303− :: ( Has sch schemas schema
304− , Has tab schema ('Table table)
305− , HasAll aliases (TableToRow table) subcolumns )
307− -- ^ specify the subcolumns which are getting checked
308− -> (forall t. Condition '[] '[] 'Ungrouped schemas '[] '[t ::: subcolumns])
309− -- ^ a closed `Condition` on those subcolumns
310− -> TableConstraintExpression sch tab schemas ('Check aliases)
311−check _cols condition = UnsafeTableConstraintExpression $
312− "CHECK" <+> parenthesized (renderSQL condition)
314−{-| A `unique` constraint ensure that the data contained in a column,
315−or a group of columns, is unique among all the rows in the table.
319− "tab" ::: 'Table( '[ "uq_a_b" ::: 'Unique '["a","b"]] :=> '[
320− "a" ::: 'NoDef :=> 'Null 'PGint4,
321− "b" ::: 'NoDef :=> 'Null 'PGint4
327− definition :: Definition (Public '[]) (Public Schema)
328− definition = createTable #tab
329− ( (int & nullable) `as` #a :*
330− (int & nullable) `as` #b )
331− ( unique (#a :* #b) `as` #uq_a_b )
334−>>> printSQL definition
335−CREATE TABLE "tab" ("a" int NULL, "b" int NULL, CONSTRAINT "uq_a_b" UNIQUE ("a", "b"));
338− :: ( Has sch schemas schema
339− , Has tab schema('Table table)
340− , HasAll aliases (TableToRow table) subcolumns )
342− -- ^ specify subcolumns which together are unique for each row
343− -> TableConstraintExpression sch tab schemas ('Unique aliases)
344−unique columns = UnsafeTableConstraintExpression $
345− "UNIQUE" <+> parenthesized (renderSQL columns)
347−{-| A `primaryKey` constraint indicates that a column, or group of columns,
348−can be used as a unique identifier for rows in the table.
349−This requires that the values be both unique and not null.
353− "tab" ::: 'Table ('[ "pk_id" ::: 'PrimaryKey '["id"]] :=> '[
354− "id" ::: 'Def :=> 'NotNull 'PGint4,
355− "name" ::: 'NoDef :=> 'NotNull 'PGtext
361− definition :: Definition (Public '[]) (Public Schema)
362− definition = createTable #tab
363− ( serial `as` #id :*
364− (text & notNullable) `as` #name )
365− ( primaryKey #id `as` #pk_id )
368−>>> printSQL definition
369−CREATE TABLE "tab" ("id" serial, "name" text NOT NULL, CONSTRAINT "pk_id" PRIMARY KEY ("id"));
372− :: ( Has sch schemas schema
373− , Has tab schema ('Table table)
374− , HasAll aliases (TableToColumns table) subcolumns
375− , AllNotNull subcolumns )
377− -- ^ specify the subcolumns which together form a primary key.
378− -> TableConstraintExpression sch tab schemas ('PrimaryKey aliases)
379−primaryKey columns = UnsafeTableConstraintExpression $
380− "PRIMARY KEY" <+> parenthesized (renderSQL columns)
382−{-| A `foreignKey` specifies that the values in a column
383−(or a group of columns) must match the values appearing in some row of
384−another table. We say this maintains the referential integrity
385−between two related tables.
389− '[ "users" ::: 'Table (
390− '[ "pk_users" ::: 'PrimaryKey '["id"] ] :=>
391− '[ "id" ::: 'Def :=> 'NotNull 'PGint4
392− , "name" ::: 'NoDef :=> 'NotNull 'PGtext
394− , "emails" ::: 'Table (
395− '[ "pk_emails" ::: 'PrimaryKey '["id"]
396− , "fk_user_id" ::: 'ForeignKey '["user_id"] "users" '["id"]
398− '[ "id" ::: 'Def :=> 'NotNull 'PGint4
399− , "user_id" ::: 'NoDef :=> 'NotNull 'PGint4
400− , "email" ::: 'NoDef :=> 'Null 'PGtext
407− setup :: Definition (Public '[]) (Public Schema)
410− ( serial `as` #id :*
411− (text & notNullable) `as` #name )
412− ( primaryKey #id `as` #pk_users ) >>>
414− ( serial `as` #id :*
415− (int & notNullable) `as` #user_id :*
416− (text & nullable) `as` #email )
417− ( primaryKey #id `as` #pk_emails :*
418− foreignKey #user_id #users #id
419− OnDeleteCascade OnUpdateCascade `as` #fk_user_id )
422−CREATE TABLE "users" ("id" serial, "name" text NOT NULL, CONSTRAINT "pk_users" PRIMARY KEY ("id"));
423−CREATE 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);
425−A `foreignKey` can even be a table self-reference.
429− '[ "employees" ::: 'Table (
430− '[ "employees_pk" ::: 'PrimaryKey '["id"]
431− , "employees_employer_fk" ::: 'ForeignKey '["employer_id"] "employees" '["id"]
433− '[ "id" ::: 'Def :=> 'NotNull 'PGint4
434− , "name" ::: 'NoDef :=> 'NotNull 'PGtext
435− , "employer_id" ::: 'NoDef :=> 'Null 'PGint4
442− setup :: Definition (Public '[]) (Public Schema)
444− createTable #employees
445− ( serial `as` #id :*
446− (text & notNullable) `as` #name :*
447− (integer & nullable) `as` #employer_id )
448− ( primaryKey #id `as` #employees_pk :*
449− foreignKey #employer_id #employees #id
450− OnDeleteCascade OnUpdateCascade `as` #employees_employer_fk )
453−CREATE 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);
456− :: (ForeignKeyed schemas sch schema child parent
462− -- ^ column or columns in the table
464− -- ^ reference table
465− -> NP Alias refcolumns
466− -- ^ reference column or columns in the reference table
468− -- ^ what to do when reference is deleted
470− -- ^ what to do when reference is updated
471− -> TableConstraintExpression sch child schemas
472− ('ForeignKey columns parent refcolumns)
473−foreignKey keys parent refs ondel onupd = UnsafeTableConstraintExpression $
474− "FOREIGN KEY" <+> parenthesized (renderSQL keys)
475− <+> "REFERENCES" <+> renderSQL parent
476− <+> parenthesized (renderSQL refs)
480−-- | A constraint synonym between types involved in a foreign key constraint.
481−type ForeignKeyed schemas
489− ( Has sch schemas schema
490− , Has child schema ('Table table)
491− , Has parent schema ('Table reftable)
492− , HasAll columns (TableToColumns table) tys
493− , reftable ~ (constraints :=> cols)
494− , HasAll refcolumns cols reftys
495− , SOP.AllZip SamePGType tys reftys
496− , Uniquely refcolumns constraints )
498−-- | `OnDeleteClause` indicates what to do with rows that reference a deleted row.
501− -- ^ if any referencing rows still exist when the constraint is checked,
502− -- an error is raised
503− | OnDeleteRestrict -- ^ prevents deletion of a referenced row
505− -- ^ specifies that when a referenced row is deleted,
506− -- row(s) referencing it should be automatically deleted as well
507− deriving (GHC.Generic,Show,Eq,Ord)
508−instance NFData OnDeleteClause
509−-- | Render `OnDeleteClause`.
510−instance RenderSQL OnDeleteClause where
512− OnDeleteNoAction -> "ON DELETE NO ACTION"
513− OnDeleteRestrict -> "ON DELETE RESTRICT"
514− OnDeleteCascade -> "ON DELETE CASCADE"
516−-- | Analagous to `OnDeleteClause` there is also `OnUpdateClause` which is invoked
517−-- when a referenced column is changed (updated).
520− -- ^ if any referencing rows has not changed when the constraint is checked,
521− -- an error is raised
522− | OnUpdateRestrict -- ^ prevents update of a referenced row
524− -- ^ the updated values of the referenced column(s) should be copied
525− -- into the referencing row(s)
526− deriving (GHC.Generic,Show,Eq,Ord)
527−instance NFData OnUpdateClause
529−-- | Render `OnUpdateClause`.
530−instance RenderSQL OnUpdateClause where
532− OnUpdateNoAction -> "ON UPDATE NO ACTION"
533− OnUpdateRestrict -> "ON UPDATE RESTRICT"
534− OnUpdateCascade -> "ON UPDATE CASCADE"
536−{-----------------------------------------
538−-----------------------------------------}
542−-- definition :: Definition '["muh_schema" ::: schema, "public" ::: public] '["public" ::: public]
543−-- definition = dropSchema #muh_schema
546−-- >>> printSQL definition
547−-- DROP SCHEMA "muh_schema";
549− :: Has sch schemas schema
551− -> Definition schemas (Drop sch schemas)
552−dropSchema sch = UnsafeDefinition $ "DROP SCHEMA" <+> renderSQL sch <> ";"
554−-- | `dropTable` removes a table from the schema.
558−-- definition :: Definition '["public" ::: '["muh_table" ::: 'Table t]] (Public '[])
559−-- definition = dropTable #muh_table
562−-- >>> printSQL definition
563−-- DROP TABLE "muh_table";
565− :: ( Has sch schemas schema
566− , Has tab schema ('Table table))
567− => QualifiedAlias sch tab -- ^ table to remove
568− -> Definition schemas (Alter sch (Drop tab schema) schemas)
569−dropTable tab = UnsafeDefinition $ "DROP TABLE" <+> renderSQL tab <> ";"
571−{-----------------------------------------
573−-----------------------------------------}
575−-- | `alterTable` changes the definition of a table from the schema.
577− :: (Has sch schemas schema, Has tab schema ('Table table0))
578− => QualifiedAlias sch tab -- ^ table to alter
579− -> AlterTable sch tab schemas table1 -- ^ alteration to perform
580− -> Definition schemas (Alter sch (Alter tab ('Table table1) schema) schemas)
581−alterTable tab alteration = UnsafeDefinition $
584− <+> renderAlterTable alteration
587−-- | `alterTableRename` changes the name of a table from the schema.
589−-- >>> printSQL $ alterTableRename #foo #bar
590−-- ALTER TABLE "foo" RENAME TO "bar";
592− :: (KnownSymbol table0, KnownSymbol table1)
593− => Alias table0 -- ^ table to rename
594− -> Alias table1 -- ^ what to rename it
595− -> Definition schema (Rename table0 table1 schema)
596−alterTableRename table0 table1 = UnsafeDefinition $
597− "ALTER TABLE" <+> renderSQL table0
598− <+> "RENAME TO" <+> renderSQL table1 <> ";"
600−-- | An `AlterTable` describes the alteration to perform on the columns
605− (schemas :: SchemasType)
606− (table :: TableType) =
607− UnsafeAlterTable {renderAlterTable :: ByteString}
608− deriving (GHC.Generic,Show,Eq,Ord,NFData)
610−-- | An `addConstraint` adds a table constraint.
614−-- definition :: Definition
615−-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'NotNull 'PGint4])]]
616−-- '["public" ::: '["tab" ::: 'Table ('["positive" ::: 'Check '["col"]] :=> '["col" ::: 'NoDef :=> 'NotNull 'PGint4])]]
617−-- definition = alterTable #tab (addConstraint #positive (check #col (#col .> 0)))
618−-- in printSQL definition
620−-- ALTER TABLE "tab" ADD CONSTRAINT "positive" CHECK (("col" > 0));
622− :: ( KnownSymbol alias
623− , Has sch schemas schema
624− , Has tab schema ('Table table0)
625− , table0 ~ (constraints :=> columns)
626− , table1 ~ (Create alias constraint constraints :=> columns) )
628− -> TableConstraintExpression sch tab schemas constraint
629− -- ^ constraint to add
630− -> AlterTable sch tab schemas table1
631−addConstraint alias constraint = UnsafeAlterTable $
632− "ADD" <+> "CONSTRAINT" <+> renderSQL alias
633− <+> renderSQL constraint
635−-- | A `dropConstraint` drops a table constraint.
639−-- definition :: Definition
640−-- '["public" ::: '["tab" ::: 'Table ('["positive" ::: Check '["col"]] :=> '["col" ::: 'NoDef :=> 'NotNull 'PGint4])]]
641−-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'NotNull 'PGint4])]]
642−-- definition = alterTable #tab (dropConstraint #positive)
643−-- in printSQL definition
645−-- ALTER TABLE "tab" DROP CONSTRAINT "positive";
647− :: ( KnownSymbol constraint
648− , Has sch schemas schema
649− , Has tab schema ('Table table0)
650− , table0 ~ (constraints :=> columns)
651− , table1 ~ (Drop constraint constraints :=> columns) )
653− -- ^ constraint to drop
654− -> AlterTable sch tab schemas table1
655−dropConstraint constraint = UnsafeAlterTable $
656− "DROP" <+> "CONSTRAINT" <+> renderSQL constraint
658−-- | An `AddColumn` is either @NULL@ or has @DEFAULT@.
659−class AddColumn ty where
660− -- | `addColumn` adds a new column, initially filled with whatever
661− -- default value is given or with @NULL@.
665− -- definition :: Definition
666− -- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col1" ::: 'NoDef :=> 'Null 'PGint4])]]
667− -- '["public" ::: '["tab" ::: 'Table ('[] :=>
668− -- '[ "col1" ::: 'NoDef :=> 'Null 'PGint4
669− -- , "col2" ::: 'Def :=> 'Null 'PGtext ])]]
670− -- definition = alterTable #tab (addColumn #col2 (text & nullable & default_ "foo"))
671− -- in printSQL definition
673− -- ALTER TABLE "tab" ADD COLUMN "col2" text NULL DEFAULT E'foo';
677− -- definition :: Definition
678− -- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col1" ::: 'NoDef :=> 'Null 'PGint4])]]
679− -- '["public" ::: '["tab" ::: 'Table ('[] :=>
680− -- '[ "col1" ::: 'NoDef :=> 'Null 'PGint4
681− -- , "col2" ::: 'NoDef :=> 'Null 'PGtext ])]]
682− -- definition = alterTable #tab (addColumn #col2 (text & nullable))
683− -- in printSQL definition
685− -- ALTER TABLE "tab" ADD COLUMN "col2" text NULL;
687− :: ( KnownSymbol column
688− , Has sch schemas schema
689− , Has tab schema ('Table table0)
690− , table0 ~ (constraints :=> columns) )
691− => Alias column -- ^ column to add
692− -> ColumnTypeExpression schemas ty -- ^ type of the new column
693− -> AlterTable sch tab schemas (constraints :=> Create column ty columns)
694− addColumn column ty = UnsafeAlterTable $
695− "ADD COLUMN" <+> renderSQL column <+> renderColumnTypeExpression ty
696−instance {-# OVERLAPPING #-} AddColumn ('Def :=> ty)
697−instance {-# OVERLAPPABLE #-} AddColumn ('NoDef :=> 'Null ty)
699−-- | A `dropColumn` removes a column. Whatever data was in the column
700−-- disappears. Table constraints involving the column are dropped, too.
701−-- However, if the column is referenced by a foreign key constraint of
702−-- another table, PostgreSQL will not silently drop that constraint.
706−-- definition :: Definition
707−-- '["public" ::: '["tab" ::: 'Table ('[] :=>
708−-- '[ "col1" ::: 'NoDef :=> 'Null 'PGint4
709−-- , "col2" ::: 'NoDef :=> 'Null 'PGtext ])]]
710−-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col1" ::: 'NoDef :=> 'Null 'PGint4])]]
711−-- definition = alterTable #tab (dropColumn #col2)
712−-- in printSQL definition
714−-- ALTER TABLE "tab" DROP COLUMN "col2";
716− :: ( KnownSymbol column
717− , Has sch schemas schema
718− , Has tab schema ('Table table0)
719− , table0 ~ (constraints :=> columns)
720− , table1 ~ (constraints :=> Drop column columns) )
721− => Alias column -- ^ column to remove
722− -> AlterTable sch tab schemas table1
723−dropColumn column = UnsafeAlterTable $
724− "DROP COLUMN" <+> renderSQL column
726−-- | A `renameColumn` renames a column.
730−-- definition :: Definition
731−-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["foo" ::: 'NoDef :=> 'Null 'PGint4])]]
732−-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["bar" ::: 'NoDef :=> 'Null 'PGint4])]]
733−-- definition = alterTable #tab (renameColumn #foo #bar)
734−-- in printSQL definition
736−-- ALTER TABLE "tab" RENAME COLUMN "foo" TO "bar";
738− :: ( KnownSymbol column0
739− , KnownSymbol column1
740− , Has sch schemas schema
741− , Has tab schema ('Table table0)
742− , table0 ~ (constraints :=> columns)
743− , table1 ~ (constraints :=> Rename column0 column1 columns) )
744− => Alias column0 -- ^ column to rename
745− -> Alias column1 -- ^ what to rename the column
746− -> AlterTable sch tab schemas table1
747−renameColumn column0 column1 = UnsafeAlterTable $
748− "RENAME COLUMN" <+> renderSQL column0 <+> "TO" <+> renderSQL column1
750−-- | An `alterColumn` alters a single column.
752− :: ( KnownSymbol column
753− , Has sch schemas schema
754− , Has tab schema ('Table table0)
755− , table0 ~ (constraints :=> columns)
756− , Has column columns ty0
757− , table1 ~ (constraints :=> Alter column ty1 columns))
758− => Alias column -- ^ column to alter
759− -> AlterColumn schemas ty0 ty1 -- ^ alteration to perform
760− -> AlterTable sch tab schemas table1
761−alterColumn column alteration = UnsafeAlterTable $
762− "ALTER COLUMN" <+> renderSQL column <+> renderAlterColumn alteration
764−-- | An `AlterColumn` describes the alteration to perform on a single column.
765−newtype AlterColumn (schemas :: SchemasType) (ty0 :: ColumnType) (ty1 :: ColumnType) =
766− UnsafeAlterColumn {renderAlterColumn :: ByteString}
767− deriving (GHC.Generic,Show,Eq,Ord,NFData)
769−-- | A `setDefault` sets a new default for a column. Note that this doesn't
770−-- affect any existing rows in the table, it just changes the default for
771−-- future insert and update commands.
775−-- definition :: Definition
776−-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'Null 'PGint4])]]
777−-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col" ::: 'Def :=> 'Null 'PGint4])]]
778−-- definition = alterTable #tab (alterColumn #col (setDefault 5))
779−-- in printSQL definition
781−-- ALTER TABLE "tab" ALTER COLUMN "col" SET DEFAULT 5;
783− :: Expression '[] '[] 'Ungrouped schemas '[] '[] ty -- ^ default value to set
784− -> AlterColumn schemas (constraint :=> ty) ('Def :=> ty)
785−setDefault expression = UnsafeAlterColumn $
786− "SET DEFAULT" <+> renderExpression expression
788−-- | A `dropDefault` removes any default value for a column.
792−-- definition :: Definition
793−-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col" ::: 'Def :=> 'Null 'PGint4])]]
794−-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'Null 'PGint4])]]
795−-- definition = alterTable #tab (alterColumn #col dropDefault)
796−-- in printSQL definition
798−-- ALTER TABLE "tab" ALTER COLUMN "col" DROP DEFAULT;
799−dropDefault :: AlterColumn schemas ('Def :=> ty) ('NoDef :=> ty)
800−dropDefault = UnsafeAlterColumn $ "DROP DEFAULT"
802−-- | A `setNotNull` adds a @NOT NULL@ constraint to a column.
803−-- The constraint will be checked immediately, so the table data must satisfy
804−-- the constraint before it can be added.
808−-- definition :: Definition
809−-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'Null 'PGint4])]]
810−-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'NotNull 'PGint4])]]
811−-- definition = alterTable #tab (alterColumn #col setNotNull)
812−-- in printSQL definition
814−-- ALTER TABLE "tab" ALTER COLUMN "col" SET NOT NULL;
816− :: AlterColumn schemas (constraint :=> 'Null ty) (constraint :=> 'NotNull ty)
817−setNotNull = UnsafeAlterColumn $ "SET NOT NULL"
819−-- | A `dropNotNull` drops a @NOT NULL@ constraint from a column.
823−-- definition :: Definition
824−-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'NotNull 'PGint4])]]
825−-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'Null 'PGint4])]]
826−-- definition = alterTable #tab (alterColumn #col dropNotNull)
827−-- in printSQL definition
829−-- ALTER TABLE "tab" ALTER COLUMN "col" DROP NOT NULL;
831− :: AlterColumn schemas (constraint :=> 'NotNull ty) (constraint :=> 'Null ty)
832−dropNotNull = UnsafeAlterColumn $ "DROP NOT NULL"
834−-- | An `alterType` converts a column to a different data type.
835−-- This will succeed only if each existing entry in the column can be
836−-- converted to the new type by an implicit cast.
840−-- definition :: Definition
841−-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'NotNull 'PGint4])]]
842−-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'NotNull 'PGnumeric])]]
844−-- alterTable #tab (alterColumn #col (alterType (numeric & notNullable)))
845−-- in printSQL definition
847−-- ALTER TABLE "tab" ALTER COLUMN "col" TYPE numeric NOT NULL;
848−alterType :: ColumnTypeExpression schemas ty -> AlterColumn schemas ty0 ty
849−alterType ty = UnsafeAlterColumn $ "TYPE" <+> renderColumnTypeExpression ty
852−>>> type ABC = '["a" ::: 'NoDef :=> 'Null 'PGint4, "b" ::: 'NoDef :=> 'Null 'PGint4, "c" ::: 'NoDef :=> 'Null 'PGint4]
853−>>> type BC = '["b" ::: 'Null 'PGint4, "c" ::: 'Null 'PGint4]
856− definition :: Definition
857− '[ "public" ::: '["abc" ::: 'Table ('[] :=> ABC)]]
858− '[ "public" ::: '["abc" ::: 'Table ('[] :=> ABC), "bc" ::: 'View BC]]
860− createView #bc (select_ (#b :* #c) (from (table #abc)))
861−in printSQL definition
863−CREATE VIEW "bc" AS SELECT "b" AS "b", "c" AS "c" FROM "abc" AS "abc";
866− :: (KnownSymbol sch, KnownSymbol vw, Has sch schemas schema)
867− => QualifiedAlias sch vw -- ^ the name of the view to add
868− -> Query '[] '[] schemas '[] view -- ^ query
869− -> Definition schemas (Alter sch (Create vw ('View view) schema) schemas)
870−createView alias query = UnsafeDefinition $
871− "CREATE" <+> "VIEW" <+> renderSQL alias <+> "AS"
872− <+> renderQuery query <> ";"
878−-- definition :: Definition
879−-- '[ "public" ::: '["abc" ::: 'Table ('[] :=> '["a" ::: 'NoDef :=> 'Null 'PGint4, "b" ::: 'NoDef :=> 'Null 'PGint4, "c" ::: 'NoDef :=> 'Null 'PGint4])
880−-- , "bc" ::: 'View ('["b" ::: 'Null 'PGint4, "c" ::: 'Null 'PGint4])]]
881−-- '[ "public" ::: '["abc" ::: 'Table ('[] :=> '["a" ::: 'NoDef :=> 'Null 'PGint4, "b" ::: 'NoDef :=> 'Null 'PGint4, "c" ::: 'NoDef :=> 'Null 'PGint4])]]
882−-- definition = dropView #bc
883−-- in printSQL definition
887− :: (Has sch schemas schema, Has vw schema ('View view))
888− => QualifiedAlias sch vw -- ^ view to remove
889− -> Definition schemas (Alter sch (Drop vw schema) schemas)
890−dropView vw = UnsafeDefinition $ "DROP VIEW" <+> renderSQL vw <> ";"
892−-- | Enumerated types are created using the `createTypeEnum` command, for example
894−-- >>> printSQL $ (createTypeEnum #mood (label @"sad" :* label @"ok" :* label @"happy") :: Definition (Public '[]) '["public" ::: '["mood" ::: 'Typedef ('PGenum '["sad","ok","happy"])]])
895−-- CREATE TYPE "mood" AS ENUM ('sad', 'ok', 'happy');
897− :: (KnownSymbol enum, Has sch schemas schema, SOP.All KnownSymbol labels)
898− => QualifiedAlias sch enum
899− -- ^ name of the user defined enumerated type
900− -> NP PGlabel labels
901− -- ^ labels of the enumerated type
902− -> Definition schemas (Alter sch (Create enum ('Typedef ('PGenum labels)) schema) schemas)
903−createTypeEnum enum labels = UnsafeDefinition $
904− "CREATE" <+> "TYPE" <+> renderSQL enum <+> "AS" <+> "ENUM" <+>
905− parenthesized (renderSQL labels) <> ";"
907−-- | Enumerated types can also be generated from a Haskell type, for example
909−-- >>> data Schwarma = Beef | Lamb | Chicken deriving GHC.Generic
910−-- >>> instance SOP.Generic Schwarma
911−-- >>> instance SOP.HasDatatypeInfo Schwarma
914−-- createSchwarma :: Definition (Public '[]) '["public" ::: '["schwarma" ::: 'Typedef (PG (Enumerated Schwarma))]]
915−-- createSchwarma = createTypeEnumFrom @Schwarma #schwarma
917−-- printSQL createSchwarma
919−-- CREATE TYPE "schwarma" AS ENUM ('Beef', 'Lamb', 'Chicken');
921− :: forall hask sch enum schemas schema.
923− , SOP.All KnownSymbol (LabelsPG hask)
925− , Has sch schemas schema )
926− => QualifiedAlias sch enum
927− -- ^ name of the user defined enumerated type
928− -> Definition schemas (Alter sch (Create enum ('Typedef (PG (Enumerated hask))) schema) schemas)
929−createTypeEnumFrom enum = createTypeEnum enum
930− (SOP.hpure label :: NP PGlabel (LabelsPG hask))
932−{- | `createTypeComposite` creates a composite type. The composite type is
933−specified by a list of attribute names and data types.
936−type PGcomplex = 'PGcomposite
937− '[ "real" ::: 'NotNull 'PGfloat8
938− , "imaginary" ::: 'NotNull 'PGfloat8 ]
943− setup :: Definition (Public '[]) '["public" ::: '["complex" ::: 'Typedef PGcomplex]]
944− setup = createTypeComposite #complex
945− (float8 `as` #real :* float8 `as` #imaginary)
948−CREATE TYPE "complex" AS ("real" float8, "imaginary" float8);
951− :: (KnownSymbol ty, Has sch schemas schema, SOP.SListI fields)
952− => QualifiedAlias sch ty
953− -- ^ name of the user defined composite type
954− -> NP (Aliased (TypeExpression schemas)) fields
955− -- ^ list of attribute names and data types
956− -> Definition schemas (Alter sch (Create ty ('Typedef ('PGcomposite fields)) schema) schemas)
957−createTypeComposite ty fields = UnsafeDefinition $
958− "CREATE" <+> "TYPE" <+> renderSQL ty <+> "AS" <+> parenthesized
959− (renderCommaSeparated renderField fields) <> ";"
961− renderField :: Aliased (TypeExpression schemas) x -> ByteString
962− renderField (typ `As` alias) =
963− renderSQL alias <+> renderSQL typ
965−-- | Composite types can also be generated from a Haskell type, for example
967−-- >>> data Complex = Complex {real :: Double, imaginary :: Double} deriving GHC.Generic
968−-- >>> instance SOP.Generic Complex
969−-- >>> instance SOP.HasDatatypeInfo Complex
970−-- >>> type Schema = '["complex" ::: 'Typedef (PG (Composite Complex))]
973−-- createComplex :: Definition (Public '[]) (Public Schema)
974−-- createComplex = createTypeCompositeFrom @Complex #complex
976−-- printSQL createComplex
978−-- CREATE TYPE "complex" AS ("real" float8, "imaginary" float8);
979−createTypeCompositeFrom
980− :: forall hask sch ty schemas schema.
981− ( SOP.All (FieldTyped schemas) (RowPG hask)
983− , Has sch schemas schema )
984− => QualifiedAlias sch ty
985− -- ^ name of the user defined composite type
986− -> Definition schemas (Alter sch (Create ty ( 'Typedef (PG (Composite hask))) schema) schemas)
987−createTypeCompositeFrom ty = createTypeComposite ty
988− (SOP.hcpure (SOP.Proxy :: SOP.Proxy (FieldTyped schemas)) fieldtype
989− :: NP (Aliased (TypeExpression schemas)) (RowPG hask))
992−`createDomain` creates a new domain. A domain is essentially a data type
993−with constraints (restrictions on the allowed set of values).
995−Domains are useful for abstracting common constraints on fields
996−into a single location for maintenance. For example, several tables might
997−contain email address columns, all requiring the same `check` constraint
998−to verify the address syntax. Define a domain rather than setting up
999−each table's constraint individually.
1003− createPositive :: Definition (Public '[]) (Public '["positive" ::: 'Typedef 'PGfloat4])
1004− createPositive = createDomain #positive real (#value .> 0 .&& (#value & isNotNull))
1005−in printSQL createPositive
1007−CREATE DOMAIN "positive" AS real CHECK ((("value" > 0) AND "value" IS NOT NULL));
1010− :: (Has sch schemas schema, KnownSymbol dom)
1011− => QualifiedAlias sch dom
1012− -> (forall nullity. TypeExpression schemas (nullity ty))
1013− -> (forall tab. Condition '[] '[] 'Ungrouped schemas '[] '[tab ::: '["value" ::: 'Null ty]])
1014− -> Definition schemas (Alter sch (Create alias ('Typedef ty) schema) schemas)
1015−createDomain dom ty condition =
1016− UnsafeDefinition $ "CREATE DOMAIN" <+> renderSQL dom
1017− <+> "AS" <+> renderTypeExpression ty
1018− <+> "CHECK" <+> parenthesized (renderSQL condition) <> ";"
1020−class FieldTyped schemas ty where
1021− fieldtype :: Aliased (TypeExpression schemas) ty
1022−instance (KnownSymbol alias, PGTyped schemas ty)
1023− => FieldTyped schemas (alias ::: ty) where
1024− fieldtype = pgtype `As` Alias
1028−-- >>> data Schwarma = Beef | Lamb | Chicken deriving GHC.Generic
1029−-- >>> instance SOP.Generic Schwarma
1030−-- >>> instance SOP.HasDatatypeInfo Schwarma
1031−-- >>> printSQL (dropType #schwarma :: Definition '["public" ::: '["schwarma" ::: 'Typedef (PG (Enumerated Schwarma))]] (Public '[]))
1032−-- DROP TYPE "schwarma";
1034− :: (Has sch schemas schema, Has td schema ('Typedef ty))
1035− => QualifiedAlias sch td
1036− -- ^ name of the user defined type
1037− -> Definition schemas (Alter sch (Drop td schema) schemas)
1038−dropType tydef = UnsafeDefinition $ "DROP" <+> "TYPE" <+> renderSQL tydef <> ";"
1040−-- | `ColumnTypeExpression`s are used in `createTable` commands.
1041−newtype ColumnTypeExpression (schemas :: SchemasType) (ty :: ColumnType)
1042− = UnsafeColumnTypeExpression { renderColumnTypeExpression :: ByteString }
1043− deriving (GHC.Generic,Show,Eq,Ord,NFData)
1044−instance RenderSQL (ColumnTypeExpression schemas ty) where
1045− renderSQL = renderColumnTypeExpression
1047−-- | used in `createTable` commands as a column constraint to note that
1048−-- @NULL@ may be present in a column
1050− :: TypeExpression schemas (nullity ty)
1051− -> ColumnTypeExpression schemas ('NoDef :=> 'Null ty)
1052−nullable ty = UnsafeColumnTypeExpression $ renderSQL ty <+> "NULL"
1054−-- | used in `createTable` commands as a column constraint to ensure
1055−-- @NULL@ is not present in a column
1057− :: TypeExpression schemas (nullity ty)
1058− -> ColumnTypeExpression schemas ('NoDef :=> 'NotNull ty)
1059−notNullable ty = UnsafeColumnTypeExpression $ renderSQL ty <+> "NOT NULL"
1061−-- | used in `createTable` commands as a column constraint to give a default
1063− :: Expression '[] '[] 'Ungrouped schemas '[] '[] ty
1064− -> ColumnTypeExpression schemas ('NoDef :=> ty)
1065− -> ColumnTypeExpression schemas ('Def :=> ty)
1066−default_ x ty = UnsafeColumnTypeExpression $
1067− renderSQL ty <+> "DEFAULT" <+> renderExpression x
1069−-- | not a true type, but merely a notational convenience for creating
1070−-- unique identifier columns with type `PGint2`
1071−serial2, smallserial
1072− :: ColumnTypeExpression schemas ('Def :=> 'NotNull 'PGint2)
1073−serial2 = UnsafeColumnTypeExpression "serial2"
1074−smallserial = UnsafeColumnTypeExpression "smallserial"
1075−-- | not a true type, but merely a notational convenience for creating
1076−-- unique identifier columns with type `PGint4`
1078− :: ColumnTypeExpression schemas ('Def :=> 'NotNull 'PGint4)
1079−serial4 = UnsafeColumnTypeExpression "serial4"
1080−serial = UnsafeColumnTypeExpression "serial"
1081−-- | not a true type, but merely a notational convenience for creating
1082−-- unique identifier columns with type `PGint8`
1084− :: ColumnTypeExpression schemas ('Def :=> 'NotNull 'PGint8)
1085−serial8 = UnsafeColumnTypeExpression "serial8"
1086−bigserial = UnsafeColumnTypeExpression "bigserial"