Skip to content

Instantly share code, notes, and snippets.

@zw963
Created January 15, 2022 16:49
Show Gist options
  • Save zw963/81519dc7f34e3d89c19b0cf97044bc3f to your computer and use it in GitHub Desktop.
Save zw963/81519dc7f34e3d89c19b0cf97044bc3f to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
begin
require "bundler/inline"
rescue LoadError => e
$stderr.puts "Bundler version 1.10 or later is required. Please update your Bundler"
raise e
end
gemfile(true) do
source "https://rubygems.org"
gem 'pg'
gem 'sequel'
gem 'minitest'
gem 'minitest-hooks'
end
system("sudo -u postgres dropdb --if-exists check_sequel_db")
system("sudo -u postgres createdb check_sequel_db")
DB = Sequel.postgres("check_sequel_db", single_threaded: true)
DB.create_table(:insiders, :ignore_index_errors=>true) do
primary_key :id
Integer :number_of_shares, :null=>false
end
class Insider < Sequel::Model
end
ENV['RACK_ENV'] = 'test'
require 'minitest/autorun'
require 'minitest/pride'
require 'minitest/hooks/default'
class Minitest::HooksSpec
def around
DB.transaction(:rollback=>:always, :savepoint=>true, :auto_savepoint=>true){super}
end
def around_all
DB.transaction(:rollback=>:always){super}
end
end
require 'logger'
LOGGER = Logger.new($stdout)
DB.loggers << LOGGER
describe 'insider' do
before(:all) do
Insider.create(number_of_shares: 200)
puts "Insider count outer thread: #{Insider.count}"
end
it 'test postgres read committed mode default lock' do
thread1 = Thread.new do
sleep rand(0.1..0.2)
DB.transaction do
puts "Insider count inner first thread: #{Insider.count}"
insider_1 = Insider.last
insider_1.update(number_of_shares: insider_1.number_of_shares - 10)
end
end
thread2 = Thread.new do
sleep rand(0.1..0.2)
DB.transaction do
insider_2 = Insider.last
insider_2.update(number_of_shares: insider_2.number_of_shares - 10)
end
end
thread1.join
thread2.join
assert_equal 180.0, Insider.last.number_of_shares
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment