简体   繁体   中英

Getting the column name of a postgres check constraint from information_schema

I can get the constraint name, the table name and the check_clause of the check constraints on a table using this query:

SELECT tc.constraint_type, tc.constraint_name, tc.table_name, cc.check_clause
FROM information_schema.table_constraints tc 
JOIN information_schema.check_constraints cc ON cc.constraint_name = tc.constraint_name 
WHERE tc.table_name = $1 and tc.constraint_type = 'CHECK'

From information_schema.constraint_column_usage I can get the columns where a PRIMARY or UNIQUE constraint applies but not a CHECK constraint:

SELECT * FROM information_schema.constraint_column_usage  where table_name = $1

This eventually worked following suggestion below:

SELECT
ccu.table_schema,
ccu.table_name,
ccu.constraint_name,
ccu.column_name,
cc.check_clause
FROM information_schema.constraint_column_usage ccu
JOIN information_schema.check_constraints cc ON ccu.constraint_name = cc.constraint_name
WHERE ccu.constraint_name IN
(
   SELECT
   constraint_name
   FROM information_schema.check_constraints
)
AND ccu.table_name = $1;

CHECK constraints can exist on domains as well as tables. To get those that are on table columns only do:

SELECT
    table_schema,
    table_name,
    column_name,
    constraint_name
FROM
    information_schema.constraint_column_usage
WHERE
    constraint_name IN (
        SELECT
            constraint_name
        FROM
            information_schema.check_constraints);

The sub select will find all the CHECK constraints in the database and the constraint_name IN will filter to only those that are a column constraint.

UPDATE

An alternative is to use the system catalogs directly:


WITH c AS (
    SELECT
        conname,
        conrelid,
        unnest(conkey) AS col_id
    FROM
        pg_catalog.pg_constraint
    WHERE
        contype = 'c'
        AND conrelid > 0
)
SELECT
    conrelid::regclass AS table_name,
    conname,
    attname
FROM
    pg_catalog.pg_attribute
    JOIN c ON c.col_id = attnum
        AND conrelid = attrelid;

What the above does is restrict the constraint type( contype ) to 'c' for CHECK and then to only those CHECK constraints that exist on table conrelid > 0 in the CTE( WITH ) and then joins the unnest ed array of columns( conkey ) to the column information in pg_catalog.pg_attribute to get the column names.. The conrelid::regclass turns the conrelid oid value into a table name.

See pg_constraint for more information.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM