From bdaf65a2566fc8ec7a73e7bc3e23ce3c3bc13581 Mon Sep 17 00:00:00 2001 From: Yera All Date: Sun, 12 Apr 2026 01:45:49 +0500 Subject: [PATCH] fix(db): avoid repeated sqlite schema initialization --- services/shared/sql_init.py | 33 +++++++++++++++++++++++---------- 1 file changed, 23 insertions(+), 10 deletions(-) diff --git a/services/shared/sql_init.py b/services/shared/sql_init.py index a5721d5..65d2595 100644 --- a/services/shared/sql_init.py +++ b/services/shared/sql_init.py @@ -1,5 +1,6 @@ from __future__ import annotations +import threading import time from sqlalchemy import inspect, text @@ -10,6 +11,10 @@ from services.shared.schema_migrations import schema_management_mode, validate_s from services.shared.sql_models import Base +_SCHEMA_INIT_LOCK = threading.Lock() +_SCHEMA_INITIALIZED = False + + def _table_columns(inspector, table_name: str) -> set[str]: return {item["name"] for item in inspector.get_columns(table_name)} @@ -588,15 +593,23 @@ def _apply_runtime_schema_compatibility() -> None: def init_sql_schema() -> None: - if schema_management_mode() == "migrations": - validate_schema_migrations_applied() + global _SCHEMA_INITIALIZED + if _SCHEMA_INITIALIZED: return - Base.metadata.create_all(bind=engine) - for attempt in range(5): - try: - _apply_runtime_schema_compatibility() + with _SCHEMA_INIT_LOCK: + if _SCHEMA_INITIALIZED: return - except OperationalError as exc: - if "database is locked" not in str(exc).lower() or attempt >= 4: - raise - time.sleep(0.25 * (attempt + 1)) + if schema_management_mode() == "migrations": + validate_schema_migrations_applied() + _SCHEMA_INITIALIZED = True + return + Base.metadata.create_all(bind=engine) + for attempt in range(5): + try: + _apply_runtime_schema_compatibility() + _SCHEMA_INITIALIZED = True + return + except OperationalError as exc: + if "database is locked" not in str(exc).lower() or attempt >= 4: + raise + time.sleep(0.25 * (attempt + 1))