执行功能后删除临时表

问题描述 投票:1回答:3

我正在从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没有丢弃函数?

python postgresql psycopg2
3个回答
1
投票

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


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
投票

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

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

不好,但诀窍。

© www.soinside.com 2019 - 2024. All rights reserved.