반응형
왜 잠기지 않는 거죠? 다른 사용자가 업데이트를 하지 못하게 하는 거죠?
이게 제 수업입니다.
class Plan < ActiveRecord::Base
def testing
self.with_lock do
update_columns(lock: true)
byebug
end
end
def testing2
self.lock!
byebug
end
end
레일 콘솔을 두 개 열었습니다.
첫 번째 콘솔:
p = Plan.create
=> (basically success)
p.id
=> 12
p.testing2
(byebug) # simulation of halting the execution,
(BYEBUG) # I just leave the rails console open and wait at here. I expect others won't be able to update p because I still got the lock.
두 번째 콘솔:
p = Plan.find(12)
=> (basically said found)
p.name = 'should not be able to be stored in database'
=> "should not be able to be stored in database"
p.save!
=> true # what????? Why can it update my object? It's lock in the other console!
lock!
에testing2
가 잠기지 않는 동안with_lock
효과가 있습니다.왜 그런지 설명해주실 분?lock!
안 돼요?
#lock!
는 SELECT ... FOR UPDATE 를 사용하여 잠금을 취득합니다.
Postgre에 따르면SQL 문서
FOR UPDATE를 지정하면 SELECT 문에 의해 취득된 행이 갱신된 것처럼 잠깁니다.따라서 현재 트랜잭션이 종료될 때까지 다른 트랜잭션에 의해 잠기거나 수정 또는 삭제되지 않습니다.
특정 행의 잠금을 유지하려면 트랜잭션이 필요합니다.
해라
console1:
Plan.transaction{Plan.find(12).lock!; sleep 100.days}
console2:
p = Plan.find(12)
p.name = 'should not be able to be stored in database'
p.save
#with_lock
트랜잭션을 취득할 수 있으므로 명시적인 트랜잭션은 필요하지 않습니다.
(Postgre 입니다)SQL 문서하지만 다른 데이터베이스들도 비슷한 논리를 구현하고 있다고 생각합니다.)
언급URL : https://stackoverflow.com/questions/54472961/why-doesnt-lock-stop-others-from-updating
반응형
'programing' 카테고리의 다른 글
Python에서 쉼표로 구분된 문자열을 목록으로 변환하는 방법은 무엇입니까? (0) | 2022.11.22 |
---|---|
시간대 변환 시 필터 간 mysql 선택 (0) | 2022.11.22 |
Javascript 초에서 분, 초 (0) | 2022.11.22 |
Python에서 오브젝트 타입을 비교하는 방법 (0) | 2022.11.22 |
어레이를 병합하고 키를 유지하는 방법 (0) | 2022.11.22 |