This plugin implements optimistic locking mechanism on PostgreSQL based on the xmin of the row. The xmin system column is automatically set to the current transaction id whenever the row is inserted or updated:
class Person < Sequel::Model plugin :pg_xmin_optimistic_locking end p1 = Person[1] p2 = Person[1] p1.update(name: 'Jim') # works p2.update(name: 'Bob') # raises Sequel::NoExistingObject
The advantage of pg_xmin_optimistic_locking plugin compared to the regular optimistic_locking plugin as that it does not require any additional columns setup on the model. This allows it to be loaded in the base model and have all subclasses automatically use optimistic locking. The disadvantage is that testing can be more difficult if you are modifying the underlying row between when a model is retrieved and when it is saved.
This plugin may not work with the class_table_inheritance plugin.
This plugin relies on the instance_filters plugin.
Classes and Modules
Constants
WILDCARD | = | LiteralString.new('*').freeze |
Public Class methods
Define the xmin column accessor
# File lib/sequel/plugins/pg_xmin_optimistic_locking.rb 32 def self.apply(model) 33 model.instance_exec do 34 plugin(:optimistic_locking_base) 35 @lock_column = :xmin 36 def_column_accessor(:xmin) 37 end 38 end
Update the dataset to append the xmin column if it is usable and there is a dataset for the model.
# File lib/sequel/plugins/pg_xmin_optimistic_locking.rb 42 def self.configure(model) 43 model.instance_exec do 44 set_dataset(@dataset) if @dataset 45 end 46 end