Last active
March 13, 2017 16:07
-
-
Save hishnash/8aa050874404d8e082e40c7f8e9ddcd4 to your computer and use it in GitHub Desktop.
This file contains 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 LockableModel(TimeStampedModel): | |
class Meta: | |
abstract = True | |
@ensure_atomic | |
@contextmanager | |
def get_exclusive_lock(self, | |
_connection=connection, | |
timeout=settings.PG_LOCKING_TIMEOUT_MS, | |
wait=True): | |
cursor = _connection.cursor() | |
# set timeout | |
cursor.execute('SET LOCAL statement_timeout = %s;', (timeout,)) | |
# build the query | |
sql = 'SELECT ctid from {table_name} WHERE id=%s FOR UPDATE'.format( | |
table_name=self._meta.db_table | |
) | |
if not wait: | |
sql += ' NOWAIT' | |
try: | |
# this will block untill timeout or the lock is aquired | |
cursor.execute(sql, (self.pk,)) | |
except OperationalError: | |
raise LockTakenException() | |
else: | |
yield True |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment