42 lines
1.1 KiB
Python
42 lines
1.1 KiB
Python
from sqlalchemy import create_engine
|
|
from sqlalchemy.ext.declarative import declarative_base
|
|
from sqlalchemy.orm import sessionmaker
|
|
from sqlalchemy.pool import StaticPool
|
|
|
|
from utils.config import settings
|
|
|
|
# Create SQLite engine with proper configuration
|
|
engine = create_engine(
|
|
settings.DATABASE_URL,
|
|
connect_args={
|
|
"check_same_thread": False, # Allow multiple threads for SQLite
|
|
"timeout": 20, # Set timeout for database operations
|
|
},
|
|
poolclass=StaticPool,
|
|
echo=settings.LOG_LEVEL == "DEBUG", # Log SQL queries in debug mode
|
|
)
|
|
|
|
# Create session factory
|
|
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
|
|
|
# Create base class for models
|
|
Base = declarative_base()
|
|
|
|
|
|
def get_db():
|
|
"""Dependency to get database session"""
|
|
db = SessionLocal()
|
|
try:
|
|
yield db
|
|
finally:
|
|
db.close()
|
|
|
|
|
|
async def init_db():
|
|
"""Initialize database tables"""
|
|
# Import all models to ensure they're registered
|
|
from adapters.sqlite import models # noqa: F401
|
|
|
|
# Create all tables
|
|
Base.metadata.create_all(bind=engine)
|