Coverage for downtify/db/errors.py: 96%

55 statements  

« prev     ^ index     » next       coverage.py v7.17.4, created at 2026-11-21 22:18 +0000

1"""Unified database exceptions for the SQLite and PostgreSQL backends. 

2 

3The classes also subclass the matching ``sqlite3`` exceptions so existing 

4code that catches ``sqlite3.OperationalError`` or ``sqlite3.IntegrityError`` 

5keeps working on the SQLite backend. 

6""" 

7 

8from __future__ import annotations 

9 

10import contextlib 

11import sqlite3 

12from collections.abc import Iterator 

13 

14import psycopg 

15 

16 

17class DatabaseError(Exception): 

18 """Base class for all translated database errors.""" 

19 

20 

21class OperationalError(DatabaseError, sqlite3.OperationalError): 

22 """Operational failure (connection, lock, runtime error).""" 

23 

24 

25class IntegrityError(DatabaseError, sqlite3.IntegrityError): 

26 """Constraint violation.""" 

27 

28 

29class ProgrammingError(DatabaseError, sqlite3.ProgrammingError): 

30 """API misuse, e.g. using a connection after its block has ended.""" 

31 

32 

33class UndefinedTable(OperationalError): 

34 """A referenced table does not exist.""" 

35 

36 

37class SerializationRetry(OperationalError): 

38 """The whole transaction is safe to retry. 

39 

40 Covers PostgreSQL deadlocks and serialization failures and the SQLite 

41 'database is locked' condition. 

42 """ 

43 

44 

45_RETRY_SQLSTATES = frozenset({'40001', '40P01'}) 

46 

47 

48def _translate_sqlite(exc: sqlite3.Error, msg: str) -> DatabaseError: 

49 if isinstance(exc, sqlite3.IntegrityError): 

50 return IntegrityError(msg) 

51 if isinstance(exc, sqlite3.OperationalError): 

52 if msg.startswith('no such table'): 

53 return UndefinedTable(msg) 

54 if 'database is locked' in msg or 'database table is locked' in msg: 

55 return SerializationRetry(msg) 

56 return OperationalError(msg) 

57 if isinstance(exc, sqlite3.ProgrammingError): 

58 return ProgrammingError(msg) 

59 return DatabaseError(msg) 

60 

61 

62def _translate_psycopg(exc: psycopg.Error, msg: str) -> DatabaseError: 

63 sqlstate = getattr(exc, 'sqlstate', None) 

64 if sqlstate in _RETRY_SQLSTATES: 

65 return SerializationRetry(msg) 

66 if sqlstate == '42P01': 

67 return UndefinedTable(msg) 

68 if (sqlstate or '').startswith('23') or isinstance( 

69 exc, psycopg.IntegrityError 

70 ): 

71 return IntegrityError(msg) 

72 if isinstance(exc, psycopg.OperationalError): 

73 return OperationalError(msg) 

74 if isinstance(exc, psycopg.ProgrammingError): 

75 return ProgrammingError(msg) 

76 return DatabaseError(msg) 

77 

78 

79def translate(exc: BaseException) -> DatabaseError | None: 

80 """Map a backend exception to a ``DatabaseError``. 

81 

82 Returns None if ``exc`` is not a database error, ``exc`` itself if it 

83 is already a ``DatabaseError``, otherwise a new translated exception 

84 with the same message. 

85 """ 

86 if isinstance(exc, DatabaseError): 

87 return exc 

88 msg = str(exc) 

89 if isinstance(exc, sqlite3.Error): 

90 return _translate_sqlite(exc, msg) 

91 if isinstance(exc, psycopg.Error): 

92 return _translate_psycopg(exc, msg) 

93 return None 

94 

95 

96@contextlib.contextmanager 

97def wrap_errors() -> Iterator[None]: 

98 """Re-raise backend database errors as translated ``DatabaseError``s. 

99 

100 The translated exception is chained to the original with ``from``. 

101 Non-database exceptions propagate unchanged. 

102 """ 

103 try: 

104 yield 

105 except BaseException as exc: 

106 translated = translate(exc) 

107 if translated is None or translated is exc: 

108 raise 

109 raise translated from exc