@@ -19,6 +19,7 @@ Squeal data definition language.
20 , LambdaCase
20 , LambdaCase
21 , MultiParamTypeClasses
21 , MultiParamTypeClasses
22 , OverloadedStrings
23 , OverloadedStrings
23 , RankNTypes
24 , RankNTypes
24 , ScopedTypeVariables
25 , ScopedTypeVariables
@@ -26,6 +27,7 @@ Squeal data definition language.
26 , TypeInType
27 , TypeInType
27 , TypeOperators
28 , TypeOperators
28 , UndecidableSuperClasses
29 , UndecidableSuperClasses
30+ , UndecidableInstances
31module Squeal.PostgreSQL.Definition
33module Squeal.PostgreSQL.Definition
@@ -33,82 +35,16 @@ module Squeal.PostgreSQL.Definition
33 Definition (..)
35 Definition (..)
35 , manipDefinition
37 , manipDefinition
39− , createSchemaIfNotExists
41− , createTableIfNotExists
45− , createTypeComposite
46− , createTypeCompositeFrom
51− , TableConstraintExpression (..)
57− , OnDeleteClause (..)
58− , OnUpdateClause (..)
82− , ColumnTypeExpression (..)
94import Control.Category
40import Control.Category
95import Control.DeepSeq
41import Control.DeepSeq
96import Data.ByteString
42import Data.ByteString
97import Data.Monoid
43import Data.Monoid
99import Prelude hiding ((.), id)
44import Prelude hiding ((.), id)
101−import qualified Generics.SOP as SOP
102import qualified GHC.Generics as GHC
46import qualified GHC.Generics as GHC
104−import Squeal.PostgreSQL.Alias
105−import Squeal.PostgreSQL.Expression
106−import Squeal.PostgreSQL.Expression.Logic
107−import Squeal.PostgreSQL.Expression.Sort
108−import Squeal.PostgreSQL.Expression.Type
109−import Squeal.PostgreSQL.List
110−import Squeal.PostgreSQL.PG
111−import Squeal.PostgreSQL.Query
112import Squeal.PostgreSQL.Manipulation
48import Squeal.PostgreSQL.Manipulation
113import Squeal.PostgreSQL.Render
49import Squeal.PostgreSQL.Render
114import Squeal.PostgreSQL.Schema
50import Squeal.PostgreSQL.Schema
@@ -144,1049 +80,3 @@ manipDefinition
144 -- ^ no input or output
80 -- ^ no input or output
145 -> Definition schemas schemas
81 -> Definition schemas schemas
146manipDefinition = UnsafeDefinition . (<> ";") . renderSQL
82manipDefinition = UnsafeDefinition . (<> ";") . renderSQL
148−{-----------------------------------------
150−-----------------------------------------}
153−`createSchema` enters a new schema into the current database.
154−The schema name must be distinct from the name of any existing schema
155−in the current database.
157−A schema is essentially a namespace: it contains named objects
158−(tables, data types, functions, and operators) whose names
159−can duplicate those of other objects existing in other schemas.
160−Named objects are accessed by `QualifiedAlias`es with the schema
166− -> Definition schemas (Create sch '[] schemas)
167−createSchema sch = UnsafeDefinition $
168− "CREATE" <+> "SCHEMA" <+> renderSQL sch <> ";"
170−{- | Idempotent version of `createSchema`. -}
171−createSchemaIfNotExists
172− :: (KnownSymbol sch, Has sch schemas schema)
174− -> Definition schemas schemas
175−createSchemaIfNotExists sch = UnsafeDefinition $
176− "CREATE" <+> "SCHEMA" <+> "IF" <+> "NOT" <+> "EXISTS"
177− <+> renderSQL sch <> ";"
179−{- | `createTable` adds a table to the schema.
181−>>> :set -XOverloadedLabels
184− '[ "a" ::: 'NoDef :=> 'Null 'PGint4
185− , "b" ::: 'NoDef :=> 'Null 'PGfloat4 ]
190− setup :: Definition (Public '[]) (Public '["tab" ::: 'Table Table])
191− setup = createTable #tab
192− (nullable int `as` #a :* nullable real `as` #b) Nil
195−CREATE TABLE "tab" ("a" int NULL, "b" real NULL);
198− :: ( KnownSymbol sch
200− , columns ~ (col ': cols)
201− , SOP.SListI columns
202− , SOP.SListI constraints
203− , Has sch schemas0 schema0
204− , schemas1 ~ Alter sch (Create tab ('Table (constraints :=> columns)) schema0) schemas0 )
205− => QualifiedAlias sch tab -- ^ the name of the table to add
206− -> NP (Aliased (ColumnTypeExpression schemas0)) columns
207− -- ^ the names and datatype of each column
208− -> NP (Aliased (TableConstraintExpression sch tab schemas1)) constraints
209− -- ^ constraints that must hold for the table
210− -> Definition schemas0 schemas1
211−createTable tab columns constraints = UnsafeDefinition $
212− "CREATE TABLE" <+> renderCreation tab columns constraints
214−{-| `createTableIfNotExists` creates a table if it doesn't exist, but does not add it to the schema.
215−Instead, the schema already has the table so if the table did not yet exist, the schema was wrong.
216−`createTableIfNotExists` fixes this. Interestingly, this property makes it an idempotent in
217−the `Category` of `Definition`s.
219−>>> :set -XOverloadedLabels -XTypeApplications
222− '[ "a" ::: 'NoDef :=> 'Null 'PGint4
223− , "b" ::: 'NoDef :=> 'Null 'PGfloat4 ]
226−>>> type Schemas = Public '["tab" ::: 'Table Table]
230− setup :: Definition Schemas Schemas
231− setup = createTableIfNotExists #tab
232− (nullable int `as` #a :* nullable real `as` #b) Nil
235−CREATE TABLE IF NOT EXISTS "tab" ("a" int NULL, "b" real NULL);
237−createTableIfNotExists
238− :: ( Has sch schemas schema
239− , Has tab schema ('Table (constraints :=> columns))
240− , SOP.SListI columns
241− , SOP.SListI constraints )
242− => QualifiedAlias sch tab -- ^ the name of the table to add
243− -> NP (Aliased (ColumnTypeExpression schemas)) columns
244− -- ^ the names and datatype of each column
245− -> NP (Aliased (TableConstraintExpression sch tab schemas)) constraints
246− -- ^ constraints that must hold for the table
247− -> Definition schemas schemas
248−createTableIfNotExists tab columns constraints = UnsafeDefinition $
249− "CREATE TABLE IF NOT EXISTS"
250− <+> renderCreation tab columns constraints
252−-- helper function for `createTable` and `createTableIfNotExists`
254− :: ( KnownSymbol sch
256− , SOP.SListI columns
257− , SOP.SListI constraints )
258− => QualifiedAlias sch tab -- ^ the name of the table to add
259− -> NP (Aliased (ColumnTypeExpression schemas0)) columns
260− -- ^ the names and datatype of each column
261− -> NP (Aliased (TableConstraintExpression sch tab schemas1)) constraints
262− -- ^ constraints that must hold for the table
264−renderCreation tab columns constraints = renderSQL tab
266− ( renderCommaSeparated renderColumnDef columns
267− <> ( case constraints of
270− renderCommaSeparated renderConstraint constraints ) )
273− renderColumnDef :: Aliased (ColumnTypeExpression schemas) x -> ByteString
274− renderColumnDef (ty `As` column) =
275− renderSQL column <+> renderColumnTypeExpression ty
277− :: Aliased (TableConstraintExpression sch tab schemas) constraint
279− renderConstraint (constraint `As` alias) =
280− "CONSTRAINT" <+> renderSQL alias <+> renderSQL constraint
282−-- | Data types are a way to limit the kind of data that can be stored in a
283−-- table. For many applications, however, the constraint they provide is
284−-- too coarse. For example, a column containing a product price should
285−-- probably only accept positive values. But there is no standard data type
286−-- that accepts only positive numbers. Another issue is that you might want
287−-- to constrain column data with respect to other columns or rows.
288−-- For example, in a table containing product information,
289−-- there should be only one row for each product number.
290−-- `TableConstraint`s give you as much control over the data in your tables
291−-- as you wish. If a user attempts to store data in a column that would
292−-- violate a constraint, an error is raised. This applies
293−-- even if the value came from the default value definition.
294−newtype TableConstraintExpression
297− (schemas :: SchemasType)
298− (constraint :: TableConstraint)
299− = UnsafeTableConstraintExpression
300− { renderTableConstraintExpression :: ByteString }
301− deriving (GHC.Generic,Show,Eq,Ord,NFData)
303− (TableConstraintExpression sch tab schemas constraint) where
304− renderSQL = renderTableConstraintExpression
306−{-| A `check` constraint is the most generic `TableConstraint` type.
307−It allows you to specify that the value in a certain column must satisfy
308−a Boolean (truth-value) expression.
312− "tab" ::: 'Table ('[ "inequality" ::: 'Check '["a","b"]] :=> '[
313− "a" ::: 'NoDef :=> 'NotNull 'PGint4,
314− "b" ::: 'NoDef :=> 'NotNull 'PGint4
320− definition :: Definition (Public '[]) (Public Schema)
321− definition = createTable #tab
322− ( (int & notNullable) `as` #a :*
323− (int & notNullable) `as` #b )
324− ( check (#a :* #b) (#a .> #b) `as` #inequality )
327−>>> printSQL definition
328−CREATE TABLE "tab" ("a" int NOT NULL, "b" int NOT NULL, CONSTRAINT "inequality" CHECK (("a" > "b")));
331− :: ( Has sch schemas schema
332− , Has tab schema ('Table table)
333− , HasAll aliases (TableToRow table) subcolumns )
335− -- ^ specify the subcolumns which are getting checked
336− -> (forall t. Condition '[] '[] 'Ungrouped schemas '[] '[t ::: subcolumns])
337− -- ^ a closed `Condition` on those subcolumns
338− -> TableConstraintExpression sch tab schemas ('Check aliases)
339−check _cols condition = UnsafeTableConstraintExpression $
340− "CHECK" <+> parenthesized (renderSQL condition)
342−{-| A `unique` constraint ensure that the data contained in a column,
343−or a group of columns, is unique among all the rows in the table.
347− "tab" ::: 'Table( '[ "uq_a_b" ::: 'Unique '["a","b"]] :=> '[
348− "a" ::: 'NoDef :=> 'Null 'PGint4,
349− "b" ::: 'NoDef :=> 'Null 'PGint4
355− definition :: Definition (Public '[]) (Public Schema)
356− definition = createTable #tab
357− ( (int & nullable) `as` #a :*
358− (int & nullable) `as` #b )
359− ( unique (#a :* #b) `as` #uq_a_b )
362−>>> printSQL definition
363−CREATE TABLE "tab" ("a" int NULL, "b" int NULL, CONSTRAINT "uq_a_b" UNIQUE ("a", "b"));
366− :: ( Has sch schemas schema
367− , Has tab schema('Table table)
368− , HasAll aliases (TableToRow table) subcolumns )
370− -- ^ specify subcolumns which together are unique for each row
371− -> TableConstraintExpression sch tab schemas ('Unique aliases)
372−unique columns = UnsafeTableConstraintExpression $
373− "UNIQUE" <+> parenthesized (renderSQL columns)
375−{-| A `primaryKey` constraint indicates that a column, or group of columns,
376−can be used as a unique identifier for rows in the table.
377−This requires that the values be both unique and not null.
381− "tab" ::: 'Table ('[ "pk_id" ::: 'PrimaryKey '["id"]] :=> '[
382− "id" ::: 'Def :=> 'NotNull 'PGint4,
383− "name" ::: 'NoDef :=> 'NotNull 'PGtext
389− definition :: Definition (Public '[]) (Public Schema)
390− definition = createTable #tab
391− ( serial `as` #id :*
392− (text & notNullable) `as` #name )
393− ( primaryKey #id `as` #pk_id )
396−>>> printSQL definition
397−CREATE TABLE "tab" ("id" serial, "name" text NOT NULL, CONSTRAINT "pk_id" PRIMARY KEY ("id"));
400− :: ( Has sch schemas schema
401− , Has tab schema ('Table table)
402− , HasAll aliases (TableToColumns table) subcolumns
403− , AllNotNull subcolumns )
405− -- ^ specify the subcolumns which together form a primary key.
406− -> TableConstraintExpression sch tab schemas ('PrimaryKey aliases)
407−primaryKey columns = UnsafeTableConstraintExpression $
408− "PRIMARY KEY" <+> parenthesized (renderSQL columns)
410−{-| A `foreignKey` specifies that the values in a column
411−(or a group of columns) must match the values appearing in some row of
412−another table. We say this maintains the referential integrity
413−between two related tables.
417− '[ "users" ::: 'Table (
418− '[ "pk_users" ::: 'PrimaryKey '["id"] ] :=>
419− '[ "id" ::: 'Def :=> 'NotNull 'PGint4
420− , "name" ::: 'NoDef :=> 'NotNull 'PGtext
422− , "emails" ::: 'Table (
423− '[ "pk_emails" ::: 'PrimaryKey '["id"]
424− , "fk_user_id" ::: 'ForeignKey '["user_id"] "users" '["id"]
426− '[ "id" ::: 'Def :=> 'NotNull 'PGint4
427− , "user_id" ::: 'NoDef :=> 'NotNull 'PGint4
428− , "email" ::: 'NoDef :=> 'Null 'PGtext
435− setup :: Definition (Public '[]) (Public Schema)
438− ( serial `as` #id :*
439− (text & notNullable) `as` #name )
440− ( primaryKey #id `as` #pk_users ) >>>
442− ( serial `as` #id :*
443− (int & notNullable) `as` #user_id :*
444− (text & nullable) `as` #email )
445− ( primaryKey #id `as` #pk_emails :*
446− foreignKey #user_id #users #id
447− OnDeleteCascade OnUpdateCascade `as` #fk_user_id )
450−CREATE TABLE "users" ("id" serial, "name" text NOT NULL, CONSTRAINT "pk_users" PRIMARY KEY ("id"));
451−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);
453−A `foreignKey` can even be a table self-reference.
457− '[ "employees" ::: 'Table (
458− '[ "employees_pk" ::: 'PrimaryKey '["id"]
459− , "employees_employer_fk" ::: 'ForeignKey '["employer_id"] "employees" '["id"]
461− '[ "id" ::: 'Def :=> 'NotNull 'PGint4
462− , "name" ::: 'NoDef :=> 'NotNull 'PGtext
463− , "employer_id" ::: 'NoDef :=> 'Null 'PGint4
470− setup :: Definition (Public '[]) (Public Schema)
472− createTable #employees
473− ( serial `as` #id :*
474− (text & notNullable) `as` #name :*
475− (integer & nullable) `as` #employer_id )
476− ( primaryKey #id `as` #employees_pk :*
477− foreignKey #employer_id #employees #id
478− OnDeleteCascade OnUpdateCascade `as` #employees_employer_fk )
481−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);
484− :: (ForeignKeyed schemas sch schema child parent
490− -- ^ column or columns in the table
492− -- ^ reference table
493− -> NP Alias refcolumns
494− -- ^ reference column or columns in the reference table
496− -- ^ what to do when reference is deleted
498− -- ^ what to do when reference is updated
499− -> TableConstraintExpression sch child schemas
500− ('ForeignKey columns parent refcolumns)
501−foreignKey keys parent refs ondel onupd = UnsafeTableConstraintExpression $
502− "FOREIGN KEY" <+> parenthesized (renderSQL keys)
503− <+> "REFERENCES" <+> renderSQL parent
504− <+> parenthesized (renderSQL refs)
508−-- | A constraint synonym between types involved in a foreign key constraint.
509−type ForeignKeyed schemas
517− ( Has sch schemas schema
518− , Has child schema ('Table table)
519− , Has parent schema ('Table reftable)
520− , HasAll columns (TableToColumns table) tys
521− , reftable ~ (constraints :=> cols)
522− , HasAll refcolumns cols reftys
523− , SOP.AllZip SamePGType tys reftys
524− , Uniquely refcolumns constraints )
526−-- | `OnDeleteClause` indicates what to do with rows that reference a deleted row.
529− -- ^ if any referencing rows still exist when the constraint is checked,
530− -- an error is raised
531− | OnDeleteRestrict -- ^ prevents deletion of a referenced row
533− -- ^ specifies that when a referenced row is deleted,
534− -- row(s) referencing it should be automatically deleted as well
535− deriving (GHC.Generic,Show,Eq,Ord)
536−instance NFData OnDeleteClause
537−-- | Render `OnDeleteClause`.
538−instance RenderSQL OnDeleteClause where
540− OnDeleteNoAction -> "ON DELETE NO ACTION"
541− OnDeleteRestrict -> "ON DELETE RESTRICT"
542− OnDeleteCascade -> "ON DELETE CASCADE"
544−-- | Analagous to `OnDeleteClause` there is also `OnUpdateClause` which is invoked
545−-- when a referenced column is changed (updated).
548− -- ^ if any referencing rows has not changed when the constraint is checked,
549− -- an error is raised
550− | OnUpdateRestrict -- ^ prevents update of a referenced row
552− -- ^ the updated values of the referenced column(s) should be copied
553− -- into the referencing row(s)
554− deriving (GHC.Generic,Show,Eq,Ord)
555−instance NFData OnUpdateClause
557−-- | Render `OnUpdateClause`.
558−instance RenderSQL OnUpdateClause where
560− OnUpdateNoAction -> "ON UPDATE NO ACTION"
561− OnUpdateRestrict -> "ON UPDATE RESTRICT"
562− OnUpdateCascade -> "ON UPDATE CASCADE"
564−{-----------------------------------------
566−-----------------------------------------}
570−-- definition :: Definition '["muh_schema" ::: schema, "public" ::: public] '["public" ::: public]
571−-- definition = dropSchema #muh_schema
574−-- >>> printSQL definition
575−-- DROP SCHEMA "muh_schema";
577− :: Has sch schemas schema
579− -> Definition schemas (Drop sch schemas)
580−dropSchema sch = UnsafeDefinition $ "DROP SCHEMA" <+> renderSQL sch <> ";"
582−-- | `dropTable` removes a table from the schema.
586−-- definition :: Definition '["public" ::: '["muh_table" ::: 'Table t]] (Public '[])
587−-- definition = dropTable #muh_table
590−-- >>> printSQL definition
591−-- DROP TABLE "muh_table";
593− :: ( Has sch schemas schema
594− , Has tab schema ('Table table))
595− => QualifiedAlias sch tab -- ^ table to remove
596− -> Definition schemas (Alter sch (Drop tab schema) schemas)
597−dropTable tab = UnsafeDefinition $ "DROP TABLE" <+> renderSQL tab <> ";"
599−{-----------------------------------------
601−-----------------------------------------}
603−-- | `alterTable` changes the definition of a table from the schema.
605− :: (Has sch schemas schema, Has tab schema ('Table table0))
606− => QualifiedAlias sch tab -- ^ table to alter
607− -> AlterTable sch tab schemas table1 -- ^ alteration to perform
608− -> Definition schemas (Alter sch (Alter tab ('Table table1) schema) schemas)
609−alterTable tab alteration = UnsafeDefinition $
612− <+> renderAlterTable alteration
615−-- | `alterTableRename` changes the name of a table from the schema.
617−-- >>> printSQL $ alterTableRename #foo #bar
618−-- ALTER TABLE "foo" RENAME TO "bar";
620− :: (KnownSymbol table0, KnownSymbol table1)
621− => Alias table0 -- ^ table to rename
622− -> Alias table1 -- ^ what to rename it
623− -> Definition schema (Rename table0 table1 schema)
624−alterTableRename table0 table1 = UnsafeDefinition $
625− "ALTER TABLE" <+> renderSQL table0
626− <+> "RENAME TO" <+> renderSQL table1 <> ";"
628−-- | An `AlterTable` describes the alteration to perform on the columns
633− (schemas :: SchemasType)
634− (table :: TableType) =
635− UnsafeAlterTable {renderAlterTable :: ByteString}
636− deriving (GHC.Generic,Show,Eq,Ord,NFData)
638−-- | An `addConstraint` adds a table constraint.
642−-- definition :: Definition
643−-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'NotNull 'PGint4])]]
644−-- '["public" ::: '["tab" ::: 'Table ('["positive" ::: 'Check '["col"]] :=> '["col" ::: 'NoDef :=> 'NotNull 'PGint4])]]
645−-- definition = alterTable #tab (addConstraint #positive (check #col (#col .> 0)))
646−-- in printSQL definition
648−-- ALTER TABLE "tab" ADD CONSTRAINT "positive" CHECK (("col" > 0));
650− :: ( KnownSymbol alias
651− , Has sch schemas schema
652− , Has tab schema ('Table table0)
653− , table0 ~ (constraints :=> columns)
654− , table1 ~ (Create alias constraint constraints :=> columns) )
656− -> TableConstraintExpression sch tab schemas constraint
657− -- ^ constraint to add
658− -> AlterTable sch tab schemas table1
659−addConstraint alias constraint = UnsafeAlterTable $
660− "ADD" <+> "CONSTRAINT" <+> renderSQL alias
661− <+> renderSQL constraint
663−-- | A `dropConstraint` drops a table constraint.
667−-- definition :: Definition
668−-- '["public" ::: '["tab" ::: 'Table ('["positive" ::: Check '["col"]] :=> '["col" ::: 'NoDef :=> 'NotNull 'PGint4])]]
669−-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'NotNull 'PGint4])]]
670−-- definition = alterTable #tab (dropConstraint #positive)
671−-- in printSQL definition
673−-- ALTER TABLE "tab" DROP CONSTRAINT "positive";
675− :: ( KnownSymbol constraint
676− , Has sch schemas schema
677− , Has tab schema ('Table table0)
678− , table0 ~ (constraints :=> columns)
679− , table1 ~ (Drop constraint constraints :=> columns) )
681− -- ^ constraint to drop
682− -> AlterTable sch tab schemas table1
683−dropConstraint constraint = UnsafeAlterTable $
684− "DROP" <+> "CONSTRAINT" <+> renderSQL constraint
686−-- | An `AddColumn` is either @NULL@ or has @DEFAULT@.
687−class AddColumn ty where
688− -- | `addColumn` adds a new column, initially filled with whatever
689− -- default value is given or with @NULL@.
693− -- definition :: Definition
694− -- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col1" ::: 'NoDef :=> 'Null 'PGint4])]]
695− -- '["public" ::: '["tab" ::: 'Table ('[] :=>
696− -- '[ "col1" ::: 'NoDef :=> 'Null 'PGint4
697− -- , "col2" ::: 'Def :=> 'Null 'PGtext ])]]
698− -- definition = alterTable #tab (addColumn #col2 (text & nullable & default_ "foo"))
699− -- in printSQL definition
701− -- ALTER TABLE "tab" ADD COLUMN "col2" text NULL DEFAULT E'foo';
705− -- definition :: Definition
706− -- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col1" ::: 'NoDef :=> 'Null 'PGint4])]]
707− -- '["public" ::: '["tab" ::: 'Table ('[] :=>
708− -- '[ "col1" ::: 'NoDef :=> 'Null 'PGint4
709− -- , "col2" ::: 'NoDef :=> 'Null 'PGtext ])]]
710− -- definition = alterTable #tab (addColumn #col2 (text & nullable))
711− -- in printSQL definition
713− -- ALTER TABLE "tab" ADD COLUMN "col2" text NULL;
715− :: ( KnownSymbol column
716− , Has sch schemas schema
717− , Has tab schema ('Table table0)
718− , table0 ~ (constraints :=> columns) )
719− => Alias column -- ^ column to add
720− -> ColumnTypeExpression schemas ty -- ^ type of the new column
721− -> AlterTable sch tab schemas (constraints :=> Create column ty columns)
722− addColumn column ty = UnsafeAlterTable $
723− "ADD COLUMN" <+> renderSQL column <+> renderColumnTypeExpression ty
724−instance {-# OVERLAPPING #-} AddColumn ('Def :=> ty)
725−instance {-# OVERLAPPABLE #-} AddColumn ('NoDef :=> 'Null ty)
727−-- | A `dropColumn` removes a column. Whatever data was in the column
728−-- disappears. Table constraints involving the column are dropped, too.
729−-- However, if the column is referenced by a foreign key constraint of
730−-- another table, PostgreSQL will not silently drop that constraint.
734−-- definition :: Definition
735−-- '["public" ::: '["tab" ::: 'Table ('[] :=>
736−-- '[ "col1" ::: 'NoDef :=> 'Null 'PGint4
737−-- , "col2" ::: 'NoDef :=> 'Null 'PGtext ])]]
738−-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col1" ::: 'NoDef :=> 'Null 'PGint4])]]
739−-- definition = alterTable #tab (dropColumn #col2)
740−-- in printSQL definition
742−-- ALTER TABLE "tab" DROP COLUMN "col2";
744− :: ( KnownSymbol column
745− , Has sch schemas schema
746− , Has tab schema ('Table table0)
747− , table0 ~ (constraints :=> columns)
748− , table1 ~ (constraints :=> Drop column columns) )
749− => Alias column -- ^ column to remove
750− -> AlterTable sch tab schemas table1
751−dropColumn column = UnsafeAlterTable $
752− "DROP COLUMN" <+> renderSQL column
754−-- | A `renameColumn` renames a column.
758−-- definition :: Definition
759−-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["foo" ::: 'NoDef :=> 'Null 'PGint4])]]
760−-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["bar" ::: 'NoDef :=> 'Null 'PGint4])]]
761−-- definition = alterTable #tab (renameColumn #foo #bar)
762−-- in printSQL definition
764−-- ALTER TABLE "tab" RENAME COLUMN "foo" TO "bar";
766− :: ( KnownSymbol column0
767− , KnownSymbol column1
768− , Has sch schemas schema
769− , Has tab schema ('Table table0)
770− , table0 ~ (constraints :=> columns)
771− , table1 ~ (constraints :=> Rename column0 column1 columns) )
772− => Alias column0 -- ^ column to rename
773− -> Alias column1 -- ^ what to rename the column
774− -> AlterTable sch tab schemas table1
775−renameColumn column0 column1 = UnsafeAlterTable $
776− "RENAME COLUMN" <+> renderSQL column0 <+> "TO" <+> renderSQL column1
778−-- | An `alterColumn` alters a single column.
780− :: ( KnownSymbol column
781− , Has sch schemas schema
782− , Has tab schema ('Table table0)
783− , table0 ~ (constraints :=> columns)
784− , Has column columns ty0
785− , table1 ~ (constraints :=> Alter column ty1 columns))
786− => Alias column -- ^ column to alter
787− -> AlterColumn schemas ty0 ty1 -- ^ alteration to perform
788− -> AlterTable sch tab schemas table1
789−alterColumn column alteration = UnsafeAlterTable $
790− "ALTER COLUMN" <+> renderSQL column <+> renderAlterColumn alteration
792−-- | An `AlterColumn` describes the alteration to perform on a single column.
793−newtype AlterColumn (schemas :: SchemasType) (ty0 :: ColumnType) (ty1 :: ColumnType) =
794− UnsafeAlterColumn {renderAlterColumn :: ByteString}
795− deriving (GHC.Generic,Show,Eq,Ord,NFData)
797−-- | A `setDefault` sets a new default for a column. Note that this doesn't
798−-- affect any existing rows in the table, it just changes the default for
799−-- future insert and update commands.
803−-- definition :: Definition
804−-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'Null 'PGint4])]]
805−-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col" ::: 'Def :=> 'Null 'PGint4])]]
806−-- definition = alterTable #tab (alterColumn #col (setDefault 5))
807−-- in printSQL definition
809−-- ALTER TABLE "tab" ALTER COLUMN "col" SET DEFAULT 5;
811− :: Expression '[] '[] 'Ungrouped schemas '[] '[] ty -- ^ default value to set
812− -> AlterColumn schemas (constraint :=> ty) ('Def :=> ty)
813−setDefault expression = UnsafeAlterColumn $
814− "SET DEFAULT" <+> renderExpression expression
816−-- | A `dropDefault` removes any default value for a column.
820−-- definition :: Definition
821−-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col" ::: 'Def :=> 'Null 'PGint4])]]
822−-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'Null 'PGint4])]]
823−-- definition = alterTable #tab (alterColumn #col dropDefault)
824−-- in printSQL definition
826−-- ALTER TABLE "tab" ALTER COLUMN "col" DROP DEFAULT;
827−dropDefault :: AlterColumn schemas ('Def :=> ty) ('NoDef :=> ty)
828−dropDefault = UnsafeAlterColumn $ "DROP DEFAULT"
830−-- | A `setNotNull` adds a @NOT NULL@ constraint to a column.
831−-- The constraint will be checked immediately, so the table data must satisfy
832−-- the constraint before it can be added.
836−-- definition :: Definition
837−-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'Null 'PGint4])]]
838−-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'NotNull 'PGint4])]]
839−-- definition = alterTable #tab (alterColumn #col setNotNull)
840−-- in printSQL definition
842−-- ALTER TABLE "tab" ALTER COLUMN "col" SET NOT NULL;
844− :: AlterColumn schemas (constraint :=> 'Null ty) (constraint :=> 'NotNull ty)
845−setNotNull = UnsafeAlterColumn $ "SET NOT NULL"
847−-- | A `dropNotNull` drops a @NOT NULL@ constraint from a column.
851−-- definition :: Definition
852−-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'NotNull 'PGint4])]]
853−-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'Null 'PGint4])]]
854−-- definition = alterTable #tab (alterColumn #col dropNotNull)
855−-- in printSQL definition
857−-- ALTER TABLE "tab" ALTER COLUMN "col" DROP NOT NULL;
859− :: AlterColumn schemas (constraint :=> 'NotNull ty) (constraint :=> 'Null ty)
860−dropNotNull = UnsafeAlterColumn $ "DROP NOT NULL"
862−-- | An `alterType` converts a column to a different data type.
863−-- This will succeed only if each existing entry in the column can be
864−-- converted to the new type by an implicit cast.
868−-- definition :: Definition
869−-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'NotNull 'PGint4])]]
870−-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'NotNull 'PGnumeric])]]
872−-- alterTable #tab (alterColumn #col (alterType (numeric & notNullable)))
873−-- in printSQL definition
875−-- ALTER TABLE "tab" ALTER COLUMN "col" TYPE numeric NOT NULL;
876−alterType :: ColumnTypeExpression schemas ty -> AlterColumn schemas ty0 ty
877−alterType ty = UnsafeAlterColumn $ "TYPE" <+> renderColumnTypeExpression ty
880−>>> type ABC = '["a" ::: 'NoDef :=> 'Null 'PGint4, "b" ::: 'NoDef :=> 'Null 'PGint4, "c" ::: 'NoDef :=> 'Null 'PGint4]
881−>>> type BC = '["b" ::: 'Null 'PGint4, "c" ::: 'Null 'PGint4]
884− definition :: Definition
885− '[ "public" ::: '["abc" ::: 'Table ('[] :=> ABC)]]
886− '[ "public" ::: '["abc" ::: 'Table ('[] :=> ABC), "bc" ::: 'View BC]]
888− createView #bc (select_ (#b :* #c) (from (table #abc)))
889−in printSQL definition
891−CREATE VIEW "bc" AS SELECT "b" AS "b", "c" AS "c" FROM "abc" AS "abc";
894− :: (KnownSymbol sch, KnownSymbol vw, Has sch schemas schema)
895− => QualifiedAlias sch vw -- ^ the name of the view to add
896− -> Query '[] '[] schemas '[] view -- ^ query
897− -> Definition schemas (Alter sch (Create vw ('View view) schema) schemas)
898−createView alias query = UnsafeDefinition $
899− "CREATE" <+> "VIEW" <+> renderSQL alias <+> "AS"
900− <+> renderQuery query <> ";"
906−-- definition :: Definition
907−-- '[ "public" ::: '["abc" ::: 'Table ('[] :=> '["a" ::: 'NoDef :=> 'Null 'PGint4, "b" ::: 'NoDef :=> 'Null 'PGint4, "c" ::: 'NoDef :=> 'Null 'PGint4])
908−-- , "bc" ::: 'View ('["b" ::: 'Null 'PGint4, "c" ::: 'Null 'PGint4])]]
909−-- '[ "public" ::: '["abc" ::: 'Table ('[] :=> '["a" ::: 'NoDef :=> 'Null 'PGint4, "b" ::: 'NoDef :=> 'Null 'PGint4, "c" ::: 'NoDef :=> 'Null 'PGint4])]]
910−-- definition = dropView #bc
911−-- in printSQL definition
915− :: (Has sch schemas schema, Has vw schema ('View view))
916− => QualifiedAlias sch vw -- ^ view to remove
917− -> Definition schemas (Alter sch (Drop vw schema) schemas)
918−dropView vw = UnsafeDefinition $ "DROP VIEW" <+> renderSQL vw <> ";"
920−-- | Enumerated types are created using the `createTypeEnum` command, for example
922−-- >>> printSQL $ (createTypeEnum #mood (label @"sad" :* label @"ok" :* label @"happy") :: Definition (Public '[]) '["public" ::: '["mood" ::: 'Typedef ('PGenum '["sad","ok","happy"])]])
923−-- CREATE TYPE "mood" AS ENUM ('sad', 'ok', 'happy');
925− :: (KnownSymbol enum, Has sch schemas schema, SOP.All KnownSymbol labels)
926− => QualifiedAlias sch enum
927− -- ^ name of the user defined enumerated type
928− -> NP PGlabel labels
929− -- ^ labels of the enumerated type
930− -> Definition schemas (Alter sch (Create enum ('Typedef ('PGenum labels)) schema) schemas)
931−createTypeEnum enum labels = UnsafeDefinition $
932− "CREATE" <+> "TYPE" <+> renderSQL enum <+> "AS" <+> "ENUM" <+>
933− parenthesized (renderSQL labels) <> ";"
935−-- | Enumerated types can also be generated from a Haskell type, for example
937−-- >>> data Schwarma = Beef | Lamb | Chicken deriving GHC.Generic
938−-- >>> instance SOP.Generic Schwarma
939−-- >>> instance SOP.HasDatatypeInfo Schwarma
942−-- createSchwarma :: Definition (Public '[]) '["public" ::: '["schwarma" ::: 'Typedef (PG (Enumerated Schwarma))]]
943−-- createSchwarma = createTypeEnumFrom @Schwarma #schwarma
945−-- printSQL createSchwarma
947−-- CREATE TYPE "schwarma" AS ENUM ('Beef', 'Lamb', 'Chicken');
949− :: forall hask sch enum schemas schema.
951− , SOP.All KnownSymbol (LabelsPG hask)
953− , Has sch schemas schema )
954− => QualifiedAlias sch enum
955− -- ^ name of the user defined enumerated type
956− -> Definition schemas (Alter sch (Create enum ('Typedef (PG (Enumerated hask))) schema) schemas)
957−createTypeEnumFrom enum = createTypeEnum enum
958− (SOP.hpure label :: NP PGlabel (LabelsPG hask))
960−{- | `createTypeComposite` creates a composite type. The composite type is
961−specified by a list of attribute names and data types.
964−type PGcomplex = 'PGcomposite
965− '[ "real" ::: 'NotNull 'PGfloat8
966− , "imaginary" ::: 'NotNull 'PGfloat8 ]
971− setup :: Definition (Public '[]) '["public" ::: '["complex" ::: 'Typedef PGcomplex]]
972− setup = createTypeComposite #complex
973− (float8 `as` #real :* float8 `as` #imaginary)
976−CREATE TYPE "complex" AS ("real" float8, "imaginary" float8);
979− :: (KnownSymbol ty, Has sch schemas schema, SOP.SListI fields)
980− => QualifiedAlias sch ty
981− -- ^ name of the user defined composite type
982− -> NP (Aliased (TypeExpression schemas)) fields
983− -- ^ list of attribute names and data types
984− -> Definition schemas (Alter sch (Create ty ('Typedef ('PGcomposite fields)) schema) schemas)
985−createTypeComposite ty fields = UnsafeDefinition $
986− "CREATE" <+> "TYPE" <+> renderSQL ty <+> "AS" <+> parenthesized
987− (renderCommaSeparated renderField fields) <> ";"
989− renderField :: Aliased (TypeExpression schemas) x -> ByteString
990− renderField (typ `As` alias) =
991− renderSQL alias <+> renderSQL typ
993−-- | Composite types can also be generated from a Haskell type, for example
995−-- >>> data Complex = Complex {real :: Double, imaginary :: Double} deriving GHC.Generic
996−-- >>> instance SOP.Generic Complex
997−-- >>> instance SOP.HasDatatypeInfo Complex
998−-- >>> type Schema = '["complex" ::: 'Typedef (PG (Composite Complex))]
1001−-- createComplex :: Definition (Public '[]) (Public Schema)
1002−-- createComplex = createTypeCompositeFrom @Complex #complex
1004−-- printSQL createComplex
1006−-- CREATE TYPE "complex" AS ("real" float8, "imaginary" float8);
1007−createTypeCompositeFrom
1008− :: forall hask sch ty schemas schema.
1009− ( SOP.All (FieldTyped schemas) (RowPG hask)
1011− , Has sch schemas schema )
1012− => QualifiedAlias sch ty
1013− -- ^ name of the user defined composite type
1014− -> Definition schemas (Alter sch (Create ty ( 'Typedef (PG (Composite hask))) schema) schemas)
1015−createTypeCompositeFrom ty = createTypeComposite ty
1016− (SOP.hcpure (SOP.Proxy :: SOP.Proxy (FieldTyped schemas)) fieldtype
1017− :: NP (Aliased (TypeExpression schemas)) (RowPG hask))
1020−`createDomain` creates a new domain. A domain is essentially a data type
1021−with constraints (restrictions on the allowed set of values).
1023−Domains are useful for abstracting common constraints on fields
1024−into a single location for maintenance. For example, several tables might
1025−contain email address columns, all requiring the same `check` constraint
1026−to verify the address syntax. Define a domain rather than setting up
1027−each table's constraint individually.
1031− createPositive :: Definition (Public '[]) (Public '["positive" ::: 'Typedef 'PGfloat4])
1032− createPositive = createDomain #positive real (#value .> 0 .&& (#value & isNotNull))
1033−in printSQL createPositive
1035−CREATE DOMAIN "positive" AS real CHECK ((("value" > 0) AND "value" IS NOT NULL));
1038− :: (Has sch schemas schema, KnownSymbol dom)
1039− => QualifiedAlias sch dom
1040− -> (forall null. TypeExpression schemas (null ty))
1041− -> (forall tab. Condition '[] '[] 'Ungrouped schemas '[] '[tab ::: '["value" ::: 'Null ty]])
1042− -> Definition schemas (Alter sch (Create dom ('Typedef ty) schema) schemas)
1043−createDomain dom ty condition =
1044− UnsafeDefinition $ "CREATE DOMAIN" <+> renderSQL dom
1045− <+> "AS" <+> renderTypeExpression ty
1046− <+> "CHECK" <+> parenthesized (renderSQL condition) <> ";"
1051− createSmallIntRange :: Definition (Public '[]) (Public '["int2range" ::: 'Typedef ('PGrange 'PGint2)])
1052− createSmallIntRange = createTypeRange #int2range int2
1053−in printSQL createSmallIntRange
1055−CREATE TYPE "int2range" AS RANGE (subtype = int2);
1058− :: (Has sch schemas schema, KnownSymbol range)
1059− => QualifiedAlias sch range
1060− -> (forall null. TypeExpression schemas (null ty))
1061− -> Definition schemas (Alter sch (Create range ('Typedef ('PGrange ty)) schema) schemas)
1062−createTypeRange range ty = UnsafeDefinition $
1063− "CREATE" <+> "TYPE" <+> renderSQL range <+> "AS" <+> "RANGE" <+>
1064− parenthesized ("subtype" <+> "=" <+> renderTypeExpression ty) <> ";"
1068−type Table = '[] :=>
1069− '[ "a" ::: 'NoDef :=> 'Null 'PGint4
1070− , "b" ::: 'NoDef :=> 'Null 'PGfloat4 ]
1075− setup :: Definition (Public '[]) (Public '["tab" ::: 'Table Table, "ix" ::: 'Index])
1077− createTable #tab (nullable int `as` #a :* nullable real `as` #b) Nil >>>
1078− createIndex #ix #tab Gin [#a & AscNullsFirst, #b & AscNullsLast]
1081−CREATE TABLE "tab" ("a" int NULL, "b" real NULL);
1082−CREATE INDEX "ix" ON "tab" USING gin (("a" ASC NULLS FIRST), ("b" ASC NULLS LAST));
1085− :: (Has sch schemas schema, Has tab schema ('Table table), KnownSymbol ix)
1087− -> QualifiedAlias sch tab
1089− -> [SortExpression '[] '[] 'Ungrouped schemas '[] '[tab ::: TableToRow table]]
1090− -> Definition schemas (Alter sch (Create ix 'Index schema) schemas)
1091−createIndex ix tab method cols = UnsafeDefinition $
1092− "CREATE" <+> "INDEX" <+> renderSQL ix <+> "ON" <+> renderSQL tab
1093− <+> "USING" <+> renderSQL method
1094− <+> parenthesized (commaSeparated (parenthesized . renderSQL <$> cols))
1104− deriving stock (Eq, Ord, Show, GHC.Generic)
1105− deriving anyclass (SOP.HasDatatypeInfo, SOP.Generic)
1106−instance RenderSQL IndexMethod where
1116−-- >>> printSQL (dropIndex #ix :: Definition (Public '["ix" ::: 'Index]) (Public '[]))
1119− :: (Has sch schemas schema, Has ix schema 'Index)
1120− => QualifiedAlias sch ix
1121− -- ^ name of the user defined type
1122− -> Definition schemas (Alter sch (Drop ix schema) schemas)
1123−dropIndex ix = UnsafeDefinition $ "DROP" <+> "INDEX" <+> renderSQL ix <> ";"
1125−-- | Lift `PGTyped` to a field
1126−class FieldTyped schemas ty where
1127− fieldtype :: Aliased (TypeExpression schemas) ty
1128−instance (KnownSymbol alias, PGTyped schemas ty)
1129− => FieldTyped schemas (alias ::: ty) where
1130− fieldtype = pgtype `As` Alias
1134−-- >>> data Schwarma = Beef | Lamb | Chicken deriving GHC.Generic
1135−-- >>> instance SOP.Generic Schwarma
1136−-- >>> instance SOP.HasDatatypeInfo Schwarma
1137−-- >>> printSQL (dropType #schwarma :: Definition '["public" ::: '["schwarma" ::: 'Typedef (PG (Enumerated Schwarma))]] (Public '[]))
1138−-- DROP TYPE "schwarma";
1140− :: (Has sch schemas schema, Has td schema ('Typedef ty))
1141− => QualifiedAlias sch td
1142− -- ^ name of the user defined type
1143− -> Definition schemas (Alter sch (Drop td schema) schemas)
1144−dropType tydef = UnsafeDefinition $ "DROP" <+> "TYPE" <+> renderSQL tydef <> ";"
1146−-- | `ColumnTypeExpression`s are used in `createTable` commands.
1147−newtype ColumnTypeExpression (schemas :: SchemasType) (ty :: ColumnType)
1148− = UnsafeColumnTypeExpression { renderColumnTypeExpression :: ByteString }
1149− deriving (GHC.Generic,Show,Eq,Ord,NFData)
1150−instance RenderSQL (ColumnTypeExpression schemas ty) where
1151− renderSQL = renderColumnTypeExpression
1153−-- | used in `createTable` commands as a column constraint to note that
1154−-- @NULL@ may be present in a column
1156− :: TypeExpression schemas (nullity ty)
1157− -> ColumnTypeExpression schemas ('NoDef :=> 'Null ty)
1158−nullable ty = UnsafeColumnTypeExpression $ renderSQL ty <+> "NULL"
1160−-- | used in `createTable` commands as a column constraint to ensure
1161−-- @NULL@ is not present in a column
1163− :: TypeExpression schemas (nullity ty)
1164− -> ColumnTypeExpression schemas ('NoDef :=> 'NotNull ty)
1165−notNullable ty = UnsafeColumnTypeExpression $ renderSQL ty <+> "NOT NULL"
1167−-- | used in `createTable` commands as a column constraint to give a default
1169− :: Expression '[] '[] 'Ungrouped schemas '[] '[] ty
1170− -> ColumnTypeExpression schemas ('NoDef :=> ty)
1171− -> ColumnTypeExpression schemas ('Def :=> ty)
1172−default_ x ty = UnsafeColumnTypeExpression $
1173− renderSQL ty <+> "DEFAULT" <+> renderExpression x
1175−-- | not a true type, but merely a notational convenience for creating
1176−-- unique identifier columns with type `PGint2`
1177−serial2, smallserial
1178− :: ColumnTypeExpression schemas ('Def :=> 'NotNull 'PGint2)
1179−serial2 = UnsafeColumnTypeExpression "serial2"
1180−smallserial = UnsafeColumnTypeExpression "smallserial"
1181−-- | not a true type, but merely a notational convenience for creating
1182−-- unique identifier columns with type `PGint4`
1184− :: ColumnTypeExpression schemas ('Def :=> 'NotNull 'PGint4)
1185−serial4 = UnsafeColumnTypeExpression "serial4"
1186−serial = UnsafeColumnTypeExpression "serial"
1187−-- | not a true type, but merely a notational convenience for creating
1188−-- unique identifier columns with type `PGint8`
1190− :: ColumnTypeExpression schemas ('Def :=> 'NotNull 'PGint8)
1191−serial8 = UnsafeColumnTypeExpression "serial8"
1192−bigserial = UnsafeColumnTypeExpression "bigserial"