在Postgresql上以编程方式生成DDL

rui*_*eco 29 postgresql ddl

如何在Postgresql上以编程方式生成表的DDL?是否有系统查询或命令来执行此操作?谷歌搜索问题没有返回指针.

Bra*_*n90 35

pg_dump与此命令一起使用:

pg_dump -U user_name -h host database -s -t table_or_view_names -f table_or_view_names.sql
Run Code Online (Sandbox Code Playgroud)

描述:

-s or --schema-only : Dump only ddl / the object definitions (schema), without data.
-t or --table Dump :  Dump only tables (or views or sequences) matching table
Run Code Online (Sandbox Code Playgroud)

例子:

-- dump each ddl table that elon build.
$ pg_dump -U elon -h localhost -s -t spacex -t tesla -t solarcity -t boring > companies.sql
Run Code Online (Sandbox Code Playgroud)

对不起,如果超出主题.只想帮助谁搜索"psql dump ddl"并重定向到此线程.


Gre*_*ill 19

您可以使用该pg_dump命令转储数据库的内容(包括架构和数据).该--schema-only交换机将只输出DDL为您桌.

  • 我不太明白你的评论.`pg_dump`随PostgreSQL一起安装,可在所有服务器上使用.使用它不需要特殊的用户权限(正常的PostgreSQL访问控制适用于您正在转储的数据库).如果您不认为这是一个程序化解决方案,您将必须指定**正在使用的编程环境以获得适当的答案. (6认同)

Way*_*rad 6

为什么 shell 到 psql 不算“以编程方式”?它会很好地转储整个模式。

无论如何,您可以从information_schema获取数据类型(以及更多)(此处引用的 8.4 文档,但这不是一个新功能):

=# select column_name, data_type from information_schema.columns
-# where table_name = 'config';
    column_name     | data_type 
--------------------+-----------
 id                 | integer
 default_printer_id | integer
 master_host_enable | boolean
(3 rows)
Run Code Online (Sandbox Code Playgroud)


Vao*_*sun 5

保存了 4 个函数来部分模拟pg_dump -s行为。基于\d+元命令。用法是类似的:

\pset format unaligned
select get_ddl_t(schemaname,tablename) as "--" from pg_tables where tableowner <> 'postgres';
Run Code Online (Sandbox Code Playgroud)

当然,您必须事先创建函数。

工作示例位于 rextester


rui*_*eco 4

答案是检查 pg_dump 的源代码并遵循它用于生成 DDL 的开关。代码内部的某个位置有许多查询用于检索用于生成 DDL 的元数据。