Spaces:
Running
Running
| from __future__ import annotations | |
| import os | |
| from sqlalchemy import create_engine | |
| # --------------------------------------------------------------------------- | |
| # Lazy engine — built on first get_connection() call, not at import time. | |
| # This allows db.py (and other modules) to import remote_db safely even when | |
| # DATABASE_URL is not yet in the environment at import time. | |
| # RuntimeError is raised when get_connection() is first called without a URL. | |
| # --------------------------------------------------------------------------- | |
| _engine = None | |
| def _get_engine(): | |
| global _engine | |
| if _engine is not None: | |
| return _engine | |
| database_url = os.getenv("DATABASE_URL", "").strip() | |
| if not database_url: | |
| raise RuntimeError("DATABASE_URL is not set") | |
| # CockroachDB requires the cockroachdb:// dialect for SQLAlchemy | |
| if database_url.startswith("postgresql://"): | |
| database_url = "cockroachdb://" + database_url[len("postgresql://"):] | |
| _engine = create_engine( | |
| database_url, | |
| pool_size=10, | |
| max_overflow=20, | |
| pool_timeout=60, | |
| pool_pre_ping=True, | |
| pool_recycle=300, | |
| ) | |
| return _engine | |
| def get_connection(): | |
| return _get_engine().connect() | |