在一个调用过的 plpython 函数中所导入的包会被缓存起来
我在 Window 7 操作系统上 安装了Python 3.3和 PostgreSQL 9.6,并在环境变量中配置好了PYTHONHOME 和 PYTHONPATH,然后将 Python33\DLLs中的python3.dll 移动到 postgresql安装目录的lib中,把它重命名为 python33。
现在,我可以在 PostgreSQL 中使用 plpython 了。
我在PostgreSQL中创建了下面的函数,它导入模块re:
create or replace function func()
returns integer
as $$
import re
return 0
$$ language plpython3u;
然后我执行了如下查询
Select func();
它返回了查询结果:
func
-------
0
接下来,我将Python的安装目录重命名为 Python33-1
并重新执行了 Select func();
它仍然能返回查询结果:
func
-------
0
接着,我创建了另一个函数,它导入模块csv:
create or replace function func1()
returns integer
as $$
import csv
return 0
$$ language plpython3u;
然后执行查询
Select func1();
这时,查询就报错了:
ERROR: ImportError: No module named 'csv'
CONTEXT: Traceback (most recent call last):
PL/Python function "func1", line 2, in <module>
import logging
PL/Python function "func1"
随后,我又将python 的安装目录 改名为 Python33。
再次执行 Select func1();
这一次,它成功返回了结果。
func
-------
0
上面的实验说明,在PostgreSQL 中,在一个 plpython 函数中导入的包,在该函数被调用后,会被缓存起来。之后即使 Python 目录不存在了,这个包仍然可以在 plpython 中被使用。
Packages imported in a plpython function are cached after the function is called.
I installed Python 3.3 and PostgreSQL 9.6 on Window 7, and configured PYTHONHOME and PYTHONPATH in the environment variables, and then moved python3.dll in Python33\DLLs to lib in the postgresql installation directory and renamed it to python33.dll.
Now I can use plpython in PostgreSQL.
I created the following function in PostgreSQL, which references the module re:
create or replace function func()
returns integer
as $$
import re
return 0
$$ language plpython3u;
Then I executed the following query
Select func();
It returned the query result
func
-------
0
Next, I rename Python's installation directory Python33 to Python 33-1,
and re-executed Select func();
It still returned the query results:
func
-------
0
Next, I created another function that imports the module csv:
create or replace function func1()
returns integer
as $$
import csv
return 0
$$ language plpython3u;
Then I executed
Select func1();
This, the query is reported wrong:
ERROR: ImportError: No module named 'csv'
CONTEXT: Traceback (most recent call last):
PL/Python function "func1", line 2, in <module>
import logging
PL/Python function "func1"
I then renamed Python's installation directory to Python33,
and re-excuted Select func1();
It returned the results successfully .
func
-------
0
The above experiment shows that in PostgreSQL, packages imported in a plpython function are cached after the function is called. After that, the package can still be used in plpython even if the Python directory does not exist.