diff --git a/CHANGES.txt b/CHANGES.txt index fd1746bb..0bd20623 100644 --- a/CHANGES.txt +++ b/CHANGES.txt @@ -8,6 +8,10 @@ next (unreleased) * Remove deprecated Pool.get #706 +* | Partially ported `PyMySQL#304 `_ #792 + | aiomysql now reraises the original exception during connect() if it's not `IOError`, `OSError` or `asyncio.TimeoutError`. + | This was previously always raised as `OperationalError`. + 0.1.1 (2022-05-08) ^^^^^^^^^^^^^^^^^^ diff --git a/aiomysql/connection.py b/aiomysql/connection.py index 022315a9..d972b7e2 100644 --- a/aiomysql/connection.py +++ b/aiomysql/connection.py @@ -555,9 +555,20 @@ async def _connect(self): self._writer.transport.close() self._reader = None self._writer = None - raise OperationalError(2003, - "Can't connect to MySQL server on %r" % - self._host) from e + + # As of 3.11, asyncio.TimeoutError is a deprecated alias of + # OSError. For consistency, we're also considering this an + # OperationalError on earlier python versions. + if isinstance(e, (IOError, OSError, asyncio.TimeoutError)): + raise OperationalError( + CR.CR_CONN_HOST_ERROR, + "Can't connect to MySQL server on %r" % self._host, + ) from e + + # If e is neither IOError nor OSError, it's a bug. + # Raising AssertionError would hide the original error, so we just + # reraise it. + raise def _set_keep_alive(self): transport = self._writer.transport diff --git a/tests/test_connection.py b/tests/test_connection.py index a0e4e00e..c0c1be3d 100644 --- a/tests/test_connection.py +++ b/tests/test_connection.py @@ -26,7 +26,8 @@ def fill_my_cnf(mysql_params): @pytest.mark.run_loop async def test_connect_timeout(connection_creator): - # All exceptions are caught and raised as operational errors + # OSErrors and asyncio.TimeoutError are caught and raised as operational + # errors with pytest.raises(aiomysql.OperationalError): await connection_creator(connect_timeout=0.000000000001) diff --git a/tests/test_issues.py b/tests/test_issues.py index 80cd6c1d..e60a5103 100644 --- a/tests/test_issues.py +++ b/tests/test_issues.py @@ -465,3 +465,13 @@ async def test_issue_323(mysql_server, loop, recwarn): finally: async with conn.cursor() as cur: await cur.execute("DELETE FROM `bugtest`.`testtable`;") + + +# https://github.com/aio-libs/aiomysql/issues/792 +@pytest.mark.run_loop +async def test_issue_792(connection_creator): + with pytest.raises(aiomysql.OperationalError) as exc_info: + await connection_creator(db="does_not_exist") + + assert exc_info.value.args[0] == 1049 + assert exc_info.value.args[1] == "Unknown database 'does_not_exist'"