In general, the way to prevent other queries from having access to a row(s) for locking purposes is to use SELECT FOR UPDATE. I'm not sure if you're using postgresql or sqlite, but you can read about the postgresql functionality here. Sqlite does not support it.
The idea is that you can lock the row you for which are interested, and then do whatever operations you need to without worrying about other queries updating that row, and then commit your transaction.
A common scenario for this would be when you're trying to book a reservation, as it looks like your example may be doing something along those lines. We would do a SELECT FOR UPDATE on the row containing the resource we want to book, then check the available dates the user is wanting to book, and once we have ensured that the dates are available for that resource, go ahead and book it. The SELECT FOR UPDATE prevents the possibility of other people trying to book the same resource at the same time we are.
发布评论
评论(2)
外,没有办法这样做。
使用
序列化
交易隔离锁定所有视线以序列化操作
不清楚您到底要做什么,但是对时间戳范围的排除限制也许会有所帮助。
There is no way to do this except
using
SERIALIZABLE
transaction isolationlocking everything in sight to serialize operations
It is unclear what exactly you are trying to do, but perhaps an exclusion constraint on timestamp ranges can help.
通常,防止其他查询以锁定目的访问行的方法是使用
选择更新
。我不确定您是否正在使用PostgreSQL或SQLITE,但是您可以阅读有关PostgreSQL功能在这里。 Sqlite不支持它。这个想法是,您可以锁定感兴趣的行,然后执行所需的任何操作,而不必担心其他查询更新该行,然后进行交易。
一个常见的情况是,当您试图预订预订时,您的示例似乎正在按照这些方式做一些事情。我们将在包含要预订的资源的行上进行
选择更新
,然后检查用户想要预订的可用日期,并且一旦我们确保可用于该资源的日期可用,继续预订。选择更新
可防止其他人试图同时预订相同资源的可能性。In general, the way to prevent other queries from having access to a row(s) for locking purposes is to use
SELECT FOR UPDATE
. I'm not sure if you're using postgresql or sqlite, but you can read about the postgresql functionality here. Sqlite does not support it.The idea is that you can lock the row you for which are interested, and then do whatever operations you need to without worrying about other queries updating that row, and then commit your transaction.
A common scenario for this would be when you're trying to book a reservation, as it looks like your example may be doing something along those lines. We would do a
SELECT FOR UPDATE
on the row containing the resource we want to book, then check the available dates the user is wanting to book, and once we have ensured that the dates are available for that resource, go ahead and book it. TheSELECT FOR UPDATE
prevents the possibility of other people trying to book the same resource at the same time we are.