programing

왜 잠기지 않는 거죠? 다른 사용자가 업데이트를 하지 못하게 하는 거죠?

randomtip 2022. 11. 22. 21:55
반응형

왜 잠기지 않는 거죠? 다른 사용자가 업데이트를 하지 못하게 하는 거죠?

이게 제 수업입니다.

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

반응형