Skip to content

Commit c3f158f

Browse files
fix: tolerate missing database on startup
1 parent 381945f commit c3f158f

File tree

3 files changed

+16
-3
lines changed

3 files changed

+16
-3
lines changed

AGENTS.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
1-
- Always run `pytest {{cookiecutter.project_slug}}/tests` and ensure all tests pass after any code changes.
2-
- Run tests even if not explicitly requested.
1+
- Always run `pytest {{cookiecutter.project_slug}}/tests` and ensure all tests pass after any code changes, even if not explicitly requested.
2+
- Always add tests, keep your branch rebased instead of merged, and adhere to the commit message recommendations from https://cbea.ms/git-commit/.

{{cookiecutter.project_slug}}/app/core/events.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,9 @@
22

33
import joblib
44
from fastapi import FastAPI
5+
from loguru import logger
6+
from sqlalchemy.exc import OperationalError
7+
58
from core.config import MEMOIZATION_FLAG
69
from db import Base, engine
710

@@ -19,6 +22,9 @@ def create_start_app_handler(app: FastAPI) -> Callable:
1922
def start_app() -> None:
2023
if MEMOIZATION_FLAG:
2124
preload_model()
22-
Base.metadata.create_all(bind=engine)
25+
try:
26+
Base.metadata.create_all(bind=engine)
27+
except OperationalError:
28+
logger.exception("failed to initialize database")
2329

2430
return start_app

{{cookiecutter.project_slug}}/tests/test_events_and_main.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
from fastapi import FastAPI
2+
from sqlalchemy.exc import OperationalError
23

34
from core import events
45
from main import get_application
@@ -27,6 +28,12 @@ def fake_preload():
2728
called["called"] = True
2829

2930
monkeypatch.setattr(events, "preload_model", fake_preload)
31+
32+
def fake_create_all(*args, **kwargs):
33+
raise OperationalError("stmt", {}, Exception("db down"))
34+
35+
monkeypatch.setattr(events.Base.metadata, "create_all", fake_create_all)
36+
3037
app = FastAPI()
3138
handler = events.create_start_app_handler(app)
3239
handler()

0 commit comments

Comments
 (0)