import datetime
import traceback
import MySQLdb
class Connection:
def __init__(self, pool, internal, readonly = True):
self.pool = pool
self.internal = internal
self.readonly = readonly
self.finished = True
self.begin()
def cursor(self):
assert not self.finished
return self.internal.cursor(MySQLdb.cursors.DictCursor)
def insert_id(self, *args, **kwargs):
assert not self.finished
return self.internal.insert_id(*args, **kwargs)
def escape(self, *args, **kwargs):
r = self.internal.escape(*args, **kwargs)
return r.decode("utf8") if type(r) is bytes else r
def escape_string(self, *args, **kwargs):
r = self.internal.escape_string(*args, **kwargs)
return r.decode("utf8") if type(r) is bytes else r
def begin(self):
assert self.finished
self.finished = False
with self.cursor() as cursor:
cursor.execute("SET autocommit=0")
if self.readonly:
with self.cursor() as cursor:
cursor.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ")
with self.cursor() as cursor:
cursor.execute("START TRANSACTION READ ONLY, WITH CONSISTENT SNAPSHOT")
else:
with self.cursor() as cursor:
cursor.execute("SET TRANSACTION ISOLATION LEVEL SERIALIZABLE")
with self.cursor() as cursor:
cursor.execute("START TRANSACTION READ WRITE")
self.now = datetime.datetime.now(self.pool.server.config['timezone'])
def commit(self):
assert not self.finished
self.internal.commit()
self.finished = True
def rollback(self):
assert not self.finished
self.internal.rollback()
self.finished = True
def release(self):
if not self.finished:
try: self.rollback()
except Exception as e:
print(traceback.format_exc())
print(e)