@@ -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,84 +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
47− , TableConstraintExpression (..)
53− , OnDeleteClause (..)
54− , OnUpdateClause (..)
77− , ColumnTypeExpression (..)
89import Control.Category
40import Control.Category
90import Control.DeepSeq
41import Control.DeepSeq
91import Data.ByteString
42import Data.ByteString
92import Data.Monoid
43import Data.Monoid
94import Prelude hiding ((.), id)
44import Prelude hiding ((.), id)
96−import qualified Generics.SOP as SOP
97import qualified GHC.Generics as GHC
46import qualified GHC.Generics as GHC
99−import Squeal.PostgreSQL.Alias
48+import Squeal.PostgreSQL.Manipulation
100−import Squeal.PostgreSQL.Expression
101−import Squeal.PostgreSQL.Expression.Logic
102−import Squeal.PostgreSQL.Expression.Type
103−import Squeal.PostgreSQL.List
104−import Squeal.PostgreSQL.PG
105−import Squeal.PostgreSQL.Query
106import Squeal.PostgreSQL.Render
49import Squeal.PostgreSQL.Render
107import Squeal.PostgreSQL.Schema
50import Squeal.PostgreSQL.Schema
@@ -130,971 +73,10 @@ instance Category Definition where
130 ddl1 . ddl0 = UnsafeDefinition $
73 ddl1 . ddl0 = UnsafeDefinition $
131 renderSQL ddl0 <> "\n" <> renderSQL ddl1
74 renderSQL ddl0 <> "\n" <> renderSQL ddl1
133−{-----------------------------------------
76+-- | A `Manipulation` without input or output can be run as a statement
134−CREATE statements
77+-- along with other `Definition`s, by embedding it using `manipDefinition`.
135−-----------------------------------------}
78+manipDefinition
136−
79+ :: Manipulation '[] schemas '[] '[]
137−{- |
80+ -- ^ no input or output
138−`createSchema` enters a new schema into the current database.
139−The schema name must be distinct from the name of any existing schema
140−in the current database.
142−A schema is essentially a namespace: it contains named objects
143−(tables, data types, functions, and operators) whose names
144−can duplicate those of other objects existing in other schemas.
145−Named objects are accessed by `QualifiedAlias`es with the schema
151− -> Definition schemas (Create sch '[] schemas)
152−createSchema sch = UnsafeDefinition $
153− "CREATE" <+> "SCHEMA" <+> renderSQL sch <> ";"
155−{- | Idempotent version of `createSchema`. -}
156−createSchemaIfNotExists
157− :: (KnownSymbol sch, Has sch schemas schema)
159 -> Definition schemas schemas
81 -> Definition schemas schemas
160−createSchemaIfNotExists sch = UnsafeDefinition $
82+manipDefinition = UnsafeDefinition . (<> ";") . renderSQL
161− "CREATE" <+> "SCHEMA" <+> "IF" <+> "NOT" <+> "EXISTS"
162− <+> renderSQL sch <> ";"
164−{- | `createTable` adds a table to the schema.
166−>>> :set -XOverloadedLabels
169− '[ "a" ::: 'NoDef :=> 'Null 'PGint4
170− , "b" ::: 'NoDef :=> 'Null 'PGfloat4 ]
175− setup :: Definition (Public '[]) (Public '["tab" ::: 'Table Table])
176− setup = createTable #tab
177− (nullable int `as` #a :* nullable real `as` #b) Nil
180−CREATE TABLE "tab" ("a" int NULL, "b" real NULL);
183− :: ( KnownSymbol sch
185− , columns ~ (col ': cols)
186− , SOP.SListI columns
187− , SOP.SListI constraints
188− , Has sch schemas0 schema0
189− , schemas1 ~ Alter sch (Create tab ('Table (constraints :=> columns)) schema0) schemas0 )
190− => QualifiedAlias sch tab -- ^ the name of the table to add
191− -> NP (Aliased (ColumnTypeExpression schemas0)) columns
192− -- ^ the names and datatype of each column
193− -> NP (Aliased (TableConstraintExpression sch tab schemas1)) constraints
194− -- ^ constraints that must hold for the table
195− -> Definition schemas0 schemas1
196−createTable tab columns constraints = UnsafeDefinition $
197− "CREATE TABLE" <+> renderCreation tab columns constraints
199−{-| `createTableIfNotExists` creates a table if it doesn't exist, but does not add it to the schema.
200−Instead, the schema already has the table so if the table did not yet exist, the schema was wrong.
201−`createTableIfNotExists` fixes this. Interestingly, this property makes it an idempotent in
202−the `Category` of `Definition`s.
204−>>> :set -XOverloadedLabels -XTypeApplications
207− '[ "a" ::: 'NoDef :=> 'Null 'PGint4
208− , "b" ::: 'NoDef :=> 'Null 'PGfloat4 ]
211−>>> type Schemas = Public '["tab" ::: 'Table Table]
215− setup :: Definition Schemas Schemas
216− setup = createTableIfNotExists #tab
217− (nullable int `as` #a :* nullable real `as` #b) Nil
220−CREATE TABLE IF NOT EXISTS "tab" ("a" int NULL, "b" real NULL);
222−createTableIfNotExists
223− :: ( Has sch schemas schema
224− , Has tab schema ('Table (constraints :=> columns))
225− , SOP.SListI columns
226− , SOP.SListI constraints )
227− => QualifiedAlias sch tab -- ^ the name of the table to add
228− -> NP (Aliased (ColumnTypeExpression schemas)) columns
229− -- ^ the names and datatype of each column
230− -> NP (Aliased (TableConstraintExpression sch tab schemas)) constraints
231− -- ^ constraints that must hold for the table
232− -> Definition schemas schemas
233−createTableIfNotExists tab columns constraints = UnsafeDefinition $
234− "CREATE TABLE IF NOT EXISTS"
235− <+> renderCreation tab columns constraints
237−-- helper function for `createTable` and `createTableIfNotExists`
239− :: ( KnownSymbol sch
241− , SOP.SListI columns
242− , SOP.SListI constraints )
243− => QualifiedAlias sch tab -- ^ the name of the table to add
244− -> NP (Aliased (ColumnTypeExpression schemas0)) columns
245− -- ^ the names and datatype of each column
246− -> NP (Aliased (TableConstraintExpression sch tab schemas1)) constraints
247− -- ^ constraints that must hold for the table
249−renderCreation tab columns constraints = renderSQL tab
251− ( renderCommaSeparated renderColumnDef columns
252− <> ( case constraints of
255− renderCommaSeparated renderConstraint constraints ) )
258− renderColumnDef :: Aliased (ColumnTypeExpression schemas) x -> ByteString
259− renderColumnDef (ty `As` column) =
260− renderSQL column <+> renderColumnTypeExpression ty
262− :: Aliased (TableConstraintExpression sch tab schemas) constraint
264− renderConstraint (constraint `As` alias) =
265− "CONSTRAINT" <+> renderSQL alias <+> renderSQL constraint
267−-- | Data types are a way to limit the kind of data that can be stored in a
268−-- table. For many applications, however, the constraint they provide is
269−-- too coarse. For example, a column containing a product price should
270−-- probably only accept positive values. But there is no standard data type
271−-- that accepts only positive numbers. Another issue is that you might want
272−-- to constrain column data with respect to other columns or rows.
273−-- For example, in a table containing product information,
274−-- there should be only one row for each product number.
275−-- `TableConstraint`s give you as much control over the data in your tables
276−-- as you wish. If a user attempts to store data in a column that would
277−-- violate a constraint, an error is raised. This applies
278−-- even if the value came from the default value definition.
279−newtype TableConstraintExpression
282− (schemas :: SchemasType)
283− (constraint :: TableConstraint)
284− = UnsafeTableConstraintExpression
285− { renderTableConstraintExpression :: ByteString }
286− deriving (GHC.Generic,Show,Eq,Ord,NFData)
288− (TableConstraintExpression sch tab schemas constraint) where
289− renderSQL = renderTableConstraintExpression
291−{-| A `check` constraint is the most generic `TableConstraint` type.
292−It allows you to specify that the value in a certain column must satisfy
293−a Boolean (truth-value) expression.
297− "tab" ::: 'Table ('[ "inequality" ::: 'Check '["a","b"]] :=> '[
298− "a" ::: 'NoDef :=> 'NotNull 'PGint4,
299− "b" ::: 'NoDef :=> 'NotNull 'PGint4
305− definition :: Definition (Public '[]) (Public Schema)
306− definition = createTable #tab
307− ( (int & notNullable) `as` #a :*
308− (int & notNullable) `as` #b )
309− ( check (#a :* #b) (#a .> #b) `as` #inequality )
312−>>> printSQL definition
313−CREATE TABLE "tab" ("a" int NOT NULL, "b" int NOT NULL, CONSTRAINT "inequality" CHECK (("a" > "b")));
316− :: ( Has sch schemas schema
317− , Has tab schema ('Table table)
318− , HasAll aliases (TableToRow table) subcolumns )
320− -- ^ specify the subcolumns which are getting checked
321− -> (forall t. Condition '[] '[] 'Ungrouped schemas '[] '[t ::: subcolumns])
322− -- ^ a closed `Condition` on those subcolumns
323− -> TableConstraintExpression sch tab schemas ('Check aliases)
324−check _cols condition = UnsafeTableConstraintExpression $
325− "CHECK" <+> parenthesized (renderSQL condition)
327−{-| A `unique` constraint ensure that the data contained in a column,
328−or a group of columns, is unique among all the rows in the table.
332− "tab" ::: 'Table( '[ "uq_a_b" ::: 'Unique '["a","b"]] :=> '[
333− "a" ::: 'NoDef :=> 'Null 'PGint4,
334− "b" ::: 'NoDef :=> 'Null 'PGint4
340− definition :: Definition (Public '[]) (Public Schema)
341− definition = createTable #tab
342− ( (int & nullable) `as` #a :*
343− (int & nullable) `as` #b )
344− ( unique (#a :* #b) `as` #uq_a_b )
347−>>> printSQL definition
348−CREATE TABLE "tab" ("a" int NULL, "b" int NULL, CONSTRAINT "uq_a_b" UNIQUE ("a", "b"));
351− :: ( Has sch schemas schema
352− , Has tab schema('Table table)
353− , HasAll aliases (TableToRow table) subcolumns )
355− -- ^ specify subcolumns which together are unique for each row
356− -> TableConstraintExpression sch tab schemas ('Unique aliases)
357−unique columns = UnsafeTableConstraintExpression $
358− "UNIQUE" <+> parenthesized (renderSQL columns)
360−{-| A `primaryKey` constraint indicates that a column, or group of columns,
361−can be used as a unique identifier for rows in the table.
362−This requires that the values be both unique and not null.
366− "tab" ::: 'Table ('[ "pk_id" ::: 'PrimaryKey '["id"]] :=> '[
367− "id" ::: 'Def :=> 'NotNull 'PGint4,
368− "name" ::: 'NoDef :=> 'NotNull 'PGtext
374− definition :: Definition (Public '[]) (Public Schema)
375− definition = createTable #tab
376− ( serial `as` #id :*
377− (text & notNullable) `as` #name )
378− ( primaryKey #id `as` #pk_id )
381−>>> printSQL definition
382−CREATE TABLE "tab" ("id" serial, "name" text NOT NULL, CONSTRAINT "pk_id" PRIMARY KEY ("id"));
385− :: ( Has sch schemas schema
386− , Has tab schema ('Table table)
387− , HasAll aliases (TableToColumns table) subcolumns
388− , AllNotNull subcolumns )
390− -- ^ specify the subcolumns which together form a primary key.
391− -> TableConstraintExpression sch tab schemas ('PrimaryKey aliases)
392−primaryKey columns = UnsafeTableConstraintExpression $
393− "PRIMARY KEY" <+> parenthesized (renderSQL columns)
395−{-| A `foreignKey` specifies that the values in a column
396−(or a group of columns) must match the values appearing in some row of
397−another table. We say this maintains the referential integrity
398−between two related tables.
402− '[ "users" ::: 'Table (
403− '[ "pk_users" ::: 'PrimaryKey '["id"] ] :=>
404− '[ "id" ::: 'Def :=> 'NotNull 'PGint4
405− , "name" ::: 'NoDef :=> 'NotNull 'PGtext
407− , "emails" ::: 'Table (
408− '[ "pk_emails" ::: 'PrimaryKey '["id"]
409− , "fk_user_id" ::: 'ForeignKey '["user_id"] "users" '["id"]
411− '[ "id" ::: 'Def :=> 'NotNull 'PGint4
412− , "user_id" ::: 'NoDef :=> 'NotNull 'PGint4
413− , "email" ::: 'NoDef :=> 'Null 'PGtext
420− setup :: Definition (Public '[]) (Public Schema)
423− ( serial `as` #id :*
424− (text & notNullable) `as` #name )
425− ( primaryKey #id `as` #pk_users ) >>>
427− ( serial `as` #id :*
428− (int & notNullable) `as` #user_id :*
429− (text & nullable) `as` #email )
430− ( primaryKey #id `as` #pk_emails :*
431− foreignKey #user_id #users #id
432− OnDeleteCascade OnUpdateCascade `as` #fk_user_id )
435−CREATE TABLE "users" ("id" serial, "name" text NOT NULL, CONSTRAINT "pk_users" PRIMARY KEY ("id"));
436−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);
438−A `foreignKey` can even be a table self-reference.
442− '[ "employees" ::: 'Table (
443− '[ "employees_pk" ::: 'PrimaryKey '["id"]
444− , "employees_employer_fk" ::: 'ForeignKey '["employer_id"] "employees" '["id"]
446− '[ "id" ::: 'Def :=> 'NotNull 'PGint4
447− , "name" ::: 'NoDef :=> 'NotNull 'PGtext
448− , "employer_id" ::: 'NoDef :=> 'Null 'PGint4
455− setup :: Definition (Public '[]) (Public Schema)
457− createTable #employees
458− ( serial `as` #id :*
459− (text & notNullable) `as` #name :*
460− (integer & nullable) `as` #employer_id )
461− ( primaryKey #id `as` #employees_pk :*
462− foreignKey #employer_id #employees #id
463− OnDeleteCascade OnUpdateCascade `as` #employees_employer_fk )
466−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);
469− :: (ForeignKeyed schemas sch schema child parent
475− -- ^ column or columns in the table
477− -- ^ reference table
478− -> NP Alias refcolumns
479− -- ^ reference column or columns in the reference table
481− -- ^ what to do when reference is deleted
483− -- ^ what to do when reference is updated
484− -> TableConstraintExpression sch child schemas
485− ('ForeignKey columns parent refcolumns)
486−foreignKey keys parent refs ondel onupd = UnsafeTableConstraintExpression $
487− "FOREIGN KEY" <+> parenthesized (renderSQL keys)
488− <+> "REFERENCES" <+> renderSQL parent
489− <+> parenthesized (renderSQL refs)
493−-- | A constraint synonym between types involved in a foreign key constraint.
494−type ForeignKeyed schemas
502− ( Has sch schemas schema
503− , Has child schema ('Table table)
504− , Has parent schema ('Table reftable)
505− , HasAll columns (TableToColumns table) tys
506− , reftable ~ (constraints :=> cols)
507− , HasAll refcolumns cols reftys
508− , SOP.AllZip SamePGType tys reftys
509− , Uniquely refcolumns constraints )
511−-- | `OnDeleteClause` indicates what to do with rows that reference a deleted row.
514− -- ^ if any referencing rows still exist when the constraint is checked,
515− -- an error is raised
516− | OnDeleteRestrict -- ^ prevents deletion of a referenced row
518− -- ^ specifies that when a referenced row is deleted,
519− -- row(s) referencing it should be automatically deleted as well
520− deriving (GHC.Generic,Show,Eq,Ord)
521−instance NFData OnDeleteClause
522−-- | Render `OnDeleteClause`.
523−instance RenderSQL OnDeleteClause where
525− OnDeleteNoAction -> "ON DELETE NO ACTION"
526− OnDeleteRestrict -> "ON DELETE RESTRICT"
527− OnDeleteCascade -> "ON DELETE CASCADE"
529−-- | Analagous to `OnDeleteClause` there is also `OnUpdateClause` which is invoked
530−-- when a referenced column is changed (updated).
533− -- ^ if any referencing rows has not changed when the constraint is checked,
534− -- an error is raised
535− | OnUpdateRestrict -- ^ prevents update of a referenced row
537− -- ^ the updated values of the referenced column(s) should be copied
538− -- into the referencing row(s)
539− deriving (GHC.Generic,Show,Eq,Ord)
540−instance NFData OnUpdateClause
542−-- | Render `OnUpdateClause`.
543−instance RenderSQL OnUpdateClause where
545− OnUpdateNoAction -> "ON UPDATE NO ACTION"
546− OnUpdateRestrict -> "ON UPDATE RESTRICT"
547− OnUpdateCascade -> "ON UPDATE CASCADE"
549−{-----------------------------------------
551−-----------------------------------------}
555−-- definition :: Definition '["muh_schema" ::: schema, "public" ::: public] '["public" ::: public]
556−-- definition = dropSchema #muh_schema
559−-- >>> printSQL definition
560−-- DROP SCHEMA "muh_schema";
562− :: Has sch schemas schema
564− -> Definition schemas (Drop sch schemas)
565−dropSchema sch = UnsafeDefinition $ "DROP SCHEMA" <+> renderSQL sch <> ";"
567−-- | `dropTable` removes a table from the schema.
571−-- definition :: Definition '["public" ::: '["muh_table" ::: 'Table t]] (Public '[])
572−-- definition = dropTable #muh_table
575−-- >>> printSQL definition
576−-- DROP TABLE "muh_table";
578− :: ( Has sch schemas schema
579− , Has tab schema ('Table table))
580− => QualifiedAlias sch tab -- ^ table to remove
581− -> Definition schemas (Alter sch (Drop tab schema) schemas)
582−dropTable tab = UnsafeDefinition $ "DROP TABLE" <+> renderSQL tab <> ";"
584−{-----------------------------------------
586−-----------------------------------------}
588−-- | `alterTable` changes the definition of a table from the schema.
590− :: (Has sch schemas schema, Has tab schema ('Table table0))
591− => QualifiedAlias sch tab -- ^ table to alter
592− -> AlterTable sch tab schemas table1 -- ^ alteration to perform
593− -> Definition schemas (Alter sch (Alter tab ('Table table1) schema) schemas)
594−alterTable tab alteration = UnsafeDefinition $
597− <+> renderAlterTable alteration
600−-- | `alterTableRename` changes the name of a table from the schema.
602−-- >>> printSQL $ alterTableRename #foo #bar
603−-- ALTER TABLE "foo" RENAME TO "bar";
605− :: (KnownSymbol table0, KnownSymbol table1)
606− => Alias table0 -- ^ table to rename
607− -> Alias table1 -- ^ what to rename it
608− -> Definition schema (Rename table0 table1 schema)
609−alterTableRename table0 table1 = UnsafeDefinition $
610− "ALTER TABLE" <+> renderSQL table0
611− <+> "RENAME TO" <+> renderSQL table1 <> ";"
613−-- | An `AlterTable` describes the alteration to perform on the columns
618− (schemas :: SchemasType)
619− (table :: TableType) =
620− UnsafeAlterTable {renderAlterTable :: ByteString}
621− deriving (GHC.Generic,Show,Eq,Ord,NFData)
623−-- | An `addConstraint` adds a table constraint.
627−-- definition :: Definition
628−-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'NotNull 'PGint4])]]
629−-- '["public" ::: '["tab" ::: 'Table ('["positive" ::: 'Check '["col"]] :=> '["col" ::: 'NoDef :=> 'NotNull 'PGint4])]]
630−-- definition = alterTable #tab (addConstraint #positive (check #col (#col .> 0)))
631−-- in printSQL definition
633−-- ALTER TABLE "tab" ADD CONSTRAINT "positive" CHECK (("col" > 0));
635− :: ( KnownSymbol alias
636− , Has sch schemas schema
637− , Has tab schema ('Table table0)
638− , table0 ~ (constraints :=> columns)
639− , table1 ~ (Create alias constraint constraints :=> columns) )
641− -> TableConstraintExpression sch tab schemas constraint
642− -- ^ constraint to add
643− -> AlterTable sch tab schemas table1
644−addConstraint alias constraint = UnsafeAlterTable $
645− "ADD" <+> "CONSTRAINT" <+> renderSQL alias
646− <+> renderSQL constraint
648−-- | A `dropConstraint` drops a table constraint.
652−-- definition :: Definition
653−-- '["public" ::: '["tab" ::: 'Table ('["positive" ::: Check '["col"]] :=> '["col" ::: 'NoDef :=> 'NotNull 'PGint4])]]
654−-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'NotNull 'PGint4])]]
655−-- definition = alterTable #tab (dropConstraint #positive)
656−-- in printSQL definition
658−-- ALTER TABLE "tab" DROP CONSTRAINT "positive";
660− :: ( KnownSymbol constraint
661− , Has sch schemas schema
662− , Has tab schema ('Table table0)
663− , table0 ~ (constraints :=> columns)
664− , table1 ~ (Drop constraint constraints :=> columns) )
666− -- ^ constraint to drop
667− -> AlterTable sch tab schemas table1
668−dropConstraint constraint = UnsafeAlterTable $
669− "DROP" <+> "CONSTRAINT" <+> renderSQL constraint
671−-- | An `AddColumn` is either @NULL@ or has @DEFAULT@.
672−class AddColumn ty where
673− -- | `addColumn` adds a new column, initially filled with whatever
674− -- default value is given or with @NULL@.
678− -- definition :: Definition
679− -- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col1" ::: 'NoDef :=> 'Null 'PGint4])]]
680− -- '["public" ::: '["tab" ::: 'Table ('[] :=>
681− -- '[ "col1" ::: 'NoDef :=> 'Null 'PGint4
682− -- , "col2" ::: 'Def :=> 'Null 'PGtext ])]]
683− -- definition = alterTable #tab (addColumn #col2 (text & nullable & default_ "foo"))
684− -- in printSQL definition
686− -- ALTER TABLE "tab" ADD COLUMN "col2" text NULL DEFAULT E'foo';
690− -- definition :: Definition
691− -- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col1" ::: 'NoDef :=> 'Null 'PGint4])]]
692− -- '["public" ::: '["tab" ::: 'Table ('[] :=>
693− -- '[ "col1" ::: 'NoDef :=> 'Null 'PGint4
694− -- , "col2" ::: 'NoDef :=> 'Null 'PGtext ])]]
695− -- definition = alterTable #tab (addColumn #col2 (text & nullable))
696− -- in printSQL definition
698− -- ALTER TABLE "tab" ADD COLUMN "col2" text NULL;
700− :: ( KnownSymbol column
701− , Has sch schemas schema
702− , Has tab schema ('Table table0)
703− , table0 ~ (constraints :=> columns) )
704− => Alias column -- ^ column to add
705− -> ColumnTypeExpression schemas ty -- ^ type of the new column
706− -> AlterTable sch tab schemas (constraints :=> Create column ty columns)
707− addColumn column ty = UnsafeAlterTable $
708− "ADD COLUMN" <+> renderSQL column <+> renderColumnTypeExpression ty
709−instance {-# OVERLAPPING #-} AddColumn ('Def :=> ty)
710−instance {-# OVERLAPPABLE #-} AddColumn ('NoDef :=> 'Null ty)
712−-- | A `dropColumn` removes a column. Whatever data was in the column
713−-- disappears. Table constraints involving the column are dropped, too.
714−-- However, if the column is referenced by a foreign key constraint of
715−-- another table, PostgreSQL will not silently drop that constraint.
719−-- definition :: Definition
720−-- '["public" ::: '["tab" ::: 'Table ('[] :=>
721−-- '[ "col1" ::: 'NoDef :=> 'Null 'PGint4
722−-- , "col2" ::: 'NoDef :=> 'Null 'PGtext ])]]
723−-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col1" ::: 'NoDef :=> 'Null 'PGint4])]]
724−-- definition = alterTable #tab (dropColumn #col2)
725−-- in printSQL definition
727−-- ALTER TABLE "tab" DROP COLUMN "col2";
729− :: ( KnownSymbol column
730− , Has sch schemas schema
731− , Has tab schema ('Table table0)
732− , table0 ~ (constraints :=> columns)
733− , table1 ~ (constraints :=> Drop column columns) )
734− => Alias column -- ^ column to remove
735− -> AlterTable sch tab schemas table1
736−dropColumn column = UnsafeAlterTable $
737− "DROP COLUMN" <+> renderSQL column
739−-- | A `renameColumn` renames a column.
743−-- definition :: Definition
744−-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["foo" ::: 'NoDef :=> 'Null 'PGint4])]]
745−-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["bar" ::: 'NoDef :=> 'Null 'PGint4])]]
746−-- definition = alterTable #tab (renameColumn #foo #bar)
747−-- in printSQL definition
749−-- ALTER TABLE "tab" RENAME COLUMN "foo" TO "bar";
751− :: ( KnownSymbol column0
752− , KnownSymbol column1
753− , Has sch schemas schema
754− , Has tab schema ('Table table0)
755− , table0 ~ (constraints :=> columns)
756− , table1 ~ (constraints :=> Rename column0 column1 columns) )
757− => Alias column0 -- ^ column to rename
758− -> Alias column1 -- ^ what to rename the column
759− -> AlterTable sch tab schemas table1
760−renameColumn column0 column1 = UnsafeAlterTable $
761− "RENAME COLUMN" <+> renderSQL column0 <+> "TO" <+> renderSQL column1
763−-- | An `alterColumn` alters a single column.
765− :: ( KnownSymbol column
766− , Has sch schemas schema
767− , Has tab schema ('Table table0)
768− , table0 ~ (constraints :=> columns)
769− , Has column columns ty0
770− , table1 ~ (constraints :=> Alter column ty1 columns))
771− => Alias column -- ^ column to alter
772− -> AlterColumn schemas ty0 ty1 -- ^ alteration to perform
773− -> AlterTable sch tab schemas table1
774−alterColumn column alteration = UnsafeAlterTable $
775− "ALTER COLUMN" <+> renderSQL column <+> renderAlterColumn alteration
777−-- | An `AlterColumn` describes the alteration to perform on a single column.
778−newtype AlterColumn (schemas :: SchemasType) (ty0 :: ColumnType) (ty1 :: ColumnType) =
779− UnsafeAlterColumn {renderAlterColumn :: ByteString}
780− deriving (GHC.Generic,Show,Eq,Ord,NFData)
782−-- | A `setDefault` sets a new default for a column. Note that this doesn't
783−-- affect any existing rows in the table, it just changes the default for
784−-- future insert and update commands.
788−-- definition :: Definition
789−-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'Null 'PGint4])]]
790−-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col" ::: 'Def :=> 'Null 'PGint4])]]
791−-- definition = alterTable #tab (alterColumn #col (setDefault 5))
792−-- in printSQL definition
794−-- ALTER TABLE "tab" ALTER COLUMN "col" SET DEFAULT 5;
796− :: Expression '[] '[] 'Ungrouped schemas '[] '[] ty -- ^ default value to set
797− -> AlterColumn schemas (constraint :=> ty) ('Def :=> ty)
798−setDefault expression = UnsafeAlterColumn $
799− "SET DEFAULT" <+> renderExpression expression
801−-- | A `dropDefault` removes any default value for a column.
805−-- definition :: Definition
806−-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col" ::: 'Def :=> 'Null 'PGint4])]]
807−-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'Null 'PGint4])]]
808−-- definition = alterTable #tab (alterColumn #col dropDefault)
809−-- in printSQL definition
811−-- ALTER TABLE "tab" ALTER COLUMN "col" DROP DEFAULT;
812−dropDefault :: AlterColumn schemas ('Def :=> ty) ('NoDef :=> ty)
813−dropDefault = UnsafeAlterColumn $ "DROP DEFAULT"
815−-- | A `setNotNull` adds a @NOT NULL@ constraint to a column.
816−-- The constraint will be checked immediately, so the table data must satisfy
817−-- the constraint before it can be added.
821−-- definition :: Definition
822−-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'Null 'PGint4])]]
823−-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'NotNull 'PGint4])]]
824−-- definition = alterTable #tab (alterColumn #col setNotNull)
825−-- in printSQL definition
827−-- ALTER TABLE "tab" ALTER COLUMN "col" SET NOT NULL;
829− :: AlterColumn schemas (constraint :=> 'Null ty) (constraint :=> 'NotNull ty)
830−setNotNull = UnsafeAlterColumn $ "SET NOT NULL"
832−-- | A `dropNotNull` drops a @NOT NULL@ constraint from a column.
836−-- definition :: Definition
837−-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'NotNull 'PGint4])]]
838−-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'Null 'PGint4])]]
839−-- definition = alterTable #tab (alterColumn #col dropNotNull)
840−-- in printSQL definition
842−-- ALTER TABLE "tab" ALTER COLUMN "col" DROP NOT NULL;
844− :: AlterColumn schemas (constraint :=> 'NotNull ty) (constraint :=> 'Null ty)
845−dropNotNull = UnsafeAlterColumn $ "DROP NOT NULL"
847−-- | An `alterType` converts a column to a different data type.
848−-- This will succeed only if each existing entry in the column can be
849−-- converted to the new type by an implicit cast.
853−-- definition :: Definition
854−-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'NotNull 'PGint4])]]
855−-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'NotNull 'PGnumeric])]]
857−-- alterTable #tab (alterColumn #col (alterType (numeric & notNullable)))
858−-- in printSQL definition
860−-- ALTER TABLE "tab" ALTER COLUMN "col" TYPE numeric NOT NULL;
861−alterType :: ColumnTypeExpression schemas ty -> AlterColumn schemas ty0 ty
862−alterType ty = UnsafeAlterColumn $ "TYPE" <+> renderColumnTypeExpression ty
865−>>> type ABC = '["a" ::: 'NoDef :=> 'Null 'PGint4, "b" ::: 'NoDef :=> 'Null 'PGint4, "c" ::: 'NoDef :=> 'Null 'PGint4]
866−>>> type BC = '["b" ::: 'Null 'PGint4, "c" ::: 'Null 'PGint4]
869− definition :: Definition
870− '[ "public" ::: '["abc" ::: 'Table ('[] :=> ABC)]]
871− '[ "public" ::: '["abc" ::: 'Table ('[] :=> ABC), "bc" ::: 'View BC]]
873− createView #bc (select_ (#b :* #c) (from (table #abc)))
874−in printSQL definition
876−CREATE VIEW "bc" AS SELECT "b" AS "b", "c" AS "c" FROM "abc" AS "abc";
879− :: (KnownSymbol sch, KnownSymbol vw, Has sch schemas schema)
880− => QualifiedAlias sch vw -- ^ the name of the view to add
881− -> Query '[] '[] schemas '[] view -- ^ query
882− -> Definition schemas (Alter sch (Create vw ('View view) schema) schemas)
883−createView alias query = UnsafeDefinition $
884− "CREATE" <+> "VIEW" <+> renderSQL alias <+> "AS"
885− <+> renderQuery query <> ";"
891−-- definition :: Definition
892−-- '[ "public" ::: '["abc" ::: 'Table ('[] :=> '["a" ::: 'NoDef :=> 'Null 'PGint4, "b" ::: 'NoDef :=> 'Null 'PGint4, "c" ::: 'NoDef :=> 'Null 'PGint4])
893−-- , "bc" ::: 'View ('["b" ::: 'Null 'PGint4, "c" ::: 'Null 'PGint4])]]
894−-- '[ "public" ::: '["abc" ::: 'Table ('[] :=> '["a" ::: 'NoDef :=> 'Null 'PGint4, "b" ::: 'NoDef :=> 'Null 'PGint4, "c" ::: 'NoDef :=> 'Null 'PGint4])]]
895−-- definition = dropView #bc
896−-- in printSQL definition
900− :: (Has sch schemas schema, Has vw schema ('View view))
901− => QualifiedAlias sch vw -- ^ view to remove
902− -> Definition schemas (Alter sch (Drop vw schema) schemas)
903−dropView vw = UnsafeDefinition $ "DROP VIEW" <+> renderSQL vw <> ";"
905−-- | Enumerated types are created using the `createTypeEnum` command, for example
907−-- >>> printSQL $ (createTypeEnum #mood (label @"sad" :* label @"ok" :* label @"happy") :: Definition (Public '[]) '["public" ::: '["mood" ::: 'Typedef ('PGenum '["sad","ok","happy"])]])
908−-- CREATE TYPE "mood" AS ENUM ('sad', 'ok', 'happy');
910− :: (KnownSymbol enum, Has sch schemas schema, SOP.All KnownSymbol labels)
911− => QualifiedAlias sch enum
912− -- ^ name of the user defined enumerated type
913− -> NP PGlabel labels
914− -- ^ labels of the enumerated type
915− -> Definition schemas (Alter sch (Create enum ('Typedef ('PGenum labels)) schema) schemas)
916−createTypeEnum enum labels = UnsafeDefinition $
917− "CREATE" <+> "TYPE" <+> renderSQL enum <+> "AS" <+> "ENUM" <+>
918− parenthesized (renderSQL labels) <> ";"
920−-- | Enumerated types can also be generated from a Haskell type, for example
922−-- >>> data Schwarma = Beef | Lamb | Chicken deriving GHC.Generic
923−-- >>> instance SOP.Generic Schwarma
924−-- >>> instance SOP.HasDatatypeInfo Schwarma
927−-- createSchwarma :: Definition (Public '[]) '["public" ::: '["schwarma" ::: 'Typedef (PG (Enumerated Schwarma))]]
928−-- createSchwarma = createTypeEnumFrom @Schwarma #schwarma
930−-- printSQL createSchwarma
932−-- CREATE TYPE "schwarma" AS ENUM ('Beef', 'Lamb', 'Chicken');
934− :: forall hask sch enum schemas schema.
936− , SOP.All KnownSymbol (LabelsPG hask)
938− , Has sch schemas schema )
939− => QualifiedAlias sch enum
940− -- ^ name of the user defined enumerated type
941− -> Definition schemas (Alter sch (Create enum ('Typedef (PG (Enumerated hask))) schema) schemas)
942−createTypeEnumFrom enum = createTypeEnum enum
943− (SOP.hpure label :: NP PGlabel (LabelsPG hask))
945−{- | `createTypeComposite` creates a composite type. The composite type is
946−specified by a list of attribute names and data types.
949−type PGcomplex = 'PGcomposite
950− '[ "real" ::: 'NotNull 'PGfloat8
951− , "imaginary" ::: 'NotNull 'PGfloat8 ]
956− setup :: Definition (Public '[]) '["public" ::: '["complex" ::: 'Typedef PGcomplex]]
957− setup = createTypeComposite #complex
958− (float8 `as` #real :* float8 `as` #imaginary)
961−CREATE TYPE "complex" AS ("real" float8, "imaginary" float8);
964− :: (KnownSymbol ty, Has sch schemas schema, SOP.SListI fields)
965− => QualifiedAlias sch ty
966− -- ^ name of the user defined composite type
967− -> NP (Aliased (TypeExpression schemas)) fields
968− -- ^ list of attribute names and data types
969− -> Definition schemas (Alter sch (Create ty ('Typedef ('PGcomposite fields)) schema) schemas)
970−createTypeComposite ty fields = UnsafeDefinition $
971− "CREATE" <+> "TYPE" <+> renderSQL ty <+> "AS" <+> parenthesized
972− (renderCommaSeparated renderField fields) <> ";"
974− renderField :: Aliased (TypeExpression schemas) x -> ByteString
975− renderField (typ `As` alias) =
976− renderSQL alias <+> renderSQL typ
978−-- | Composite types can also be generated from a Haskell type, for example
980−-- >>> data Complex = Complex {real :: Double, imaginary :: Double} deriving GHC.Generic
981−-- >>> instance SOP.Generic Complex
982−-- >>> instance SOP.HasDatatypeInfo Complex
983−-- >>> type Schema = '["complex" ::: 'Typedef (PG (Composite Complex))]
986−-- createComplex :: Definition (Public '[]) (Public Schema)
987−-- createComplex = createTypeCompositeFrom @Complex #complex
989−-- printSQL createComplex
991−-- CREATE TYPE "complex" AS ("real" float8, "imaginary" float8);
992−createTypeCompositeFrom
993− :: forall hask sch ty schemas schema.
994− ( SOP.All (FieldTyped schemas) (RowPG hask)
996− , Has sch schemas schema )
997− => QualifiedAlias sch ty
998− -- ^ name of the user defined composite type
999− -> Definition schemas (Alter sch (Create ty ( 'Typedef (PG (Composite hask))) schema) schemas)
1000−createTypeCompositeFrom ty = createTypeComposite ty
1001− (SOP.hcpure (SOP.Proxy :: SOP.Proxy (FieldTyped schemas)) fieldtype
1002− :: NP (Aliased (TypeExpression schemas)) (RowPG hask))
1005−`createDomain` creates a new domain. A domain is essentially a data type
1006−with constraints (restrictions on the allowed set of values).
1008−Domains are useful for abstracting common constraints on fields
1009−into a single location for maintenance. For example, several tables might
1010−contain email address columns, all requiring the same `check` constraint
1011−to verify the address syntax. Define a domain rather than setting up
1012−each table's constraint individually.
1016− createPositive :: Definition (Public '[]) (Public '["positive" ::: 'Typedef 'PGfloat4])
1017− createPositive = createDomain #positive real (#value .> 0 .&& (#value & isNotNull))
1018−in printSQL createPositive
1020−CREATE DOMAIN "positive" AS real CHECK ((("value" > 0) AND "value" IS NOT NULL));
1023− :: (Has sch schemas schema, KnownSymbol dom)
1024− => QualifiedAlias sch dom
1025− -> (forall nullity. TypeExpression schemas (nullity ty))
1026− -> (forall tab. Condition '[] '[] 'Ungrouped schemas '[] '[tab ::: '["value" ::: 'Null ty]])
1027− -> Definition schemas (Alter sch (Create alias ('Typedef ty) schema) schemas)
1028−createDomain dom ty condition =
1029− UnsafeDefinition $ "CREATE DOMAIN" <+> renderSQL dom
1030− <+> "AS" <+> renderTypeExpression ty
1031− <+> "CHECK" <+> parenthesized (renderSQL condition) <> ";"
1033−-- | Lift `PGTyped` to a field
1034−class FieldTyped schemas ty where
1035− fieldtype :: Aliased (TypeExpression schemas) ty
1036−instance (KnownSymbol alias, PGTyped schemas ty)
1037− => FieldTyped schemas (alias ::: ty) where
1038− fieldtype = pgtype `As` Alias
1042−-- >>> data Schwarma = Beef | Lamb | Chicken deriving GHC.Generic
1043−-- >>> instance SOP.Generic Schwarma
1044−-- >>> instance SOP.HasDatatypeInfo Schwarma
1045−-- >>> printSQL (dropType #schwarma :: Definition '["public" ::: '["schwarma" ::: 'Typedef (PG (Enumerated Schwarma))]] (Public '[]))
1046−-- DROP TYPE "schwarma";
1048− :: (Has sch schemas schema, Has td schema ('Typedef ty))
1049− => QualifiedAlias sch td
1050− -- ^ name of the user defined type
1051− -> Definition schemas (Alter sch (Drop td schema) schemas)
1052−dropType tydef = UnsafeDefinition $ "DROP" <+> "TYPE" <+> renderSQL tydef <> ";"
1054−-- | `ColumnTypeExpression`s are used in `createTable` commands.
1055−newtype ColumnTypeExpression (schemas :: SchemasType) (ty :: ColumnType)
1056− = UnsafeColumnTypeExpression { renderColumnTypeExpression :: ByteString }
1057− deriving (GHC.Generic,Show,Eq,Ord,NFData)
1058−instance RenderSQL (ColumnTypeExpression schemas ty) where
1059− renderSQL = renderColumnTypeExpression
1061−-- | used in `createTable` commands as a column constraint to note that
1062−-- @NULL@ may be present in a column
1064− :: TypeExpression schemas (nullity ty)
1065− -> ColumnTypeExpression schemas ('NoDef :=> 'Null ty)
1066−nullable ty = UnsafeColumnTypeExpression $ renderSQL ty <+> "NULL"
1068−-- | used in `createTable` commands as a column constraint to ensure
1069−-- @NULL@ is not present in a column
1071− :: TypeExpression schemas (nullity ty)
1072− -> ColumnTypeExpression schemas ('NoDef :=> 'NotNull ty)
1073−notNullable ty = UnsafeColumnTypeExpression $ renderSQL ty <+> "NOT NULL"
1075−-- | used in `createTable` commands as a column constraint to give a default
1077− :: Expression '[] '[] 'Ungrouped schemas '[] '[] ty
1078− -> ColumnTypeExpression schemas ('NoDef :=> ty)
1079− -> ColumnTypeExpression schemas ('Def :=> ty)
1080−default_ x ty = UnsafeColumnTypeExpression $
1081− renderSQL ty <+> "DEFAULT" <+> renderExpression x
1083−-- | not a true type, but merely a notational convenience for creating
1084−-- unique identifier columns with type `PGint2`
1085−serial2, smallserial
1086− :: ColumnTypeExpression schemas ('Def :=> 'NotNull 'PGint2)
1087−serial2 = UnsafeColumnTypeExpression "serial2"
1088−smallserial = UnsafeColumnTypeExpression "smallserial"
1089−-- | not a true type, but merely a notational convenience for creating
1090−-- unique identifier columns with type `PGint4`
1092− :: ColumnTypeExpression schemas ('Def :=> 'NotNull 'PGint4)
1093−serial4 = UnsafeColumnTypeExpression "serial4"
1094−serial = UnsafeColumnTypeExpression "serial"
1095−-- | not a true type, but merely a notational convenience for creating
1096−-- unique identifier columns with type `PGint8`
1098− :: ColumnTypeExpression schemas ('Def :=> 'NotNull 'PGint8)
1099−serial8 = UnsafeColumnTypeExpression "serial8"
1100−bigserial = UnsafeColumnTypeExpression "bigserial"