Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

return exceptions on Execute commands for postgresql (asyncpg driver) #1320

Merged
merged 1 commit into from
Oct 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 56 additions & 6 deletions asyncdb/drivers/pg.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,9 @@
UndefinedColumnError,
UndefinedTableError,
UniqueViolationError,
ForeignKeyViolationError,
NotNullViolationError,
QueryCanceledError
)
from asyncpg.pgproto import pgproto
from ..exceptions import (
Expand Down Expand Up @@ -414,10 +417,25 @@ async def execute(self, sentence, *args):
"""
try:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (complexity): Consider extracting duplicated error handling logic into a reusable decorator function

The error handling logic is duplicated across execute(), execute_many() and the pool's execute(). Consider extracting this into a decorator:

def handle_pg_errors(f):
    async def wrapper(*args, **kwargs):
        try:
            return await f(*args, **kwargs)
        except (
            QueryCanceledError,
            StatementError, 
            UniqueViolationError,
            ForeignKeyViolationError,
            NotNullViolationError
        ) as err:
            self._logger.warning(f"AsyncPg: {err}")
            raise
        except (
            InvalidSQLStatementNameError,
            PostgresSyntaxError, 
            UndefinedColumnError,
            UndefinedTableError
        ) as err:
            return await self._serializer(None, err)
        except Exception as err:
            return await self._serializer(None, f"Error: {err}")
    return wrapper

@handle_pg_errors
async def execute(self, sentence, *args, **kwargs):
    self.start_timing()
    await self.valid_operation(sentence)
    self._result = await self._connection.execute(sentence, *args, **kwargs)
    self.generated_at()
    return await self._serializer(self._result, None)

This maintains the improved error handling while eliminating duplication. The decorator can be reused across all execute methods.

return await self._pool.execute(sentence, *args)
except (
QueryCanceledError,
StatementError,
UniqueViolationError,
ForeignKeyViolationError,
NotNullViolationError
) as err:
self._logger.warning(
f"AsyncPg: {err}"
)
raise
except InterfaceError as err:
raise ProviderError(f"Execute Interface Error: {err}") from err
raise ProviderError(
f"Execute Interface Error: {err}"
) from err
except Exception as err:
raise ProviderError(f"Execute Error: {err}") from err
raise ProviderError(
f"Execute Error: {err}"
) from err


class pgCursor(SQLCursor):
Expand Down Expand Up @@ -795,8 +813,24 @@ async def execute(self, sentence: Any, *args, **kwargs) -> Optional[Any]:
await self.valid_operation(sentence)
try:
self._result = await self._connection.execute(sentence, *args, **kwargs)
except (InvalidSQLStatementNameError, PostgresSyntaxError, UndefinedColumnError, UndefinedTableError) as err:
error = f"Sentence Error: {err}"
except (
QueryCanceledError,
StatementError,
UniqueViolationError,
ForeignKeyViolationError,
NotNullViolationError
) as err:
self._logger.warning(
f"AsyncPg: {err}"
)
raise
except (
InvalidSQLStatementNameError,
PostgresSyntaxError,
UndefinedColumnError,
UndefinedTableError
) as err:
error = err
except DuplicateTableError as err:
error = f"Duplicated table: {err}"
except PostgresError as err:
Expand All @@ -813,10 +847,26 @@ async def execute_many(self, sentence: str, *args):
await self.valid_operation(sentence)
try:
self._result = await self._connection.executemany(sentence, *args)
except (
QueryCanceledError,
StatementError,
UniqueViolationError,
ForeignKeyViolationError,
NotNullViolationError
) as err:
self._logger.warning(
f"AsyncPg: {err}"
)
raise
except InterfaceWarning as err:
error = f"Interface Warning: {err}"
except (InvalidSQLStatementNameError, PostgresSyntaxError, UndefinedColumnError, UndefinedTableError) as err:
error = f"Sentence Error: {err}"
except (
InvalidSQLStatementNameError,
PostgresSyntaxError,
UndefinedColumnError,
UndefinedTableError
) as err:
error = err
except DuplicateTableError as err:
error = f"Duplicated table: {err}"
except PostgresError as err:
Expand Down
2 changes: 1 addition & 1 deletion asyncdb/version.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
__title__ = "asyncdb"
__description__ = "Library for Asynchronous data source connections \
Collection of asyncio drivers."
__version__ = "2.9.3"
__version__ = "2.9.4"
__author__ = "Jesus Lara"
__author_email__ = "[email protected]"
__license__ = "BSD"