5

I'm trying to get FULL definition text of a function, but the query that everyone suggests returns the functions script without the header and footer parts.

Here's what I'm using:

select prosrc from pg_proc where proname='my_func';

Here's what is returned:

DECLARE
some_var1 TEXT;
some_var2 TEXT;
Status character varying;

BEGIN
--SCRIPT CODE HERE

RETURN retval;
END;

But what I want is this:

CREATE OR REPLACE FUNCTION my_func(logdate_utc date)
RETURNS character varying
LANGUAGE 'plpgsql'

COST 100
VOLATILE 
AS $BODY$
DECLARE
some_var1 TEXT;
some_var2 TEXT;
Status character varying;

BEGIN
--SCRIPT CODE HERE

RETURN retval;
END;
$BODY$;

ALTER FUNCTION my_func(date)
    OWNER TO some_owner;

Searched around and haven't found much. How can I get that result?

3 Answers 3

12

Using SQL:

 select pg_catalog.pg_get_functiondef('my_func(date)'::regprocedure::oid);

Doc

Note that you should to use regprocedure type if you specify the parameters list and regproc type if you specify only function name (like 'my_func'::regproc::oid)

And using command line psql with \sf meta-command:

This command fetches and shows the definition of the named function, in the form of a CREATE OR REPLACE FUNCTION command. The definition is printed to the current query output channel, as set by \o.

The target function can be specified by name alone, or by name and arguments, for example foo(integer, text). The argument types must be given if there is more than one function of the same name.

from the documentation.

For example:

psql -c '\sf my_func(date)'

And to retrieve function's owner name you can use next query:

select proowner::regrole
from pg_proc
where oid = 'my_func(date)'::regprocedure;
Sign up to request clarification or add additional context in comments.

Comments

9

Use pg_get_functiondef(func_oid):

SELECT pg_get_functiondef('my_func'::regproc);

Comments

1

SELECT pg_get_functiondef(( SELECT oid FROM pg_proc where proname= 'my_func'));

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.