执行功能后删除临时表

时间:2017-01-26 11:27:58

标签: python postgresql psycopg2

我在postgresql中多次在循环中执行自写Python函数。我正在使用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的结果存储在临时表中应该替换通常会创建输出表的CREATE TABLE ...部分 从postgres执行函数后,为什么Python不会删除函数?

3 个答案:

答案 0 :(得分:3)

循环中的所有函数调用都在单个事务中执行,因此每次都不会删除临时表。设置autocommit应该会改变此行为:

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

答案 1 :(得分:1)

会话结束时删除临时表。由于您的会话不以函数调用结束,因此第二个函数调用将尝试再次创建表。您需要更改商店功能并检查临时表是否已存在,如果不存在则创建临时表。 http://codepen.io/AceDesigns/pen/ZLXLKa帖子可以帮助您这样做。

答案 2 :(得分:1)

另一个快速的脏点是在每次函数调用后连接和解除连接。

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()

不太好,但有诀窍。