【发布时间】:2013-03-25 20:28:53
【问题描述】:
我正在使用 Postgresql 9.0.5,并且我有一个 cron 作业,它定期从表中读取新创建的行并将其值累积到具有每小时数据的汇总表中。
我需要获取已提交的最新 ID(序列号)以及提交之前的所有行。
currval 函数在这种情况下不会给出正确的值,因为插入 currval 的事务可能比其他事务更早提交。暂时使用 SELECT 语句,我可以看到 Id 列不连续,因为某些行仍未提交。
Here is some sample code I have used to test:
--test race condition
create table mydata(id serial,val int);
--run in thread 1
create or replace function insert_delay() returns void as $$
begin
insert into mydata(val) values (1);
perform pg_sleep(60);
end;
$$ language 'plpgsql';
--run in thread 2
create or replace function insert_ok() returns void as $$
begin
insert into mydata(val) values (2);
end;
$$ language 'plpgsql';
--run in thread 3
mytest=# select * from mydata; --SHOULD HAVE SEEN id = 1 and 2;
id | val
----+-----
2 | 2
(1 row)
我什至尝试了一些类似下面的陈述;
select max(id) from mydata age(xmin) >= age(txid_snapshot_xmin(txid_current_snapshot())::text::xid);
但是在生产线(运行大容量事务)中,返回的 max(id) 不会向前移动(即使所有繁忙的事务都已完成)。所以这也不起作用。
【问题讨论】:
-
有什么理由不能让触发器实时构建汇总表?
-
1.我会用时间戳列来做到这一点。 2.我还没有完全理解你想要做什么,但如果你还没有看到它:你可以通过事务隔离来控制读取级别:postgresql.org/docs/9.1/static/transaction-iso.html 这样你就可以“看到”另一个,非已提交的事务
-
这和stackoverflow.com/questions/9226322/… 基本上是同一个问题(虽然从不同的角度问),stackoverflow.com/questions/9226322/… 本身就像stackoverflow.com/questions/1914675/…,看看。
标签: postgresql