LoginSignup
3
2

PostgreSQLでテーブルとカラムのコメント抽出

Last updated at Posted at 2022-03-08

備忘録。

テーブルやカラムにつけたコメントをまとめて表示する。
WHEREにて、テーブル指定やコメント文字列指定、NULL指定ができる。

コンセプトは、把握できていないDBについて、コメントを横断検索して、調査の手がかりにすること。

ビューに対応させる気がなかったので、
必要な人はpg_stat_user_tablesをpg_classに変えること。
ユーザテーブルに絞り込まれているので便利。

確認:PostgreSQL12

PostgreSQL
SELECT
    pg_stat_user_tables.schemaname,
    (SELECT pg_description.description
    FROM pg_description
    WHERE pg_stat_user_tables.schemaname::regnamespace = pg_description.objoid
    ) AS schemacomment,
    pg_stat_user_tables.relname,
    (SELECT pg_description.description
    FROM pg_description
    WHERE pg_stat_user_tables.relid = pg_description.objoid
    AND pg_description.objsubid = 0
    ) AS relcomment,
    information_schema.columns.column_name,
    pg_description.description AS colcomment,
    information_schema.columns.data_type,
    information_schema.columns.character_octet_length,
    information_schema.columns.numeric_precision || ',' ||
      information_schema.columns.numeric_scale AS numeric_length
FROM pg_stat_user_tables
LEFT JOIN information_schema.columns
    ON pg_stat_user_tables.schemaname = information_schema.columns.table_schema
    AND pg_stat_user_tables.relname = information_schema.columns.table_name
LEFT JOIN pg_description
    ON pg_description.objoid = pg_stat_user_tables.relid
    AND pg_description.objsubid = information_schema.columns.ordinal_position
WHERE 1 = 1
/*    AND pg_description.objsubid = 1 */
/*    AND pg_stat_user_tables.schemaname = 'schema' */
/*    AND pg_stat_user_tables.relname = 'table' */
/*    AND EXISTS
    (SELECT 1 FROM pg_description
    WHERE pg_stat_user_tables.relid = pg_description.objoid
    AND pg_description.objsubid = 0
    AND pg_description.description = 'relcomment'
    ) */
/*    AND information_schema.columns.column_name = 'column' */
/*    AND pg_description.description = 'colcomment' */
ORDER BY pg_stat_user_tables.schemaname,
    pg_stat_user_tables.relname,
    information_schema.columns.ordinal_position;

参考:https://ufirst.jp/memo/2014/11/30/postgresでテーブルのカラム一覧をコメント付きで取得/

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2