Prevent race conditions on postgres#16
Conversation
|
Here is the test code: Model class SequentialTest < ActiveRecord::Base
acts_as_sequenced scope: :sequential_scope_id
endMigration class CreateSequentialTests < ActiveRecord::Migration
def change
create_table :sequential_tests do |t|
t.integer :sequential_id, null: false
t.integer :sequential_scope_id, null: false, default: 1
end
add_index :sequential_tests, [:sequential_id, :sequential_scope_id], unique: true
end
endTest THREADS = 50
def test
SequentialTest.destroy_all
initial = 0
threads = (1..THREADS).map do |i|
Thread.new do
ActiveRecord::Base.connection_pool.with_connection do
SequentialTest.create!
end
end
end
threads.each {|t| t.join}
final = SequentialTest.pluck('max(sequential_id)')[0]
fail('not concurrent-safe') unless final == initial + THREADS
end |
0f308e0 to
b98beaa
Compare
b98beaa to
a2e8bdf
Compare
|
@djreimer I enabled postgresql for your test suite and wrote a test case. It fails without the locking, and succeeds with locking enabled. Travis CI will automatically run all tests on both databases. You can run the test manually using postgres like this: |
8a77a94 to
50ec373
Compare
50ec373 to
96b2f70
Compare
|
Rock on! 🤘 This is great. I want to run some tests on my local machine, but looks like you've covered all the bases. This should be merged soon. Thanks! |
|
@djreimer Hey man. Let me know if there's anything you need from me or comments you have on the code that I can fix 👍 |
|
Cool will do. This is in on my todo list for a lazy post-Thanksgiving Friday On Friday, November 27, 2015, Sam Philip notifications@github.com wrote:
Derrick |
…able_locks Prevent race conditions on postgres
Tested with 50 simultaneous connections. This 100% guarantees correctness of the sequential_id in Postgres and makes no change to the previous behavior for other database adapters.
Unfortunately this is not so trivial to implement in MySQL because table locks must be manually released.