Spaces:
Running
Running
File size: 1,774 Bytes
ee1f067 c554d52 ee1f067 c554d52 ee1f067 5deccb5 ee1f067 | 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 | from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from sqlalchemy.orm import sessionmaker, declarative_base
from config import settings
DATABASE_URL = settings.database_url
if not DATABASE_URL:
raise ValueError(
"DATABASE_URL not found in environment variables. "
"Please set it in .env file. Example: "
"postgresql+asyncpg://user:password@localhost:5432/kairo_db"
)
# Create async engine
engine = create_async_engine(
DATABASE_URL,
echo=False, # Set to True for SQL logging
future=True,
pool_pre_ping=True, # Verify connections before using
pool_size=10,
max_overflow=20,
)
# Create async session factory
async_session = sessionmaker(
engine, class_=AsyncSession, expire_on_commit=False, autoflush=False
)
# Base class for all models
Base = declarative_base()
async def get_db() -> AsyncSession:
"""Dependency for getting async database session"""
async with async_session() as session:
try:
yield session
finally:
await session.close()
async def init_db():
"""Initialize database by creating all tables"""
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all)
# Safely migrate existing Postgres table to add the 'what' column
try:
from sqlalchemy import text
await conn.execute(text("ALTER TABLE portfolio_items ADD COLUMN IF NOT EXISTS what TEXT;"))
print("🚀 'what' column migration completed successfully")
except Exception as e:
print(f"⚠️ SQL migration warning (might be SQLite or column already exists): {e}")
async def close_db():
"""Close database connections"""
await engine.dispose()
|