Oracle數(shù)據(jù)庫(kù)妓蛮,查詢(xún)語(yǔ)句不會(huì)鎖表怠李,但PostgreSQL在開(kāi)啟事務(wù)后,查詢(xún)數(shù)據(jù)表會(huì)鎖表蛤克,在試圖DROP/TRUNCATE TABLE時(shí)會(huì)一直等待捺癞。
--------------------------- Session A
drop table if exists t1;
-- 開(kāi)啟事務(wù)
begin;
-- 查詢(xún)當(dāng)前事務(wù)號(hào)
select txid_current();?
-- 創(chuàng)建表&插入100w數(shù)據(jù)
create table t1(id int,c1 varchar(20));
-- 查詢(xún)當(dāng)前事務(wù)號(hào)
select txid_current();?
insert into t1 select generate_series(1,1000000),'#TESTDATA#';
-- 提交事務(wù)
end;
--------------------------- Session B
-- 開(kāi)啟事務(wù)
begin;
-- 查詢(xún)當(dāng)前事務(wù)號(hào)
select txid_current();?
-- 查詢(xún)數(shù)據(jù)表
select count(*) from t1;
--------------------------- Session A
-- 重新回到Session A,刪除數(shù)據(jù)表
drop table t1; -- 這時(shí)會(huì)一直等待
查詢(xún)數(shù)據(jù)庫(kù)鎖信息:
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)查詢(xún)t1(1574為Session B的pid)時(shí)會(huì)持有AccessShareLock构挤,導(dǎo)致drop table一直等待該鎖釋放后才能執(zhí)行髓介。
參考:
https://www.postgresql.org/docs/11/static/explicit-locking.html