Skip to content

Commit

Permalink
main: run db migrations on startup
Browse files Browse the repository at this point in the history
We set an extra attribute on the alembic config to prevent it from
overriding the existing logger config in WAS. Without this, alembic
overwrites the root logger and WAS appears to hang after the migration
has completed, while it is just logging that is no longer correctly
configured.
  • Loading branch information
stintel committed Dec 7, 2023
1 parent 1e09878 commit 239e3e7
Show file tree
Hide file tree
Showing 4 changed files with 16 additions and 7 deletions.
1 change: 1 addition & 0 deletions app/const.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
ALEMBIC_CONFIG = '/app/alembic.ini'
DB_URL = 'sqlite:////app/storage/was.db'
DIR_ASSET = '/app/storage/asset'
DIR_OTA = '/app/storage/ota'
Expand Down
4 changes: 0 additions & 4 deletions app/db/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,6 @@
engine = create_engine(DB_URL, echo=True, connect_args=connect_args)


def create_db_and_tables():
SQLModel.metadata.create_all(engine)


def get_config_db():
config = WillowConfig()

Expand Down
15 changes: 13 additions & 2 deletions app/main.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import asyncio
import json
import os

import alembic
import alembic.config
from fastapi import (
FastAPI,
Header,
Expand All @@ -18,13 +21,14 @@
from fastapi.middleware.cors import CORSMiddleware

from app.const import (
ALEMBIC_CONFIG,
DIR_OTA,
STORAGE_USER_CLIENT_CONFIG,
STORAGE_USER_CONFIG,
STORAGE_USER_NVS,
)

from app.db.main import create_db_and_tables, migrate_user_client_config, migrate_user_config, migrate_user_nvs
from app.db.main import migrate_user_client_config, migrate_user_config, migrate_user_nvs
from app.internal.command_endpoints import (
CommandEndpointResponse,
CommandEndpointResult,
Expand Down Expand Up @@ -63,9 +67,16 @@
pass


def db_migrations():
cfg = alembic.config.Config(ALEMBIC_CONFIG)
cfg.attributes['logger'] = log
alembic.command.upgrade(cfg, "head")


@asynccontextmanager
async def lifespan(app: FastAPI):
create_db_and_tables()
# database schema migrations
db_migrations()

migrate_user_files()
get_tz_config(refresh=True)
Expand Down
3 changes: 2 additions & 1 deletion migrations/env.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@

# Interpret the config file for Python logging.
# This line sets up loggers basically.
if config.config_file_name is not None:
# We must skip this when config has a logger attribute to prevent the WAS logger config from being overwritten
if config.config_file_name is not None and config.attributes.get('logger', None) is None:
fileConfig(config.config_file_name)

# add your model's MetaData object here
Expand Down

0 comments on commit 239e3e7

Please sign in to comment.