Skip to content
Open
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
25 changes: 25 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,31 @@ The Microsoft **mssql-python** module is designed to be fully compliant with the

By adhering to the DB API 2.0 specification, the mssql-python module ensures compatibility with a wide range of Python applications and frameworks, making it a versatile choice for developers working with Microsoft SQL Server, Azure SQL Database, and Azure SQL Managed Instance.

### Error classification with SQLSTATE

DB-API exceptions expose `sqlstate: str | None`. Synchronous ODBC errors retain
their diagnostic SQLSTATE, including codes not recognized by the driver's
exception mapping. When no SQLSTATE is available, the attribute is `None`.
Python-created errors and async Rust/TDS errors default to `None`.

```python
from mssql_python import Error

try:
cursor.execute("SELECT * FROM missing_table")
except Error as exc:
# getattr also supports driver versions without the sqlstate attribute.
if getattr(exc, "sqlstate", None) == "42S02":
print("The requested table was not found.")
raise
```

Existing exception types, two-argument constructors, messages, and `args` are
unchanged. Constructors also accept the optional keyword-only `sqlstate` argument,
and SQLSTATE metadata survives pickling and copying. A SQLSTATE alone does not
guarantee that retrying an operation is safe. Native SQL Server error numbers are
not exposed by this attribute.

### Enhanced Pythonic Features

