9

How to get list of all user defined functions via SQL query ?


I find this code here

SELECT p.proname, p.pronargs, t.typname
 FROM pg_proc p, pg_language l, pg_type t
 WHERE p.prolang = l.oid
 and p.prorettype = t.oid
 and l.lanname = 'c'
ORDER BY proname;

but this gets C-functions

How to get user defined, procedural language functions, writen for example in plpgsql language?

Oto Shavadze
  • 40,603
  • 55
  • 152
  • 236

1 Answers1

29

Consider:

select 
    pp.proname,
    pl.lanname,
    pn.nspname,
    pg_get_functiondef(pp.oid)
from pg_proc pp
inner join pg_namespace pn on (pp.pronamespace = pn.oid)
inner join pg_language pl on (pp.prolang = pl.oid)
where pl.lanname NOT IN ('c','internal') 
  and pn.nspname NOT LIKE 'pg_%'
  and pn.nspname <> 'information_schema';

See also: What is the command to find script of a existing function in postgresql?

Use pg_get_functiondef or the prosrc column from pg_proc directly. The key idea is to join on pg_namespace and filter out the PostgreSQL catalog functions, which will probably be adequate for most purposes:

FROM pg_proc pp INNER JOIN pg_namespace ON (pp.pronamespace = pn.oid)
WHERE pn.nspname <> 'pg_catalog'

The trouble with obtaining the source code for user defined functions is deciding what user means. Many types of functions can be created:

  • Functions using CREATE EXTENSION.
  • Functions created by PostgreSQL.
  • Functions compiled and installed by an administrator.

Superusers with sufficent grants can define functions in pg_proc, but usually don't.

Since only superusers can create C language functions, exclude them. Such functions can be custom-installed on a particular database by the admin, but not a normal user.

Community
  • 1
  • 1
Craig Ringer
  • 307,061
  • 76
  • 688
  • 778
  • Thank you, using this query `SELECT proname,pg_get_functiondef(oid) FROM pg_proc ` we get all functions name (and definition code) right? and how get only functions, which is create from user, there is some condition in `where` clause for this? – Oto Shavadze May 19 '13 at 07:15
  • 1
    @OTARIKI If I understand you correctly you want only *user defined* functions. The trouble there is deciding what "user" means. Are functions added by CREATE EXTENSION user defined? What I'd suggest doing is `FROM pg_proc pp INNER JOIN pg_namespace ON (pp.pronamespace = pn.oid)` then filtering on `WHERE pn.nspname <> 'pg_catalog'` to exclude functions defined in `pg_catalog`. Users *can* define functions in `pg_proc` (if they're superuser or `GRANT`ed the rights to) but usually don't. – Craig Ringer May 19 '13 at 11:06
  • @ CraigRinger, ErwinBrandstetter - Thanks very much – Oto Shavadze May 19 '13 at 11:57