Spaces:
Runtime error
Runtime error
File size: 5,155 Bytes
30be4c2 0164fe8 30be4c2 0164fe8 30be4c2 0164fe8 30be4c2 0164fe8 30be4c2 0164fe8 30be4c2 0164fe8 30be4c2 0164fe8 30be4c2 0164fe8 30be4c2 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 | """
Async database connection setup for FastAPI with PostgreSQL + PostGIS.
Requires: asyncpg, sqlalchemy[asyncio]
"""
import os
from typing import AsyncGenerator
from sqlalchemy import text
from sqlalchemy.ext.asyncio import (
AsyncSession,
async_sessionmaker,
create_async_engine,
)
from sqlalchemy.orm import declarative_base
from .models import Base
# Database URL from environment variable
# Format: postgresql+asyncpg://user:password@host:port/database
DATABASE_URL = os.getenv("DATABASE_URL")
if DATABASE_URL:
# Clean common copy-paste errors
DATABASE_URL = DATABASE_URL.strip().strip('"').strip("'")
# Handle users accidentally pasting the PowerShell prefix $env:DATABASE_URL=
if DATABASE_URL.lower().startswith("$env:database_url="):
DATABASE_URL = DATABASE_URL.split("=", 1)[1].strip().strip('"').strip("'")
from urllib.parse import urlparse, urlunparse
try:
parsed = urlparse(DATABASE_URL)
# Mask the URL for logging (hide password)
masked_url = f"{parsed.scheme}://{parsed.username}:****@{parsed.hostname}:{parsed.port}{parsed.path}"
print(f"INFO: Attempting to connect to: {masked_url}")
# Ensure we have the +asyncpg driver if it's missing (common mistake)
if parsed.scheme == "postgresql":
DATABASE_URL = DATABASE_URL.replace("postgresql://", "postgresql+asyncpg://", 1)
parsed = urlparse(DATABASE_URL)
print(f"INFO: Automatically added +asyncpg driver to DATABASE_URL")
if not parsed.path or parsed.path == '/':
# No database name specified, default to postgres for Supabase
new_path = "/postgres"
parsed = parsed._replace(path=new_path)
DATABASE_URL = urlunparse(parsed)
print(f"INFO: No database name in URL, using default: {DATABASE_URL.split('@')[-1]}")
except Exception as e:
print(f"WARNING: Error sanitizing DATABASE_URL: {e}")
if not DATABASE_URL:
error_msg = (
"DATABASE_URL environment variable is not set! "
"Please set it in your environment or Hugging Face Secrets."
)
print("=" * 60)
print(f"ERROR: {error_msg}")
print("=" * 60)
raise ValueError(error_msg)
# Create async engine
engine = create_async_engine(
DATABASE_URL,
echo=os.getenv("DB_ECHO", "false").lower() == "true", # Set DB_ECHO=true for SQL logging
future=True,
pool_pre_ping=True, # Verify connections before using
pool_size=10,
max_overflow=20,
)
# Create async session factory
AsyncSessionLocal = async_sessionmaker(
engine,
class_=AsyncSession,
expire_on_commit=False,
autocommit=False,
autoflush=False,
)
async def get_db() -> AsyncGenerator[AsyncSession, None]:
"""
Dependency function for FastAPI to get database session.
Usage in FastAPI:
@app.get("/items")
async def get_items(db: AsyncSession = Depends(get_db)):
...
"""
async with AsyncSessionLocal() as session:
try:
yield session
await session.commit()
except Exception:
await session.rollback()
raise
finally:
await session.close()
async def init_db() -> None:
"""
Initialize database - create all tables.
Call this once at application startup.
Usage:
@app.on_event("startup")
async def startup():
await init_db()
"""
async with engine.begin() as conn:
# Ensure PostGIS extension exists so GeoAlchemy geography types work.
# This is safe to run multiple times.
try:
await conn.execute(text('CREATE EXTENSION IF NOT EXISTS postgis'))
except Exception as exc:
# Log a clear message but don't swallow the error silently.
print("=" * 60)
print("ERROR: Failed to create PostGIS extension.")
print(
"Make sure PostGIS is installed in your PostgreSQL instance.\n"
"On Windows with PostgreSQL App/StackBuilder, add the PostGIS extension\n"
"to your server, then re-run the backend."
)
print(f"Underlying error: {exc}")
print("=" * 60)
raise
# Create all tables after PostGIS extension is available.
await conn.run_sync(Base.metadata.create_all)
async def close_db() -> None:
"""
Close database connections.
Call this at application shutdown.
Usage:
@app.on_event("shutdown")
async def shutdown():
await close_db()
"""
await engine.dispose()
# Health check function
async def check_db_health() -> bool:
"""
Check if database connection is healthy.
Returns:
bool: True if database is accessible, False otherwise
"""
try:
from sqlalchemy import text
async with AsyncSessionLocal() as session:
# Simple query to test connection
result = await session.execute(text("SELECT 1"))
return result.scalar() == 1
except Exception:
return False
|