53 lines
1.5 KiB
Python
53 lines
1.5 KiB
Python
"""Database base configuration"""
|
|
import os
|
|
from pathlib import Path
|
|
from sqlalchemy.ext.declarative import declarative_base
|
|
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_sessionmaker
|
|
from app.core.config import settings
|
|
|
|
# Create base class for models
|
|
Base = declarative_base()
|
|
|
|
# Ensure database directory exists
|
|
db_path = Path.home() / ".config" / "syui" / "ai" / "card"
|
|
db_path.mkdir(parents=True, exist_ok=True)
|
|
|
|
# Select database URL based on configuration
|
|
database_url = settings.database_url_supabase if settings.use_supabase else settings.database_url
|
|
|
|
# Expand ~ in database URL
|
|
if database_url.startswith("sqlite"):
|
|
database_url = database_url.replace("~", str(Path.home()))
|
|
|
|
# Create async engine (SQLite-optimized settings)
|
|
if "sqlite" in database_url:
|
|
engine = create_async_engine(
|
|
database_url,
|
|
echo=settings.debug,
|
|
future=True,
|
|
# SQLite-specific optimizations
|
|
connect_args={"check_same_thread": False}
|
|
)
|
|
else:
|
|
# PostgreSQL settings (fallback)
|
|
engine = create_async_engine(
|
|
database_url,
|
|
echo=settings.debug,
|
|
future=True,
|
|
pool_pre_ping=True,
|
|
pool_size=5,
|
|
max_overflow=10
|
|
)
|
|
|
|
# Create async session factory
|
|
async_session = async_sessionmaker(
|
|
engine,
|
|
class_=AsyncSession,
|
|
expire_on_commit=False
|
|
)
|
|
|
|
|
|
async def get_session() -> AsyncSession:
|
|
"""Dependency to get database session"""
|
|
async with async_session() as session:
|
|
yield session |