【问题标题】:PostgreSQL read commit on different transactionsPostgreSQL 读取不同事务的提交
【发布时间】:2021-10-08 22:42:17
【问题描述】:

我正在运行一些测试以更好地理解 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;

第一个事务会选择前 500 个 id,然后通过休眠 10s 来持有 id 平均而言,第二个事务将查询表中的前 500 行。

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

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

【问题讨论】:

  • 为什么第二个事务要读取不同的行集?你没有锁定任何东西。,
  • 我试图通过已提交的读取来执行此操作,我的理解是,由于未提交第一个事务中的选定项目,因此第二个事务不应选择相同的内容。我知道我可以通过 select ...for update 来实现它,但我只是想知道为什么它不适用于已提交的读取
  • 您的事务不会更改任何数据,因此隔离级别无关紧要

标签: postgresql read-committed


【解决方案1】:

您误解了read committed 的含义。这意味着事务无法看到(选择)未提交的更新。请尝试以下操作:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-11
    • 2019-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-15
    相关资源
    最近更新 更多