如何导出Postgres DDL元数据为可粘贴至Google Sheets的格式
如何在PostgreSQL中生成逐列的schema、table、column、type、attributes输出
我来帮你调整查询思路——你之前的写法把同一表的所有列聚合到了一行,这就是为什么没法得到逐列的结果。下面是能直接生成你需要的格式(每行对应一个列,包含完整属性)的查询:
SELECT c.table_schema AS schema, c.table_name AS table, c.column_name AS column, -- 优化数据类型显示,比如带长度的字符类型 CASE WHEN c.data_type = 'character varying' THEN 'varchar(' || c.character_maximum_length || ')' WHEN c.data_type = 'character' THEN 'char(' || c.character_maximum_length || ')' WHEN c.data_type = 'numeric' THEN 'numeric(' || c.numeric_precision || ',' || c.numeric_scale || ')' ELSE c.data_type END AS type, -- 拼接列属性:NOT NULL、PRIMARY KEY等 STRING_AGG(DISTINCT attr.attribute, ' ' ORDER BY attr.attribute) AS attributes FROM information_schema.columns c LEFT JOIN ( -- 收集NOT NULL属性 SELECT table_schema, table_name, column_name, 'NOT NULL' AS attribute FROM information_schema.columns WHERE is_nullable = 'NO' UNION ALL -- 收集PRIMARY KEY属性 SELECT tc.table_schema, tc.table_name, kcu.column_name, 'PRIMARY KEY' AS attribute FROM information_schema.table_constraints tc JOIN information_schema.key_column_usage kcu ON tc.constraint_name = kcu.constraint_name AND tc.table_schema = kcu.table_schema AND tc.table_name = kcu.table_name WHERE tc.constraint_type = 'PRIMARY KEY' ) attr ON c.table_schema = attr.table_schema AND c.table_name = attr.table_name AND c.column_name = attr.column_name WHERE c.table_schema = 'public' -- 可根据需要修改目标schema GROUP BY c.table_schema, c.table_name, c.column_name, c.data_type, c.character_maximum_length, c.numeric_precision, c.numeric_scale ORDER BY c.table_schema, c.table_name, c.ordinal_position;
关键说明:
- 逐行输出:主查询基于
information_schema.columns的每一行(即每个列)进行分组,避免了原查询的聚合操作,自然得到每行对应一个列的结果。 - 友好的类型显示:通过
CASE语句把PostgreSQL内部的数据类型名称(比如character varying)转换成更常用的写法(比如varchar(50)),同时处理了数值类型的精度和小数位。 - 完整属性拼接:通过子查询
attr整合了两类常见属性:- 从
information_schema.columns获取NOT NULL标记 - 关联
table_constraints和key_column_usage获取PRIMARY KEY标记
最后用STRING_AGG把同一列的多个属性(比如同时是主键且非空)拼接成一个字符串,按顺序排列。
- 从
- 排序逻辑:按
ordinal_position排序,保证输出的列顺序和表定义中的顺序一致。
扩展功能(可选):
如果需要添加其他属性(比如UNIQUE、FOREIGN KEY),只需在子查询中添加对应的UNION ALL块即可,示例:
-- 添加UNIQUE约束属性 UNION ALL SELECT tc.table_schema, tc.table_name, kcu.column_name, 'UNIQUE' AS attribute FROM information_schema.table_constraints tc JOIN information_schema.key_column_usage kcu ON tc.constraint_name = kcu.constraint_name AND tc.table_schema = kcu.table_schema AND tc.table_name = kcu.table_name WHERE tc.constraint_type = 'UNIQUE'
这个查询的结果直接导出为CSV即可,已经包含了你需要的列标题,完全符合你的需求。
内容的提问来源于stack exchange,提问作者Eric Lubow
相关产品推荐
相关产品推荐

