Skip to content

src/genro_asgi/db.py

Source from this local checkout, regenerated when the reader rebuilds. Line links use #L<number>; a GitHub line range opens its first line.

1 # Copyright 2025 Softwell S.r.l.2 #3 # Licensed under the Apache License, Version 2.0 (the "License");4 # you may not use this file except in compliance with the License.5 # You may obtain a copy of the License at6 #7 #     https://www.apache.org/licenses/LICENSE-2.08 #9 # Unless required by applicable law or agreed to in writing, software10 # distributed under the License is distributed on an "AS IS" BASIS,11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12 # See the License for the specific language governing permissions and13 # limitations under the License.14 15 """Database handler — the core's minimal contract for a mounted database.16 17 A ``database`` declared in the config names a ``db_class`` (the imported class18 that builds the real db from the connection parameters) and, optionally, a19 ``db_handler_class`` (default ``AsgiDbHandlerBase``). At mount time the server20 builds ``db_handler_class(db_class(**params))`` and registers the handler.21 22 The handler is what lives in the registry and what ``request.db`` returns. It23 proxies every attribute to the wrapped db via ``__getattr__`` (so the db's own24 interface — ``execute`` and the rest — stays transparent), while owning the one25 method the core itself calls: ``closeConnection`` (registered as a request26 cleanup). Concrete db classes and custom handlers live outside the core; the27 core only defines this contract.28 """29 30 from __future__ import annotations31 32 from typing import Any33 34 __all__ = ["AsgiDbHandlerBase"]35 36 37 class AsgiDbHandlerBase:38     """Wraps a database object: owns ``closeConnection``, proxies the rest.39 40     Subclass to customise lifecycle (e.g. a legacy backend); the default41     proxies every non-underscore attribute to the wrapped db.42     """43 44     __slots__ = ("_db",)45 46     def __init__(self, db: Any) -> None:47         self._db = db48 49     def closeConnection(self) -> None:50         """Close the wrapped db's connection if it exposes ``closeConnection``."""51         close = getattr(self._db, "closeConnection", None)52         if callable(close):53             close()54 55     def __getattr__(self, name: str) -> Any:56         # __getattr__ runs only for attributes not found normally; ``_db`` is a57         # real slot, so it never recurses here. Underscore names are never58         # proxied: this both guards against recursion (when ``_db`` is not yet59         # set) and keeps the db's internals out of the public proxy surface.60         if name.startswith("_"):61             raise AttributeError(name)62         return getattr(self._db, name)63 64     def __repr__(self) -> str:65         return f"{type(self).__name__}({type(self._db).__name__})"