Skip to content

Commit 761b5a7

Browse files
committed
Extend exception mapping to all connection methods
Address reviewer feedback: wrap remaining connection methods that call C++ to ensure complete SQLSTATE error mapping coverage. Additional methods now wrapped with try-catch + _raise_connection_error: - autocommit property getter (get_autocommit) - set_attr() for connection attributes - getinfo() for connection information - close() internal rollback during cleanup This ensures users never see raw RuntimeError with SQLSTATE prefixes from any connection operation. All C++ checkError() calls now properly map to correct DB-API 2.0 exception types. Addresses review comment on PR #562
1 parent c3b8b97 commit 761b5a7

1 file changed

Lines changed: 15 additions & 2 deletions

File tree

mssql_python/connection.py

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -496,7 +496,10 @@ def autocommit(self) -> bool:
496496
Returns:
497497
bool: True if autocommit is enabled, False otherwise.
498498
"""
499-
return self._conn.get_autocommit()
499+
try:
500+
return self._conn.get_autocommit()
501+
except RuntimeError as e:
502+
_raise_connection_error(e)
500503

501504
@autocommit.setter
502505
def autocommit(self, value: bool) -> None:
@@ -928,6 +931,9 @@ def set_attr(self, attribute: int, value: Union[int, str, bytes, bytearray]) ->
928931
self._conn.set_attr(attribute, value)
929932
logger.info(f"Connection attribute {sanitized_attr} set successfully")
930933

934+
except RuntimeError as e:
935+
# Handle C++ layer RuntimeError with proper DB-API exception mapping
936+
_raise_connection_error(e)
931937
except Exception as e:
932938
error_msg = f"Failed to set connection attribute {sanitized_attr}: {str(e)}"
933939

@@ -1308,6 +1314,9 @@ def getinfo(self, info_type: int) -> Union[str, int, bool, None]:
13081314
# Get the raw result from the C++ layer
13091315
try:
13101316
raw_result = self._conn.get_info(info_type)
1317+
except RuntimeError as e:
1318+
# Handle C++ layer RuntimeError with proper DB-API exception mapping
1319+
_raise_connection_error(e)
13111320
except Exception as e: # pylint: disable=broad-exception-caught
13121321
# Log the error and return None for invalid info types
13131322
logger.warning(f"getinfo({info_type}) failed: {e}")
@@ -1619,7 +1628,11 @@ def close(self) -> None:
16191628
# For autocommit True, this is not necessary as each statement is
16201629
# committed immediately
16211630
logger.debug("Rolling back uncommitted changes before closing connection.")
1622-
self._conn.rollback()
1631+
try:
1632+
self._conn.rollback()
1633+
except RuntimeError as e:
1634+
# Handle C++ layer RuntimeError with proper DB-API exception mapping
1635+
_raise_connection_error(e)
16231636
# TODO: Check potential race conditions in case of multithreaded scenarios
16241637
# Close the connection
16251638
self._conn.close()

0 commit comments

Comments
 (0)