From 39ba4642371351101665f4daf147c15c7f50b870 Mon Sep 17 00:00:00 2001 From: Linus Vogel Date: Thu, 25 Dec 2025 20:17:36 +0100 Subject: [PATCH] automatically apply new database migrations on startup, and handle the race condition of multiple workers starting up simultaneously --- pillar_tool/db/__init__.py | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/pillar_tool/db/__init__.py b/pillar_tool/db/__init__.py index 708e90c..f2c670d 100644 --- a/pillar_tool/db/__init__.py +++ b/pillar_tool/db/__init__.py @@ -1,9 +1,8 @@ -import os - -import alembic +from os import lockf, F_LOCK +from os.path import dirname, realpath from alembic.config import Config -from alembic.command import upgrade +from alembic.command import upgrade, check, util from pillar_tool.util import config @@ -16,10 +15,12 @@ host = cfg.db.host port = cfg.db.port database = cfg.db.database alembic_cfg = Config() -alembic_cfg.set_main_option('script_location', f'{os.path.dirname(os.path.realpath(__file__))}/migrations') +alembic_cfg.set_main_option('script_location', f'{dirname(realpath(__file__))}/migrations') alembic_cfg.set_main_option('sqlalchemy.url', f'postgresql://{user}:{password}@{host}:{port}/{database}') alembic_cfg.set_main_option('prepend_sys_path', '.') def run_db_migrations(): - upgrade(config=alembic_cfg, revision='head') + with open(realpath(__file__), 'a') as f: + lockf(f.fileno(), F_LOCK, 0) + upgrade(config=alembic_cfg, revision='head')