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
« 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.
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"""
8from __future__ import annotations
10import contextlib
11import sqlite3
12from collections.abc import Iterator
14import psycopg
17class DatabaseError(Exception):
18 """Base class for all translated database errors."""
21class OperationalError(DatabaseError, sqlite3.OperationalError):
22 """Operational failure (connection, lock, runtime error)."""
25class IntegrityError(DatabaseError, sqlite3.IntegrityError):
26 """Constraint violation."""
29class ProgrammingError(DatabaseError, sqlite3.ProgrammingError):
30 """API misuse, e.g. using a connection after its block has ended."""
33class UndefinedTable(OperationalError):
34 """A referenced table does not exist."""
37class SerializationRetry(OperationalError):
38 """The whole transaction is safe to retry.
40 Covers PostgreSQL deadlocks and serialization failures and the SQLite
41 'database is locked' condition.
42 """
45_RETRY_SQLSTATES = frozenset({'40001', '40P01'})
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)
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)
79def translate(exc: BaseException) -> DatabaseError | None:
80 """Map a backend exception to a ``DatabaseError``.
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
96@contextlib.contextmanager
97def wrap_errors() -> Iterator[None]:
98 """Re-raise backend database errors as translated ``DatabaseError``s.
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