Oracle數(shù)據(jù)庫,查詢語句不會鎖表,但PostgreSQL在開啟事務后,查詢數(shù)據(jù)表會鎖表,在試圖DROP/TRUNCATE TABLE時會一直等待。
--------------------------- Session A
drop table if exists t1;
-- 開啟事務
begin;
-- 查詢當前事務號
select txid_current();?
-- 創(chuàng)建表&插入100w數(shù)據(jù)
create table t1(id int,c1 varchar(20));
-- 查詢當前事務號
select txid_current();?
insert into t1 select generate_series(1,1000000),'#TESTDATA#';
-- 提交事務
end;
--------------------------- Session B
-- 開啟事務
begin;
-- 查詢當前事務號
select txid_current();?
-- 查詢數(shù)據(jù)表
select count(*) from t1;
--------------------------- Session A
-- 重新回到Session A,刪除數(shù)據(jù)表
drop table t1; -- 這時會一直等待
查詢數(shù)據(jù)庫鎖信息:
testdb=# SELECT pid, relname , locktype, mode
testdb-# FROM pg_locks l JOIN pg_class t ON l.relation = t.oid
testdb-#? ? ? AND t.relkind = 'r'
testdb-# WHERE t.relname = 't1';
pid? | relname | locktype |? ? ? ? mode? ? ? ?
------+---------+----------+---------------------
1574 | t1? ? ? | relation | AccessShareLock
1585 | t1? ? ? | relation | AccessExclusiveLock
(2 rows)
發(fā)現(xiàn)查詢t1(1574為Session B的pid)時會持有AccessShareLock,導致drop table一直等待該鎖釋放后才能執(zhí)行。
參考:
https://www.postgresql.org/docs/11/static/explicit-locking.html