【问题标题】:PostgreSQL: dropping functions using information_schemePostgreSQL:使用 information_schema 删除函数
【发布时间】:2025-12-30 10:05:12
【问题描述】:

我了解到我可以使用以下方法选择所有具有相同名称的函数:

select *
from information_schema.routines
where routine_type='FUNCTION' and routine_name='test';

但是,显然这是一种观点,当我尝试时:

delete
from information_schema.routines
where routine_type='FUNCTION' and routine_name='test';

我收到无法从视图中删除的消息。

我最初采用这种方法的原因是因为我想要一个不需要命名参数的惰性删除函数——我正在开发一些新函数,并且在这种状态下,参数列表将是可变的。

我可以使用这种技术来删除具有相同名称的函数吗?怎么样?

【问题讨论】:

  • 一种懒惰的删除函数的方法是在psql 中使用自动完成功能,而不是从目录中删除一行

标签: postgresql function information-schema


【解决方案1】:

永远不要弄乱系统目录。

你可以创建一个小脚本来做你想做的事:

do
$$
declare
  proc_rec record;
  drop_ddl   text;
begin
  for proc_rec in SELECT n.nspname, p.proname, 
                         pg_get_function_arguments(p.oid) as args
                  FROM pg_catalog.pg_proc p  
                    JOIN pg_catalog.pg_namespace n on p.pronamespace = n.oid 
                  where n.nspname = 'public' -- don't forget the function's schema!
                    and p.proname = 'test'
  loop 
    drop_ddl := format('drop function %I.%I(%s)', proc_rec.nspname, proc_rec.proname, proc_rec.args);
    raise notice '%', drop_ddl;
    -- execute drop_ddl; -- uncomment to actually drop the function
  end loop;
end;
$$

如果您需要更频繁地执行此操作,您可以将该代码放入一个函数中。

【讨论】: