【问题标题】:Clever ways to generate JSON blob from PostgresSQL database schema从 Postgresql 数据库模式生成 JSON blob 的巧妙方法
【发布时间】:2020-01-20 17:05:24
【问题描述】:

我正在寻找巧妙的方法来生成我们的小型 postgresql 数据库模式的大型 json 对象。任何人都有这样做的经验吗?我们可以在 postgres 中编写一些简单的查询吗?我知道 json 得到了很好的支持。只是查找表名、这些表中的列以及它们的列类型。

有点像

{ "schema": [ {"books": 
{ "columns": [ { "id": {"type": "int"}... ] }}]}

编辑:输出格式并不重要,只是寻找生成数据库模式的 json 对象的方法。

【问题讨论】:

    标签: json postgresql schema


    【解决方案1】:

    类似这样的:

    select jsonb_build_object(table_schema, 
                              jsonb_agg(jsonb_build_object(table_name, columns))) as schema_info
    from (
      select t.table_schema, t.table_name, 
             jsonb_build_object('columns', jsonb_agg(jsonb_build_object(c.column_name, jsonb_build_object('type', c.data_type)) 
                                                     order by c.ordinal_position)
                               ) as columns
      from information_schema.tables t
        join information_schema.columns c 
           on c.table_schema = t.table_schema 
          and c.table_name = t.table_name
      where t.table_schema in ('public', 'foo', 'bar')
      group by t.table_schema, t.table_name
    ) t1
    group by table_schema;
    

    这将为最里面的 where 子句中列出的每个模式返回一个 JSON 值。如果需要,您可以进一步聚合它们。您可能还想对数据类型的检索进行更多调整,例如包括 VARCHAR 列的长度

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-07
      • 2015-07-29
      • 1970-01-01
      • 1970-01-01
      • 2016-05-15
      • 1970-01-01
      • 2015-01-28
      • 1970-01-01
      相关资源
      最近更新 更多