我如何看待有关PostgreSQL约束的评论?

时间:2018-12-03 22:23:03

标签: postgresql

PostgreSQL在约束上具有COMMENT的语法:

COMMENT ON CONSTRAINT` constraint_name ON table_name IS 'text'`

示例:

COMMENT ON CONSTRAINT bar_col_cons ON bar IS 'Constrains column col';

这告诉我如何定义关于约束的注释。但是我该如何查看已定义的注释?

该表上\d+的输出包括约束列表,但不显示注释。

3 个答案:

答案 0 :(得分:3)

\dd <constraint_name>应该显示注释,但不过滤表名。

答案 1 :(得分:3)

您可以使用系统目录pg_constraintpg_description查询关于约束的注释。

带有约束条件注释的示例表:

create table test(
    id int unique,
    str text check(str <> '')
);

comment on constraint test_id_key on test is 'my comment on test_id_key';
comment on constraint test_str_check on test is 'my comment on test_str_check';

选择有关表test的约束的所有注释:

select c.relname, t.conname, d.description
from pg_class c
join pg_constraint t on c.oid = t.conrelid
join pg_description d on t.oid = d.objoid and t.tableoid = d.classoid
where c.relname = 'test'

 relname |    conname     |         description          
---------+----------------+------------------------------
 test    | test_str_check | my comment on test_str_check
 test    | test_id_key    | my comment on test_id_key
(2 rows)    

答案 2 :(得分:0)

另一种方法是查询 pg_constraint 并使用 obj_description() 函数,如下所示:

select conname, obj_description(oid) as description
from pg_constraint
where conrelid = '(myschema.)mytable'::regclass;