Refactor database URL handling in Alembic environment

- Introduced a new function to normalize database URLs for Alembic, ensuring compatibility with different PostgreSQL drivers.
- Updated the `get_database_url` function to prioritize the use of the `TEST_DATABASE_URL` environment variable for CI and testing scenarios.
- Enhanced error messaging to clarify configuration requirements for database connections.

This change aims to improve the flexibility and reliability of database connections in the testing environment.
This commit is contained in:
2026-03-24 15:28:41 -05:00
parent 3ba9359881
commit 4b2a3da611
2 changed files with 24 additions and 3 deletions

View File

@@ -18,9 +18,29 @@ logger = logging.getLogger(__name__)
config = context.config
def _normalize_alembic_sqlalchemy_url(url: str) -> str:
"""Alembic usa el driver síncrono psycopg2; normaliza DSN típicos de app/tests."""
url = url.strip()
if url.startswith("postgresql+asyncpg://"):
return url.replace("postgresql+asyncpg://", "postgresql+psycopg2://", 1)
if url.startswith("postgresql+psycopg2://"):
return url
if url.startswith("postgresql://"):
return url.replace("postgresql://", "postgresql+psycopg2://", 1)
if url.startswith("postgres://"):
return url.replace("postgres://", "postgresql+psycopg2://", 1)
return url
def get_database_url():
"""Obtiene la URL de la base de datos (PostgreSQL) desde variables de entorno o alembic.ini."""
# Intentar construir desde variables de entorno primero
# CI / pytest: misma URL que los tests (secret TEST_DATABASE_URL) o DATABASE_URL explícita
for env_key in ("TEST_DATABASE_URL"):
raw = os.environ.get(env_key)
if raw and raw.strip():
return _normalize_alembic_sqlalchemy_url(raw)
# Construcción desde settings (CORE_DB_* en .env / entorno)
host = settings.CORE_DB_HOST
db = settings.CORE_DB_NAME
user = settings.CORE_DB_USER
@@ -41,7 +61,8 @@ def get_database_url():
if not url:
raise RuntimeError(
"No se ha configurado la cadena de conexión a PostgreSQL. "
"Proporciona las variables de entorno POSTGRES_* o configura sqlalchemy.url en alembic.ini"
"Define TEST_DATABASE_URL o DATABASE_URL, o CORE_DB_HOST/CORE_DB_USER/CORE_DB_PASSWORD/CORE_DB_NAME, "
"o sqlalchemy.url en alembic.ini"
)
return url