do incremented_value_for in a transaction to make sure we get the right key back

do sqlite checks based on Keystore.connection.adapter_name rather
than assuming one environment uses sqlite and the others don't
This commit is contained in:
joshua stein 2012-10-08 12:45:15 -05:00
parent 72b67b0103
commit 47f1c44fc9

View file

@ -8,7 +8,7 @@ class Keystore < ActiveRecord::Base
end
def self.put(key, value)
if Rails.env == "test"
if Keystore.connection.adapter_name == "SQLite"
Keystore.connection.execute("INSERT OR REPLACE INTO " <<
"#{Keystore.table_name} (`key`, `value`) VALUES " <<
"(#{q(key)}, #{q(value)})")
@ -28,19 +28,23 @@ class Keystore < ActiveRecord::Base
def self.incremented_value_for(key, amount = 1)
new_value = nil
if Rails.env == "test"
Keystore.connection.execute("INSERT OR IGNORE INTO " <<
"#{Keystore.table_name} (`key`, `value`) VALUES " <<
"(#{q(key)}, 0)")
Keystore.connection.execute("UPDATE #{Keystore.table_name} " <<
"SET `value` = `value` + #{q(amount)} WHERE `key` = #{q(key)}")
else
Keystore.connection.execute("INSERT INTO #{Keystore.table_name} (" +
"`key`, `value`) VALUES (#{q(key)}, #{q(amount)}) ON DUPLICATE KEY " +
"UPDATE `value` = `value` + #{q(amount)}")
Keystore.transaction do
if Keystore.connection.adapter_name == "SQLite"
Keystore.connection.execute("INSERT OR IGNORE INTO " <<
"#{Keystore.table_name} (`key`, `value`) VALUES " <<
"(#{q(key)}, 0)")
Keystore.connection.execute("UPDATE #{Keystore.table_name} " <<
"SET `value` = `value` + #{q(amount)} WHERE `key` = #{q(key)}")
else
Keystore.connection.execute("INSERT INTO #{Keystore.table_name} (" +
"`key`, `value`) VALUES (#{q(key)}, #{q(amount)}) ON DUPLICATE KEY " +
"UPDATE `value` = `value` + #{q(amount)}")
end
new_value = self.value_for(key)
end
return self.value_for(key)
return new_value
end
def self.decrement_value_for(key, amount = -1)