在调用它之前如何检查 postgresql 过程是否存在

How do I check is a postgresql procedure exists before calling it

我有一个程序可能不存在于架构中(它会在服务启动时自行安装)

我目前正在使用

从另一个过程中调用它

perform some_schema.some_job(x)

如何在调用之前检查此过程是否存在?

你可以运行

IF NOT EXISTS (SELECT 1
               FROM pg_catalog.pg_proc
               WHERE proname = 'some_job'
                 AND pronamespace = 'some_schema'::regnamespace)
THEN
   ...
END IF;

但这是个坏主意,因为存在竞争条件。 如果并发会话 运行 使用相同的代码并在检查和函数调用之间创建函数怎么办?

通常最好这样做:

BEGIN
   /* might fail if the function does not exist */
   PERFORM some_schema.some_job(x);
EXCEPTION
   WHEN undefined_function THEN
      BEGIN
         CREATE FUNCTION ...
      EXCEPTION
         WHEN duplicate_function THEN
            /* this is ok, concurrent process created it */
            NULL;
      END;

      /* now it cannot fail */
      PERFORM some_schema.some_job(x);
END;