From 0168a2513d1a228e02c4db56f99386a67a50db0e Mon Sep 17 00:00:00 2001 From: OD Date: Mon, 17 Apr 2023 12:27:03 +0800 Subject: [PATCH] make the code concise --- databases/core.py | 30 ++++++++++++++++-------------- requirements.txt | 2 ++ 2 files changed, 18 insertions(+), 14 deletions(-) diff --git a/databases/core.py b/databases/core.py index f4820c91..76b25cda 100644 --- a/databases/core.py +++ b/databases/core.py @@ -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() @@ -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): diff --git a/requirements.txt b/requirements.txt index 0699d3cc..1394fcc8 100644 --- a/requirements.txt +++ b/requirements.txt @@ -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 @@ -29,3 +30,4 @@ mkautodoc==0.1.0 # Packaging twine==4.0.1 wheel==0.38.1 +