@@ -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,84 +35,16 @@ module Squeal.PostgreSQL.Definition
33 Definition (..)
35 Definition (..)
35 , manipDefinition
37 , manipDefinition
39− , createSchemaIfNotExists
41− , createTableIfNotExists
45− , createTypeComposite
46− , createTypeCompositeFrom
52− , TableConstraintExpression (..)
58− , OnDeleteClause (..)
59− , OnUpdateClause (..)
84− , ColumnTypeExpression (..)
96import Control.Category
40import Control.Category
97import Control.DeepSeq
41import Control.DeepSeq
98import Data.ByteString
42import Data.ByteString
99import Data.Monoid
43import Data.Monoid
101import Prelude hiding ((.), id)
44import Prelude hiding ((.), id)
103−import qualified Generics.SOP as SOP
104import qualified GHC.Generics as GHC
46import qualified GHC.Generics as GHC
106−import Squeal.PostgreSQL.Alias
107−import Squeal.PostgreSQL.Expression
108−import Squeal.PostgreSQL.Expression.Logic
109−import Squeal.PostgreSQL.Expression.Sort
110−import Squeal.PostgreSQL.Expression.Type
111−import Squeal.PostgreSQL.List
112−import Squeal.PostgreSQL.PG
113−import Squeal.PostgreSQL.Query
114import Squeal.PostgreSQL.Manipulation
48import Squeal.PostgreSQL.Manipulation
115import Squeal.PostgreSQL.Render
49import Squeal.PostgreSQL.Render
116import Squeal.PostgreSQL.Schema
50import Squeal.PostgreSQL.Schema
@@ -146,1074 +80,3 @@ manipDefinition
146 -- ^ no input or output
80 -- ^ no input or output
147 -> Definition schemas schemas
81 -> Definition schemas schemas
148manipDefinition = UnsafeDefinition . (<> ";") . renderSQL
82manipDefinition = UnsafeDefinition . (<> ";") . renderSQL
150−{-----------------------------------------
152−-----------------------------------------}
155−`createSchema` enters a new schema into the current database.
156−The schema name must be distinct from the name of any existing schema
157−in the current database.
159−A schema is essentially a namespace: it contains named objects
160−(tables, data types, functions, and operators) whose names
161−can duplicate those of other objects existing in other schemas.
162−Named objects are accessed by `QualifiedAlias`es with the schema
168− -> Definition schemas (Create sch '[] schemas)
169−createSchema sch = UnsafeDefinition $
170− "CREATE" <+> "SCHEMA" <+> renderSQL sch <> ";"
172−{- | Idempotent version of `createSchema`. -}
173−createSchemaIfNotExists
174− :: (KnownSymbol sch, Has sch schemas schema)
176− -> Definition schemas schemas
177−createSchemaIfNotExists sch = UnsafeDefinition $
178− "CREATE" <+> "SCHEMA" <+> "IF" <+> "NOT" <+> "EXISTS"
179− <+> renderSQL sch <> ";"
181−{- | `createTable` adds a table to the schema.
183−>>> :set -XOverloadedLabels
186− '[ "a" ::: 'NoDef :=> 'Null 'PGint4
187− , "b" ::: 'NoDef :=> 'Null 'PGfloat4 ]
192− setup :: Definition (Public '[]) (Public '["tab" ::: 'Table Table])
193− setup = createTable #tab
194− (nullable int `as` #a :* nullable real `as` #b) Nil
197−CREATE TABLE "tab" ("a" int NULL, "b" real NULL);
200− :: ( KnownSymbol sch
202− , columns ~ (col ': cols)
203− , SOP.SListI columns
204− , SOP.SListI constraints
205− , Has sch schemas0 schema0
206− , schemas1 ~ Alter sch (Create tab ('Table (constraints :=> columns)) schema0) schemas0 )
207− => QualifiedAlias sch tab -- ^ the name of the table to add
208− -> NP (Aliased (ColumnTypeExpression schemas0)) columns
209− -- ^ the names and datatype of each column
210− -> NP (Aliased (TableConstraintExpression sch tab schemas1)) constraints
211− -- ^ constraints that must hold for the table
212− -> Definition schemas0 schemas1
213−createTable tab columns constraints = UnsafeDefinition $
214− "CREATE TABLE" <+> renderCreation tab columns constraints
216−{-| `createTableIfNotExists` creates a table if it doesn't exist, but does not add it to the schema.
217−Instead, the schema already has the table so if the table did not yet exist, the schema was wrong.
218−`createTableIfNotExists` fixes this. Interestingly, this property makes it an idempotent in
219−the `Category` of `Definition`s.
221−>>> :set -XOverloadedLabels -XTypeApplications
224− '[ "a" ::: 'NoDef :=> 'Null 'PGint4
225− , "b" ::: 'NoDef :=> 'Null 'PGfloat4 ]
228−>>> type Schemas = Public '["tab" ::: 'Table Table]
232− setup :: Definition Schemas Schemas
233− setup = createTableIfNotExists #tab
234− (nullable int `as` #a :* nullable real `as` #b) Nil
237−CREATE TABLE IF NOT EXISTS "tab" ("a" int NULL, "b" real NULL);
239−createTableIfNotExists
240− :: ( Has sch schemas schema
241− , Has tab schema ('Table (constraints :=> columns))
242− , SOP.SListI columns
243− , SOP.SListI constraints )
244− => QualifiedAlias sch tab -- ^ the name of the table to add
245− -> NP (Aliased (ColumnTypeExpression schemas)) columns
246− -- ^ the names and datatype of each column
247− -> NP (Aliased (TableConstraintExpression sch tab schemas)) constraints
248− -- ^ constraints that must hold for the table
249− -> Definition schemas schemas
250−createTableIfNotExists tab columns constraints = UnsafeDefinition $
251− "CREATE TABLE IF NOT EXISTS"
252− <+> renderCreation tab columns constraints
254−-- helper function for `createTable` and `createTableIfNotExists`
256− :: ( KnownSymbol sch
258− , SOP.SListI columns
259− , SOP.SListI constraints )
260− => QualifiedAlias sch tab -- ^ the name of the table to add
261− -> NP (Aliased (ColumnTypeExpression schemas0)) columns
262− -- ^ the names and datatype of each column
263− -> NP (Aliased (TableConstraintExpression sch tab schemas1)) constraints
264− -- ^ constraints that must hold for the table
266−renderCreation tab columns constraints = renderSQL tab
268− ( renderCommaSeparated renderColumnDef columns
269− <> ( case constraints of
272− renderCommaSeparated renderConstraint constraints ) )
275− renderColumnDef :: Aliased (ColumnTypeExpression schemas) x -> ByteString
276− renderColumnDef (ty `As` column) =
277− renderSQL column <+> renderColumnTypeExpression ty
279− :: Aliased (TableConstraintExpression sch tab schemas) constraint
281− renderConstraint (constraint `As` alias) =
282− "CONSTRAINT" <+> renderSQL alias <+> renderSQL constraint
284−-- | Data types are a way to limit the kind of data that can be stored in a
285−-- table. For many applications, however, the constraint they provide is
286−-- too coarse. For example, a column containing a product price should
287−-- probably only accept positive values. But there is no standard data type
288−-- that accepts only positive numbers. Another issue is that you might want
289−-- to constrain column data with respect to other columns or rows.
290−-- For example, in a table containing product information,
291−-- there should be only one row for each product number.
292−-- `TableConstraint`s give you as much control over the data in your tables
293−-- as you wish. If a user attempts to store data in a column that would
294−-- violate a constraint, an error is raised. This applies
295−-- even if the value came from the default value definition.
296−newtype TableConstraintExpression
299− (schemas :: SchemasType)
300− (constraint :: TableConstraint)
301− = UnsafeTableConstraintExpression
302− { renderTableConstraintExpression :: ByteString }
303− deriving (GHC.Generic,Show,Eq,Ord,NFData)
305− (TableConstraintExpression sch tab schemas constraint) where
306− renderSQL = renderTableConstraintExpression
308−{-| A `check` constraint is the most generic `TableConstraint` type.
309−It allows you to specify that the value in a certain column must satisfy
310−a Boolean (truth-value) expression.
314− "tab" ::: 'Table ('[ "inequality" ::: 'Check '["a","b"]] :=> '[
315− "a" ::: 'NoDef :=> 'NotNull 'PGint4,
316− "b" ::: 'NoDef :=> 'NotNull 'PGint4
322− definition :: Definition (Public '[]) (Public Schema)
323− definition = createTable #tab
324− ( (int & notNullable) `as` #a :*
325− (int & notNullable) `as` #b )
326− ( check (#a :* #b) (#a .> #b) `as` #inequality )
329−>>> printSQL definition
330−CREATE TABLE "tab" ("a" int NOT NULL, "b" int NOT NULL, CONSTRAINT "inequality" CHECK (("a" > "b")));
333− :: ( Has sch schemas schema
334− , Has tab schema ('Table table)
335− , HasAll aliases (TableToRow table) subcolumns )
337− -- ^ specify the subcolumns which are getting checked
338− -> (forall t. Condition '[] '[] 'Ungrouped schemas '[] '[t ::: subcolumns])
339− -- ^ a closed `Condition` on those subcolumns
340− -> TableConstraintExpression sch tab schemas ('Check aliases)
341−check _cols condition = UnsafeTableConstraintExpression $
342− "CHECK" <+> parenthesized (renderSQL condition)
344−{-| A `unique` constraint ensure that the data contained in a column,
345−or a group of columns, is unique among all the rows in the table.
349− "tab" ::: 'Table( '[ "uq_a_b" ::: 'Unique '["a","b"]] :=> '[
350− "a" ::: 'NoDef :=> 'Null 'PGint4,
351− "b" ::: 'NoDef :=> 'Null 'PGint4
357− definition :: Definition (Public '[]) (Public Schema)
358− definition = createTable #tab
359− ( (int & nullable) `as` #a :*
360− (int & nullable) `as` #b )
361− ( unique (#a :* #b) `as` #uq_a_b )
364−>>> printSQL definition
365−CREATE TABLE "tab" ("a" int NULL, "b" int NULL, CONSTRAINT "uq_a_b" UNIQUE ("a", "b"));
368− :: ( Has sch schemas schema
369− , Has tab schema('Table table)
370− , HasAll aliases (TableToRow table) subcolumns )
372− -- ^ specify subcolumns which together are unique for each row
373− -> TableConstraintExpression sch tab schemas ('Unique aliases)
374−unique columns = UnsafeTableConstraintExpression $
375− "UNIQUE" <+> parenthesized (renderSQL columns)
377−{-| A `primaryKey` constraint indicates that a column, or group of columns,
378−can be used as a unique identifier for rows in the table.
379−This requires that the values be both unique and not null.
383− "tab" ::: 'Table ('[ "pk_id" ::: 'PrimaryKey '["id"]] :=> '[
384− "id" ::: 'Def :=> 'NotNull 'PGint4,
385− "name" ::: 'NoDef :=> 'NotNull 'PGtext
391− definition :: Definition (Public '[]) (Public Schema)
392− definition = createTable #tab
393− ( serial `as` #id :*
394− (text & notNullable) `as` #name )
395− ( primaryKey #id `as` #pk_id )
398−>>> printSQL definition
399−CREATE TABLE "tab" ("id" serial, "name" text NOT NULL, CONSTRAINT "pk_id" PRIMARY KEY ("id"));
402− :: ( Has sch schemas schema
403− , Has tab schema ('Table table)
404− , HasAll aliases (TableToColumns table) subcolumns
405− , AllNotNull subcolumns )
407− -- ^ specify the subcolumns which together form a primary key.
408− -> TableConstraintExpression sch tab schemas ('PrimaryKey aliases)
409−primaryKey columns = UnsafeTableConstraintExpression $
410− "PRIMARY KEY" <+> parenthesized (renderSQL columns)
412−{-| A `foreignKey` specifies that the values in a column
413−(or a group of columns) must match the values appearing in some row of
414−another table. We say this maintains the referential integrity
415−between two related tables.
419− '[ "users" ::: 'Table (
420− '[ "pk_users" ::: 'PrimaryKey '["id"] ] :=>
421− '[ "id" ::: 'Def :=> 'NotNull 'PGint4
422− , "name" ::: 'NoDef :=> 'NotNull 'PGtext
424− , "emails" ::: 'Table (
425− '[ "pk_emails" ::: 'PrimaryKey '["id"]
426− , "fk_user_id" ::: 'ForeignKey '["user_id"] "users" '["id"]
428− '[ "id" ::: 'Def :=> 'NotNull 'PGint4
429− , "user_id" ::: 'NoDef :=> 'NotNull 'PGint4
430− , "email" ::: 'NoDef :=> 'Null 'PGtext
437− setup :: Definition (Public '[]) (Public Schema)
440− ( serial `as` #id :*
441− (text & notNullable) `as` #name )
442− ( primaryKey #id `as` #pk_users ) >>>
444− ( serial `as` #id :*
445− (int & notNullable) `as` #user_id :*
446− (text & nullable) `as` #email )
447− ( primaryKey #id `as` #pk_emails :*
448− foreignKey #user_id #users #id
449− OnDeleteCascade OnUpdateCascade `as` #fk_user_id )
452−CREATE TABLE "users" ("id" serial, "name" text NOT NULL, CONSTRAINT "pk_users" PRIMARY KEY ("id"));
453−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);
455−A `foreignKey` can even be a table self-reference.
459− '[ "employees" ::: 'Table (
460− '[ "employees_pk" ::: 'PrimaryKey '["id"]
461− , "employees_employer_fk" ::: 'ForeignKey '["employer_id"] "employees" '["id"]
463− '[ "id" ::: 'Def :=> 'NotNull 'PGint4
464− , "name" ::: 'NoDef :=> 'NotNull 'PGtext
465− , "employer_id" ::: 'NoDef :=> 'Null 'PGint4
472− setup :: Definition (Public '[]) (Public Schema)
474− createTable #employees
475− ( serial `as` #id :*
476− (text & notNullable) `as` #name :*
477− (integer & nullable) `as` #employer_id )
478− ( primaryKey #id `as` #employees_pk :*
479− foreignKey #employer_id #employees #id
480− OnDeleteCascade OnUpdateCascade `as` #employees_employer_fk )
483−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);
486− :: (ForeignKeyed schemas sch schema child parent
492− -- ^ column or columns in the table
494− -- ^ reference table
495− -> NP Alias refcolumns
496− -- ^ reference column or columns in the reference table
498− -- ^ what to do when reference is deleted
500− -- ^ what to do when reference is updated
501− -> TableConstraintExpression sch child schemas
502− ('ForeignKey columns parent refcolumns)
503−foreignKey keys parent refs ondel onupd = UnsafeTableConstraintExpression $
504− "FOREIGN KEY" <+> parenthesized (renderSQL keys)
505− <+> "REFERENCES" <+> renderSQL parent
506− <+> parenthesized (renderSQL refs)
510−-- | A constraint synonym between types involved in a foreign key constraint.
511−type ForeignKeyed schemas
519− ( Has sch schemas schema
520− , Has child schema ('Table table)
521− , Has parent schema ('Table reftable)
522− , HasAll columns (TableToColumns table) tys
523− , reftable ~ (constraints :=> cols)
524− , HasAll refcolumns cols reftys
525− , SOP.AllZip SamePGType tys reftys
526− , Uniquely refcolumns constraints )
528−-- | `OnDeleteClause` indicates what to do with rows that reference a deleted row.
531− -- ^ if any referencing rows still exist when the constraint is checked,
532− -- an error is raised
533− | OnDeleteRestrict -- ^ prevents deletion of a referenced row
535− -- ^ specifies that when a referenced row is deleted,
536− -- row(s) referencing it should be automatically deleted as well
537− deriving (GHC.Generic,Show,Eq,Ord)
538−instance NFData OnDeleteClause
539−-- | Render `OnDeleteClause`.
540−instance RenderSQL OnDeleteClause where
542− OnDeleteNoAction -> "ON DELETE NO ACTION"
543− OnDeleteRestrict -> "ON DELETE RESTRICT"
544− OnDeleteCascade -> "ON DELETE CASCADE"
546−-- | Analagous to `OnDeleteClause` there is also `OnUpdateClause` which is invoked
547−-- when a referenced column is changed (updated).
550− -- ^ if any referencing rows has not changed when the constraint is checked,
551− -- an error is raised
552− | OnUpdateRestrict -- ^ prevents update of a referenced row
554− -- ^ the updated values of the referenced column(s) should be copied
555− -- into the referencing row(s)
556− deriving (GHC.Generic,Show,Eq,Ord)
557−instance NFData OnUpdateClause
559−-- | Render `OnUpdateClause`.
560−instance RenderSQL OnUpdateClause where
562− OnUpdateNoAction -> "ON UPDATE NO ACTION"
563− OnUpdateRestrict -> "ON UPDATE RESTRICT"
564− OnUpdateCascade -> "ON UPDATE CASCADE"
566−{-----------------------------------------
568−-----------------------------------------}
572−-- definition :: Definition '["muh_schema" ::: schema, "public" ::: public] '["public" ::: public]
573−-- definition = dropSchema #muh_schema
576−-- >>> printSQL definition
577−-- DROP SCHEMA "muh_schema";
579− :: Has sch schemas schema
581− -> Definition schemas (Drop sch schemas)
582−dropSchema sch = UnsafeDefinition $ "DROP SCHEMA" <+> renderSQL sch <> ";"
584−-- | `dropTable` removes a table from the schema.
588−-- definition :: Definition '["public" ::: '["muh_table" ::: 'Table t]] (Public '[])
589−-- definition = dropTable #muh_table
592−-- >>> printSQL definition
593−-- DROP TABLE "muh_table";
595− :: ( Has sch schemas schema
596− , Has tab schema ('Table table))
597− => QualifiedAlias sch tab -- ^ table to remove
598− -> Definition schemas (Alter sch (Drop tab schema) schemas)
599−dropTable tab = UnsafeDefinition $ "DROP TABLE" <+> renderSQL tab <> ";"
601−{-----------------------------------------
603−-----------------------------------------}
605−-- | `alterTable` changes the definition of a table from the schema.
607− :: (Has sch schemas schema, Has tab schema ('Table table0))
608− => QualifiedAlias sch tab -- ^ table to alter
609− -> AlterTable sch tab schemas table1 -- ^ alteration to perform
610− -> Definition schemas (Alter sch (Alter tab ('Table table1) schema) schemas)
611−alterTable tab alteration = UnsafeDefinition $
614− <+> renderAlterTable alteration
617−-- | `alterTableRename` changes the name of a table from the schema.
619−-- >>> printSQL $ alterTableRename #foo #bar
620−-- ALTER TABLE "foo" RENAME TO "bar";
622− :: (KnownSymbol table0, KnownSymbol table1)
623− => Alias table0 -- ^ table to rename
624− -> Alias table1 -- ^ what to rename it
625− -> Definition schema (Rename table0 table1 schema)
626−alterTableRename table0 table1 = UnsafeDefinition $
627− "ALTER TABLE" <+> renderSQL table0
628− <+> "RENAME TO" <+> renderSQL table1 <> ";"
630−-- | An `AlterTable` describes the alteration to perform on the columns
635− (schemas :: SchemasType)
636− (table :: TableType) =
637− UnsafeAlterTable {renderAlterTable :: ByteString}
638− deriving (GHC.Generic,Show,Eq,Ord,NFData)
640−-- | An `addConstraint` adds a table constraint.
644−-- definition :: Definition
645−-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'NotNull 'PGint4])]]
646−-- '["public" ::: '["tab" ::: 'Table ('["positive" ::: 'Check '["col"]] :=> '["col" ::: 'NoDef :=> 'NotNull 'PGint4])]]
647−-- definition = alterTable #tab (addConstraint #positive (check #col (#col .> 0)))
648−-- in printSQL definition
650−-- ALTER TABLE "tab" ADD CONSTRAINT "positive" CHECK (("col" > 0));
652− :: ( KnownSymbol alias
653− , Has sch schemas schema
654− , Has tab schema ('Table table0)
655− , table0 ~ (constraints :=> columns)
656− , table1 ~ (Create alias constraint constraints :=> columns) )
658− -> TableConstraintExpression sch tab schemas constraint
659− -- ^ constraint to add
660− -> AlterTable sch tab schemas table1
661−addConstraint alias constraint = UnsafeAlterTable $
662− "ADD" <+> "CONSTRAINT" <+> renderSQL alias
663− <+> renderSQL constraint
665−-- | A `dropConstraint` drops a table constraint.
669−-- definition :: Definition
670−-- '["public" ::: '["tab" ::: 'Table ('["positive" ::: Check '["col"]] :=> '["col" ::: 'NoDef :=> 'NotNull 'PGint4])]]
671−-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'NotNull 'PGint4])]]
672−-- definition = alterTable #tab (dropConstraint #positive)
673−-- in printSQL definition
675−-- ALTER TABLE "tab" DROP CONSTRAINT "positive";
677− :: ( KnownSymbol constraint
678− , Has sch schemas schema
679− , Has tab schema ('Table table0)
680− , table0 ~ (constraints :=> columns)
681− , table1 ~ (Drop constraint constraints :=> columns) )
683− -- ^ constraint to drop
684− -> AlterTable sch tab schemas table1
685−dropConstraint constraint = UnsafeAlterTable $
686− "DROP" <+> "CONSTRAINT" <+> renderSQL constraint
688−-- | An `AddColumn` is either @NULL@ or has @DEFAULT@.
689−class AddColumn ty where
690− -- | `addColumn` adds a new column, initially filled with whatever
691− -- default value is given or with @NULL@.
695− -- definition :: Definition
696− -- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col1" ::: 'NoDef :=> 'Null 'PGint4])]]
697− -- '["public" ::: '["tab" ::: 'Table ('[] :=>
698− -- '[ "col1" ::: 'NoDef :=> 'Null 'PGint4
699− -- , "col2" ::: 'Def :=> 'Null 'PGtext ])]]
700− -- definition = alterTable #tab (addColumn #col2 (text & nullable & default_ "foo"))
701− -- in printSQL definition
703− -- ALTER TABLE "tab" ADD COLUMN "col2" text NULL DEFAULT E'foo';
707− -- definition :: Definition
708− -- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col1" ::: 'NoDef :=> 'Null 'PGint4])]]
709− -- '["public" ::: '["tab" ::: 'Table ('[] :=>
710− -- '[ "col1" ::: 'NoDef :=> 'Null 'PGint4
711− -- , "col2" ::: 'NoDef :=> 'Null 'PGtext ])]]
712− -- definition = alterTable #tab (addColumn #col2 (text & nullable))
713− -- in printSQL definition
715− -- ALTER TABLE "tab" ADD COLUMN "col2" text NULL;
717− :: ( KnownSymbol column
718− , Has sch schemas schema
719− , Has tab schema ('Table table0)
720− , table0 ~ (constraints :=> columns) )
721− => Alias column -- ^ column to add
722− -> ColumnTypeExpression schemas ty -- ^ type of the new column
723− -> AlterTable sch tab schemas (constraints :=> Create column ty columns)
724− addColumn column ty = UnsafeAlterTable $
725− "ADD COLUMN" <+> renderSQL column <+> renderColumnTypeExpression ty
726−instance {-# OVERLAPPING #-} AddColumn ('Def :=> ty)
727−instance {-# OVERLAPPABLE #-} AddColumn ('NoDef :=> 'Null ty)
729−-- | A `dropColumn` removes a column. Whatever data was in the column
730−-- disappears. Table constraints involving the column are dropped, too.
731−-- However, if the column is referenced by a foreign key constraint of
732−-- another table, PostgreSQL will not silently drop that constraint.
736−-- definition :: Definition
737−-- '["public" ::: '["tab" ::: 'Table ('[] :=>
738−-- '[ "col1" ::: 'NoDef :=> 'Null 'PGint4
739−-- , "col2" ::: 'NoDef :=> 'Null 'PGtext ])]]
740−-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col1" ::: 'NoDef :=> 'Null 'PGint4])]]
741−-- definition = alterTable #tab (dropColumn #col2)
742−-- in printSQL definition
744−-- ALTER TABLE "tab" DROP COLUMN "col2";
746− :: ( KnownSymbol column
747− , Has sch schemas schema
748− , Has tab schema ('Table table0)
749− , table0 ~ (constraints :=> columns)
750− , table1 ~ (constraints :=> Drop column columns) )
751− => Alias column -- ^ column to remove
752− -> AlterTable sch tab schemas table1
753−dropColumn column = UnsafeAlterTable $
754− "DROP COLUMN" <+> renderSQL column
756−-- | A `renameColumn` renames a column.
760−-- definition :: Definition
761−-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["foo" ::: 'NoDef :=> 'Null 'PGint4])]]
762−-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["bar" ::: 'NoDef :=> 'Null 'PGint4])]]
763−-- definition = alterTable #tab (renameColumn #foo #bar)
764−-- in printSQL definition
766−-- ALTER TABLE "tab" RENAME COLUMN "foo" TO "bar";
768− :: ( KnownSymbol column0
769− , KnownSymbol column1
770− , Has sch schemas schema
771− , Has tab schema ('Table table0)
772− , table0 ~ (constraints :=> columns)
773− , table1 ~ (constraints :=> Rename column0 column1 columns) )
774− => Alias column0 -- ^ column to rename
775− -> Alias column1 -- ^ what to rename the column
776− -> AlterTable sch tab schemas table1
777−renameColumn column0 column1 = UnsafeAlterTable $
778− "RENAME COLUMN" <+> renderSQL column0 <+> "TO" <+> renderSQL column1
780−-- | An `alterColumn` alters a single column.
782− :: ( KnownSymbol column
783− , Has sch schemas schema
784− , Has tab schema ('Table table0)
785− , table0 ~ (constraints :=> columns)
786− , Has column columns ty0
787− , table1 ~ (constraints :=> Alter column ty1 columns))
788− => Alias column -- ^ column to alter
789− -> AlterColumn schemas ty0 ty1 -- ^ alteration to perform
790− -> AlterTable sch tab schemas table1
791−alterColumn column alteration = UnsafeAlterTable $
792− "ALTER COLUMN" <+> renderSQL column <+> renderAlterColumn alteration
794−-- | An `AlterColumn` describes the alteration to perform on a single column.
795−newtype AlterColumn (schemas :: SchemasType) (ty0 :: ColumnType) (ty1 :: ColumnType) =
796− UnsafeAlterColumn {renderAlterColumn :: ByteString}
797− deriving (GHC.Generic,Show,Eq,Ord,NFData)
799−-- | A `setDefault` sets a new default for a column. Note that this doesn't
800−-- affect any existing rows in the table, it just changes the default for
801−-- future insert and update commands.
805−-- definition :: Definition
806−-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'Null 'PGint4])]]
807−-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col" ::: 'Def :=> 'Null 'PGint4])]]
808−-- definition = alterTable #tab (alterColumn #col (setDefault 5))
809−-- in printSQL definition
811−-- ALTER TABLE "tab" ALTER COLUMN "col" SET DEFAULT 5;
813− :: Expression '[] '[] 'Ungrouped schemas '[] '[] ty -- ^ default value to set
814− -> AlterColumn schemas (constraint :=> ty) ('Def :=> ty)
815−setDefault expression = UnsafeAlterColumn $
816− "SET DEFAULT" <+> renderExpression expression
818−-- | A `dropDefault` removes any default value for a column.
822−-- definition :: Definition
823−-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col" ::: 'Def :=> 'Null 'PGint4])]]
824−-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'Null 'PGint4])]]
825−-- definition = alterTable #tab (alterColumn #col dropDefault)
826−-- in printSQL definition
828−-- ALTER TABLE "tab" ALTER COLUMN "col" DROP DEFAULT;
829−dropDefault :: AlterColumn schemas ('Def :=> ty) ('NoDef :=> ty)
830−dropDefault = UnsafeAlterColumn $ "DROP DEFAULT"
832−-- | A `setNotNull` adds a @NOT NULL@ constraint to a column.
833−-- The constraint will be checked immediately, so the table data must satisfy
834−-- the constraint before it can be added.
838−-- definition :: Definition
839−-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'Null 'PGint4])]]
840−-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'NotNull 'PGint4])]]
841−-- definition = alterTable #tab (alterColumn #col setNotNull)
842−-- in printSQL definition
844−-- ALTER TABLE "tab" ALTER COLUMN "col" SET NOT NULL;
846− :: AlterColumn schemas (constraint :=> 'Null ty) (constraint :=> 'NotNull ty)
847−setNotNull = UnsafeAlterColumn $ "SET NOT NULL"
849−-- | A `dropNotNull` drops a @NOT NULL@ constraint from a column.
853−-- definition :: Definition
854−-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'NotNull 'PGint4])]]
855−-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'Null 'PGint4])]]
856−-- definition = alterTable #tab (alterColumn #col dropNotNull)
857−-- in printSQL definition
859−-- ALTER TABLE "tab" ALTER COLUMN "col" DROP NOT NULL;
861− :: AlterColumn schemas (constraint :=> 'NotNull ty) (constraint :=> 'Null ty)
862−dropNotNull = UnsafeAlterColumn $ "DROP NOT NULL"
864−-- | An `alterType` converts a column to a different data type.
865−-- This will succeed only if each existing entry in the column can be
866−-- converted to the new type by an implicit cast.
870−-- definition :: Definition
871−-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'NotNull 'PGint4])]]
872−-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'NotNull 'PGnumeric])]]
874−-- alterTable #tab (alterColumn #col (alterType (numeric & notNullable)))
875−-- in printSQL definition
877−-- ALTER TABLE "tab" ALTER COLUMN "col" TYPE numeric NOT NULL;
878−alterType :: ColumnTypeExpression schemas ty -> AlterColumn schemas ty0 ty
879−alterType ty = UnsafeAlterColumn $ "TYPE" <+> renderColumnTypeExpression ty
882−>>> type ABC = '["a" ::: 'NoDef :=> 'Null 'PGint4, "b" ::: 'NoDef :=> 'Null 'PGint4, "c" ::: 'NoDef :=> 'Null 'PGint4]
883−>>> type BC = '["b" ::: 'Null 'PGint4, "c" ::: 'Null 'PGint4]
886− definition :: Definition
887− '[ "public" ::: '["abc" ::: 'Table ('[] :=> ABC)]]
888− '[ "public" ::: '["abc" ::: 'Table ('[] :=> ABC), "bc" ::: 'View BC]]
890− createView #bc (select_ (#b :* #c) (from (table #abc)))
891−in printSQL definition
893−CREATE VIEW "bc" AS SELECT "b" AS "b", "c" AS "c" FROM "abc" AS "abc";
896− :: (KnownSymbol sch, KnownSymbol vw, Has sch schemas schema)
897− => QualifiedAlias sch vw -- ^ the name of the view to add
898− -> Query '[] '[] schemas '[] view -- ^ query
899− -> Definition schemas (Alter sch (Create vw ('View view) schema) schemas)
900−createView alias query = UnsafeDefinition $
901− "CREATE" <+> "VIEW" <+> renderSQL alias <+> "AS"
902− <+> renderQuery query <> ";"
908−-- definition :: Definition
909−-- '[ "public" ::: '["abc" ::: 'Table ('[] :=> '["a" ::: 'NoDef :=> 'Null 'PGint4, "b" ::: 'NoDef :=> 'Null 'PGint4, "c" ::: 'NoDef :=> 'Null 'PGint4])
910−-- , "bc" ::: 'View ('["b" ::: 'Null 'PGint4, "c" ::: 'Null 'PGint4])]]
911−-- '[ "public" ::: '["abc" ::: 'Table ('[] :=> '["a" ::: 'NoDef :=> 'Null 'PGint4, "b" ::: 'NoDef :=> 'Null 'PGint4, "c" ::: 'NoDef :=> 'Null 'PGint4])]]
912−-- definition = dropView #bc
913−-- in printSQL definition
917− :: (Has sch schemas schema, Has vw schema ('View view))
918− => QualifiedAlias sch vw -- ^ view to remove
919− -> Definition schemas (Alter sch (Drop vw schema) schemas)
920−dropView vw = UnsafeDefinition $ "DROP VIEW" <+> renderSQL vw <> ";"
922−-- | Enumerated types are created using the `createTypeEnum` command, for example
924−-- >>> printSQL $ (createTypeEnum #mood (label @"sad" :* label @"ok" :* label @"happy") :: Definition (Public '[]) '["public" ::: '["mood" ::: 'Typedef ('PGenum '["sad","ok","happy"])]])
925−-- CREATE TYPE "mood" AS ENUM ('sad', 'ok', 'happy');
927− :: (KnownSymbol enum, Has sch schemas schema, SOP.All KnownSymbol labels)
928− => QualifiedAlias sch enum
929− -- ^ name of the user defined enumerated type
930− -> NP PGlabel labels
931− -- ^ labels of the enumerated type
932− -> Definition schemas (Alter sch (Create enum ('Typedef ('PGenum labels)) schema) schemas)
933−createTypeEnum enum labels = UnsafeDefinition $
934− "CREATE" <+> "TYPE" <+> renderSQL enum <+> "AS" <+> "ENUM" <+>
935− parenthesized (renderSQL labels) <> ";"
937−-- | Enumerated types can also be generated from a Haskell type, for example
939−-- >>> data Schwarma = Beef | Lamb | Chicken deriving GHC.Generic
940−-- >>> instance SOP.Generic Schwarma
941−-- >>> instance SOP.HasDatatypeInfo Schwarma
944−-- createSchwarma :: Definition (Public '[]) '["public" ::: '["schwarma" ::: 'Typedef (PG (Enumerated Schwarma))]]
945−-- createSchwarma = createTypeEnumFrom @Schwarma #schwarma
947−-- printSQL createSchwarma
949−-- CREATE TYPE "schwarma" AS ENUM ('Beef', 'Lamb', 'Chicken');
951− :: forall hask sch enum schemas schema.
953− , SOP.All KnownSymbol (LabelsPG hask)
955− , Has sch schemas schema )
956− => QualifiedAlias sch enum
957− -- ^ name of the user defined enumerated type
958− -> Definition schemas (Alter sch (Create enum ('Typedef (PG (Enumerated hask))) schema) schemas)
959−createTypeEnumFrom enum = createTypeEnum enum
960− (SOP.hpure label :: NP PGlabel (LabelsPG hask))
962−{- | `createTypeComposite` creates a composite type. The composite type is
963−specified by a list of attribute names and data types.
966−type PGcomplex = 'PGcomposite
967− '[ "real" ::: 'NotNull 'PGfloat8
968− , "imaginary" ::: 'NotNull 'PGfloat8 ]
973− setup :: Definition (Public '[]) '["public" ::: '["complex" ::: 'Typedef PGcomplex]]
974− setup = createTypeComposite #complex
975− (float8 `as` #real :* float8 `as` #imaginary)
978−CREATE TYPE "complex" AS ("real" float8, "imaginary" float8);
981− :: (KnownSymbol ty, Has sch schemas schema, SOP.SListI fields)
982− => QualifiedAlias sch ty
983− -- ^ name of the user defined composite type
984− -> NP (Aliased (TypeExpression schemas)) fields
985− -- ^ list of attribute names and data types
986− -> Definition schemas (Alter sch (Create ty ('Typedef ('PGcomposite fields)) schema) schemas)
987−createTypeComposite ty fields = UnsafeDefinition $
988− "CREATE" <+> "TYPE" <+> renderSQL ty <+> "AS" <+> parenthesized
989− (renderCommaSeparated renderField fields) <> ";"
991− renderField :: Aliased (TypeExpression schemas) x -> ByteString
992− renderField (typ `As` alias) =
993− renderSQL alias <+> renderSQL typ
995−-- | Composite types can also be generated from a Haskell type, for example
997−-- >>> data Complex = Complex {real :: Double, imaginary :: Double} deriving GHC.Generic
998−-- >>> instance SOP.Generic Complex
999−-- >>> instance SOP.HasDatatypeInfo Complex
1000−-- >>> type Schema = '["complex" ::: 'Typedef (PG (Composite Complex))]
1003−-- createComplex :: Definition (Public '[]) (Public Schema)
1004−-- createComplex = createTypeCompositeFrom @Complex #complex
1006−-- printSQL createComplex
1008−-- CREATE TYPE "complex" AS ("real" float8, "imaginary" float8);
1009−createTypeCompositeFrom
1010− :: forall hask sch ty schemas schema.
1011− ( SOP.All (FieldTyped schemas) (RowPG hask)
1013− , Has sch schemas schema )
1014− => QualifiedAlias sch ty
1015− -- ^ name of the user defined composite type
1016− -> Definition schemas (Alter sch (Create ty ( 'Typedef (PG (Composite hask))) schema) schemas)
1017−createTypeCompositeFrom ty = createTypeComposite ty
1018− (SOP.hcpure (SOP.Proxy :: SOP.Proxy (FieldTyped schemas)) fieldtype
1019− :: NP (Aliased (TypeExpression schemas)) (RowPG hask))
1022−`createDomain` creates a new domain. A domain is essentially a data type
1023−with constraints (restrictions on the allowed set of values).
1025−Domains are useful for abstracting common constraints on fields
1026−into a single location for maintenance. For example, several tables might
1027−contain email address columns, all requiring the same `check` constraint
1028−to verify the address syntax. Define a domain rather than setting up
1029−each table's constraint individually.
1033− createPositive :: Definition (Public '[]) (Public '["positive" ::: 'Typedef 'PGfloat4])
1034− createPositive = createDomain #positive real (#value .> 0 .&& (#value & isNotNull))
1035−in printSQL createPositive
1037−CREATE DOMAIN "positive" AS real CHECK ((("value" > 0) AND "value" IS NOT NULL));
1040− :: (Has sch schemas schema, KnownSymbol dom)
1041− => QualifiedAlias sch dom
1042− -> (forall null. TypeExpression schemas (null ty))
1043− -> (forall tab. Condition '[] '[] 'Ungrouped schemas '[] '[tab ::: '["value" ::: 'Null ty]])
1044− -> Definition schemas (Alter sch (Create dom ('Typedef ty) schema) schemas)
1045−createDomain dom ty condition =
1046− UnsafeDefinition $ "CREATE DOMAIN" <+> renderSQL dom
1047− <+> "AS" <+> renderTypeExpression ty
1048− <+> "CHECK" <+> parenthesized (renderSQL condition) <> ";"
1053− createSmallIntRange :: Definition (Public '[]) (Public '["int2range" ::: 'Typedef ('PGrange 'PGint2)])
1054− createSmallIntRange = createTypeRange #int2range int2
1055−in printSQL createSmallIntRange
1057−CREATE TYPE "int2range" AS RANGE (subtype = int2);
1060− :: (Has sch schemas schema, KnownSymbol range)
1061− => QualifiedAlias sch range
1062− -> (forall null. TypeExpression schemas (null ty))
1063− -> Definition schemas (Alter sch (Create range ('Typedef ('PGrange ty)) schema) schemas)
1064−createTypeRange range ty = UnsafeDefinition $
1065− "CREATE" <+> "TYPE" <+> renderSQL range <+> "AS" <+> "RANGE" <+>
1066− parenthesized ("subtype" <+> "=" <+> renderTypeExpression ty) <> ";"
1070−type Table = '[] :=>
1071− '[ "a" ::: 'NoDef :=> 'Null 'PGint4
1072− , "b" ::: 'NoDef :=> 'Null 'PGfloat4 ]
1077− setup :: Definition (Public '[]) (Public '["tab" ::: 'Table Table, "ix" ::: 'Index])
1079− createTable #tab (nullable int `as` #a :* nullable real `as` #b) Nil >>>
1080− createIndex #ix #tab Gin [#a & AscNullsFirst, #b & AscNullsLast]
1083−CREATE TABLE "tab" ("a" int NULL, "b" real NULL);
1084−CREATE INDEX "ix" ON "tab" USING gin (("a" ASC NULLS FIRST), ("b" ASC NULLS LAST));
1087− :: (Has sch schemas schema, Has tab schema ('Table table), KnownSymbol ix)
1089− -> QualifiedAlias sch tab
1091− -> [SortExpression '[] '[] 'Ungrouped schemas '[] '[tab ::: TableToRow table]]
1092− -> Definition schemas (Alter sch (Create ix 'Index schema) schemas)
1093−createIndex ix tab method cols = UnsafeDefinition $
1094− "CREATE" <+> "INDEX" <+> renderSQL ix <+> "ON" <+> renderSQL tab
1095− <+> "USING" <+> renderSQL method
1096− <+> parenthesized (commaSeparated (parenthesized . renderSQL <$> cols))
1106− deriving stock (Eq, Ord, Show, GHC.Generic)
1107− deriving anyclass (SOP.HasDatatypeInfo, SOP.Generic)
1108−instance RenderSQL IndexMethod where
1118− :: (Has sch schemas schema, KnownSymbol fun)
1119− => QualifiedAlias sch fun
1120− -> TypeExpression schemas arg
1121− -> TypeExpression schemas ret
1122− -> FunctionDefinition schemas arg ret
1123− -> Definition schemas (Alter sch (Create fun ('Function arg ret) schema) schemas)
1124−createFunction fun arg ret fundef = UnsafeDefinition $
1125− "CREATE" <+> "FUNCTION" <+> renderSQL fun <+> parenthesized (renderSQL arg)
1126− <+> "RETURNS" <+> renderSQL ret <+> renderSQL fundef <> ";"
1129− :: (Has sch schemas schema, Has fun schema ('Function arg ret))
1130− => QualifiedAlias sch fun
1131− -- ^ name of the user defined function
1132− -> Definition schemas (Alter sch (Drop ix schema) schemas)
1133−dropFunction fun = UnsafeDefinition $
1134− "DROP" <+> "Function" <+> renderSQL fun <> ";"
1136−newtype FunctionDefinition schemas arg ret = UnsafeFunctionDefinition
1137− { renderFunctionDefinition :: ByteString }
1138− deriving (Eq,Show,GHC.Generic,NFData)
1139−instance RenderSQL (FunctionDefinition schemas arg ret) where
1140− renderSQL = renderFunctionDefinition
1143−-- >>> printSQL (dropIndex #ix :: Definition (Public '["ix" ::: 'Index]) (Public '[]))
1146− :: (Has sch schemas schema, Has ix schema 'Index)
1147− => QualifiedAlias sch ix
1148− -- ^ name of the user defined index
1149− -> Definition schemas (Alter sch (Drop ix schema) schemas)
1150−dropIndex ix = UnsafeDefinition $ "DROP" <+> "INDEX" <+> renderSQL ix <> ";"
1152−-- | Lift `PGTyped` to a field
1153−class FieldTyped schemas ty where
1154− fieldtype :: Aliased (TypeExpression schemas) ty
1155−instance (KnownSymbol alias, PGTyped schemas ty)
1156− => FieldTyped schemas (alias ::: ty) where
1157− fieldtype = pgtype `As` Alias
1161−-- >>> data Schwarma = Beef | Lamb | Chicken deriving GHC.Generic
1162−-- >>> instance SOP.Generic Schwarma
1163−-- >>> instance SOP.HasDatatypeInfo Schwarma
1164−-- >>> printSQL (dropType #schwarma :: Definition '["public" ::: '["schwarma" ::: 'Typedef (PG (Enumerated Schwarma))]] (Public '[]))
1165−-- DROP TYPE "schwarma";
1167− :: (Has sch schemas schema, Has td schema ('Typedef ty))
1168− => QualifiedAlias sch td
1169− -- ^ name of the user defined type
1170− -> Definition schemas (Alter sch (Drop td schema) schemas)
1171−dropType tydef = UnsafeDefinition $ "DROP" <+> "TYPE" <+> renderSQL tydef <> ";"
1173−-- | `ColumnTypeExpression`s are used in `createTable` commands.
1174−newtype ColumnTypeExpression (schemas :: SchemasType) (ty :: ColumnType)
1175− = UnsafeColumnTypeExpression { renderColumnTypeExpression :: ByteString }
1176− deriving (GHC.Generic,Show,Eq,Ord,NFData)
1177−instance RenderSQL (ColumnTypeExpression schemas ty) where
1178− renderSQL = renderColumnTypeExpression
1180−-- | used in `createTable` commands as a column constraint to note that
1181−-- @NULL@ may be present in a column
1183− :: TypeExpression schemas (nullity ty)
1184− -> ColumnTypeExpression schemas ('NoDef :=> 'Null ty)
1185−nullable ty = UnsafeColumnTypeExpression $ renderSQL ty <+> "NULL"
1187−-- | used in `createTable` commands as a column constraint to ensure
1188−-- @NULL@ is not present in a column
1190− :: TypeExpression schemas (nullity ty)
1191− -> ColumnTypeExpression schemas ('NoDef :=> 'NotNull ty)
1192−notNullable ty = UnsafeColumnTypeExpression $ renderSQL ty <+> "NOT NULL"
1194−-- | used in `createTable` commands as a column constraint to give a default
1196− :: Expression '[] '[] 'Ungrouped schemas '[] '[] ty
1197− -> ColumnTypeExpression schemas ('NoDef :=> ty)
1198− -> ColumnTypeExpression schemas ('Def :=> ty)
1199−default_ x ty = UnsafeColumnTypeExpression $
1200− renderSQL ty <+> "DEFAULT" <+> renderExpression x
1202−-- | not a true type, but merely a notational convenience for creating
1203−-- unique identifier columns with type `PGint2`
1204−serial2, smallserial
1205− :: ColumnTypeExpression schemas ('Def :=> 'NotNull 'PGint2)
1206−serial2 = UnsafeColumnTypeExpression "serial2"
1207−smallserial = UnsafeColumnTypeExpression "smallserial"
1208−-- | not a true type, but merely a notational convenience for creating
1209−-- unique identifier columns with type `PGint4`
1211− :: ColumnTypeExpression schemas ('Def :=> 'NotNull 'PGint4)
1212−serial4 = UnsafeColumnTypeExpression "serial4"
1213−serial = UnsafeColumnTypeExpression "serial"
1214−-- | not a true type, but merely a notational convenience for creating
1215−-- unique identifier columns with type `PGint8`
1217− :: ColumnTypeExpression schemas ('Def :=> 'NotNull 'PGint8)
1218−serial8 = UnsafeColumnTypeExpression "serial8"
1219−bigserial = UnsafeColumnTypeExpression "bigserial"