NDOJ/judge/dblock.py

26 lines
726 B
Python
Raw Permalink Normal View History

2020-01-21 06:35:58 +00:00
from itertools import chain
from django.db import connection, transaction
class LockModel(object):
def __init__(self, write, read=()):
2022-05-14 17:57:27 +00:00
self.tables = ", ".join(
chain(
("`%s` WRITE" % model._meta.db_table for model in write),
("`%s` READ" % model._meta.db_table for model in read),
)
)
2020-01-21 06:35:58 +00:00
self.cursor = connection.cursor()
def __enter__(self):
2022-05-14 17:57:27 +00:00
self.cursor.execute("LOCK TABLES " + self.tables)
2020-01-21 06:35:58 +00:00
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type is None:
transaction.commit()
else:
transaction.rollback()
2022-05-14 17:57:27 +00:00
self.cursor.execute("UNLOCK TABLES")
2020-01-21 06:35:58 +00:00
self.cursor.close()