执行函数后删除临时 Table

Drop Temporary Table after execution of function

我正在从 Python 开始多次循环执行自己编写的 postgresql 函数。我正在使用 psycopg2 框架来执行此操作。 我写的函数结构如下:

CREATE OR REPLACE FUNCTION my_func()
RETURNS void AS
$$
BEGIN
    -- create a temporary table that should be deleted after  
    -- the functions finishes
    -- normally a CREATE TABLE ... would be here
    CREATE TEMPORARY TABLE temp_t
        (
          seq integer,
          ...
        ) ON COMMIT DROP;

    -- now the insert    
    INSERT INTO temp_t
        SELECT
        ...

END
$$
LANGUAGE 'plpgsql';

基本上就是 python 部分

import time
import psycopg2
conn = psycopg2.connect(host="localhost", user="user", password="...", dbname="some_db")
cur = conn.cursor()
for i in range(1, 11):
    print i
    print time.clock()
    cur.callproc("my_func")
    print time.clock()
cur.close()
conn.close()

我在 运行 python 脚本时得到的错误是:

---> relation "temp_t" already exists

基本上我想测量执行函数需要多长时间。这样做,循环应 运行 几次。将 SELECT 的结果存储在临时的 table 中应该会替换通常会创建输出 table 的 CREATE TABLE ... 部分 为什么我从 Python 执行函数后 postgres 不删除函数?

临时 tables 在会话结束时被丢弃。由于您的会话未以函数调用结束,因此第二个函数调用将尝试再次创建 table。您需要更改存储功能并检查临时 table 是否已存在,如果不存在则创建它。 This post 可以帮助您做到这一点。

另一个快速 n dirty 是在每次函数调用后连接和断开连接。

import time
import psycopg2
for i in range(1, 11):
    conn = psycopg2.connect(host="localhost", user="user", password="...",   dbname="some_db")
    cur = conn.cursor()
    print i
    print time.clock()
    cur.callproc("my_func")
    print time.clock()
    cur.close()
    conn.close()

不太好,但确实有用。

循环中的所有函数调用都在一个事务中执行,因此临时 table 不会每次都被丢弃。设置 autocommit 应该会改变这个行为:

...
conn = psycopg2.connect(host="localhost", user="user", password="...", dbname="some_db")
conn.autocommit = True
cur = conn.cursor()
for i in range(1, 11):
    ...