on dev help sign in
Merge pull request #107 from morphismtech/dev-domain2

createDomain

commite4ec3b26dc163beae7f3e738c850dc42d7eb9d0c authorEitan Chatav <eitan.chatav@gmail.com> dateSat 2 Mar 2019, 11:26 (8 years ago) parentfcc6bce02bbfc6
1 file changed+30
squeal-postgresql/src/Squeal/PostgreSQL/Definition.hs+30
squeal-postgresql/src/Squeal/PostgreSQL/Definition.hs+30
@@ -42,6 +42,7 @@ module Squeal.PostgreSQL.Definition
4242 , createTypeEnumFrom
4343 , createTypeComposite
4444 , createTypeCompositeFrom
45+ , createDomain
4546 , TableConstraintExpression (..)
4647 , check
4748 , unique
@@ -980,6 +981,35 @@ createTypeCompositeFrom ty = createTypeComposite ty
980981 (SOP.hcpure (SOP.Proxy :: SOP.Proxy (FieldTyped schemas)) fieldtype
981982 :: NP (Aliased (TypeExpression schemas)) (RowPG hask))
982983
984+{-|
985+`createDomain` creates a new domain. A domain is essentially a data type
986+with constraints (restrictions on the allowed set of values).
987+
988+Domains are useful for abstracting common constraints on fields
989+into a single location for maintenance. For example, several tables might
990+contain email address columns, all requiring the same `check` constraint
991+to verify the address syntax. Define a domain rather than setting up
992+each table's constraint individually.
993+
994+>>> :{
995+let
996+ createPositive :: Definition (Public '[]) (Public '["positive" ::: 'Typedef 'PGfloat4])
997+ createPositive = createDomain #positive real (#value .> 0 .&& (#value & isNotNull))
998+in printSQL createPositive
999+:}
1000+CREATE DOMAIN "positive" AS real CHECK ((("value" > 0) AND "value" IS NOT NULL));
1001+-}
1002+createDomain
1003+ :: (Has sch schemas schema, KnownSymbol dom)
1004+ => QualifiedAlias sch dom
1005+ -> (forall nullity. TypeExpression schemas (nullity ty))
1006+ -> (forall tab. Condition '[] 'Ungrouped '[] schemas '[] '[tab ::: '["value" ::: 'Null ty]])
1007+ -> Definition schemas (Alter sch (Create alias ('Typedef ty) schema) schemas)
1008+createDomain dom ty condition =
1009+ UnsafeDefinition $ "CREATE DOMAIN" <+> renderSQL dom
1010+ <+> "AS" <+> renderTypeExpression ty
1011+ <+> "CHECK" <+> parenthesized (renderSQL condition) <> ";"
1012+
9831013class FieldTyped schemas ty where
9841014 fieldtype :: Aliased (TypeExpression schemas) ty
9851015instance (KnownSymbol alias, PGTyped schemas ty)