PostgreSQL: How to list all stored functions that access specific table
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) ~* '\mbig\M';
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:
- How to drop all of my functions in PostgreSQL?
This query is pretty easy to use:
SELECT proname, proargnames, prosrc FROM pg_proc WHERE prosrc ILIKE '%Text to search%';