基本查询
此查询创建所有必要的 DDL 语句:
SELECT 'DROP FUNCTION ' || oid::regprocedure
FROM pg_proc
WHERE proname = 'my_function_name' -- name without schema-qualification
AND pg_function_is_visible(oid); -- restrict to current search_path
输出:
DROP FUNCTION my_function_name(string text, form text, maxlen integer);
DROP FUNCTION my_function_name(string text, form text);
DROP FUNCTION my_function_name(string text);
检查合理性后执行命令。
传递函数名称区分大小写且不添加双引号以匹配pg_proc.proname。
转换为对象标识符类型regprocedure (oid::regprocedure),然后隐式转换为text,生成带有参数类型的函数名称,根据自动双引号和模式限定到当前的search_path 需要的地方。 没有 SQL 注入可能。
pg_function_is_visible(oid) 将选择限制为当前search_path(“可见”)中的函数。你可能想要也可能不想要这个。
如果您在多个架构中有多个同名函数,或者具有不同函数参数的重载函数,所有将分别列出。您可能希望限制为特定模式或特定函数参数。
相关:
功能
您可以围绕此构建一个plpgsql 函数以立即使用EXECUTE 执行语句。对于 Postgres 9.1 或更高版本:
小心!它会降低你的功能!
CREATE OR REPLACE FUNCTION f_delfunc(_name text, OUT functions_dropped int)
LANGUAGE plpgsql AS
$func$
-- drop all functions with given _name in the current search_path, regardless of function parameters
DECLARE
_sql text;
BEGIN
SELECT count(*)::int
, 'DROP FUNCTION ' || string_agg(oid::regprocedure::text, '; DROP FUNCTION ')
FROM pg_catalog.pg_proc
WHERE proname = _name
AND pg_function_is_visible(oid) -- restrict to current search_path
INTO functions_dropped, _sql; -- count only returned if subsequent DROPs succeed
IF functions_dropped > 0 THEN -- only if function(s) found
EXECUTE _sql;
END IF;
END
$func$;
呼叫:
SELECT f_delfunc('my_function_name');
如果没有引发异常,该函数将返回找到和删除的函数数。 0 如果没有找到。
进一步阅读:
对于使用 regproc 和 pg_get_function_identity_arguments(oid) 的函数的 9.1 或更早版本的 Postgres 版本,请检查此答案的编辑历史记录。