Coverage for dataexcept/database_exceptions.py: 100%

26 statements  

« prev     ^ index     » next       coverage.py v7.15.4, created at 2026-09-03 20:46 +0000

1"""Custom exceptions for database operations.""" 

2 

3from __future__ import annotations 

4 

5from .base import DataExceptError 

6from .redaction import redact_url 

7 

8 

9class DatabaseError(DataExceptError): 

10 """Base exception for database-related errors.""" 

11 

12 pass 

13 

14 

15class DatabaseConnectionError(DatabaseError): 

16 """Raised when connecting to the database fails.""" 

17 

18 def __init__(self, db_url: str, message: str | None = None) -> None: 

19 """Initialize DatabaseConnectionError. 

20 

21 Args: 

22 db_url: Database connection URL. 

23 message: Optional custom error message. 

24 """ 

25 # A connection URL routinely carries a username and password. 

26 self.db_url = redact_url(db_url) 

27 default = f"Failed to connect to database at '{self.db_url}'" 

28 super().__init__(message or default) 

29 

30 

31class QueryExecutionError(DatabaseError): 

32 """Raised when a database query execution fails.""" 

33 

34 def __init__(self, query: str, original: Exception | None = None) -> None: 

35 """Initialize QueryExecutionError. 

36 

37 Args: 

38 query: SQL query string. 

39 original: Optional underlying exception. 

40 """ 

41 self.query = query 

42 self.original = original 

43 msg = f"Query failed: {query}" 

44 if original: 

45 msg += f" ({original})" 

46 super().__init__(msg) 

47 

48 

49class TransactionError(DatabaseError): 

50 """Raised when a database transaction fails.""" 

51 

52 def __init__( 

53 self, 

54 transaction_id: str | None = None, 

55 message: str | None = None, 

56 ) -> None: 

57 """Initialize TransactionError. 

58 

59 Args: 

60 transaction_id: Identifier for the transaction. 

61 message: Optional custom error message. 

62 """ 

63 self.transaction_id = transaction_id 

64 default = "Database transaction failed" 

65 if transaction_id: 

66 default += f" (id={transaction_id})" 

67 super().__init__(message or default) 

68 

69 

70__all__ = [ 

71 "DatabaseError", 

72 "DatabaseConnectionError", 

73 "QueryExecutionError", 

74 "TransactionError", 

75]