Created
April 19, 2024 06:06
-
-
Save chensoren/d334e34012316de8bc572f0e5327ee07 to your computer and use it in GitHub Desktop.
pg advisory locks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class LockManager | |
def self.with_transaction_lock(lock_name) | |
lock_id = Zlib.crc32(lock_name.to_s) | |
ActiveRecord::Base.transaction do | |
ActiveRecord::Base.connection.execute("SELECT pg_advisory_xact_lock(#{lock_id})") | |
yield | |
end | |
end | |
def self.with_session_lock(lock_name) | |
lock_id = Zlib.crc32(lock_name.to_s) | |
begin | |
ActiveRecord::Base.connection.execute("SELECT pg_advisory_lock(#{lock_id})") | |
yield | |
ensure | |
ActiveRecord::Base.connection.execute("SELECT pg_advisory_unlock(#{lock_id})") | |
end | |
end | |
end | |
LockManager.with_transaction_lock("subscription_usage_#{user_id}") do | |
user = User.find(user_id) | |
new_usage = user.current_subscription_usage | |
user.update_attributes!(subscription_usage: new_usage) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment