from alembic import command from alembic.config import Config from wce_crm import constants from wce_crm.logging import logger_base as logger def check_and_run_migrations() -> None: logger.info("[DB migration - Alembic] Start...") alembic_base_folder = constants.Config.ALEMBIC_PATH alembic_ini_file = alembic_base_folder / "alembic.ini" alembic_working_dir = alembic_base_folder / "alembic" assert alembic_ini_file.exists(), "Alembic INI file not found" assert alembic_working_dir.exists(), "Alembic working dir not found" assert alembic_working_dir.is_dir(), "Alembic working dir is not a directory" logger.info("[DB migration - Alembic] Initialise config...") alembic_cfg = Config(alembic_ini_file) alembic_cfg.set_main_option("script_location", str(alembic_working_dir)) logger.info("[DB migration - Alembic] Run...") try: command.upgrade(alembic_cfg, "head") logger.info("[DB migration - Alembic] Database up-to-date.") except Exception as err: logger.info( "[DB migration - Alembic] An error occurred during the migration:\n%s", err, stack_info=True, ) if __name__ == "__main__": # start migration process before app start check_and_run_migrations()