先日、PostgreSQL テーブルのコメント一覧を抽出 - Oboe吹きプログラマの黙示録 を書いたので、
今度は、テーブルの列の定義とコメント一覧を抽出
任意のスキーマ、テーブルを指定して次のSQLで求める。
スキーマ名='public'
テーブル名='t_items'
SELECT a.relname AS table_name, c.description AS table_comment, b.column_name, d.description AS column_comment, b.data_type, b.udt_name, b.character_octet_length, b.numeric_precision || ',' ||b.numeric_scale AS numeric_length, b.is_nullable, b.column_default FROM pg_stat_user_tables a LEFT JOIN information_schema.COLUMNS b ON a.schemaname = b.table_schema AND a.relname = b.table_name LEFT JOIN pg_description c ON a.relid = c.objoid AND c.objsubid = 0 LEFT JOIN pg_description d ON a.relid = d.objoid AND b.ordinal_position = d.objsubid WHERE a.schemaname = 'public' AND a.relname = 't_items' ORDER BY b.ordinal_position ASC
data_type と udt_name は、以下の結果になることに注意しよう。
| data_type | udt_name |
| bigint | int8 |
| integer | int4 |
| smallint | int2 |
| character varying | varchar |