首页 > 解决方案 > 如何列出所有未注释的 PostgreSQL 列?

问题描述

我正在使用 PostgreSQL 内置的注释功能记录数据库的模式。在某些时候,我忘了评论一些专栏,但我不确定哪些专栏。

有没有办法列出架构中未注释的所有列?能够结束对所有列的评论将非常有帮助。

标签: sqlpostgresql

解决方案


是的,这是可能的。为此,您需要找出架构中未在pg_description. 您可以开始列出数据库中的所有列注释:

SELECT * 
FROM pg_description
WHERE  objsubid > 0;
objoid | classoid | objsubid | description
-------|----------|----------|------------
68258  | 1259     | 10       | The number of individual Devices used in the exposure.
68258  | 1259     | 11       | A key to the provider who administered the... 

Columnobjsubid是指表中的列顺序,如果行对象是列,对于所有其他对象类型,objsubid为零。

informataion_schema.columns然后通过检查关系找到架构中的所有列:

SELECT
  (cols.table_schema || '.' || cols.table_name)::regclass, 
  cols.table_name, 
  cols.column_name, 
  cols.ordinal_position
FROM 
  information_schema.columns AS cols 
WHERE 
  cols.table_schema = 'my_schema';
table_name | column_name  | ordinal_position | oid
-----------|--------------|------------------|----
concept    | concept_id   | 1                | 67630
concept    | concept_name | 2                | 67630

ordinal_positioncolumn 指的是该列在表中的位置,位置指的是相同的objsubid。该语句(cols.table_schema || '.' || cols.table_name)::regclass创建表(例如my_schema.my_table)的字符串表示,它指向内部 Postgres 标识符objoid,该标识符与表中的标识符相同pg_description

最后,在未注释的列中LEFT JOIN出现pg_description结果。请记住将 更改table_schema为您的架构。或者,您可以忽略内部未注释的内容cols.table_schema != 'pg_catalog' AND cols.table_schema != 'information_schema'

SELECT
   column_name,
   table_name
FROM (
    SELECT
        cols.table_name,
        cols.column_name,
        cols.ordinal_position,
        (cols.table_schema || '.' || cols.table_name)::regclass AS table_oid
    FROM information_schema.columns AS cols
    WHERE cols.table_schema = 'my_schema'
) AS column_table_oid
LEFT JOIN pg_description 
    ON pg_description.objsubid = column_table_oid.ordinal_position
    AND pg_description.objoid = column_table_oid.table_oid
WHERE 
    pg_description.objoid IS NULL
    AND pg_description.objsubid IS NULL;

推荐阅读