从另一个 PL/Python 块调用 postgres PL/Python 存储函数

Call postgres PL/Python stored function from another PL/Python block

是否可以像普通 Python 函数一样从其他 PL/Python 块调用 PL/Python 函数。

比如我有一个函数f1:

create or replace function f1() returns text as $$
    return "hello"
$$ language 'plpython3u';

我想从其他函数或块调用此函数,例如这个匿名块:

do $$
begin
    ...
    t = f1()
    ...
end;
$$ language 'plpython3u';

这可以使用 t = plpy.execute("select f1()") 来完成,但我希望,如果可能的话,将其作为普通 Python 函数调用,以避免类型转换(例如 jsonb 等)。

(我用的是plpython3u~Python3).

更详细的答案在这里:Reusing pure Python functions between PL/Python functions

我的方法是使用 PG 为您提供的 GD 和 SD 词典,more here

我通常有一个函数来准备我的环境,而且我可以使用纯 python 函数而不会产生开销。在您的情况下,这看起来像:

create or replace function _meta() returns bool as $$
  def f1():
    return "hello"

  GD["f1"] = f1
  return True
$$ language 'plpython3u';

您会在每个数据库会话开始时调用 _meta,并且您的 python 函数将能够访问 f1 函数,如 GD["f1"]():

do $$
begin
    ...
    t = GD["f1"]()
    ...
end;
$$ language 'plpython3u';