@@ -21,18 +21,41 @@ async def lifespan(app: FastAPI):
2121 from pathlib import Path
2222
2323 backend_dir = Path (__file__ ).parent .parent # /app in container
24- result = subprocess .run (
25- [sys .executable , "-m" , "alembic" , "upgrade" , "head" ],
26- capture_output = True , text = True , cwd = str (backend_dir )
27- )
28- if result .returncode != 0 :
29- print (f"[ALEMBIC] Migration warning: { result .stderr } " )
30- else :
31- print (f"[ALEMBIC] { result .stdout .strip () or 'Migrations up to date' } " )
32-
33- await init_db () # create_all for any tables not covered by migrations
24+
25+ # Try to run migrations, but don't fail if tables already exist
26+ try :
27+ result = subprocess .run (
28+ [sys .executable , "-m" , "alembic" , "upgrade" , "head" ],
29+ capture_output = True , text = True , cwd = str (backend_dir )
30+ )
31+ if result .returncode != 0 :
32+ # Check if it's just a "tables already exist" error
33+ if "already exists" in result .stderr :
34+ print (f"[ALEMBIC] Tables already exist, marking migrations as applied..." )
35+ # Mark the current migration as applied without running it
36+ subprocess .run (
37+ [sys .executable , "-m" , "alembic" , "stamp" , "head" ],
38+ capture_output = True , text = True , cwd = str (backend_dir )
39+ )
40+ print (f"[ALEMBIC] Migrations marked as applied" )
41+ else :
42+ print (f"[ALEMBIC] Migration warning: { result .stderr } " )
43+ else :
44+ print (f"[ALEMBIC] { result .stdout .strip () or 'Migrations up to date' } " )
45+ except Exception as e :
46+ print (f"[ALEMBIC] Migration error (continuing anyway): { e } " )
47+
48+ try :
49+ await init_db () # create_all for any tables not covered by migrations
50+ except Exception as e :
51+ print (f"[DB] Database initialization error: { e } " )
52+
3453 yield
35- await close_db ()
54+
55+ try :
56+ await close_db ()
57+ except Exception as e :
58+ print (f"[DB] Database cleanup error: { e } " )
3659
3760
3861def create_app () -> FastAPI :
0 commit comments