From 5f8851cb44a0bef3ace27b229409667bdc01707b Mon Sep 17 00:00:00 2001 From: Sam Date: Wed, 2 Oct 2013 12:17:27 +1000 Subject: [PATCH] Avoid superfluous transaction when saving drafts --- app/models/draft.rb | 6 ++---- lib/freedom_patches/active_record_base.rb | 14 ++++++++++++++ 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/app/models/draft.rb b/app/models/draft.rb index 012fb1c35bc..0972eb25e21 100644 --- a/app/models/draft.rb +++ b/app/models/draft.rb @@ -7,12 +7,10 @@ class Draft < ActiveRecord::Base d = find_draft(user,key) if d return if d.sequence > sequence - d.data = data - d.sequence = sequence + d.update_columns(data: data, sequence: sequence) else - d = Draft.new(user_id: user.id, draft_key: key, data: data, sequence: sequence) + Draft.create!(user_id: user.id, draft_key: key, data: data, sequence: sequence) end - d.save! end def self.get(user, key, sequence) diff --git a/lib/freedom_patches/active_record_base.rb b/lib/freedom_patches/active_record_base.rb index 21c97119783..96b2a1b232e 100644 --- a/lib/freedom_patches/active_record_base.rb +++ b/lib/freedom_patches/active_record_base.rb @@ -11,6 +11,20 @@ class ActiveRecord::Base exec_sql(*args).cmd_tuples end + # note: update_attributes still spins up a transaction this can cause contention + # this method performs the raw update sidestepping AR + def update_columns(hash) + sql = "UPDATE #{ self.class.table_name } SET " + + sql << hash.map do |k,v| + "#{k} = :#{k}" + end.join(",") + + sql << " WHERE id = :id" + + exec_sql(sql, hash.merge(id: self.id)) + end + def exec_sql(*args) ActiveRecord::Base.exec_sql(*args) end