Skip to content

Instantly share code, notes, and snippets.

@systemsoverload
Created July 14, 2015 16:42
Show Gist options
  • Save systemsoverload/b0f47bb4555ccc1d5134 to your computer and use it in GitHub Desktop.
Save systemsoverload/b0f47bb4555ccc1d5134 to your computer and use it in GitHub Desktop.
Simple context manager to wrap django utilities in pg_advisory locks
from django.db import connection, transaction
from contextlib import contextmanager
@contextmanager
def pg_advisory_xact_lock(*keys):
"""
Acquire an exclusive database lock against an arbitrary string key
"""
string_key = '.'.join(keys)
lock_key = sha1(string_key).digest().__hash__()
lockstring = 'SELECT pg_advisory_xact_lock({0});'.format(lock_key)
transaction.set_autocommit(False)
try:
connection.cursor().execute(lockstring)
yield
finally:
transaction.commit()
transaction.set_autocommit(True)
@mikaraunio
Copy link

WARNING in case anyone stumbles upon this nine+ years later, don't use as-is without rolling your own hashing mechanism: __hash__() isn't stable so you'll end up getting different locks for the same keys.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment