Postgres交易并移动一行

时间:2015-02-04 22:41:18

标签: postgresql concurrency transactions

我有一个tableA,我需要在其中删除一行,但我想要一个已删除行的备份日志,所以我会将它插入tableB拳头,如此(表A和B是相同的)

DO $$
BEGIN
   Insert into tableB select * from tableA where (extract(epoch from (now() - keepalivedate))) > 120;
   Delete from tableA where (extract(epoch from (now() - keepalivedate))) > 120;
END
$$;

我的问题是如果我在插入和删除之间的另一个连接上更新Keepalivedate会发生什么?为了模拟,我做了这个:

DO $$
BEGIN
   Insert into tableB select * from tableA where (extract(epoch from (now() - keepalivedate))) > 120;
    PERFORM pg_sleep(60);
   Delete from tableA where (extract(epoch from (now() - keepalivedate))) > 120;
END
$$;

并运行不同的连接:        update tableA set keepalivedate = now();

发生的事情是TableB获得了原始时间的记录,tableA保留了更新时间的记录。这打破了我的日志。

我希望这个插入删除会被频繁调用,但是大部分时间都应该失败。我也期待keepalivetime的更新频繁发生。

我的解决方法是选择PK进入临时表,然后运行插入并删除其中id为temptable的OR

DO $$
BEGIN
   PERFORM Processid From docsadm.LicenceCount where (extract(epoch from (now() - keepalivedate))) > 120
           for update;
   Insert into tableB select * from tableA where (extract(epoch from (now() - keepalivedate))) > 120;
   Delete from tableA where (extract(epoch from (now() - keepalivedate))) > 120;
END
$$;

或者我只是让这变得复杂,我应该用我原来的陈述?

0 个答案:

没有答案