Skip to content

Commit a7d62ea

Browse files
fix(db): create base schema before running migrations
Migrations ran before `_Base.metadata.create_all()`, so migration 3->4 (`ALTER TABLE user_mappings ADD COLUMN avatar_url`) failed on a fresh or partially-initialized database where the ORM-model tables did not yet exist — no migration creates the core tables (user_mappings, message_mappings, user_bindings, binding_codes); they are defined only by the ORM models, while migrations 0->3 touch only the forward_* tables. Move `create_all` ahead of `_run_migrations` in `MessageDB.__init__` and drop the migration call from `_create_engine_from_config`. Init is now self-healing: create_all builds the current schema (recreating any missing tables), then idempotent migrations apply incremental ALTERs. Fixes "Startup aborted: database initialization failed".
1 parent cb2ddbd commit a7d62ea

1 file changed

Lines changed: 6 additions & 2 deletions

File tree

services/db.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -119,7 +119,13 @@ def __init__(self, engine: Engine | None = None):
119119
engine: Optional SQLAlchemy engine. If not provided, will be created from config.
120120
"""
121121
self._engine = engine or self._create_engine_from_config()
122+
# Create the base ORM schema BEFORE running incremental migrations.
123+
# Tables like `user_mappings` are defined only by the ORM models, and
124+
# migrations (e.g. 3->4 `ALTER TABLE user_mappings ...`) assume they
125+
# already exist. Running migrations first would fail on a fresh or
126+
# partially-initialized database.
122127
_Base.metadata.create_all(self._engine)
128+
self._run_migrations(self._engine)
123129

124130
@staticmethod
125131
def _create_engine_from_config() -> Engine:
@@ -180,8 +186,6 @@ def _create_engine_from_config() -> Engine:
180186
logger.info(f"Initializing database engine: {url.split('://')[0]}")
181187
engine = create_engine(url, **engine_kwargs)
182188

183-
MessageDB._run_migrations(engine)
184-
185189
return engine
186190

187191
@staticmethod

0 commit comments

Comments
 (0)