如何将 Postgres DDL 转储到可以粘贴到 Google 表格中的 CSV 文件中?
How do I dump a Postgres DDL into a CSV that can be pasted into Google Sheets?
我正在尝试从 Postgres 创建一个输出,它将执行如下操作:
schema, table, column, type, attributes
public, table1, id, bigserial, not null primary key
public, table1, name, string, not null
...
只要输出格式为 headers 列,即使不是 CSV 也可以(我可以将普通查询导出为 CSV 就好了)。我在思考正确的查询时遇到问题。
我最接近的如下。但感觉我走错了路,有一种 simpler/cleaner 方法可以做到这一点。我目前也没有在每个 table 列中得到一行(这是我想要的)。
SELECT table_schema || ',' || table_name || ',' ||
string_agg(column_list.column_expr, ';' || '') ||
'' || ');'
FROM (
SELECT table_schema, table_name, ' ' || column_name || ',' || data_type ||
coalesce('(' || character_maximum_length || ')', ', ') ||
case when is_nullable = 'YES' then '' else ' NOT NULL' end as column_expr
FROM information_schema.columns
WHERE table_schema = 'public'
ORDER BY ordinal_position) column_list
group by table_schema,table_name;
我想我有点想多了。这是我最后使用的 SQL:
SELECT table_schema, table_name, column_list.column_name, column_list.column_expr
FROM (
SELECT table_schema, table_name, column_name, data_type ||
coalesce('(' || character_maximum_length, ' ') ||
case when is_nullable = 'YES' then '' else ' NOT NULL' end as column_expr
FROM information_schema.columns
WHERE table_schema = 'public'
ORDER BY table_name, column_name) column_list;
我正在尝试从 Postgres 创建一个输出,它将执行如下操作:
schema, table, column, type, attributes
public, table1, id, bigserial, not null primary key
public, table1, name, string, not null
...
只要输出格式为 headers 列,即使不是 CSV 也可以(我可以将普通查询导出为 CSV 就好了)。我在思考正确的查询时遇到问题。
我最接近的如下。但感觉我走错了路,有一种 simpler/cleaner 方法可以做到这一点。我目前也没有在每个 table 列中得到一行(这是我想要的)。
SELECT table_schema || ',' || table_name || ',' ||
string_agg(column_list.column_expr, ';' || '') ||
'' || ');'
FROM (
SELECT table_schema, table_name, ' ' || column_name || ',' || data_type ||
coalesce('(' || character_maximum_length || ')', ', ') ||
case when is_nullable = 'YES' then '' else ' NOT NULL' end as column_expr
FROM information_schema.columns
WHERE table_schema = 'public'
ORDER BY ordinal_position) column_list
group by table_schema,table_name;
我想我有点想多了。这是我最后使用的 SQL:
SELECT table_schema, table_name, column_list.column_name, column_list.column_expr
FROM (
SELECT table_schema, table_name, column_name, data_type ||
coalesce('(' || character_maximum_length, ' ') ||
case when is_nullable = 'YES' then '' else ' NOT NULL' end as column_expr
FROM information_schema.columns
WHERE table_schema = 'public'
ORDER BY table_name, column_name) column_list;