将postgres db模式转换为json格式

时间:2014-03-08 17:49:56

标签: json postgresql-9.2

我正在寻找一种将postgres数据库模式转换为JSON格式数据的方法。

e.g:

{"Table" : 
   {"name": "varchar(20)",
    "Age" : "int"
   },
}

有人可以帮我这个吗?

1 个答案:

答案 0 :(得分:3)

这是使用php的解决方案:

$conn = pg_connect("host={$host} port=5432 dbname={$db} user={$user} password={$pass}");

$sql = <<<SQL
SELECT tables.table_name, columns.column_name, columns.data_type, columns.udt_name
FROM information_schema.tables AS tables
    JOIN information_schema.columns AS columns
        ON tables.table_name = columns.table_name
WHERE tables.table_type = 'BASE TABLE'
AND tables.table_schema NOT IN
('pg_catalog', 'information_schema');
SQL;

$result = pg_query($conn, $sql);
$table_meta = new stdClass;
while ($row =  pg_fetch_object($result)) {
    if (!isset($table_meta->{$row->table_name})) $table_meta->{$row->table_name} = new stdClass;
    $table_meta->{$row->table_name}->{$row->column_name} = $row->udt_name;
}

$table_json = json_encode($table_meta);

echo $table_json;

这与我使用postgres 9.2.4一样接近

select row_to_json(table_schema)
from (
    select t.table_name, array_agg( c ) as columns
    from information_schema.tables t
    inner join (
        select cl.table_name, cl.column_name, cl.udt_name
        from information_schema.columns cl
    ) c (table_name,column_name,udt_name) on c.table_name = t.table_name
    where t.table_type = 'BASE TABLE'
    AND t.table_schema NOT IN ('pg_catalog', 'information_schema')
    group by t.table_name
) table_schema;

结果并不漂亮:

{"table_name":"users","columns":[
    {"table_name":"users","column_name":"user_id","udt_name":"int4"},
    {"table_name":"users","column_name":"user_email","udt_name":"varchar"}
]}
postgres 9.3提供了比9.2更多的json功能。如果可能,请升级并查看9.3 json function文档。如果无法升级,我会使用像我之前发布的php代码这样的脚本完成此任务。