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