从PL / Python函数中访问PostgreSQL函数

时间:2017-10-05 22:30:20

标签: postgresql postgresql-9.5 plpython

有没有办法从PL / Python函数中访问PostgreSQL函数?

当我用PL / pgSQL编写时,我可以调用它们。例如,我可以在PL / pgSQL中编写char_length('Bob'),它将使用内置的PostgreSQL函数char_length。当我尝试使用PL / Python时,char_length的错误是未定义的。是否有可以访问内置函数的命名空间? plpy.functions.whatever或类似的东西?

我在PostgreSQL 9.5.9上使用plpython3u。

1 个答案:

答案 0 :(得分:1)

您可以使用函数plpy.execute(),示例执行任何sql命令:

create or replace function py_test(str text)
    returns int
    language plpython3u
as $$
    res = plpy.execute("select char_length('{}')".format(str))
    return res[0]["char_length"]
$$;

select py_test('abc');

 py_test 
---------
       3
(1 row) 

请阅读文档:Database Access Functions.