Skip to content

Instantly share code, notes, and snippets.

@hishnash
Last active March 13, 2017 16:07
Show Gist options
  • Save hishnash/8aa050874404d8e082e40c7f8e9ddcd4 to your computer and use it in GitHub Desktop.
Save hishnash/8aa050874404d8e082e40c7f8e9ddcd4 to your computer and use it in GitHub Desktop.
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