PostgreSQL: How to list all stored functions that access specific table

Posted on

Question :


PostgreSQL database with several hundred of stored functions, including obsolete, not used etc.


I need to find out all the stored functions that have any relationship to the table X – as I want to change the table structure. Some of them might be not used, so I can’t do that just by looking through the code.

The solution I have ATM is running psql’s df+ and grepping output, but I’d prefer more database-like solution, i.e. by using information schema. This will definitely be a repetitive task and I’d like to have it nice and clean.

Any suggestions?

Answer :

The body of a function is just stored as string. There is no list of referenced objects. (That’s different from views, for instance, where actual links to referenced tables are saved.)

This query for Postgres 10 or older uses the system catalog information function pg_get_functiondef() to reconstruct the CREATE FUNCTION script for relevant functions and searches for the table name with a case-insensitive regular expression:

SELECT n.nspname AS schema_name
     , p.proname AS function_name
     , pg_get_function_arguments(p.oid) AS args
     , pg_get_functiondef(p.oid) AS func_def
FROM   pg_proc p
JOIN   pg_namespace n ON n.oid = p.pronamespace
WHERE  NOT p.proisagg
AND    n.nspname NOT LIKE 'pg_%'
AND    n.nspname <> 'information_schema'
AND    pg_get_functiondef(p.oid) ~* 'mbigM';

It should do the job, but it’s obviously not bullet-proof. It can fail for dynamic SQL where the table name is generated dynamically and it can return any number of false positives – especially if the table name is a common word.

Aggregate functions and all functions from system schemas are excluded.

m and M mark the beginning and end of a word in the regular expression.

The system catalog pg_proc changed in Postgres 11. proisagg was replaced by prokind, true stored procedures were added. You need to adapt. Related:

This query is pretty easy to use:

SELECT proname, proargnames, prosrc FROM pg_proc WHERE prosrc ILIKE '%Text to search%';

Leave a Reply

Your email address will not be published. Required fields are marked *