【问题标题】:Get definition of function, sequence, type etc. in Postgresql with SQL query使用 SQL 查询在 Postgresql 中获取函数、序列、类型等的定义
【发布时间】:2012-08-27 20:11:43
【问题描述】:

我需要 PostgreSQL 数据库对象的创建脚本。

我无权访问 pg_dump。所以我必须使用 SQL 查询来获取所有内容。我怎么能这样做?

【问题讨论】:

标签: sql postgresql ddl


【解决方案1】:

要获取函数的定义,请使用pg_get_functiondef():

select pg_get_functiondef(oid)
from pg_proc
where proname = 'foo';

有类似的函数来检索索引、视图、规则等的定义。详情见手册:http://www.postgresql.org/docs/current/static/functions-info.html

获取用户类型的定义有点棘手。您需要为此查询information_schema.attributes

select attribute_name, data_type
from information_schema.attributes
where udt_schema = 'public'
  and udt_name = 'footype'
order by ordinal_position;

您需要重新组装create type 语句。

更多详细信息,您需要阅读系统目录的文档:http://www.postgresql.org/docs/current/static/catalogs.html

但如果 information_schema 视图返回相同的信息,您应该更喜欢它们。

【讨论】:

  • 感谢您的回复。我的数据库中有大约 8 个用户类型,但是当我查看 information_schema.attributes 时,有 0 行。有什么想法吗?
  • @John:不知道。你能发布这些类型的定义吗?要获得更详细的语句,请遵循 Erwin 的建议并使用 -E 开关启动 psql 以查看它正在使用哪些语句。很可能涉及 pg_type 和 pg_attribute。
【解决方案2】:

您会发现psql -E 有助于您查询这些问题。
它显示 psql 在执行其反斜杠命令时使用的查询 - 如 \df+ myfunc 以了解有关此功能的详细信息。

【讨论】:

    【解决方案3】:

    这是一个使用 pg_get_functiondef 的完整示例查询:

    WITH funcs AS (
      SELECT
        n.nspname AS schema
        ,proname AS sproc_name
        ,proargnames AS arg_names
        ,t.typname AS return_type
        ,d.description
        ,pg_get_functiondef(p.oid) as definition
      FROM pg_proc p
        JOIN pg_type t on p.prorettype = t.oid
        JOIN pg_description d on p.oid = d.objoid
        JOIN pg_namespace n on n.oid = p.pronamespace
      WHERE n.nspname = 'some_schema_name_here'
    )
    SELECT *
    FROM funcs
    ;;
    

    注意,您显然应该指定架构名称,(如果您使用的是该架构,则为“public”)

    【讨论】:

    • 注意,我更喜欢这种格式,因为我可以使用此查询来搜索包含描述(我的基本函数文档)或函数定义中的特定文本的函数。
    猜你喜欢
    • 1970-01-01
    • 2019-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-09
    • 2010-09-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多