在PostgreSQL中查找约束

时间:2016-04-13 19:43:30

标签: postgresql constraints

我只需要在一次咨询中找到所有限制因素,而且我不知道该怎么做。

我正试图在下一个查询中执行此操作:

SELECT UPPER(conname) AS restriccion, UPPER(relname) AS tabla, UPPER(pg_catalog.pg_attribute.attname) AS columna

FROM pg_catalog.pg_constraint, pg_catalog.pg_class, pg_catalog.pg_attribute

WHERE contype = 'u'

AND conrelid = pg_catalog.pg_class.oid

AND conrelid = pg_catalog.pg_attribute.attrelid

AND pg_catalog.pg_attribute.attnum = pg_catalog.pg_constraint.conkey[1]

ORDER BY UPPER(conname), UPPER(relname), UPPER(pg_catalog.pg_attribute.attname);

我正在改变这封信'你'与' c'看看检查限制但是有点困难...

是否有另一种方法可以只在一个查询中查看所有约束?谢谢!

1 个答案:

答案 0 :(得分:0)

如果仅查找检查和唯一约束,以下是否可以帮助您入门?

SELECT nr.nspname AS table_schema,
        r.relname AS table_name,
        c.conname AS constraint_name,
        CASE
            WHEN c.contype = 'c' THEN c.consrc 
            END AS search_condition,
        CASE
            WHEN c.contype = 'u' 
                THEN split_part ( split_part ( pg_get_constraintdef ( c.oid ), '(', 2 ), ')', 1 )
            END AS column_names,
        d.description AS comments
    FROM pg_class r
    INNER JOIN pg_namespace nr
        ON ( nr.oid = r.relnamespace )
    INNER JOIN pg_constraint c
        ON ( c.conrelid = r.oid )
    INNER JOIN pg_namespace nc
        ON ( nc.oid = c.connamespace )
    LEFT OUTER JOIN pg_description d
        ON ( d.objoid = c.oid )
    WHERE r.relkind = 'r'
        AND c.contype IN ( 'c', 'u' )
    ORDER BY r.relname,
        c.conname ;

更新2016-04-14:在pg_constraint表中找不到非空约束。 pg_attribute表包含以下信息:

SELECT nr.nspname AS table_schema,
        r.relname AS table_name,
        null::text AS constraint_name,
        'Not Null'::text AS null_condition,
        a.attname AS column_name,
        pg_catalog.col_description ( a.attrelid, a.attnum ) AS comments
    FROM pg_catalog.pg_class r
    LEFT OUTER JOIN pg_catalog.pg_namespace nr
        ON ( nr.oid = r.relnamespace )
    LEFT OUTER JOIN pg_catalog.pg_attribute a
        ON ( c.oid = a.attrelid
            AND a.attnum > 0
            AND NOT a.attisdropped )
    WHERE r.relkind IN ( 'r', 'f', 'm' ) -- tables(r), foreign tables(f), and materialized views(m)
        AND a.attnotnull
    ORDER BY nr.nspname,
        r.relname,
        a.attname ;