我需要创建PostgreSQL数据库对象的脚本。
我没有访问pg_dump的权限,因此必须使用SQL查询获取所有内容。我该怎么做?
我需要创建PostgreSQL数据库对象的脚本。
我没有访问pg_dump的权限,因此必须使用SQL查询获取所有内容。我该怎么做?
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
视图返回相同的信息,则应优先使用它们。
在你探索查询的过程中,你会发现psql -E
非常有用。
它显示了psql
执行反斜杠命令时使用的查询语句-比如\df+ myfunc
以获取有关此函数的详细信息。
以下是使用 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
;;
您也可以在psql中使用\sf来查看用户定义的函数。
SELECT
pp.proname, --function name.
pp.pronamespace::regnamespace::text AS schema, --function located schema
pg_get_functiondef(oid), --function def
pg_get_function_arguments(oid), --(including default values).
pg_get_function_identity_arguments(oid), --This form omits default values.
pg_get_function_result(oid) --Reconstructs the RETURNS clause of a function
FROM
pg_proc pp
WHERE
proname = 'eval_safe';
来自手册
pg_get_functiondef ( func oid ) → text
pg_get_function_arguments ( func oid ) → text
pg_get_function_identity_arguments ( func oid ) → text
pg_get_function_result ( func oid ) → text
\ef
,它可以“编辑CREATE FUNCTION命令形式的函数”(http://www.postgresql.org/docs/9.3/static/app-psql.html)。 - Jared Beck