The driver offers a suite of Pythonic enhancements that streamline database interactions, making it easier for developers to execute queries, manage connections, and handle data more efficiently.
Expand Down
1 change: 1 addition & 0 deletions mssql_python/connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -242,6 +242,7 @@ def _raise_connection_error(e: RuntimeError) -> NoReturn:
raise DatabaseError(
driver_error=f"An error occurred with SQLSTATE code: {sqlstate}",
ddbc_error=ddbc_error,
sqlstate=sqlstate,
) from None
logger.error("Connection error (SQLSTATE %s): %s", sqlstate, ddbc_error)
raise exc from None
Expand Down
76 changes: 54 additions & 22 deletions mssql_python/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,11 +37,16 @@ def __reduce__(self) -> tuple[type["ConnectionStringParseError"], tuple[list[str
class Exception(builtins.Exception):
"""
Base class for all DB API 2.0 exceptions.

sqlstate is the diagnostic SQLSTATE when available, otherwise None.
"""

def __init__(self, driver_error: str, ddbc_error: str) -> None:
def __init__(
self, driver_error: str, ddbc_error: str, *, sqlstate: Optional[str] = None
) -> None:
self.driver_error = driver_error
self.ddbc_error = truncate_error_message(ddbc_error)
self.sqlstate = sqlstate or None
if self.ddbc_error:
# Both driver and DDBC errors are present
self.message = f"Driver Error: {self.driver_error}; DDBC Error: {self.ddbc_error}"
Expand All @@ -55,12 +60,14 @@ def __reduce__(
) -> tuple[
Callable[[type["Exception"], str, str, str], "Exception"],
tuple[type["Exception"], str, str, str],
dict[str, Optional[str]],
]:
# Reconstruct without re-running __init__/truncate_error_message() to avoid
# emitting warnings for already-truncated "[Microsoft]..." messages.
return (
Exception._unpickle,
(self.__class__, self.driver_error, self.ddbc_error, self.message),
{"sqlstate": self.sqlstate},
)

@staticmethod
Expand All @@ -71,6 +78,7 @@ def _unpickle(
obj.driver_error = driver_error
obj.ddbc_error = ddbc_error
obj.message = message
obj.sqlstate = None
builtins.Exception.__init__(obj, message)
return obj

Expand All @@ -80,17 +88,21 @@ class Warning(Exception):
Exception raised for important warnings like data truncations while inserting, etc.
"""

def __init__(self, driver_error: str, ddbc_error: str) -> None:
super().__init__(driver_error, ddbc_error)
def __init__(
self, driver_error: str, ddbc_error: str, *, sqlstate: Optional[str] = None
) -> None:
super().__init__(driver_error, ddbc_error, sqlstate=sqlstate)


class Error(Exception):
"""
Base class for errors.
"""

def __init__(self, driver_error: str, ddbc_error: str) -> None:
super().__init__(driver_error, ddbc_error)
def __init__(
self, driver_error: str, ddbc_error: str, *, sqlstate: Optional[str] = None
) -> None:
super().__init__(driver_error, ddbc_error, sqlstate=sqlstate)


class InterfaceError(Error):
Expand All @@ -99,17 +111,21 @@ class InterfaceError(Error):
interface rather than the database itself.
"""

def __init__(self, driver_error: str, ddbc_error: str) -> None:
super().__init__(driver_error, ddbc_error)
def __init__(
self, driver_error: str, ddbc_error: str, *, sqlstate: Optional[str] = None
) -> None:
super().__init__(driver_error, ddbc_error, sqlstate=sqlstate)


class DatabaseError(Error):
"""
Exception raised for errors that are related to the database.
"""

def __init__(self, driver_error: str, ddbc_error: str) -> None:
super().__init__(driver_error, ddbc_error)
def __init__(
self, driver_error: str, ddbc_error: str, *, sqlstate: Optional[str] = None
) -> None:
super().__init__(driver_error, ddbc_error, sqlstate=sqlstate)


class DataError(DatabaseError):
Expand All @@ -118,8 +134,10 @@ class DataError(DatabaseError):
processed data like division by zero, numeric value out of range, etc.
"""

def __init__(self, driver_error: str, ddbc_error: str) -> None:
super().__init__(driver_error, ddbc_error)
def __init__(
self, driver_error: str, ddbc_error: str, *, sqlstate: Optional[str] = None
) -> None:
super().__init__(driver_error, ddbc_error, sqlstate=sqlstate)


class OperationalError(DatabaseError):
Expand All @@ -128,8 +146,10 @@ class OperationalError(DatabaseError):
and not necessarily under the control of the programmer.
"""

def __init__(self, driver_error: str, ddbc_error: str) -> None:
super().__init__(driver_error, ddbc_error)
def __init__(
self, driver_error: str, ddbc_error: str, *, sqlstate: Optional[str] = None
) -> None:
super().__init__(driver_error, ddbc_error, sqlstate=sqlstate)


class IntegrityError(DatabaseError):
Expand All @@ -138,8 +158,10 @@ class IntegrityError(DatabaseError):
e.g., a foreign key check fails.
"""

def __init__(self, driver_error: str, ddbc_error: str) -> None:
super().__init__(driver_error, ddbc_error)
def __init__(
self, driver_error: str, ddbc_error: str, *, sqlstate: Optional[str] = None
) -> None:
super().__init__(driver_error, ddbc_error, sqlstate=sqlstate)


class InternalError(DatabaseError):
Expand All @@ -148,8 +170,10 @@ class InternalError(DatabaseError):
e.g., the cursor is not valid anymore, the transaction is out of sync, etc.
"""

def __init__(self, driver_error: str, ddbc_error: str) -> None:
super().__init__(driver_error, ddbc_error)
def __init__(
self, driver_error: str, ddbc_error: str, *, sqlstate: Optional[str] = None
) -> None:
super().__init__(driver_error, ddbc_error, sqlstate=sqlstate)


class ProgrammingError(DatabaseError):
Expand All @@ -159,8 +183,10 @@ class ProgrammingError(DatabaseError):
wrong number of parameters specified, etc.
"""

def __init__(self, driver_error: str, ddbc_error: str) -> None:
super().__init__(driver_error, ddbc_error)
def __init__(
self, driver_error: str, ddbc_error: str, *, sqlstate: Optional[str] = None
) -> None:
super().__init__(driver_error, ddbc_error, sqlstate=sqlstate)


class NotSupportedError(DatabaseError):
Expand All @@ -170,8 +196,10 @@ class NotSupportedError(DatabaseError):
on a connection that does not support transaction or has transactions turned off.
"""

def __init__(self, driver_error: str, ddbc_error: str) -> None:
super().__init__(driver_error, ddbc_error)
def __init__(
self, driver_error: str, ddbc_error: str, *, sqlstate: Optional[str] = None
) -> None:
super().__init__(driver_error, ddbc_error, sqlstate=sqlstate)


# Mapping SQLSTATE codes to custom exception classes
Expand Down Expand Up @@ -550,7 +578,10 @@ def sqlstate_to_exception(sqlstate: str, ddbc_error: str) -> Optional[Exception]
driver_error="Corrupt file data source", ddbc_error=ddbc_error
), # Corrupt file data source
}
return mapping.get(sqlstate, None)
exception = mapping.get(sqlstate)
if exception is not None:
exception.sqlstate = sqlstate or None
return exception


def truncate_error_message(error_message: str) -> str:
Expand Down Expand Up @@ -592,4 +623,5 @@ def raise_exception(sqlstate: str, ddbc_error: str) -> None:
raise DatabaseError(
driver_error=f"An error occurred with SQLSTATE code: {sqlstate}",
ddbc_error=f"{ddbc_error}" if ddbc_error else "Unknown DDBC error",
sqlstate=sqlstate,
)
42 changes: 32 additions & 10 deletions mssql_python/mssql_python.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -103,40 +103,62 @@ def Binary(value: Union[str, bytes, bytearray, memoryview]) -> bytes: ...
# DB-API 2.0 Exception Hierarchy
# https://www.python.org/dev/peps/pep-0249/#exceptions
class Warning(Exception):
def __init__(self, driver_error: str, ddbc_error: str) -> None: ...
def __init__(
self, driver_error: str, ddbc_error: str, *, sqlstate: Optional[str] = None
) -> None: ...
driver_error: str
ddbc_error: str
message: str
sqlstate: Optional[str]

class Error(Exception):
def __init__(self, driver_error: str, ddbc_error: str) -> None: ...
def __init__(
self, driver_error: str, ddbc_error: str, *, sqlstate: Optional[str] = None
) -> None: ...
driver_error: str
ddbc_error: str
message: str
sqlstate: Optional[str]

class InterfaceError(Error):
def __init__(self, driver_error: str, ddbc_error: str) -> None: ...
def __init__(
self, driver_error: str, ddbc_error: str, *, sqlstate: Optional[str] = None
) -> None: ...

class DatabaseError(Error):
def __init__(self, driver_error: str, ddbc_error: str) -> None: ...
def __init__(
self, driver_error: str, ddbc_error: str, *, sqlstate: Optional[str] = None
) -> None: ...

class DataError(DatabaseError):
def __init__(self, driver_error: str, ddbc_error: str) -> None: ...
def __init__(
self, driver_error: str, ddbc_error: str, *, sqlstate: Optional[str] = None
) -> None: ...

class OperationalError(DatabaseError):
def __init__(self, driver_error: str, ddbc_error: str) -> None: ...
def __init__(
self, driver_error: str, ddbc_error: str, *, sqlstate: Optional[str] = None
) -> None: ...

class IntegrityError(DatabaseError):
def __init__(self, driver_error: str, ddbc_error: str) -> None: ...
def __init__(
self, driver_error: str, ddbc_error: str, *, sqlstate: Optional[str] = None
) -> None: ...

class InternalError(DatabaseError):
def __init__(self, driver_error: str, ddbc_error: str) -> None: ...
def __init__(
self, driver_error: str, ddbc_error: str, *, sqlstate: Optional[str] = None
) -> None: ...

class ProgrammingError(DatabaseError):
def __init__(self, driver_error: str, ddbc_error: str) -> None: ...
def __init__(
self, driver_error: str, ddbc_error: str, *, sqlstate: Optional[str] = None
) -> None: ...

class NotSupportedError(DatabaseError):
def __init__(self, driver_error: str, ddbc_error: str) -> None: ...
def __init__(
self, driver_error: str, ddbc_error: str, *, sqlstate: Optional[str] = None
) -> None: ...

# Row Object
class Row:
Expand Down
1 change: 1 addition & 0 deletions tests/AsyncTest/test_003_async_exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ def test_translates_each_native_dbapi_exception(name):
assert isinstance(translated, getattr(public_exceptions, name))
assert translated.driver_error == "Async operation failed"
assert translated.ddbc_error == "native failure"
assert translated.sqlstate is None


def test_translation_normalizes_native_detail_as_backend_error():
Expand Down
Loading
Loading