我正在Postgres数据库上运行一个项目,需要检索数据库中列的注释,以用作表格标题等.我已经看到有几个内置函数(pg_description和col_description),但我无法找到如何使用它们的例子,并且使用它们已经证明是徒劳的.
所以我想知道是否有人能够做到这一点,如果是这样,怎么样?
SELECT c.table_schema,c.table_name,c.column_name,pgd.description FROM pg_catalog.pg_statio_all_tables as st inner join pg_catalog.pg_description pgd on (pgd.objoid=st.relid) inner join information_schema.columns c on (pgd.objsubid=c.ordinal_position and c.table_schema=st.schemaname and c.table_name=st.relname);
这一切都是由oid工作的,
mat=> SELECT c.oid FROM pg_catalog.pg_class c WHERE c.relname = 'customers'; oid ------- 23208 (1 row)
现在,我有那张桌子的oid,所以我可以问:
mat=> select pg_catalog.obj_description(23208); obj_description ------------------- Customers (1 row)
然后,我可以要求第四栏的描述:
mat=> select pg_catalog.col_description(23208,4); col_description ----------------------------------------- Customer codes, CHS, FACTPOST, POWER... (1 row)
如果您想知道在psql
执行时运行了哪些查询,\dt+
或者\d+ customers
只是运行它-E
.
注意模式,这段代码考虑它们:
SELECT cols.column_name, ( SELECT pg_catalog.col_description(c.oid, cols.ordinal_position::int) FROM pg_catalog.pg_class c WHERE c.oid = (SELECT ('"' || cols.table_name || '"')::regclass::oid) AND c.relname = cols.table_name ) AS column_comment FROM information_schema.columns cols WHERE cols.table_catalog = 'your_database' AND cols.table_name = 'your_table' AND cols.table_schema = 'your_schema';
参考文献:
Postgresql文档表和列描述表和列的注释
在Postgres 9.1中确定表的OID?