On Friday, July 5, 2019 at 5:54:43 PM UTC-7, Janko Marohnić wrote:
>
> Hello,
>
> Active Record has `ActiveRecord::Base#lock!` method just like Sequel, and
> additionally it has `ActiveRecord::Base#with_lock`, which wraps the
> `#lock!` in a transaction:
>
> model.with_lock do
> # ...
> end
>
> # which translates to
>
> model.transaction do
> model.lock!
> # ...
> end
>
> rom-sql has a similar convenience method as well. I was thinking that it
> could be useful to add the same kind of method to Sequel, since it's a
> common pattern. What do you think?
>
One thing I don't like about Model#lock! is that it is prone to race
conditions, even though you think it wouldn't be. Consider:
model = Model.first(:foo=>'bar')
# ...
model.db.transaction do
model.lock!
# ...
model.update(some_hash)
end
The race condition here is that at the time lock! is called, it is possible
that model.foo is not bar as it was updated by another connection before
the lock. About the only time lock! is safe is when you are retrieving the
record by primary key (assuming that you are not modifying the primary
key), or you are otherwise sure that at the point of lock!, the original
selection conditions are still true.
I don't really want to encourage usage of lock!. It is better to use
for_update when doing the initial selection if you are trying to avoid race
conditions (which if you are using lock!, you probably are trying to do).
That being said, I understand this is convenient and I would consider it in
a plugin that ships with Sequel, if you would like to send in a pull
request.
Thanks,
Jeremy
--
You received this message because you are subscribed to the Google Groups
"sequel-talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
Visit this group at https://groups.google.com/group/sequel-talk.
To view this discussion on the web visit
https://groups.google.com/d/msgid/sequel-talk/d57d4963-a1af-4375-9627-56d269489b81%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.