from __future__ import annotations import fcntl from contextlib import contextmanager from pathlib import Path from flask import Flask from .database_init import initialize_database from .database_migrations import migrate_database @contextmanager def _startup_lock(app: Flask): lock_path = Path(app.instance_path) / ".database-startup.lock" lock_path.parent.mkdir(parents=True, exist_ok=True) with lock_path.open("w") as lock_file: fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX) try: yield finally: fcntl.flock(lock_file.fileno(), fcntl.LOCK_UN) def prepare_database(app: Flask) -> list[str]: with app.app_context(), _startup_lock(app): initialize_database() return migrate_database() __all__ = ["initialize_database", "migrate_database", "prepare_database"]