4

Consider the following scenario:

CREATE DOMAIN dom_zipcode AS text;
ALTER DOMAIN dom_zipcode
  ADD CONSTRAINT zipchk CHECK (char_length(VALUE) = 5);

Now, if I want to drop that constraint with ALTER DOMAIN, The manual says:

ALTER DOMAIN name
    DROP CONSTRAINT [ IF EXISTS ] constraint_name [ RESTRICT | CASCADE ]

But how can we find constraint_name? \dD only shows the constraint's definition (CHECK statement).

\dD dom_zipcode ;
                             List of domains
 Schema |    Name     | Type | Modifier |             Check
--------+-------------+------+----------+--------------------------------
 public | dom_zipcode | text |          | CHECK (char_length(VALUE) = 5)
(1 row)

I can dump the schema using pg_dump, but I believe there must exist a more elegant way to establish this using the psql terminal.

Evan Carroll
  • 65,432
  • 50
  • 254
  • 507
Adam Matan
  • 12,079
  • 30
  • 82
  • 96

3 Answers3

3

PostgreSQL's System Catalog

SELECT conname
FROM pg_constraint
WHERE contypid = 'dom_zipcode'::regtype;
Evan Carroll
  • 65,432
  • 50
  • 254
  • 507
Mladen Uzelac
  • 829
  • 5
  • 8
0

SQL Spec's INFORMATION_SCHEMA.DOMAIN_CONSTRAINTS

You can also query this in domain_constraints table of the information_schema

SELECT FORMAT('%I.%I.%I', constraint_schema, constraint_catalog, constraint_name)
FROM information_schema.domain_constraints
WHERE (domain_catalog,domain_schema,domain_name) = ('test','public','dom_zipcode');
Evan Carroll
  • 65,432
  • 50
  • 254
  • 507
0

this query outputs exactly what pgsql shows.

SELECT nsp.nspname                   as "Schema",
       typ.typname                   as "Name",
       tt.typname                    as "Type",
       pc.collname                   as "Collation",
       typ.typnotnull                as "Nullable",
       typ.typdefault                as "Default",
       con.conname                   as "Constraint Name",
       pg_get_constraintdef(con.oid) as "Constraint Definition"
FROM pg_catalog.pg_type typ
         inner join pg_catalog.pg_namespace nsp ON nsp.oid = typ.typnamespace
         inner join pg_catalog.pg_type tt on typ.typbasetype = tt.oid
         left join pg_collation pc on typ.typcollation = pc.oid
         left JOIN pg_catalog.pg_constraint con ON con.contypid = typ.oid
WHERE nsp.nspname = '<Schema Name>'
  and typ.typtype = 'd';

test this by creating two domains :

create domain type1 varchar default 0 not null
    constraint ss check ( value in ('ff')) COLLATE "af-NA-x-icu";

create domain type2 int default null;

psql output:

enter image description here

query output:

enter image description here