Get definition of function, sequence, type etc. in Postgresql with SQL query

狂风中的少年 提交于 2019-12-18 13:01:28

问题


I need the create scripts for PostgreSQL database objects.

I have not access to pg_dump. So I have to get everything with SQL queries. How could I do this?


回答1:


To get the definition of a function use pg_get_functiondef():

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

There are similar functions to retrieve the definition of an index, a view, a rule and so on. For details see the manual: http://www.postgresql.org/docs/current/static/functions-info.html

Getting the definition of a user type is a bit more tricky. You will need to query information_schema.attributes for that:

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

From that you need to re-assemble the create type statement.

For more details you will need to read through the documentation of the system catalog: http://www.postgresql.org/docs/current/static/catalogs.html

But you should prefer information_schema views if they return the same information.




回答2:


You will find psql -E instrumental in your quest for those queries.
It displays the queries psql uses when executing its backslash-commands - like \df+ myfunc for details about this function.




回答3:


Here is a complete sample query using 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
;;

Note, you should obviously specify the schema name, (or "public" if you are using that schema)



来源:https://stackoverflow.com/questions/12148914/get-definition-of-function-sequence-type-etc-in-postgresql-with-sql-query

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!