mirror of
https://github.com/discourse/discourse.git
synced 2025-03-22 11:35:35 +08:00
FIX: Use PostgreSQL 'ON CONFLICT' to deal with race condition
On busy sites, concurrent requests to insert into post_timings can occur, which was dealt with using Ruby exceptions. This moves the handling to PostgreSQL which makes it a bit faster, and prevents a spam of ERROR in the database logs.
This commit is contained in:
parent
bfadb1fabc
commit
526e76ced2
@ -33,20 +33,12 @@ class PostTiming < ActiveRecord::Base
|
|||||||
end
|
end
|
||||||
|
|
||||||
def self.record_new_timing(args)
|
def self.record_new_timing(args)
|
||||||
begin
|
DB.exec("INSERT INTO post_timings (topic_id, user_id, post_number, msecs)
|
||||||
DB.exec("INSERT INTO post_timings (topic_id, user_id, post_number, msecs)
|
SELECT :topic_id, :user_id, :post_number, :msecs
|
||||||
SELECT :topic_id, :user_id, :post_number, :msecs
|
ON CONFLICT DO NOTHING",
|
||||||
WHERE NOT EXISTS(SELECT 1 FROM post_timings
|
args)
|
||||||
WHERE topic_id = :topic_id
|
# concurrency is hard, we are not running serialized so this can possibly
|
||||||
AND user_id = :user_id
|
# still happen, if it happens we just don't care, its an invalid record anyway
|
||||||
AND post_number = :post_number)",
|
|
||||||
args)
|
|
||||||
rescue PG::UniqueViolation
|
|
||||||
# concurrency is hard, we are not running serialized so this can possibly
|
|
||||||
# still happen, if it happens we just don't care, its an invalid record anyway
|
|
||||||
return
|
|
||||||
end
|
|
||||||
|
|
||||||
Post.where(['topic_id = :topic_id and post_number = :post_number', args]).update_all 'reads = reads + 1'
|
Post.where(['topic_id = :topic_id and post_number = :post_number', args]).update_all 'reads = reads + 1'
|
||||||
UserStat.where(user_id: args[:user_id]).update_all 'posts_read_count = posts_read_count + 1'
|
UserStat.where(user_id: args[:user_id]).update_all 'posts_read_count = posts_read_count + 1'
|
||||||
end
|
end
|
||||||
|
Loading…
x
Reference in New Issue
Block a user