【问题标题】:how to get last Postresql serial ID that all rows before it are committed?如何获取提交之前所有行的最后一个 Postgresql 序列号?
【发布时间】: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) 不会向前移动(即使所有繁忙的事务都已完成)。所以这也不起作用。

【问题讨论】:

标签: postgresql


【解决方案1】:

没有一个非常好的方法可以直接执行此操作。我认为最好的选择确实是创建一个在事务提交时截断的临时表,以及一个将此类插入到该表中的触发器。然后您可以从临时表中查找值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-13
    • 1970-01-01
    • 2013-05-25
    • 2020-01-25
    • 1970-01-01
    • 1970-01-01
    • 2015-03-21
    • 1970-01-01
    相关资源
    最近更新 更多