@@ -11,15 +11,13 @@ Squeal data definition language.
1111{-# LANGUAGE
1212 AllowAmbiguousTypes
1313 , ConstraintKinds
14− , DeriveAnyClass
1514 , DeriveGeneric
16− , DerivingStrategies
1715 , FlexibleContexts
1816 , FlexibleInstances
1917 , GADTs
18+ , GeneralizedNewtypeDeriving
2019 , LambdaCase
2120 , MultiParamTypeClasses
22− , OverloadedLabels
2321 , OverloadedStrings
2422 , RankNTypes
2523 , ScopedTypeVariables
@@ -27,25 +25,83 @@ Squeal data definition language.
2725 , TypeInType
2826 , TypeOperators
2927 , UndecidableSuperClasses
30− , UndecidableInstances
3128#-}
3229
3330module Squeal.PostgreSQL.Definition
3431 ( -- * Definition
3532 Definition (..)
3633 , (>>>)
37− , manipDefinition
34+ -- * Tables
35+ -- ** Create
36+ , createSchema
37+ , createSchemaIfNotExists
38+ , createTable
39+ , createTableIfNotExists
40+ , createView
41+ , createTypeEnum
42+ , createTypeEnumFrom
43+ , createTypeComposite
44+ , createTypeCompositeFrom
45+ , createDomain
46+ , TableConstraintExpression (..)
47+ , check
48+ , unique
49+ , primaryKey
50+ , foreignKey
51+ , ForeignKeyed
52+ , OnDeleteClause (..)
53+ , OnUpdateClause (..)
54+ -- ** Drop
55+ , dropSchema
56+ , dropTable
57+ , dropView
58+ , dropType
59+ -- ** Alter
60+ , alterTable
61+ , alterTableRename
62+ , AlterTable (..)
63+ , addConstraint
64+ , dropConstraint
65+ , AddColumn (..)
66+ , dropColumn
67+ , renameColumn
68+ , alterColumn
69+ , AlterColumn (..)
70+ , setDefault
71+ , dropDefault
72+ , setNotNull
73+ , dropNotNull
74+ , alterType
75+ -- * Columns
76+ , ColumnTypeExpression (..)
77+ , nullable
78+ , notNullable
79+ , default_
80+ , serial2
81+ , smallserial
82+ , serial4
83+ , serial
84+ , serial8
85+ , bigserial
3886 ) where
3987
4088import Control.Category
4189import Control.DeepSeq
4290import Data.ByteString
4391import Data.Monoid
92+import GHC.TypeLits
4493import Prelude hiding ((.), id)
4594
95+import qualified Generics.SOP as SOP
4696import qualified GHC.Generics as GHC
4797
48−import Squeal.PostgreSQL.Manipulation
98+import Squeal.PostgreSQL.Alias
99+import Squeal.PostgreSQL.Expression
100+import Squeal.PostgreSQL.Expression.Logic
101+import Squeal.PostgreSQL.Expression.Type
102+import Squeal.PostgreSQL.List
103+import Squeal.PostgreSQL.PG
104+import Squeal.PostgreSQL.Query
49105import Squeal.PostgreSQL.Render
50106import Squeal.PostgreSQL.Schema
51107
@@ -73,10 +129,970 @@ instance Category Definition where
73129 ddl1 . ddl0 = UnsafeDefinition $
74130 renderSQL ddl0 <> "\n" <> renderSQL ddl1
75131
76−-- | A `Manipulation` without input or output can be run as a statement
77−-- along with other `Definition`s, by embedding it using `manipDefinition`.
78−manipDefinition
79− :: Manipulation '[] schemas '[] '[]
80− -- ^ no input or output
132+{-----------------------------------------
133+CREATE statements
134+-----------------------------------------}
135+
136+{- |
137+`createSchema` enters a new schema into the current database.
138+The schema name must be distinct from the name of any existing schema
139+in the current database.
140+
141+A schema is essentially a namespace: it contains named objects
142+(tables, data types, functions, and operators) whose names
143+can duplicate those of other objects existing in other schemas.
144+Named objects are accessed by `QualifiedAlias`es with the schema
145+name as a prefix.
146+-}
147+createSchema
148+ :: KnownSymbol sch
149+ => Alias sch
150+ -> Definition schemas (Create sch '[] schemas)
151+createSchema sch = UnsafeDefinition $
152+ "CREATE" <+> "SCHEMA" <+> renderSQL sch <> ";"
153+
154+{- | Idempotent version of `createSchema`. -}
155+createSchemaIfNotExists
156+ :: (KnownSymbol sch, Has sch schemas schema)
157+ => Alias sch
81158 -> Definition schemas schemas
82−manipDefinition = UnsafeDefinition . (<> ";") . renderSQL
159+createSchemaIfNotExists sch = UnsafeDefinition $
160+ "CREATE" <+> "SCHEMA" <+> "IF" <+> "NOT" <+> "EXISTS"
161+ <+> renderSQL sch <> ";"
162+
163+{- | `createTable` adds a table to the schema.
164+
165+>>> :set -XOverloadedLabels
166+>>> :{
167+type Table = '[] :=>
168+ '[ "a" ::: 'NoDef :=> 'Null 'PGint4
169+ , "b" ::: 'NoDef :=> 'Null 'PGfloat4 ]
170+:}
171+
172+>>> :{
173+let
174+ setup :: Definition (Public '[]) (Public '["tab" ::: 'Table Table])
175+ setup = createTable #tab
176+ (nullable int `as` #a :* nullable real `as` #b) Nil
177+in printSQL setup
178+:}
179+CREATE TABLE "tab" ("a" int NULL, "b" real NULL);
180+-}
181+createTable
182+ :: ( KnownSymbol sch
183+ , KnownSymbol tab
184+ , columns ~ (col ': cols)
185+ , SOP.SListI columns
186+ , SOP.SListI constraints
187+ , Has sch schemas0 schema0
188+ , schemas1 ~ Alter sch (Create tab ('Table (constraints :=> columns)) schema0) schemas0 )
189+ => QualifiedAlias sch tab -- ^ the name of the table to add
190+ -> NP (Aliased (ColumnTypeExpression schemas0)) columns
191+ -- ^ the names and datatype of each column
192+ -> NP (Aliased (TableConstraintExpression sch tab schemas1)) constraints
193+ -- ^ constraints that must hold for the table
194+ -> Definition schemas0 schemas1
195+createTable tab columns constraints = UnsafeDefinition $
196+ "CREATE TABLE" <+> renderCreation tab columns constraints
197+
198+{-| `createTableIfNotExists` creates a table if it doesn't exist, but does not add it to the schema.
199+Instead, the schema already has the table so if the table did not yet exist, the schema was wrong.
200+`createTableIfNotExists` fixes this. Interestingly, this property makes it an idempotent in
201+the `Category` of `Definition`s.
202+
203+>>> :set -XOverloadedLabels -XTypeApplications
204+>>> :{
205+type Table = '[] :=>
206+ '[ "a" ::: 'NoDef :=> 'Null 'PGint4
207+ , "b" ::: 'NoDef :=> 'Null 'PGfloat4 ]
208+:}
209+
210+>>> type Schemas = Public '["tab" ::: 'Table Table]
211+
212+>>> :{
213+let
214+ setup :: Definition Schemas Schemas
215+ setup = createTableIfNotExists #tab
216+ (nullable int `as` #a :* nullable real `as` #b) Nil
217+in printSQL setup
218+:}
219+CREATE TABLE IF NOT EXISTS "tab" ("a" int NULL, "b" real NULL);
220+-}
221+createTableIfNotExists
222+ :: ( Has sch schemas schema
223+ , Has tab schema ('Table (constraints :=> columns))
224+ , SOP.SListI columns
225+ , SOP.SListI constraints )
226+ => QualifiedAlias sch tab -- ^ the name of the table to add
227+ -> NP (Aliased (ColumnTypeExpression schemas)) columns
228+ -- ^ the names and datatype of each column
229+ -> NP (Aliased (TableConstraintExpression sch tab schemas)) constraints
230+ -- ^ constraints that must hold for the table
231+ -> Definition schemas schemas
232+createTableIfNotExists tab columns constraints = UnsafeDefinition $
233+ "CREATE TABLE IF NOT EXISTS"
234+ <+> renderCreation tab columns constraints
235+
236+-- helper function for `createTable` and `createTableIfNotExists`
237+renderCreation
238+ :: ( KnownSymbol sch
239+ , KnownSymbol tab
240+ , SOP.SListI columns
241+ , SOP.SListI constraints )
242+ => QualifiedAlias sch tab -- ^ the name of the table to add
243+ -> NP (Aliased (ColumnTypeExpression schemas0)) columns
244+ -- ^ the names and datatype of each column
245+ -> NP (Aliased (TableConstraintExpression sch tab schemas1)) constraints
246+ -- ^ constraints that must hold for the table
247+ -> ByteString
248+renderCreation tab columns constraints = renderSQL tab
249+ <+> parenthesized
250+ ( renderCommaSeparated renderColumnDef columns
251+ <> ( case constraints of
252+ Nil -> ""
253+ _ -> ", " <>
254+ renderCommaSeparated renderConstraint constraints ) )
255+ <> ";"
256+ where
257+ renderColumnDef :: Aliased (ColumnTypeExpression schemas) x -> ByteString
258+ renderColumnDef (ty `As` column) =
259+ renderSQL column <+> renderColumnTypeExpression ty
260+ renderConstraint
261+ :: Aliased (TableConstraintExpression sch tab schemas) constraint
262+ -> ByteString
263+ renderConstraint (constraint `As` alias) =
264+ "CONSTRAINT" <+> renderSQL alias <+> renderSQL constraint
265+
266+-- | Data types are a way to limit the kind of data that can be stored in a
267+-- table. For many applications, however, the constraint they provide is
268+-- too coarse. For example, a column containing a product price should
269+-- probably only accept positive values. But there is no standard data type
270+-- that accepts only positive numbers. Another issue is that you might want
271+-- to constrain column data with respect to other columns or rows.
272+-- For example, in a table containing product information,
273+-- there should be only one row for each product number.
274+-- `TableConstraint`s give you as much control over the data in your tables
275+-- as you wish. If a user attempts to store data in a column that would
276+-- violate a constraint, an error is raised. This applies
277+-- even if the value came from the default value definition.
278+newtype TableConstraintExpression
279+ (sch :: Symbol)
280+ (tab :: Symbol)
281+ (schemas :: SchemasType)
282+ (constraint :: TableConstraint)
283+ = UnsafeTableConstraintExpression
284+ { renderTableConstraintExpression :: ByteString }
285+ deriving (GHC.Generic,Show,Eq,Ord,NFData)
286+instance RenderSQL
287+ (TableConstraintExpression sch tab schemas constraint) where
288+ renderSQL = renderTableConstraintExpression
289+
290+{-| A `check` constraint is the most generic `TableConstraint` type.
291+It allows you to specify that the value in a certain column must satisfy
292+a Boolean (truth-value) expression.
293+
294+>>> :{
295+type Schema = '[
296+ "tab" ::: 'Table ('[ "inequality" ::: 'Check '["a","b"]] :=> '[
297+ "a" ::: 'NoDef :=> 'NotNull 'PGint4,
298+ "b" ::: 'NoDef :=> 'NotNull 'PGint4
299+ ])]
300+:}
301+
302+>>> :{
303+let
304+ definition :: Definition (Public '[]) (Public Schema)
305+ definition = createTable #tab
306+ ( (int & notNullable) `as` #a :*
307+ (int & notNullable) `as` #b )
308+ ( check (#a :* #b) (#a .> #b) `as` #inequality )
309+:}
310+
311+>>> printSQL definition
312+CREATE TABLE "tab" ("a" int NOT NULL, "b" int NOT NULL, CONSTRAINT "inequality" CHECK (("a" > "b")));
313+-}
314+check
315+ :: ( Has sch schemas schema
316+ , Has tab schema ('Table table)
317+ , HasAll aliases (TableToRow table) subcolumns )
318+ => NP Alias aliases
319+ -- ^ specify the subcolumns which are getting checked
320+ -> (forall t. Condition '[] '[] 'Ungrouped schemas '[] '[t ::: subcolumns])
321+ -- ^ a closed `Condition` on those subcolumns
322+ -> TableConstraintExpression sch tab schemas ('Check aliases)
323+check _cols condition = UnsafeTableConstraintExpression $
324+ "CHECK" <+> parenthesized (renderSQL condition)
325+
326+{-| A `unique` constraint ensure that the data contained in a column,
327+or a group of columns, is unique among all the rows in the table.
328+
329+>>> :{
330+type Schema = '[
331+ "tab" ::: 'Table( '[ "uq_a_b" ::: 'Unique '["a","b"]] :=> '[
332+ "a" ::: 'NoDef :=> 'Null 'PGint4,
333+ "b" ::: 'NoDef :=> 'Null 'PGint4
334+ ])]
335+:}
336+
337+>>> :{
338+let
339+ definition :: Definition (Public '[]) (Public Schema)
340+ definition = createTable #tab
341+ ( (int & nullable) `as` #a :*
342+ (int & nullable) `as` #b )
343+ ( unique (#a :* #b) `as` #uq_a_b )
344+:}
345+
346+>>> printSQL definition
347+CREATE TABLE "tab" ("a" int NULL, "b" int NULL, CONSTRAINT "uq_a_b" UNIQUE ("a", "b"));
348+-}
349+unique
350+ :: ( Has sch schemas schema
351+ , Has tab schema('Table table)
352+ , HasAll aliases (TableToRow table) subcolumns )
353+ => NP Alias aliases
354+ -- ^ specify subcolumns which together are unique for each row
355+ -> TableConstraintExpression sch tab schemas ('Unique aliases)
356+unique columns = UnsafeTableConstraintExpression $
357+ "UNIQUE" <+> parenthesized (renderSQL columns)
358+
359+{-| A `primaryKey` constraint indicates that a column, or group of columns,
360+can be used as a unique identifier for rows in the table.
361+This requires that the values be both unique and not null.
362+
363+>>> :{
364+type Schema = '[
365+ "tab" ::: 'Table ('[ "pk_id" ::: 'PrimaryKey '["id"]] :=> '[
366+ "id" ::: 'Def :=> 'NotNull 'PGint4,
367+ "name" ::: 'NoDef :=> 'NotNull 'PGtext
368+ ])]
369+:}
370+
371+>>> :{
372+let
373+ definition :: Definition (Public '[]) (Public Schema)
374+ definition = createTable #tab
375+ ( serial `as` #id :*
376+ (text & notNullable) `as` #name )
377+ ( primaryKey #id `as` #pk_id )
378+:}
379+
380+>>> printSQL definition
381+CREATE TABLE "tab" ("id" serial, "name" text NOT NULL, CONSTRAINT "pk_id" PRIMARY KEY ("id"));
382+-}
383+primaryKey
384+ :: ( Has sch schemas schema
385+ , Has tab schema ('Table table)
386+ , HasAll aliases (TableToColumns table) subcolumns
387+ , AllNotNull subcolumns )
388+ => NP Alias aliases
389+ -- ^ specify the subcolumns which together form a primary key.
390+ -> TableConstraintExpression sch tab schemas ('PrimaryKey aliases)
391+primaryKey columns = UnsafeTableConstraintExpression $
392+ "PRIMARY KEY" <+> parenthesized (renderSQL columns)
393+
394+{-| A `foreignKey` specifies that the values in a column
395+(or a group of columns) must match the values appearing in some row of
396+another table. We say this maintains the referential integrity
397+between two related tables.
398+
399+>>> :{
400+type Schema =
401+ '[ "users" ::: 'Table (
402+ '[ "pk_users" ::: 'PrimaryKey '["id"] ] :=>
403+ '[ "id" ::: 'Def :=> 'NotNull 'PGint4
404+ , "name" ::: 'NoDef :=> 'NotNull 'PGtext
405+ ])
406+ , "emails" ::: 'Table (
407+ '[ "pk_emails" ::: 'PrimaryKey '["id"]
408+ , "fk_user_id" ::: 'ForeignKey '["user_id"] "users" '["id"]
409+ ] :=>
410+ '[ "id" ::: 'Def :=> 'NotNull 'PGint4
411+ , "user_id" ::: 'NoDef :=> 'NotNull 'PGint4
412+ , "email" ::: 'NoDef :=> 'Null 'PGtext
413+ ])
414+ ]
415+:}
416+
417+>>> :{
418+let
419+ setup :: Definition (Public '[]) (Public Schema)
420+ setup =
421+ createTable #users
422+ ( serial `as` #id :*
423+ (text & notNullable) `as` #name )
424+ ( primaryKey #id `as` #pk_users ) >>>
425+ createTable #emails
426+ ( serial `as` #id :*
427+ (int & notNullable) `as` #user_id :*
428+ (text & nullable) `as` #email )
429+ ( primaryKey #id `as` #pk_emails :*
430+ foreignKey #user_id #users #id
431+ OnDeleteCascade OnUpdateCascade `as` #fk_user_id )
432+in printSQL setup
433+:}
434+CREATE TABLE "users" ("id" serial, "name" text NOT NULL, CONSTRAINT "pk_users" PRIMARY KEY ("id"));
435+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);
436+
437+A `foreignKey` can even be a table self-reference.
438+
439+>>> :{
440+type Schema =
441+ '[ "employees" ::: 'Table (
442+ '[ "employees_pk" ::: 'PrimaryKey '["id"]
443+ , "employees_employer_fk" ::: 'ForeignKey '["employer_id"] "employees" '["id"]
444+ ] :=>
445+ '[ "id" ::: 'Def :=> 'NotNull 'PGint4
446+ , "name" ::: 'NoDef :=> 'NotNull 'PGtext
447+ , "employer_id" ::: 'NoDef :=> 'Null 'PGint4
448+ ])
449+ ]
450+:}
451+
452+>>> :{
453+let
454+ setup :: Definition (Public '[]) (Public Schema)
455+ setup =
456+ createTable #employees
457+ ( serial `as` #id :*
458+ (text & notNullable) `as` #name :*
459+ (integer & nullable) `as` #employer_id )
460+ ( primaryKey #id `as` #employees_pk :*
461+ foreignKey #employer_id #employees #id
462+ OnDeleteCascade OnUpdateCascade `as` #employees_employer_fk )
463+in printSQL setup
464+:}
465+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);
466+-}
467+foreignKey
468+ :: (ForeignKeyed schemas sch schema child parent
469+ table reftable
470+ columns refcolumns
471+ constraints cols
472+ reftys tys )
473+ => NP Alias columns
474+ -- ^ column or columns in the table
475+ -> Alias parent
476+ -- ^ reference table
477+ -> NP Alias refcolumns
478+ -- ^ reference column or columns in the reference table
479+ -> OnDeleteClause
480+ -- ^ what to do when reference is deleted
481+ -> OnUpdateClause
482+ -- ^ what to do when reference is updated
483+ -> TableConstraintExpression sch child schemas
484+ ('ForeignKey columns parent refcolumns)
485+foreignKey keys parent refs ondel onupd = UnsafeTableConstraintExpression $
486+ "FOREIGN KEY" <+> parenthesized (renderSQL keys)
487+ <+> "REFERENCES" <+> renderSQL parent
488+ <+> parenthesized (renderSQL refs)
489+ <+> renderSQL ondel
490+ <+> renderSQL onupd
491+
492+-- | A constraint synonym between types involved in a foreign key constraint.
493+type ForeignKeyed schemas
494+ sch
495+ schema
496+ child parent
497+ table reftable
498+ columns refcolumns
499+ constraints cols
500+ reftys tys =
501+ ( Has sch schemas schema
502+ , Has child schema ('Table table)
503+ , Has parent schema ('Table reftable)
504+ , HasAll columns (TableToColumns table) tys
505+ , reftable ~ (constraints :=> cols)
506+ , HasAll refcolumns cols reftys
507+ , SOP.AllZip SamePGType tys reftys
508+ , Uniquely refcolumns constraints )
509+
510+-- | `OnDeleteClause` indicates what to do with rows that reference a deleted row.
511+data OnDeleteClause
512+ = OnDeleteNoAction
513+ -- ^ if any referencing rows still exist when the constraint is checked,
514+ -- an error is raised
515+ | OnDeleteRestrict -- ^ prevents deletion of a referenced row
516+ | OnDeleteCascade
517+ -- ^ specifies that when a referenced row is deleted,
518+ -- row(s) referencing it should be automatically deleted as well
519+ deriving (GHC.Generic,Show,Eq,Ord)
520+instance NFData OnDeleteClause
521+-- | Render `OnDeleteClause`.
522+instance RenderSQL OnDeleteClause where
523+ renderSQL = \case
524+ OnDeleteNoAction -> "ON DELETE NO ACTION"
525+ OnDeleteRestrict -> "ON DELETE RESTRICT"
526+ OnDeleteCascade -> "ON DELETE CASCADE"
527+
528+-- | Analagous to `OnDeleteClause` there is also `OnUpdateClause` which is invoked
529+-- when a referenced column is changed (updated).
530+data OnUpdateClause
531+ = OnUpdateNoAction
532+ -- ^ if any referencing rows has not changed when the constraint is checked,
533+ -- an error is raised
534+ | OnUpdateRestrict -- ^ prevents update of a referenced row
535+ | OnUpdateCascade
536+ -- ^ the updated values of the referenced column(s) should be copied
537+ -- into the referencing row(s)
538+ deriving (GHC.Generic,Show,Eq,Ord)
539+instance NFData OnUpdateClause
540+
541+-- | Render `OnUpdateClause`.
542+instance RenderSQL OnUpdateClause where
543+ renderSQL = \case
544+ OnUpdateNoAction -> "ON UPDATE NO ACTION"
545+ OnUpdateRestrict -> "ON UPDATE RESTRICT"
546+ OnUpdateCascade -> "ON UPDATE CASCADE"
547+
548+{-----------------------------------------
549+DROP statements
550+-----------------------------------------}
551+
552+-- | >>> :{
553+-- let
554+-- definition :: Definition '["muh_schema" ::: schema, "public" ::: public] '["public" ::: public]
555+-- definition = dropSchema #muh_schema
556+-- :}
557+--
558+-- >>> printSQL definition
559+-- DROP SCHEMA "muh_schema";
560+dropSchema
561+ :: Has sch schemas schema
562+ => Alias sch
563+ -> Definition schemas (Drop sch schemas)
564+dropSchema sch = UnsafeDefinition $ "DROP SCHEMA" <+> renderSQL sch <> ";"
565+
566+-- | `dropTable` removes a table from the schema.
567+--
568+-- >>> :{
569+-- let
570+-- definition :: Definition '["public" ::: '["muh_table" ::: 'Table t]] (Public '[])
571+-- definition = dropTable #muh_table
572+-- :}
573+--
574+-- >>> printSQL definition
575+-- DROP TABLE "muh_table";
576+dropTable
577+ :: ( Has sch schemas schema
578+ , Has tab schema ('Table table))
579+ => QualifiedAlias sch tab -- ^ table to remove
580+ -> Definition schemas (Alter sch (Drop tab schema) schemas)
581+dropTable tab = UnsafeDefinition $ "DROP TABLE" <+> renderSQL tab <> ";"
582+
583+{-----------------------------------------
584+ALTER statements
585+-----------------------------------------}
586+
587+-- | `alterTable` changes the definition of a table from the schema.
588+alterTable
589+ :: (Has sch schemas schema, Has tab schema ('Table table0))
590+ => QualifiedAlias sch tab -- ^ table to alter
591+ -> AlterTable sch tab schemas table1 -- ^ alteration to perform
592+ -> Definition schemas (Alter sch (Alter tab ('Table table1) schema) schemas)
593+alterTable tab alteration = UnsafeDefinition $
594+ "ALTER TABLE"
595+ <+> renderSQL tab
596+ <+> renderAlterTable alteration
597+ <> ";"
598+
599+-- | `alterTableRename` changes the name of a table from the schema.
600+--
601+-- >>> printSQL $ alterTableRename #foo #bar
602+-- ALTER TABLE "foo" RENAME TO "bar";
603+alterTableRename
604+ :: (KnownSymbol table0, KnownSymbol table1)
605+ => Alias table0 -- ^ table to rename
606+ -> Alias table1 -- ^ what to rename it
607+ -> Definition schema (Rename table0 table1 schema)
608+alterTableRename table0 table1 = UnsafeDefinition $
609+ "ALTER TABLE" <+> renderSQL table0
610+ <+> "RENAME TO" <+> renderSQL table1 <> ";"
611+
612+-- | An `AlterTable` describes the alteration to perform on the columns
613+-- of a table.
614+newtype AlterTable
615+ (sch :: Symbol)
616+ (tab :: Symbol)
617+ (schemas :: SchemasType)
618+ (table :: TableType) =
619+ UnsafeAlterTable {renderAlterTable :: ByteString}
620+ deriving (GHC.Generic,Show,Eq,Ord,NFData)
621+
622+-- | An `addConstraint` adds a table constraint.
623+--
624+-- >>> :{
625+-- let
626+-- definition :: Definition
627+-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'NotNull 'PGint4])]]
628+-- '["public" ::: '["tab" ::: 'Table ('["positive" ::: 'Check '["col"]] :=> '["col" ::: 'NoDef :=> 'NotNull 'PGint4])]]
629+-- definition = alterTable #tab (addConstraint #positive (check #col (#col .> 0)))
630+-- in printSQL definition
631+-- :}
632+-- ALTER TABLE "tab" ADD CONSTRAINT "positive" CHECK (("col" > 0));
633+addConstraint
634+ :: ( KnownSymbol alias
635+ , Has sch schemas schema
636+ , Has tab schema ('Table table0)
637+ , table0 ~ (constraints :=> columns)
638+ , table1 ~ (Create alias constraint constraints :=> columns) )
639+ => Alias alias
640+ -> TableConstraintExpression sch tab schemas constraint
641+ -- ^ constraint to add
642+ -> AlterTable sch tab schemas table1
643+addConstraint alias constraint = UnsafeAlterTable $
644+ "ADD" <+> "CONSTRAINT" <+> renderSQL alias
645+ <+> renderSQL constraint
646+
647+-- | A `dropConstraint` drops a table constraint.
648+--
649+-- >>> :{
650+-- let
651+-- definition :: Definition
652+-- '["public" ::: '["tab" ::: 'Table ('["positive" ::: Check '["col"]] :=> '["col" ::: 'NoDef :=> 'NotNull 'PGint4])]]
653+-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'NotNull 'PGint4])]]
654+-- definition = alterTable #tab (dropConstraint #positive)
655+-- in printSQL definition
656+-- :}
657+-- ALTER TABLE "tab" DROP CONSTRAINT "positive";
658+dropConstraint
659+ :: ( KnownSymbol constraint
660+ , Has sch schemas schema
661+ , Has tab schema ('Table table0)
662+ , table0 ~ (constraints :=> columns)
663+ , table1 ~ (Drop constraint constraints :=> columns) )
664+ => Alias constraint
665+ -- ^ constraint to drop
666+ -> AlterTable sch tab schemas table1
667+dropConstraint constraint = UnsafeAlterTable $
668+ "DROP" <+> "CONSTRAINT" <+> renderSQL constraint
669+
670+-- | An `AddColumn` is either @NULL@ or has @DEFAULT@.
671+class AddColumn ty where
672+ -- | `addColumn` adds a new column, initially filled with whatever
673+ -- default value is given or with @NULL@.
674+ --
675+ -- >>> :{
676+ -- let
677+ -- definition :: Definition
678+ -- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col1" ::: 'NoDef :=> 'Null 'PGint4])]]
679+ -- '["public" ::: '["tab" ::: 'Table ('[] :=>
680+ -- '[ "col1" ::: 'NoDef :=> 'Null 'PGint4
681+ -- , "col2" ::: 'Def :=> 'Null 'PGtext ])]]
682+ -- definition = alterTable #tab (addColumn #col2 (text & nullable & default_ "foo"))
683+ -- in printSQL definition
684+ -- :}
685+ -- ALTER TABLE "tab" ADD COLUMN "col2" text NULL DEFAULT E'foo';
686+ --
687+ -- >>> :{
688+ -- let
689+ -- definition :: Definition
690+ -- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col1" ::: 'NoDef :=> 'Null 'PGint4])]]
691+ -- '["public" ::: '["tab" ::: 'Table ('[] :=>
692+ -- '[ "col1" ::: 'NoDef :=> 'Null 'PGint4
693+ -- , "col2" ::: 'NoDef :=> 'Null 'PGtext ])]]
694+ -- definition = alterTable #tab (addColumn #col2 (text & nullable))
695+ -- in printSQL definition
696+ -- :}
697+ -- ALTER TABLE "tab" ADD COLUMN "col2" text NULL;
698+ addColumn
699+ :: ( KnownSymbol column
700+ , Has sch schemas schema
701+ , Has tab schema ('Table table0)
702+ , table0 ~ (constraints :=> columns) )
703+ => Alias column -- ^ column to add
704+ -> ColumnTypeExpression schemas ty -- ^ type of the new column
705+ -> AlterTable sch tab schemas (constraints :=> Create column ty columns)
706+ addColumn column ty = UnsafeAlterTable $
707+ "ADD COLUMN" <+> renderSQL column <+> renderColumnTypeExpression ty
708+instance {-# OVERLAPPING #-} AddColumn ('Def :=> ty)
709+instance {-# OVERLAPPABLE #-} AddColumn ('NoDef :=> 'Null ty)
710+
711+-- | A `dropColumn` removes a column. Whatever data was in the column
712+-- disappears. Table constraints involving the column are dropped, too.
713+-- However, if the column is referenced by a foreign key constraint of
714+-- another table, PostgreSQL will not silently drop that constraint.
715+--
716+-- >>> :{
717+-- let
718+-- definition :: Definition
719+-- '["public" ::: '["tab" ::: 'Table ('[] :=>
720+-- '[ "col1" ::: 'NoDef :=> 'Null 'PGint4
721+-- , "col2" ::: 'NoDef :=> 'Null 'PGtext ])]]
722+-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col1" ::: 'NoDef :=> 'Null 'PGint4])]]
723+-- definition = alterTable #tab (dropColumn #col2)
724+-- in printSQL definition
725+-- :}
726+-- ALTER TABLE "tab" DROP COLUMN "col2";
727+dropColumn
728+ :: ( KnownSymbol column
729+ , Has sch schemas schema
730+ , Has tab schema ('Table table0)
731+ , table0 ~ (constraints :=> columns)
732+ , table1 ~ (constraints :=> Drop column columns) )
733+ => Alias column -- ^ column to remove
734+ -> AlterTable sch tab schemas table1
735+dropColumn column = UnsafeAlterTable $
736+ "DROP COLUMN" <+> renderSQL column
737+
738+-- | A `renameColumn` renames a column.
739+--
740+-- >>> :{
741+-- let
742+-- definition :: Definition
743+-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["foo" ::: 'NoDef :=> 'Null 'PGint4])]]
744+-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["bar" ::: 'NoDef :=> 'Null 'PGint4])]]
745+-- definition = alterTable #tab (renameColumn #foo #bar)
746+-- in printSQL definition
747+-- :}
748+-- ALTER TABLE "tab" RENAME COLUMN "foo" TO "bar";
749+renameColumn
750+ :: ( KnownSymbol column0
751+ , KnownSymbol column1
752+ , Has sch schemas schema
753+ , Has tab schema ('Table table0)
754+ , table0 ~ (constraints :=> columns)
755+ , table1 ~ (constraints :=> Rename column0 column1 columns) )
756+ => Alias column0 -- ^ column to rename
757+ -> Alias column1 -- ^ what to rename the column
758+ -> AlterTable sch tab schemas table1
759+renameColumn column0 column1 = UnsafeAlterTable $
760+ "RENAME COLUMN" <+> renderSQL column0 <+> "TO" <+> renderSQL column1
761+
762+-- | An `alterColumn` alters a single column.
763+alterColumn
764+ :: ( KnownSymbol column
765+ , Has sch schemas schema
766+ , Has tab schema ('Table table0)
767+ , table0 ~ (constraints :=> columns)
768+ , Has column columns ty0
769+ , table1 ~ (constraints :=> Alter column ty1 columns))
770+ => Alias column -- ^ column to alter
771+ -> AlterColumn schemas ty0 ty1 -- ^ alteration to perform
772+ -> AlterTable sch tab schemas table1
773+alterColumn column alteration = UnsafeAlterTable $
774+ "ALTER COLUMN" <+> renderSQL column <+> renderAlterColumn alteration
775+
776+-- | An `AlterColumn` describes the alteration to perform on a single column.
777+newtype AlterColumn (schemas :: SchemasType) (ty0 :: ColumnType) (ty1 :: ColumnType) =
778+ UnsafeAlterColumn {renderAlterColumn :: ByteString}
779+ deriving (GHC.Generic,Show,Eq,Ord,NFData)
780+
781+-- | A `setDefault` sets a new default for a column. Note that this doesn't
782+-- affect any existing rows in the table, it just changes the default for
783+-- future insert and update commands.
784+--
785+-- >>> :{
786+-- let
787+-- definition :: Definition
788+-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'Null 'PGint4])]]
789+-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col" ::: 'Def :=> 'Null 'PGint4])]]
790+-- definition = alterTable #tab (alterColumn #col (setDefault 5))
791+-- in printSQL definition
792+-- :}
793+-- ALTER TABLE "tab" ALTER COLUMN "col" SET DEFAULT 5;
794+setDefault
795+ :: Expression '[] '[] 'Ungrouped schemas '[] '[] ty -- ^ default value to set
796+ -> AlterColumn schemas (constraint :=> ty) ('Def :=> ty)
797+setDefault expression = UnsafeAlterColumn $
798+ "SET DEFAULT" <+> renderExpression expression
799+
800+-- | A `dropDefault` removes any default value for a column.
801+--
802+-- >>> :{
803+-- let
804+-- definition :: Definition
805+-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col" ::: 'Def :=> 'Null 'PGint4])]]
806+-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'Null 'PGint4])]]
807+-- definition = alterTable #tab (alterColumn #col dropDefault)
808+-- in printSQL definition
809+-- :}
810+-- ALTER TABLE "tab" ALTER COLUMN "col" DROP DEFAULT;
811+dropDefault :: AlterColumn schemas ('Def :=> ty) ('NoDef :=> ty)
812+dropDefault = UnsafeAlterColumn $ "DROP DEFAULT"
813+
814+-- | A `setNotNull` adds a @NOT NULL@ constraint to a column.
815+-- The constraint will be checked immediately, so the table data must satisfy
816+-- the constraint before it can be added.
817+--
818+-- >>> :{
819+-- let
820+-- definition :: Definition
821+-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'Null 'PGint4])]]
822+-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'NotNull 'PGint4])]]
823+-- definition = alterTable #tab (alterColumn #col setNotNull)
824+-- in printSQL definition
825+-- :}
826+-- ALTER TABLE "tab" ALTER COLUMN "col" SET NOT NULL;
827+setNotNull
828+ :: AlterColumn schemas (constraint :=> 'Null ty) (constraint :=> 'NotNull ty)
829+setNotNull = UnsafeAlterColumn $ "SET NOT NULL"
830+
831+-- | A `dropNotNull` drops a @NOT NULL@ constraint from a column.
832+--
833+-- >>> :{
834+-- let
835+-- definition :: Definition
836+-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'NotNull 'PGint4])]]
837+-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'Null 'PGint4])]]
838+-- definition = alterTable #tab (alterColumn #col dropNotNull)
839+-- in printSQL definition
840+-- :}
841+-- ALTER TABLE "tab" ALTER COLUMN "col" DROP NOT NULL;
842+dropNotNull
843+ :: AlterColumn schemas (constraint :=> 'NotNull ty) (constraint :=> 'Null ty)
844+dropNotNull = UnsafeAlterColumn $ "DROP NOT NULL"
845+
846+-- | An `alterType` converts a column to a different data type.
847+-- This will succeed only if each existing entry in the column can be
848+-- converted to the new type by an implicit cast.
849+--
850+-- >>> :{
851+-- let
852+-- definition :: Definition
853+-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'NotNull 'PGint4])]]
854+-- '["public" ::: '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'NotNull 'PGnumeric])]]
855+-- definition =
856+-- alterTable #tab (alterColumn #col (alterType (numeric & notNullable)))
857+-- in printSQL definition
858+-- :}
859+-- ALTER TABLE "tab" ALTER COLUMN "col" TYPE numeric NOT NULL;
860+alterType :: ColumnTypeExpression schemas ty -> AlterColumn schemas ty0 ty
861+alterType ty = UnsafeAlterColumn $ "TYPE" <+> renderColumnTypeExpression ty
862+
863+{- | Create a view.
864+>>> type ABC = '["a" ::: 'NoDef :=> 'Null 'PGint4, "b" ::: 'NoDef :=> 'Null 'PGint4, "c" ::: 'NoDef :=> 'Null 'PGint4]
865+>>> type BC = '["b" ::: 'Null 'PGint4, "c" ::: 'Null 'PGint4]
866+>>> :{
867+let
868+ definition :: Definition
869+ '[ "public" ::: '["abc" ::: 'Table ('[] :=> ABC)]]
870+ '[ "public" ::: '["abc" ::: 'Table ('[] :=> ABC), "bc" ::: 'View BC]]
871+ definition =
872+ createView #bc (select_ (#b :* #c) (from (table #abc)))
873+in printSQL definition
874+:}
875+CREATE VIEW "bc" AS SELECT "b" AS "b", "c" AS "c" FROM "abc" AS "abc";
876+-}
877+createView
878+ :: (KnownSymbol sch, KnownSymbol vw, Has sch schemas schema)
879+ => QualifiedAlias sch vw -- ^ the name of the view to add
880+ -> Query '[] '[] schemas '[] view -- ^ query
881+ -> Definition schemas (Alter sch (Create vw ('View view) schema) schemas)
882+createView alias query = UnsafeDefinition $
883+ "CREATE" <+> "VIEW" <+> renderSQL alias <+> "AS"
884+ <+> renderQuery query <> ";"
885+
886+-- | Drop a view.
887+--
888+-- >>> :{
889+-- let
890+-- definition :: Definition
891+-- '[ "public" ::: '["abc" ::: 'Table ('[] :=> '["a" ::: 'NoDef :=> 'Null 'PGint4, "b" ::: 'NoDef :=> 'Null 'PGint4, "c" ::: 'NoDef :=> 'Null 'PGint4])
892+-- , "bc" ::: 'View ('["b" ::: 'Null 'PGint4, "c" ::: 'Null 'PGint4])]]
893+-- '[ "public" ::: '["abc" ::: 'Table ('[] :=> '["a" ::: 'NoDef :=> 'Null 'PGint4, "b" ::: 'NoDef :=> 'Null 'PGint4, "c" ::: 'NoDef :=> 'Null 'PGint4])]]
894+-- definition = dropView #bc
895+-- in printSQL definition
896+-- :}
897+-- DROP VIEW "bc";
898+dropView
899+ :: (Has sch schemas schema, Has vw schema ('View view))
900+ => QualifiedAlias sch vw -- ^ view to remove
901+ -> Definition schemas (Alter sch (Drop vw schema) schemas)
902+dropView vw = UnsafeDefinition $ "DROP VIEW" <+> renderSQL vw <> ";"
903+
904+-- | Enumerated types are created using the `createTypeEnum` command, for example
905+--
906+-- >>> printSQL $ (createTypeEnum #mood (label @"sad" :* label @"ok" :* label @"happy") :: Definition (Public '[]) '["public" ::: '["mood" ::: 'Typedef ('PGenum '["sad","ok","happy"])]])
907+-- CREATE TYPE "mood" AS ENUM ('sad', 'ok', 'happy');
908+createTypeEnum
909+ :: (KnownSymbol enum, Has sch schemas schema, SOP.All KnownSymbol labels)
910+ => QualifiedAlias sch enum
911+ -- ^ name of the user defined enumerated type
912+ -> NP PGlabel labels
913+ -- ^ labels of the enumerated type
914+ -> Definition schemas (Alter sch (Create enum ('Typedef ('PGenum labels)) schema) schemas)
915+createTypeEnum enum labels = UnsafeDefinition $
916+ "CREATE" <+> "TYPE" <+> renderSQL enum <+> "AS" <+> "ENUM" <+>
917+ parenthesized (renderSQL labels) <> ";"
918+
919+-- | Enumerated types can also be generated from a Haskell type, for example
920+--
921+-- >>> data Schwarma = Beef | Lamb | Chicken deriving GHC.Generic
922+-- >>> instance SOP.Generic Schwarma
923+-- >>> instance SOP.HasDatatypeInfo Schwarma
924+-- >>> :{
925+-- let
926+-- createSchwarma :: Definition (Public '[]) '["public" ::: '["schwarma" ::: 'Typedef (PG (Enumerated Schwarma))]]
927+-- createSchwarma = createTypeEnumFrom @Schwarma #schwarma
928+-- in
929+-- printSQL createSchwarma
930+-- :}
931+-- CREATE TYPE "schwarma" AS ENUM ('Beef', 'Lamb', 'Chicken');
932+createTypeEnumFrom
933+ :: forall hask sch enum schemas schema.
934+ ( SOP.Generic hask
935+ , SOP.All KnownSymbol (LabelsPG hask)
936+ , KnownSymbol enum
937+ , Has sch schemas schema )
938+ => QualifiedAlias sch enum
939+ -- ^ name of the user defined enumerated type
940+ -> Definition schemas (Alter sch (Create enum ('Typedef (PG (Enumerated hask))) schema) schemas)
941+createTypeEnumFrom enum = createTypeEnum enum
942+ (SOP.hpure label :: NP PGlabel (LabelsPG hask))
943+
944+{- | `createTypeComposite` creates a composite type. The composite type is
945+specified by a list of attribute names and data types.
946+
947+>>> :{
948+type PGcomplex = 'PGcomposite
949+ '[ "real" ::: 'NotNull 'PGfloat8
950+ , "imaginary" ::: 'NotNull 'PGfloat8 ]
951+:}
952+
953+>>> :{
954+let
955+ setup :: Definition (Public '[]) '["public" ::: '["complex" ::: 'Typedef PGcomplex]]
956+ setup = createTypeComposite #complex
957+ (float8 `as` #real :* float8 `as` #imaginary)
958+in printSQL setup
959+:}
960+CREATE TYPE "complex" AS ("real" float8, "imaginary" float8);
961+-}
962+createTypeComposite
963+ :: (KnownSymbol ty, Has sch schemas schema, SOP.SListI fields)
964+ => QualifiedAlias sch ty
965+ -- ^ name of the user defined composite type
966+ -> NP (Aliased (TypeExpression schemas)) fields
967+ -- ^ list of attribute names and data types
968+ -> Definition schemas (Alter sch (Create ty ('Typedef ('PGcomposite fields)) schema) schemas)
969+createTypeComposite ty fields = UnsafeDefinition $
970+ "CREATE" <+> "TYPE" <+> renderSQL ty <+> "AS" <+> parenthesized
971+ (renderCommaSeparated renderField fields) <> ";"
972+ where
973+ renderField :: Aliased (TypeExpression schemas) x -> ByteString
974+ renderField (typ `As` alias) =
975+ renderSQL alias <+> renderSQL typ
976+
977+-- | Composite types can also be generated from a Haskell type, for example
978+--
979+-- >>> data Complex = Complex {real :: Double, imaginary :: Double} deriving GHC.Generic
980+-- >>> instance SOP.Generic Complex
981+-- >>> instance SOP.HasDatatypeInfo Complex
982+-- >>> type Schema = '["complex" ::: 'Typedef (PG (Composite Complex))]
983+-- >>> :{
984+-- let
985+-- createComplex :: Definition (Public '[]) (Public Schema)
986+-- createComplex = createTypeCompositeFrom @Complex #complex
987+-- in
988+-- printSQL createComplex
989+-- :}
990+-- CREATE TYPE "complex" AS ("real" float8, "imaginary" float8);
991+createTypeCompositeFrom
992+ :: forall hask sch ty schemas schema.
993+ ( SOP.All (FieldTyped schemas) (RowPG hask)
994+ , KnownSymbol ty
995+ , Has sch schemas schema )
996+ => QualifiedAlias sch ty
997+ -- ^ name of the user defined composite type
998+ -> Definition schemas (Alter sch (Create ty ( 'Typedef (PG (Composite hask))) schema) schemas)
999+createTypeCompositeFrom ty = createTypeComposite ty
1000+ (SOP.hcpure (SOP.Proxy :: SOP.Proxy (FieldTyped schemas)) fieldtype
1001+ :: NP (Aliased (TypeExpression schemas)) (RowPG hask))
1002+
1003+{-|
1004+`createDomain` creates a new domain. A domain is essentially a data type
1005+with constraints (restrictions on the allowed set of values).
1006+
1007+Domains are useful for abstracting common constraints on fields
1008+into a single location for maintenance. For example, several tables might
1009+contain email address columns, all requiring the same `check` constraint
1010+to verify the address syntax. Define a domain rather than setting up
1011+each table's constraint individually.
1012+
1013+>>> :{
1014+let
1015+ createPositive :: Definition (Public '[]) (Public '["positive" ::: 'Typedef 'PGfloat4])
1016+ createPositive = createDomain #positive real (#value .> 0 .&& (#value & isNotNull))
1017+in printSQL createPositive
1018+:}
1019+CREATE DOMAIN "positive" AS real CHECK ((("value" > 0) AND "value" IS NOT NULL));
1020+-}
1021+createDomain
1022+ :: (Has sch schemas schema, KnownSymbol dom)
1023+ => QualifiedAlias sch dom
1024+ -> (forall nullity. TypeExpression schemas (nullity ty))
1025+ -> (forall tab. Condition '[] '[] 'Ungrouped schemas '[] '[tab ::: '["value" ::: 'Null ty]])
1026+ -> Definition schemas (Alter sch (Create alias ('Typedef ty) schema) schemas)
1027+createDomain dom ty condition =
1028+ UnsafeDefinition $ "CREATE DOMAIN" <+> renderSQL dom
1029+ <+> "AS" <+> renderTypeExpression ty
1030+ <+> "CHECK" <+> parenthesized (renderSQL condition) <> ";"
1031+
1032+class FieldTyped schemas ty where
1033+ fieldtype :: Aliased (TypeExpression schemas) ty
1034+instance (KnownSymbol alias, PGTyped schemas ty)
1035+ => FieldTyped schemas (alias ::: ty) where
1036+ fieldtype = pgtype `As` Alias
1037+
1038+-- | Drop a type.
1039+--
1040+-- >>> data Schwarma = Beef | Lamb | Chicken deriving GHC.Generic
1041+-- >>> instance SOP.Generic Schwarma
1042+-- >>> instance SOP.HasDatatypeInfo Schwarma
1043+-- >>> printSQL (dropType #schwarma :: Definition '["public" ::: '["schwarma" ::: 'Typedef (PG (Enumerated Schwarma))]] (Public '[]))
1044+-- DROP TYPE "schwarma";
1045+dropType
1046+ :: (Has sch schemas schema, Has td schema ('Typedef ty))
1047+ => QualifiedAlias sch td
1048+ -- ^ name of the user defined type
1049+ -> Definition schemas (Alter sch (Drop td schema) schemas)
1050+dropType tydef = UnsafeDefinition $ "DROP" <+> "TYPE" <+> renderSQL tydef <> ";"
1051+
1052+-- | `ColumnTypeExpression`s are used in `createTable` commands.
1053+newtype ColumnTypeExpression (schemas :: SchemasType) (ty :: ColumnType)
1054+ = UnsafeColumnTypeExpression { renderColumnTypeExpression :: ByteString }
1055+ deriving (GHC.Generic,Show,Eq,Ord,NFData)
1056+instance RenderSQL (ColumnTypeExpression schemas ty) where
1057+ renderSQL = renderColumnTypeExpression
1058+
1059+-- | used in `createTable` commands as a column constraint to note that
1060+-- @NULL@ may be present in a column
1061+nullable
1062+ :: TypeExpression schemas (nullity ty)
1063+ -> ColumnTypeExpression schemas ('NoDef :=> 'Null ty)
1064+nullable ty = UnsafeColumnTypeExpression $ renderSQL ty <+> "NULL"
1065+
1066+-- | used in `createTable` commands as a column constraint to ensure
1067+-- @NULL@ is not present in a column
1068+notNullable
1069+ :: TypeExpression schemas (nullity ty)
1070+ -> ColumnTypeExpression schemas ('NoDef :=> 'NotNull ty)
1071+notNullable ty = UnsafeColumnTypeExpression $ renderSQL ty <+> "NOT NULL"
1072+
1073+-- | used in `createTable` commands as a column constraint to give a default
1074+default_
1075+ :: Expression '[] '[] 'Ungrouped schemas '[] '[] ty
1076+ -> ColumnTypeExpression schemas ('NoDef :=> ty)
1077+ -> ColumnTypeExpression schemas ('Def :=> ty)
1078+default_ x ty = UnsafeColumnTypeExpression $
1079+ renderSQL ty <+> "DEFAULT" <+> renderExpression x
1080+
1081+-- | not a true type, but merely a notational convenience for creating
1082+-- unique identifier columns with type `PGint2`
1083+serial2, smallserial
1084+ :: ColumnTypeExpression schemas ('Def :=> 'NotNull 'PGint2)
1085+serial2 = UnsafeColumnTypeExpression "serial2"
1086+smallserial = UnsafeColumnTypeExpression "smallserial"
1087+-- | not a true type, but merely a notational convenience for creating
1088+-- unique identifier columns with type `PGint4`
1089+serial4, serial
1090+ :: ColumnTypeExpression schemas ('Def :=> 'NotNull 'PGint4)
1091+serial4 = UnsafeColumnTypeExpression "serial4"
1092+serial = UnsafeColumnTypeExpression "serial"
1093+-- | not a true type, but merely a notational convenience for creating
1094+-- unique identifier columns with type `PGint8`
1095+serial8, bigserial
1096+ :: ColumnTypeExpression schemas ('Def :=> 'NotNull 'PGint8)
1097+serial8 = UnsafeColumnTypeExpression "serial8"
1098+bigserial = UnsafeColumnTypeExpression "bigserial"