【问题标题】:Is there a build-in function or a simple way to get DDL of a table in PostgreSQL 12?在 PostgreSQL 12 中是否有内置函数或简单的方法来获取表的 DDL?
【发布时间】:2019-10-23 13:41:15
【问题描述】:

我想在 PostgreSQL 中获取一个表的 DDL,如下所示:

CREATE TABLE public.person (
    id serial NOT NULL,
    "name" varchar(50) NOT NULL,
    age int4 NOT NULL,
    CONSTRAINT person_name_uk UNIQUE (name),
    CONSTRAINT person_pkey PRIMARY KEY (id)
);

我记得,在 MySQL 中有一个查询 SHOW CREATE TABLE。在 PostgreSQL 中是否有类似的方法来获得相同的结果?

我对 PostgreSQL 12 版本的解决方案感兴趣。

我需要一个完全在 SQL 中的解决方案,所以我可以在 SQL 函数内部使用。因此\d+pg_dump 不适合。

【问题讨论】:

    标签: postgresql


    【解决方案1】:

    使用pg_dump:

    pg_dump -U user_name -h host database -s -t table_name -f table_name.sql
    

    仅供参考

    -s or --schema-only : Dump only ddl without data.
    -t or --table Dump :  Dump only tables
    

    您可以尝试在PostgreSQL 日志文件中跟踪pg_dump 的实际操作。您可以使用相同的策略。

    【讨论】:

    • 感谢您的回答。但是我需要一个完全针对 SQL 的解决方案,而不是借助终端中的特殊实用程序。我将编辑我的问题。
    • 那么 pg_dump 使用的转储策略可能有助于识别。
    【解决方案2】:

    一个地方是 information_schema 列视图:

    https://www.postgresql.org/docs/current/infoschema-columns.html

    您可能会发现此线程相关:

    How to generate the "create table" sql statement for an existing table in postgreSQL

    无数的客户端工具可以为您编写CREATE TABLE 脚本。除了检查 pg_dump 本身的极好建议之外,这是另一个查找相关脚本的地方。

    【讨论】:

      猜你喜欢
      • 2011-05-08
      • 1970-01-01
      • 2021-04-29
      • 1970-01-01
      • 2010-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多