diff --git a/CHANGELOG.md b/CHANGELOG.md index 233f27eb4..03eec8a12 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,11 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/#semantic-versioning-200). +## [Unreleased] + +### :magic_wand: Added +* The `failover` and `failover_v2` plugins currently rewraps all errors to an AwsWrapperError even when the errors do not trigger failover. Set the `preserve_driver_exception_type` configuration parameter to `True` to re-raise the target driver errors as-is for the failover plugins. Failover errors are unaffected and are still raised as `FailoverSuccessError`, `FailoverFailedError` or `TransactionResolutionUnknownError`. This is useful for ORMs to properly classify the errors. ([Issue #1275](https://github.com/aws/aws-advanced-python-wrapper/issues/1275)) + ## [3.1.0] - 2026-08-24 ### :magic_wand: Added * Python 3.14 support. ([PR #1252](https://github.com/aws/aws-advanced-python-wrapper/pull/1252)) diff --git a/aws_advanced_python_wrapper/failover_plugin.py b/aws_advanced_python_wrapper/failover_plugin.py index 6ae4d8f47..ef9e1a093 100644 --- a/aws_advanced_python_wrapper/failover_plugin.py +++ b/aws_advanced_python_wrapper/failover_plugin.py @@ -80,6 +80,7 @@ def __init__(self, plugin_service: PluginService, props: Properties): self._writer_failover_handler: WriterFailoverHandler self._enable_failover_setting = WrapperProperties.ENABLE_FAILOVER.get_bool(self._properties) + self._preserve_driver_exception_type = WrapperProperties.PRESERVE_DRIVER_EXCEPTION_TYPE.get_bool(self._properties) self._failover_timeout_sec = WrapperProperties.FAILOVER_TIMEOUT_SEC.get_float(self._properties) self._failover_cluster_topology_refresh_rate_sec = WrapperProperties.FAILOVER_CLUSTER_TOPOLOGY_REFRESH_RATE_SEC.get_float( self._properties) @@ -175,6 +176,15 @@ def execute(self, target: type, method_name: str, execute_func: Callable, *args: self._pick_new_connection() self._last_exception = ex + + # This line is only reachable if the original error does not trigger a connection switch. + if self._preserve_driver_exception_type: + # Re-raise the error as-is. + raise + + # Replacing the error discards the driver's exception class, which is what SQLAlchemy, + # Django and similar libraries classify a failure by. Kept as the default for backwards + # compatibility. raise AwsWrapperError(Messages.get_formatted("FailoverPlugin.DetectedException", str(ex)), ex) from ex def notify_host_list_changed(self, changes: Dict[str, Set[HostEvent]]): diff --git a/aws_advanced_python_wrapper/failover_v2_plugin.py b/aws_advanced_python_wrapper/failover_v2_plugin.py index 65e365d4a..73d8cdead 100644 --- a/aws_advanced_python_wrapper/failover_v2_plugin.py +++ b/aws_advanced_python_wrapper/failover_v2_plugin.py @@ -14,7 +14,7 @@ from __future__ import annotations import time -from typing import TYPE_CHECKING, Any, Callable, Dict, Optional, Set +from typing import TYPE_CHECKING, Any, Callable, Dict, NoReturn, Optional, Set from aws_advanced_python_wrapper.pep249_methods import DbApiMethod @@ -83,6 +83,7 @@ def __init__(self, plugin_service: PluginService, props: Properties): strategy = WrapperProperties.FAILOVER_READER_HOST_SELECTOR_STRATEGY.get(self._properties) self._failover_reader_host_selector_strategy: str = strategy if strategy is not None else "" self._enable_connect_failover = WrapperProperties.ENABLE_CONNECT_FAILOVER.get_bool(self._properties) + self._preserve_driver_exception_type = WrapperProperties.PRESERVE_DRIVER_EXCEPTION_TYPE.get_bool(self._properties) self._closed_explicitly = False self._is_closed = False @@ -109,13 +110,11 @@ def execute(self, target: type, method_name: str, execute_func: Callable, *args, self._invalid_invocation_on_closed_connection() try: - result = execute_func() + return execute_func() except Exception as e: logger.debug("FailoverPlugin.DetectedException", str(e)) self._deal_with_original_exception(e) - return result - def init_host_provider( self, props: Properties, @@ -195,7 +194,7 @@ def _invalid_invocation_on_closed_connection(self) -> None: else: raise AwsWrapperError("No operations allowed after connection closed") - def _deal_with_original_exception(self, original_exception: Exception) -> None: + def _deal_with_original_exception(self, original_exception: Exception) -> NoReturn: if (self._last_exception_dealt_with != original_exception and (self._should_exception_trigger_connection_switch(original_exception))): self._invalidate_current_connection() @@ -204,6 +203,14 @@ def _deal_with_original_exception(self, original_exception: Exception) -> None: self._pick_new_connection() self._last_exception_dealt_with = original_exception + # This line is only reachable if the original error does not trigger a connection switch. + if self._preserve_driver_exception_type: + # Re-raise the error as-is. + raise original_exception + + # Replacing the error discards the driver's exception class, which is what SQLAlchemy, + # Django and similar libraries classify a failure by. Kept as the default for backwards + # compatibility. raise AwsWrapperError(Messages.get_formatted("FailoverPlugin.DetectedException", str(original_exception)), original_exception) \ from original_exception diff --git a/aws_advanced_python_wrapper/sqlalchemy_dialects/_exception_handling.py b/aws_advanced_python_wrapper/sqlalchemy_dialects/_exception_handling.py index ef7a41321..0bea34f93 100644 --- a/aws_advanced_python_wrapper/sqlalchemy_dialects/_exception_handling.py +++ b/aws_advanced_python_wrapper/sqlalchemy_dialects/_exception_handling.py @@ -58,10 +58,18 @@ What this module DOES do ------------------------ Normalize *raw driver-native* DBAPI errors (``mysql.connector.errors.*`` / -``psycopg.*`` / ``pymysql.*``) into the wrapper's PEP-249 equivalents, for plugin -chains that do not already re-wrap them (``iam`` / ``aws_secrets_manager`` / no -plugins). Without that SA cannot classify them at all, so e.g. ``has_table`` -never sees MySQL's 1146 and ``create_all`` fails. +``psycopg.*`` / ``pymysql.*``) into the wrapper's PEP-249 equivalents. SA cannot +classify driver-native errors at all, because ``loaded_dbapi`` is this package +rather than the driver: without the normalization ``has_table`` never sees +MySQL's 1146 and ``create_all`` fails, and an application's +``except sqlalchemy.exc.IntegrityError:`` never fires on a duplicate key. + +A driver error arrives here raw from any chain that does not substitute it -- +``iam`` / ``aws_secrets_manager`` / no plugins, and the ``failover`` / +``failover_v2`` plugins once ``preserve_driver_exception_type`` is set. At that +property's default those plugins replace the driver error with a generic +``AwsWrapperError``, which is already a wrapper PEP-249 error, so it is passed +through untouched and SA can only classify it as ``sqlalchemy.exc.DBAPIError``. """ from __future__ import annotations @@ -71,21 +79,11 @@ def _normalize_driver_error(e, driver_error_module): """Translate a raw driver-native DBAPI error into the wrapper's PEP-249 equivalent so SQLAlchemy's classifier recognizes it. - SA wraps an exception into ``sqlalchemy.exc.DBAPIError`` (enabling + SQLAlchemy wraps an error into ``sqlalchemy.exc.DBAPIError`` (enabling ``has_table`` / ``is_disconnect`` / retry handling) only when - ``isinstance(e, dialect.dbapi.Error)`` -- and ``dialect.dbapi.Error`` is the - wrapper's PEP-249 ``Error``. Plugin chains that re-wrap driver errors as - ``AwsWrapperError`` (e.g. failover) are already recognized, but auth-only - chains (``iam`` / ``aws_secrets_manager`` / no plugins) let the raw driver - error (``mysql.connector.errors.*``, ``psycopg.*``, ``pymysql.*``) escape -- - which SA cannot classify, so e.g. ``has_table`` never catches a 1146 - "table doesn't exist" and ``create_all`` fails. - - Returns an equivalent wrapper PEP-249 error (same PEP-249 subtype matched by - name; ``errno`` / ``sqlstate`` / ``pgcode`` preserved so the dialect's - ``_extract_error_code`` still reads the numeric code; original chained via - ``__cause__``), or ``None`` if ``e`` is already a wrapper error or not a - recognizable driver error (caller should re-raise the original). + ``isinstance(e, dialect.dbapi.Error)``. + + Wrap and return an equivalent wrapper PEP-249 `dialect.dbapi.Error`` if necessary. """ from aws_advanced_python_wrapper import pep249 if isinstance(e, pep249.Error): diff --git a/aws_advanced_python_wrapper/sqlalchemy_dialects/mysql.py b/aws_advanced_python_wrapper/sqlalchemy_dialects/mysql.py index 6a7ddbdf9..e4706293b 100644 --- a/aws_advanced_python_wrapper/sqlalchemy_dialects/mysql.py +++ b/aws_advanced_python_wrapper/sqlalchemy_dialects/mysql.py @@ -52,15 +52,6 @@ def create_connect_args(self, url): return args, kwargs def _extract_error_code(self, exception: BaseException) -> int: - # Plugins such as failover re-raise the underlying driver error - # wrapped in an ``AwsWrapperError``, which hides the numeric MySQL - # error code that SA's ``has_table`` / ``is_disconnect`` logic keys - # off. In particular ``has_table`` must see 1146 ("table doesn't - # exist") to return False so ``create_all`` can proceed -- otherwise - # the wrapped error propagates and ORM table setup fails. Unwrap to - # the underlying mysql-connector error so the stock classifier can - # read ``.errno``. Restores the override that main's - # SqlAlchemyOrmMysqlDialect carried before it was dropped in the merge. from aws_advanced_python_wrapper.errors import AwsWrapperError if isinstance(exception, AwsWrapperError) and exception.driver_error is not None: exception = exception.driver_error diff --git a/aws_advanced_python_wrapper/utils/properties.py b/aws_advanced_python_wrapper/utils/properties.py index 2dc524fa2..33b379c40 100644 --- a/aws_advanced_python_wrapper/utils/properties.py +++ b/aws_advanced_python_wrapper/utils/properties.py @@ -284,6 +284,14 @@ class WrapperProperties: "Reader connection attempt timeout in seconds during a reader failover process.", 30, ) + PRESERVE_DRIVER_EXCEPTION_TYPE = WrapperProperty( + "preserve_driver_exception_type", + """Re-raise a target driver exception unchanged when it does not trigger a connection switch, + instead of replacing it with an AwsWrapperError. The driver's exception class is what SQLAlchemy, + Django and similar libraries use to classify a failure, so preserving it keeps a duplicate key + reaching the application as an integrity error rather than a generic database error.""", + False, + ) # Failover2Plugin properties FAILOVER_READER_HOST_SELECTOR_STRATEGY = WrapperProperty( diff --git a/docs/using-the-python-wrapper/SqlAlchemySupport.md b/docs/using-the-python-wrapper/SqlAlchemySupport.md index 124b7e26c..b4d5afd76 100644 --- a/docs/using-the-python-wrapper/SqlAlchemySupport.md +++ b/docs/using-the-python-wrapper/SqlAlchemySupport.md @@ -132,7 +132,27 @@ Wrapper errors are classified so SQLAlchemy maps them to the correct `sqlalchemy | `UnsupportedOperationError` | `sqlalchemy.exc.NotSupportedError` | | `AwsWrapperError` (generic) | `sqlalchemy.exc.DBAPIError` | -Applications writing SA retry loops can `except sqlalchemy.exc.OperationalError` and catch failover events naturally. Target-driver exceptions (e.g., `psycopg.errors.*`, `mysql.connector.errors.*`) are not remapped and flow through SA's dialect-specific classification unchanged. +Applications writing SQLAlchemy retry loops can `except sqlalchemy.exc.OperationalError` and catch failover events naturally. + +### Target driver errors + +An error raised by the target driver that is not a failover condition — a duplicate key, a syntax error, a constraint violation — keeps its PEP-249 category only if the failover plugins are told to preserve it: + +```python +engine = create_engine( + "mysql+aws_wrapper_mysqlconnector://user:password@my-cluster.cluster-xyz.us-east-2.rds.amazonaws.com/db" + "?preserve_driver_exception_type=True" +) + +try: + session.add(obj) + session.commit() +except sqlalchemy.exc.IntegrityError: # duplicate key, FK violation, ... + session.rollback() +``` +The `failover` and `failover_v2` plugins currently wrap a target driver error that does not trigger failover in a generic `AwsWrapperError`, which SQLAlchemy can only classify as `sqlalchemy.exc.DBAPIError`. Applications catching these errors with `except sqlalchemy.exc.IntegrityError:` therefore do not match them. The driver's error is still reachable as `err.orig.driver_error`. + +Set the [`preserve_driver_exception_type`](./using-plugins/UsingTheFailover2Plugin.md#failover-plugin-v2-configuration-parameters) parameter to `True` to propagate target driver errors as-is, so SQLAlchemy classifies them by PEP-249 category and `except sqlalchemy.exc.IntegrityError:` matches again. ## Resource cleanup diff --git a/docs/using-the-python-wrapper/using-plugins/UsingTheFailover2Plugin.md b/docs/using-the-python-wrapper/using-plugins/UsingTheFailover2Plugin.md index 9551ad3d0..e742cc76f 100644 --- a/docs/using-the-python-wrapper/using-plugins/UsingTheFailover2Plugin.md +++ b/docs/using-the-python-wrapper/using-plugins/UsingTheFailover2Plugin.md @@ -53,6 +53,7 @@ With the `failover_v2` plugin: > - **`enable_connect_failover`** *(boolean, default `True`)* — accepted by the async plugin for API parity with sync v2, but async failover currently only triggers on the execute path. When async grows connect-time failover, this flag will gate that path. > - **`telemetry_failover_additional_top_trace`** *(boolean, default `False`)* — honored by both sync v2 and async. When `True`, the per-failover span is also emitted at `FORCE_TOP_LEVEL` so backends that sample only top-level spans (e.g. X-Ray, OTLP-with-head-sampling) still capture failover events. > - **`init_host_provider` plugin hook** — sync v2 uses this to install `MonitoringRdsHostListProvider`. Async injects the `AsyncHostListProvider` at plugin construction, so no analogous hook is exposed. +> - **`preserve_driver_exception_type`** *(boolean, default `False`)* — sync only. The async plugin always re-raises a driver exception that does not trigger failover, which is the behavior this parameter enables for sync. ## Using the Failover Plugin v2 The Failover Plugin, not the Failover Plugin v2, will be enabled by default if the [`wrapperPlugins`](../UsingThePythonWrapper.md#connection-plugin-manager-parameters) value is not specified. If you would like to override the default plugins, you can explicitly include the failover plugin v2 in your list of plugins by adding the plugin code `failover_v2` to the [`wrapperPlugins`](../UsingThePythonWrapper.md#aws-advanced-Python-wrapper-parameters) value, or by adding it to the current [driver profile](../UsingThePythonWrapper.md#connection-plugin-manager-parameters). After you load the plugin, the failover v2 feature will be enabled. @@ -75,6 +76,7 @@ In addition to the parameters that you can configure for the underlying driver, | `cluster_topology_high_refresh_rate_ms` | Integer | No | Interval of time in milliseconds to wait between attempts to update cluster topology after the writer has come back online following a failover event. It corresponds to the increased monitoring rate described earlier. Usually, the topology monitoring component uses this increased monitoring rate for 30s after a new writer was detected. | `100` | | `failover_reader_host_selector_strategy` | String | No | Strategy used to select a reader host during failover. For more information on the available reader selection strategies, see this [table](../ReaderSelectionStrategies.md). | `random` | | `enable_connect_failover` | Boolean | No | Enable/disable cluster-aware failover if the initial connection to the database fails due to a network exception. Note that this may result in a connection to a different instance in the cluster than was specified by the URL. | `False` | +| `preserve_driver_exception_type` | Boolean | No | Re-raise the target driver's error unchanged when it does not trigger failover, instead of wrapping it with an `AwsWrapperError`. This allows libraries such as SQLAlchemy and Django to better classify and handle them by their PEP-249 category. | `False` | Please refer to the original [Failover Plugin](./UsingTheFailoverPlugin.md) for more details about error codes, configurations, connection pooling and sample codes. diff --git a/docs/using-the-python-wrapper/using-plugins/UsingTheFailoverPlugin.md b/docs/using-the-python-wrapper/using-plugins/UsingTheFailoverPlugin.md index 7e8880b14..6b50f5789 100644 --- a/docs/using-the-python-wrapper/using-plugins/UsingTheFailoverPlugin.md +++ b/docs/using-the-python-wrapper/using-plugins/UsingTheFailoverPlugin.md @@ -36,6 +36,7 @@ In addition to the parameters that you can configure for the underlying driver, | `failover_reader_connect_timeout_sec` | Integer | No | Maximum allowed time in seconds to attempt to connect to a reader instance during a reader failover process. | `30` | | `failover_timeout_sec` | Integer | No | Maximum allowed time in seconds to attempt reconnecting to a new writer or reader instance after a cluster failover is initiated. | `300` | | `failover_writer_reconnect_interval_sec` | Integer | No | Interval of time in seconds to wait between attempts to reconnect to a failed writer during a writer failover process. | `2` | +| `preserve_driver_exception_type` | Boolean | No | Re-raise the target driver's error unchanged when it does not trigger failover, instead of wrapping it with an `AwsWrapperError`. This allows libraries such as SQLAlchemy and Django to better classify and handle them by their PEP-249 category. | `False` | ## Host Pattern diff --git a/tests/unit/test_failover_plugin.py b/tests/unit/test_failover_plugin.py index 3d1581d91..2ba1bdbb5 100644 --- a/tests/unit/test_failover_plugin.py +++ b/tests/unit/test_failover_plugin.py @@ -27,7 +27,7 @@ from unittest.mock import MagicMock, PropertyMock from aws_advanced_python_wrapper.errors import ( - FailoverSuccessError, TransactionResolutionUnknownError) + AwsWrapperError, FailoverSuccessError, TransactionResolutionUnknownError) from aws_advanced_python_wrapper.failover_plugin import (FailoverMode, FailoverPlugin) from aws_advanced_python_wrapper.failover_result import (ReaderFailoverResult, @@ -416,3 +416,54 @@ def test_execute(plugin_service_mock, mock_sql_method): plugin.execute(None, "close", mock_sql_method) assert mock_sql_method.call_count == 2 + + +def test_execute_preserves_non_failover_driver_exception(plugin_service_mock, mock_sql_method): + """With preserve_driver_exception_type, a non-failover driver error keeps its class. + + Its class is what SQLAlchemy, Django and other libraries use to decide what + kind of database error occurred, so it is re-raised unchanged. + """ + from mysql.connector import errors as mysql_errors + + plugin_service_mock.is_network_exception.return_value = False + plugin_service_mock.is_read_only_connection_exception.return_value = False + + properties = Properties() + WrapperProperties.ENABLE_FAILOVER.set(properties, "True") + WrapperProperties.PRESERVE_DRIVER_EXCEPTION_TYPE.set(properties, "True") + plugin = FailoverPlugin(plugin_service_mock, properties) + plugin._pick_new_connection = MagicMock() + + driver_exception = mysql_errors.IntegrityError( + "1062 (23000): Duplicate entry 'a' for key 'tbl.col'") + mock_sql_method.side_effect = driver_exception + + with pytest.raises(mysql_errors.IntegrityError) as exc_info: + plugin.execute(None, "Cursor.execute", mock_sql_method) + + assert exc_info.value is driver_exception + plugin._pick_new_connection.assert_not_called() + + +def test_execute_wraps_non_failover_driver_exception_by_default(plugin_service_mock, mock_sql_method): + """Default behavior: the driver error is replaced with an AwsWrapperError.""" + from mysql.connector import errors as mysql_errors + + plugin_service_mock.is_network_exception.return_value = False + plugin_service_mock.is_read_only_connection_exception.return_value = False + + properties = Properties() + WrapperProperties.ENABLE_FAILOVER.set(properties, "True") + plugin = FailoverPlugin(plugin_service_mock, properties) + plugin._pick_new_connection = MagicMock() + + driver_exception = mysql_errors.IntegrityError( + "1062 (23000): Duplicate entry 'a' for key 'tbl.col'") + mock_sql_method.side_effect = driver_exception + + with pytest.raises(AwsWrapperError) as exc_info: + plugin.execute(None, "Cursor.execute", mock_sql_method) + + assert exc_info.value.driver_error is driver_exception + plugin._pick_new_connection.assert_not_called() diff --git a/tests/unit/test_failover_v2_plugin.py b/tests/unit/test_failover_v2_plugin.py index 030bce709..df36d0eeb 100644 --- a/tests/unit/test_failover_v2_plugin.py +++ b/tests/unit/test_failover_v2_plugin.py @@ -20,6 +20,7 @@ import psycopg import pytest +from mysql.connector import errors as mysql_errors from aws_advanced_python_wrapper.errors import ( AwsWrapperError, FailoverFailedError, FailoverSuccessError, @@ -79,6 +80,13 @@ def failover_v2_plugin(plugin_service_mock, properties): return FailoverV2Plugin(plugin_service_mock, properties) +@pytest.fixture +def preserve_type_plugin(plugin_service_mock, properties): + props = Properties(properties) + WrapperProperties.PRESERVE_DRIVER_EXCEPTION_TYPE.set(props, "true") + return FailoverV2Plugin(plugin_service_mock, props) + + class TestFailoverV2Plugin: def test_execute_direct_close_method(self, failover_v2_plugin, connection_mock, mock_sql_method): failover_v2_plugin.execute(connection_mock, "Connection.close", mock_sql_method) @@ -141,27 +149,84 @@ def test_invalid_invocation_on_closed_connection_explicit(self, failover_v2_plug failover_v2_plugin._invalid_invocation_on_closed_connection() def test_deal_with_original_exception_network_error(self, failover_v2_plugin): + # A real _pick_new_connection signals the outcome of the switch by + # raising, so the original exception is never reached. network_exception = Exception("Network error") failover_v2_plugin._plugin_service.is_network_exception.return_value = True failover_v2_plugin._invalidate_current_connection = MagicMock() - failover_v2_plugin._pick_new_connection = MagicMock() + failover_v2_plugin._pick_new_connection = MagicMock(side_effect=FailoverSuccessError()) - with pytest.raises(AwsWrapperError): + with pytest.raises(FailoverSuccessError): failover_v2_plugin._deal_with_original_exception(network_exception) failover_v2_plugin._invalidate_current_connection.assert_called_once() failover_v2_plugin._pick_new_connection.assert_called_once() def test_deal_with_original_exception_non_network_error(self, failover_v2_plugin): - non_network_exception = ValueError("Not a network error") + # Default behavior: the driver's exception is replaced, and only + # reachable through driver_error. + non_network_exception = mysql_errors.IntegrityError( + "1062 (23000): Duplicate entry 'a' for key 'tbl.col'") failover_v2_plugin._plugin_service.is_network_exception.return_value = False failover_v2_plugin._invalidate_current_connection = MagicMock() - with pytest.raises(AwsWrapperError): + with pytest.raises(AwsWrapperError) as exc_info: failover_v2_plugin._deal_with_original_exception(non_network_exception) + assert exc_info.value.driver_error is non_network_exception failover_v2_plugin._invalidate_current_connection.assert_not_called() + def test_deal_with_original_exception_preserves_driver_exception_type(self, preserve_type_plugin): + # With preserve_driver_exception_type the driver's exception is re-raised + # as-is: its class is what SQLAlchemy, Django and others classify by. + non_network_exception = mysql_errors.IntegrityError( + "1062 (23000): Duplicate entry 'a' for key 'tbl.col'") + preserve_type_plugin._plugin_service.is_network_exception.return_value = False + preserve_type_plugin._invalidate_current_connection = MagicMock() + + with pytest.raises(mysql_errors.IntegrityError) as exc_info: + preserve_type_plugin._deal_with_original_exception(non_network_exception) + + assert exc_info.value is non_network_exception + preserve_type_plugin._invalidate_current_connection.assert_not_called() + + def test_execute_preserves_non_failover_driver_exception(self, preserve_type_plugin, connection_mock): + # End-to-end through execute(): a duplicate-key error is not a failover + # condition and reaches the caller with its class intact. + driver_exception = mysql_errors.IntegrityError( + "1062 (23000): Duplicate entry 'a' for key 'tbl.col'") + preserve_type_plugin._plugin_service.is_network_exception.return_value = False + preserve_type_plugin._plugin_service.is_read_only_connection_exception.return_value = False + preserve_type_plugin._invalidate_current_connection = MagicMock() + preserve_type_plugin._pick_new_connection = MagicMock() + + def failing_func(): + raise driver_exception + + with pytest.raises(mysql_errors.IntegrityError) as exc_info: + preserve_type_plugin.execute(connection_mock, "Cursor.execute", failing_func) + + assert exc_info.value is driver_exception + preserve_type_plugin._pick_new_connection.assert_not_called() + + def test_execute_wraps_non_failover_driver_exception_by_default(self, failover_v2_plugin, connection_mock): + # Same path with the property unset: the exception is replaced. + driver_exception = mysql_errors.IntegrityError( + "1062 (23000): Duplicate entry 'a' for key 'tbl.col'") + failover_v2_plugin._plugin_service.is_network_exception.return_value = False + failover_v2_plugin._plugin_service.is_read_only_connection_exception.return_value = False + failover_v2_plugin._invalidate_current_connection = MagicMock() + failover_v2_plugin._pick_new_connection = MagicMock() + + def failing_func(): + raise driver_exception + + with pytest.raises(AwsWrapperError) as exc_info: + failover_v2_plugin.execute(connection_mock, "Cursor.execute", failing_func) + + assert exc_info.value.driver_error is driver_exception + failover_v2_plugin._pick_new_connection.assert_not_called() + def test_failover_writer_mode(self, failover_v2_plugin): failover_v2_plugin._failover_mode = FailoverMode.STRICT_WRITER failover_v2_plugin._failover_writer = MagicMock() diff --git a/tests/unit/test_sqlalchemy_dialects.py b/tests/unit/test_sqlalchemy_dialects.py index 686877c30..073535d72 100644 --- a/tests/unit/test_sqlalchemy_dialects.py +++ b/tests/unit/test_sqlalchemy_dialects.py @@ -265,3 +265,58 @@ def test_async_dialects_define_do_ping(): # Each defines its own do_ping (not merely inherited from the stock base). assert "do_ping" in AwsWrapperMySQLAiomysqlAsyncDialect.__dict__ assert "do_ping" in AwsWrapperPGPsycopgAsyncDialect.__dict__ + + +# --- driver-error classification (issue #1275) ------------------------------- +# +# SQLAlchemy picks the ``sqlalchemy.exc`` class by walking the raised +# exception's MRO and matching base class *names*. Because ``loaded_dbapi`` is +# this package, that only produces the right answer if the exception reaching SA +# carries a base named after its PEP-249 category. These tests pin both halves +# of that: the dialect normalizes a driver error into such a class, and a +# generic ``AwsWrapperError`` -- what the failover plugins raise in place of the +# driver's exception unless ``preserve_driver_exception_type`` is set -- does not +# classify at all. + +def test_driver_integrity_error_classifies_as_sa_integrity_error(): + from mysql.connector import errors as mysql_errors + from sqlalchemy import exc as sa_exc + + import aws_advanced_python_wrapper + from aws_advanced_python_wrapper.sqlalchemy_dialects._exception_handling import \ + _normalize_driver_error + + driver_error = mysql_errors.IntegrityError( + "1062 (23000): Duplicate entry 'a' for key 'tbl.col'") + normalized = _normalize_driver_error(driver_error, mysql_errors) + + classified = sa_exc.DBAPIError.instance( + "INSERT INTO tbl (col) VALUES (%s)", {}, normalized, + aws_advanced_python_wrapper.Error) + + assert type(classified) is sa_exc.IntegrityError + assert classified.orig is normalized + + +def test_generic_aws_wrapper_error_does_not_classify(): + """Why the failover plugins must not substitute the driver's exception. + + ``AwsWrapperError``'s MRO contributes only the names ``AwsWrapperError``, + ``Error`` and ``Exception``, none of which ``sqlalchemy.exc`` exports, so + SA falls back to the generic ``DBAPIError`` and every + ``except sqlalchemy.exc.IntegrityError:`` recovery path stops matching. + """ + from mysql.connector import errors as mysql_errors + from sqlalchemy import exc as sa_exc + + import aws_advanced_python_wrapper + from aws_advanced_python_wrapper.errors import AwsWrapperError + + driver_error = mysql_errors.IntegrityError( + "1062 (23000): Duplicate entry 'a' for key 'tbl.col'") + classified = sa_exc.DBAPIError.instance( + "INSERT INTO tbl (col) VALUES (%s)", {}, + AwsWrapperError("wrapped", driver_error), + aws_advanced_python_wrapper.Error) + + assert type(classified) is sa_exc.DBAPIError