Add transaction demo

This commit is contained in:
wqy
2022-09-03 10:19:08 +08:00
parent 8430b02785
commit a44977974d
2 changed files with 56 additions and 16 deletions

View File

@@ -3,7 +3,7 @@ from .connection import g_conn_dict as conn
def _get_current_transaction(name: str) -> Row | None:
with conn[name].cursor(row_factory=dict_row) as cur:
cur.execute(f"select id from transaction_operation")
cur.execute(f"select * from transaction_operation")
return cur.fetchone()
def _get_current_transaction_id(name: str) -> int:
@@ -20,7 +20,6 @@ def _remove_operation(name: str, id: int) -> None:
cur.execute(f"delete from transaction_operation where id = {id}") # this should not happen
cur.execute(f"delete from snapshot_operation where id = {id}") # this may happen
cur.execute(f"delete from operation where id = {id}")
return int(cur.fetchone()['id'])
def _get_parents(name: str, id: int) -> list[int]:
ids = [id]
@@ -81,14 +80,15 @@ def execute_undo(name: str, discard: bool = False) -> None:
curr = _get_current_operation(name)
# transaction control
tran = _get_current_transaction(name)
if int(tran['id']) >= 0:
if bool(tran['strict']): # strict mode disallow undo
print("Do not allow to undo in strict transaction mode!")
return
elif tran <= curr: # normal mode disallow undo start point, and there is foreign key constraint
print("Do not allow to undo transaction start point!")
return
if have_transaction(name):
tran = _get_current_transaction(name)
if tran != None and int(tran['id']) >= 0:
if bool(tran['strict']): # strict mode disallow undo
print("Do not allow to undo in strict transaction mode!")
return
elif int(tran['id']) >= curr: # normal mode disallow undo start point, and there is foreign key constraint
print("Do not allow to undo transaction start point!")
return
row = _query_undo(name, curr)
undo = row['undo']
@@ -183,7 +183,9 @@ def pick_snapshot(name: str, tag: str) -> None:
# it may remove snapshot tag if snapshot in a rollback transaction
def have_transaction(name: str) -> bool:
return _get_current_transaction_id(name) >= 0
with conn[name].cursor(row_factory=dict_row) as cur:
cur.execute(f"select * from transaction_operation")
return cur.rowcount > 0
def start_transaction(name: str, strict: bool = False) -> None:
if have_transaction(name):
@@ -203,11 +205,12 @@ def commit_transaction(name: str) -> None:
_remove_transaction(name)
def abort_transaction(name: str) -> None:
tran = _get_current_transaction_id(name)
if tran >= 0:
if not have_transaction(name):
print("No active transaction!")
return
tran = _get_current_transaction_id(name)
curr = _get_current_operation(name)
curr_parents = _get_parents(name, curr)