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