在PL / Python函数之间重用纯Python函数 [英] Reusing pure Python functions between PL/Python functions
问题描述
我想在
两个或多个PL / Python函数之间声明并共享一些简单的纯python函数。我正在使用Postgres 9.3。
I would like to declare and share some simple, pure python functions between two or more PL/Python functions. I am using Postgres 9.3.
例如,我有:
CREATE OR REPLACE FUNCTION get_mod(modifier varchar)
RETURNS varchar
AS $$
def is_float(val):
try:
if val:
float(val)
return True
else:
return False
except ValueError:
return False
if modifier is None:
return "NOMOD"
if is_float(modifier):
return str(float(modifier)*1)
return modifier
$$ LANGUAGE plpythonu;
我想在其中使用函数 is_float
其他一些PL / Python函数。
我知道我可以将其创建为可调用的PL / Python函数,但是我发现它比直接调用纯Python自定义实用程序函数要麻烦得多(执行对PL / Python的基于SQL的调用)。
I would like to use function is_float
in some other PL/Python function.
I understand I could create it as callable PL/Python function, but I find that much clunkier (to execute SQL-based call to PL/Python) than just making a straight call to a pure Python, custom utility function.
是否可以在Postgres上通过PL / Python可重用的纯Python函数创建和公开?
Is it possible to create and expose through PL/Python reusable pure Python functions on Postgres?
推荐答案
我通常要做的是使用 GD 。缺点是,由于GD是每个会话对象,因此每次启动新会话时都需要加载它。解决此问题的方法是在每个会话开始时运行一个启动功能,该功能填充数据库以供进一步使用。
What I usually do is pass the functions around using GD. The downside is that since GD is a per session object you need to load it each time you start a new session. The way you can approach this is to have a bootstrap function that you run at the beginning of each session that primes the database for further use. Something like:
create or replace function bootstrap() returns void
as
$$
def is_float(val):
# did some simplifying here,
try:
float(val) # Take notice that booleans will convert to float successfully
return True
except (ValueError, TypeError):
return False
GD['is_float'] = is_float
$$ language plpythonu;
现在您可以修改原始功能:
Now you can modify your original function:
CREATE OR REPLACE FUNCTION get_mod(modifier varchar)
RETURNS varchar
AS $$
# Optionally run bootstrap() here
plpy.execute("select bootstrap()")
###
if modifier is None:
return "NOMOD"
if GD['is_float'](modifier):
return str(float(modifier)*1)
return modifier
$$ LANGUAGE plpythonu;
要执行此操作,您必须运行 select bootstrap( );
在每个会话的开始,或者作为流程的一部分正在调用的第一个函数的一部分……或者实际上是您原始函数的一部分。
In order for this to work you'd have to run select bootstrap();
at the start of each session, or as part of the first function you are calling as part of the flow... Or indeed as part of your original function.
这篇关于在PL / Python函数之间重用纯Python函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!