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