Reputation: 4380
I have a problem in my tests running some SQL queries in different threads. I expect that running simple select and counts in SQL would return the same results, but if I run these methods in threads (process_new_followers
and process_lost_followers
) they return different results.
Here is the (basic) code:
def compute_followers
followers = Follower.where({ user_id: user_id, is_following: true }).count # => returns 10 always
calculate_differences
thread1 = Thread.new { process_new_followers }
thread2 = Thread.new { process_lost_followers }
thread1.join
thread2.join
end
def process_new_followers
puts Follower.where({ user_id: user_id, is_following: true }).count # => returns 0 if threaded and 10 if not
... I commented out this code so it only prints the count and nothing changes, so no db changes are happening in this method
end
def process_lost_followers
puts Follower.where({ user_id: user_id, is_following: true }).count # => returns 0 if threaded and 10 if not
... I commented out this code so it only prints the count and nothing changes, so no db changes are happening in this method
end
Why would the threading effect this SQL query?
Upvotes: 1
Views: 282
Reputation: 486
Since this is in a Rails app using ActiveRecord, Rails will rollback all transactions in it's test suite. Since you're stepping outside of it in a thread, the transaction has most likely already rolled back, which would explain why you're seeing 0 count in threaded and 10 in non-threaded call.
Upvotes: 2