PostgreSQL 对不同事务的读取提交

PostgreSQL read commit on different transactions

我运行 进行了一些测试以更好地理解 postgresql 的读取提交。 我有两笔交易 运行 并行:

-- transaction 1
begin;
select id from item order by id asc FETCH FIRST 500 ROWS ONLY;
select pg_sleep(10);
commit;
--transaction 2 
begin;
select id from item order by id asc FETCH FIRST 500 ROWS ONLY;
commit;

第一笔交易将select前500个id然后通过休眠10s来持有id 第二个事务将在 table.

中查询前 500 行

根据我对读取提交的理解,第一个事务将 select 1 到 500 条记录,第二个事务将 select 501 到 1000 条记录。 但实际结果是,两次交易都是select1到500条记录。

如果有人能指出哪一部分是错误的,我将不胜感激。谢谢

您误解了 read committed 的意思。这意味着事务看不到 (select) 未提交的更新。请尝试以下操作:

create table read_create_test( id integer generated always as identity 
                             , cola text 
                             ) ; 
                             
insert into read_create_test(cola)
  select 'item-' || to_char(n,'fm000')
    from generate_series(1,50) gs(n); 
    
-- transaction 1 
do $$
   max_val integer; 
begin
   insert into read_create_test(cola)
     select 'item2-' || to_char(n+100,'fm000')
       from generate_series(1,50) gs(n);
      
   select max(id)
     into max_val
     from read_create_test; 
   raise notice 'Transaction 1 Max id: %',max_val;
   select pg_sleep(30);      -- make sure 2nd transaction has time to start 
   commit; 
end;
$$; 

-- transaction 2 (run after transaction 1 begins but before it ends)  
do $$
   max_val integer; 
begin
   select max(id)
     into max_val
     from read_create_test; 
    
   raise notice 'Transaction 2 Max id: %',max_val;
end;
$$; 

-- transaction 3 (run after transaction 1 ends)  
do $$
   max_val integer; 
begin
   select max(id)
     into max_val
     from read_create_test; 
    
   raise notice 'Transaction 3 Max id: %',max_val;
end;
$$;

分析结果时牢记 A transaction cannot see uncommitted DML