【问题标题】:Drop Temporary Table after execution of function执行函数后删除临时表
【发布时间】:2018-04-03 00:28:32
【问题描述】:

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

【问题讨论】:

    标签: python postgresql psycopg2


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        【解决方案3】:

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

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

        不是很好,但可以。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多