lodopidolo
lodopidolo

Reputation: 175

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

Is it possible to call PL/Python function from other PL/Python block as a normal Python function.

For example, I have a function f1:

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

I want call this function from other function or block, for example this anonymous block:

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

This can be done using t = plpy.execute("select f1()"), but I want, if it is possible, call it as a normal Python function to avoid type conversions (for example jsonb, etc).

(I'm using plpython3u ~ Python 3).

Upvotes: 2

Views: 2652

Answers (1)

Drazen Urch
Drazen Urch

Reputation: 2901

More detailed answer here: Reusing pure Python functions between PL/Python functions

The way I approach this is by using GD and SD dictionaries that PG provides for you, more here.

I usually have one function that prepares my environment and than I can use pure python functions without overhead. In your case this would look like:

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

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

You would than call _meta at the beginning of each DB session, and your python functions would be able to access the f1 function as GD["f1"]():

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

Upvotes: 4

Related Questions