from __future__ import annotations import logging from pathlib import Path logger = logging.getLogger(__name__) def run_migrations(db_url: str, plugin_migration_dirs: list[Path] | None = None) -> None: """Run core + plugin Alembic migrations synchronously. Called during create_app() before the event loop starts. Applies all pending migrations in dependency order. Plugin migration dirs are included via Alembic's version_locations. """ from alembic import command from alembic.config import Config core_migrations = Path(__file__).parent.parent / "migrations" core_versions = core_migrations / "versions" cfg = Config() cfg.set_main_option("script_location", str(core_migrations)) cfg.set_main_option("sqlalchemy.url", db_url) # Build version_locations: core + any plugin version directories version_locs = [str(core_versions)] for plugin_dir in (plugin_migration_dirs or []): pv = plugin_dir / "versions" if pv.exists(): version_locs.append(str(pv)) cfg.set_main_option("version_locations", " ".join(version_locs)) logger.info("Running migrations (version_locations: %s)", " ".join(version_locs)) command.upgrade(cfg, "heads") logger.info("Migrations complete") def get_plugin_migration_dirs(plugin_dir: Path, plugins_cfg: dict) -> list[Path]: """Return migration directories for all enabled plugins that have one. Does not import any Python code — filesystem scan only. Used to collect migration dirs before importing plugins, so migrations can run before plugin Python code is loaded. """ dirs = [] for name, cfg in plugins_cfg.items(): if not cfg.get("enabled", False): continue mdir = plugin_dir / name / "migrations" if mdir.exists(): dirs.append(mdir) return dirs