@@ -23,6 +23,17 @@ def _mask_url(url: str) -> str:
2323 return url
2424
2525
26+ def _has_version_stamp (engine ) -> bool :
27+ """Check if the version table has any stamps"""
28+ try :
29+ with engine .connect () as conn :
30+ result = conn .execute (text (f"SELECT COUNT(*) FROM { VERSION_TABLE } " ))
31+ count = result .scalar ()
32+ return count > 0
33+ except Exception :
34+ return False
35+
36+
2637def run_migrations_on_startup ():
2738 if os .getenv ("BIOMERO_RUN_MIGRATIONS" , "1" ) != "1" :
2839 return
@@ -59,35 +70,29 @@ def run_migrations_on_startup():
5970 if engine is None :
6071 engine = create_engine (db_url )
6172
62- # Check if there are any migration files first
63- versions_dir = pathlib .Path (MIGRATIONS_DIR ) / "versions"
64- migration_files = []
65- if versions_dir .exists ():
66- migration_files = [f for f in versions_dir .glob ("*.py" )
67- if not f .name .startswith ("__" )]
73+ # Setup Alembic configuration
74+ cfg = Config ()
75+ cfg .set_main_option ("script_location" , MIGRATIONS_DIR )
76+ # Don't set sqlalchemy.url in config - let env.py use environment variable
77+ cfg .set_main_option ("version_table" , VERSION_TABLE )
78+
79+ insp = inspect (engine )
80+ has_version_table = insp .has_table (VERSION_TABLE )
6881
69- if not migration_files :
70- logger .info ("No migration files found. Auto-stamping existing schema as head." )
71- # Just stamp the current schema as head if tables exist
72- insp = inspect (engine )
82+ # If no version table or it's empty, and we have BIOMERO tables,
83+ # stamp to head to establish baseline
84+ if not has_version_table or not _has_version_stamp (engine ):
7385 known_tables = {
7486 "biomero_job_view" ,
7587 "biomero_job_progress_view" ,
7688 "biomero_workflow_progress_view" ,
7789 "biomero_task_execution"
7890 }
7991 if any (insp .has_table (t ) for t in known_tables ):
80- cfg = Config ()
81- cfg .set_main_option ("script_location" , MIGRATIONS_DIR )
82- # Don't set sqlalchemy.url in config - let env.py use environment variable
83- cfg .set_main_option ("version_table" , VERSION_TABLE )
84-
85- # Just stamp to head - no actual migration needed
92+ logger .info ("Stamping existing BIOMERO schema to head" )
8693 command .stamp (cfg , "head" )
87- logger .info ("Stamped database to head revision (no migration files exist)" )
8894 else :
8995 logger .info ("No BIOMERO tables found, skipping stamp" )
90- return
9196
9297 cfg = Config ()
9398 cfg .set_main_option ("script_location" , MIGRATIONS_DIR )
0 commit comments