module Sequel::Plugins::PgXminOptimisticLocking

  1. lib/sequel/plugins/pg_xmin_optimistic_locking.rb

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.

Methods

Public Class

  1. apply
  2. configure

Constants

WILDCARD = LiteralString.new('*').freeze  

Public Class methods

apply(model)

Define the xmin column accessor

[show source]
   # 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
configure(model)

Update the dataset to append the xmin column if it is usable and there is a dataset for the model.

[show source]
   # 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