Commit c9fbde98 authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Fix DATABASE_URL silently ignoring .env outside the FastAPI app

database.py read os.getenv("DATABASE_URL") at import time, relying on
config.py's load_dotenv() having already run first. Anything that imports
database.py directly - alembic/env.py, the standalone Telegram bot's
init_db() - never loads .env at all and silently falls back to the
sqlite:///./stax.db default, no matter what .env actually says. Found
while deploying to a fresh prod server: alembic kept migrating a stale
leftover database instead of the one set up for it.
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parent 7f2abd19
Pipeline #1251 failed with stage
import os import os
from dotenv import load_dotenv
from sqlalchemy import create_engine, event, Column, Integer, String, DateTime, ForeignKey, Boolean, Float, UniqueConstraint from sqlalchemy import create_engine, event, Column, Integer, String, DateTime, ForeignKey, Boolean, Float, UniqueConstraint
from sqlalchemy.orm import declarative_base, sessionmaker from sqlalchemy.orm import declarative_base, sessionmaker
from datetime import datetime, timezone from datetime import datetime, timezone
# config.py also calls this, but this module must not depend on import order to see .env -
# alembic/env.py imports this module directly (never config.py), and without this call it
# silently falls back to the sqlite:///./stax.db default regardless of what .env says.
# load_dotenv() is idempotent (safe to call more than once per process).
load_dotenv()
DATABASE_URL = os.getenv("DATABASE_URL", "sqlite:///./stax.db") DATABASE_URL = os.getenv("DATABASE_URL", "sqlite:///./stax.db")
db_dir = os.path.dirname(DATABASE_URL.replace("sqlite:///", "")) db_dir = os.path.dirname(DATABASE_URL.replace("sqlite:///", ""))
if db_dir and not os.path.exists(db_dir): if db_dir and not os.path.exists(db_dir):
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment