Skip to content

fix(db): strip whitespace from DATABASE_URL to prevent SQLAlchemy crash at startup#292

Open
kapil971390 wants to merge 1 commit into
FujiwaraChoki:mainfrom
kapil971390:fix/database-url-whitespace-handling
Open

fix(db): strip whitespace from DATABASE_URL to prevent SQLAlchemy crash at startup#292
kapil971390 wants to merge 1 commit into
FujiwaraChoki:mainfrom
kapil971390:fix/database-url-whitespace-handling

Conversation

@kapil971390

Copy link
Copy Markdown

What

_database_url() in Backend/db.py used a bare truthiness check on the value returned by os.getenv("DATABASE_URL"). In Python a whitespace-only string (" ", "\t", "\n") is truthy, so the guard passed that raw value straight into create_engine() — which immediately crashes with an invalid connection URL.

Root cause

# Before
if database_url:          # "   " passes this check
    return database_url   # returns "   " → SQLAlchemy crash

Fix

# After
if database_url and database_url.strip():
    return database_url.strip()

Both the guard and the return value now strip surrounding whitespace, so any whitespace-only DATABASE_URL falls through to the safe SQLite default.

Edge cases verified

DATABASE_URL value Before fix After fix
" " (spaces) truthy → crash stripped → empty → SQLite fallback ✓
"\t" (tab) truthy → crash stripped → empty → SQLite fallback ✓
"\n" (newline) truthy → crash stripped → empty → SQLite fallback ✓
"" (empty string) falsy → SQLite fallback ✓ unchanged ✓
unset (None) falsy → SQLite fallback ✓ unchanged ✓
valid URL returned as-is ✓ returned stripped ✓

Impact

  • No behavior change for correctly set DATABASE_URL values
  • Prevents silent crash when DATABASE_URL is accidentally set to whitespace (e.g. trailing space in .env)

os.getenv("DATABASE_URL") with a whitespace-only value (e.g. "   ",
"\t", "\n") is truthy in Python, so the old guard silently passed the
raw string to SQLAlchemy's create_engine — causing an immediate
connection crash at startup.

Edge cases verified:
- "   " (spaces)  → truthy, was returned as-is → SQLAlchemy crash
- "\t" (tab)       → truthy, was returned as-is → SQLAlchemy crash
- "\n" (newline)   → truthy, was returned as-is → SQLAlchemy crash
- ""  (empty)      → falsy → SQLite fallback ✓ (already safe)
- unset            → None  → falsy → SQLite fallback ✓ (already safe)

Fix: call .strip() in both the guard and the return value so any
whitespace-only DATABASE_URL falls through to the SQLite default.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant