Skip to content

Commit

Permalink
make the code concise
Browse files Browse the repository at this point in the history
  • Loading branch information
ODD2 committed Apr 17, 2023
1 parent 81d2641 commit 0168a25
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 14 deletions.
30 changes: 16 additions & 14 deletions databases/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -363,11 +363,7 @@ async def __aexit__(
Called when exiting `async with database.transaction()`
"""
if exc_type is not None or self._force_rollback:
if exc_type == OperationalError and exc_value.args[0] == 2013:
await self.rollback(skip=True)
raise exc_value
else:
await self.rollback()
await self.rollback()
else:
await self.commit()

Expand Down Expand Up @@ -400,27 +396,33 @@ async def start(self) -> "Transaction":
await self._transaction.start(
is_root=is_root, extra_options=self._extra_options
)
except OperationalError as e:
await self._connection.__aexit__()
raise e
else:
self._connection._transaction_stack.append(self)
except Exception as e:
await self._connection.__aexit__()
raise e
return self

async def commit(self) -> None:
async with self._connection._transaction_lock:
assert self._connection._transaction_stack[-1] is self
self._connection._transaction_stack.pop()
await self._transaction.commit()
await self._connection.__aexit__()
try:
await self._transaction.commit()
except Exception as e:
raise e
finally:
await self._connection.__aexit__()

async def rollback(self, skip=False) -> None:
async def rollback(self) -> None:
async with self._connection._transaction_lock:
assert self._connection._transaction_stack[-1] is self
self._connection._transaction_stack.pop()
if(not skip):
try:
await self._transaction.rollback()
await self._connection.__aexit__()
except Exception as e:
raise e
finally:
await self._connection.__aexit__()


class _EmptyNetloc(str):
Expand Down
2 changes: 2 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ pytest==7.1.2
pytest-cov==3.0.0
starlette==0.20.4
requests==2.28.1
types-PyMySQL==1.0.19.1

# Documentation
mkdocs==1.3.1
Expand All @@ -29,3 +30,4 @@ mkautodoc==0.1.0
# Packaging
twine==4.0.1
wheel==0.38.1

0 comments on commit 0168a25

Please sign in to comment.