From 26e06ddeaa0be90d06ebee5dfd1e07b3bf0c9bce Mon Sep 17 00:00:00 2001 From: mohamad Date: Sun, 1 Jun 2025 17:03:13 +0200 Subject: [PATCH] refactor: Simplify Dockerfile by reorganizing Alembic file copying and enhance migration handling in application startup --- be/Dockerfile | 4 ++-- be/app/main.py | 31 ++++++++++++++++++++----------- 2 files changed, 22 insertions(+), 13 deletions(-) diff --git a/be/Dockerfile b/be/Dockerfile index e50caea..7365f1a 100644 --- a/be/Dockerfile +++ b/be/Dockerfile @@ -45,10 +45,10 @@ WORKDIR /app # Copy only necessary application files (be selective) COPY --chown=appuser:appuser app/ ./app/ +COPY --chown=appuser:appuser alembic/ ./alembic/ +COPY --chown=appuser:appuser alembic.ini ./ COPY --chown=appuser:appuser *.py ./ COPY --chown=appuser:appuser requirements.txt ./ -COPY --chown=appuser:appuser alembic.ini ./ -COPY --chown=appuser:appuser alembic/ ./alembic/ # Create logs directory RUN mkdir -p /app/logs && chown -R appuser:appuser /app diff --git a/be/app/main.py b/be/app/main.py index a2b4bee..0346cef 100644 --- a/be/app/main.py +++ b/be/app/main.py @@ -9,6 +9,7 @@ from sentry_sdk.integrations.fastapi import FastApiIntegration from fastapi_users.authentication import JWTStrategy from pydantic import BaseModel from jose import jwt, JWTError +from sqlalchemy.ext.asyncio import AsyncEngine from alembic.config import Config from alembic import command import os @@ -213,25 +214,33 @@ async def read_root(): } # --- End Root Endpoint --- +async def run_migrations(): + """Run database migrations.""" + try: + logger.info("Running database migrations...") + # Get the path to the alembic.ini file + alembic_ini_path = os.path.join(os.path.dirname(__file__), '..', 'alembic.ini') + + # Create Alembic configuration + alembic_cfg = Config(alembic_ini_path) + + # Run the migration + command.upgrade(alembic_cfg, "head") + + logger.info("Database migrations completed successfully.") + except Exception as e: + logger.error(f"Error running migrations: {e}") + raise -# --- Application Startup/Shutdown Events (Optional) --- @app.on_event("startup") async def startup_event(): """Initialize services on startup.""" logger.info(f"Application startup in {settings.ENVIRONMENT} environment...") # Run database migrations - try: - logger.info("Running database migrations...") - alembic_cfg = Config() - alembic_cfg.set_main_option("script_location", "alembic") - alembic_cfg.set_main_option("sqlalchemy.url", settings.DATABASE_URL) - command.upgrade(alembic_cfg, "head") - logger.info("Database migrations completed successfully.") - except Exception as e: - logger.error(f"Failed to run database migrations: {e}") - raise + await run_migrations() + # Initialize scheduler init_scheduler() logger.info("Application startup complete.") -- 2.45.2