Really-amin's picture
Upload 329 files
f26bf97 verified
raw
history blame
2.63 kB
"""Database package exports.
This package exposes both the new SQLAlchemy-based ``DatabaseManager`` used by the
API monitoring subsystem, and the legacy SQLite-backed database implementation
used by the older crypto dashboard code.
Compatibility guarantees
------------------------
- Code that does ``from database import Database`` will receive the legacy
implementation if ``database.py`` exists and defines either ``Database`` or
``CryptoDatabase``. Otherwise it will fall back to ``DatabaseManager``.
- Code that does ``from database import CryptoDatabase`` will likewise receive
the legacy implementation when available, with a safe fallback to
``DatabaseManager``.
- ``from database import db_manager`` continues to work and returns the
``database.db_manager`` module.
"""
from importlib import util as _importlib_util
from pathlib import Path as _Path
from typing import Optional as _Optional
from .db_manager import DatabaseManager
from . import db_manager as db_manager # re-export module for tests and callers
def _load_legacy_database() -> _Optional[type]:
"""
Try to load the legacy database class from the root ``database.py`` module.
We support both the older ``Database`` name (as mentioned in some docs)
and the newer ``CryptoDatabase`` class name used in the current codebase.
"""
root_module_path = _Path(__file__).resolve().parent.parent / "database.py"
if not root_module_path.exists():
return None
spec = _importlib_util.spec_from_file_location("legacy_database", root_module_path)
if spec is None or spec.loader is None:
return None
module = _importlib_util.module_from_spec(spec)
try:
spec.loader.exec_module(module) # type: ignore[union-attr]
except Exception:
# If loading the legacy module fails we silently fall back to DatabaseManager
return None
# Prefer a class called "Database" if present, but also support "CryptoDatabase"
legacy_cls = getattr(module, "Database", None)
if legacy_cls is None:
legacy_cls = getattr(module, "CryptoDatabase", None)
return legacy_cls
_LegacyDatabase = _load_legacy_database()
if _LegacyDatabase is not None:
# On projects that still use the legacy implementation, both public names
# point to the same underlying class.
Database = _LegacyDatabase
CryptoDatabase = _LegacyDatabase
else:
# If the legacy module is missing or broken, fall back to the new manager.
Database = DatabaseManager
CryptoDatabase = DatabaseManager
__all__ = ["DatabaseManager", "Database", "CryptoDatabase", "db_manager"]