50 lines
1.1 KiB
Python
50 lines
1.1 KiB
Python
"""
|
|
数据库基础配置
|
|
"""
|
|
from sqlalchemy import create_engine
|
|
from sqlalchemy.ext.declarative import declarative_base
|
|
from sqlalchemy.orm import sessionmaker
|
|
from contextlib import contextmanager
|
|
import logging
|
|
|
|
from app.core.config import settings
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
# 创建数据库引擎
|
|
engine = create_engine(
|
|
settings.get_database_url,
|
|
pool_pre_ping=True,
|
|
pool_size=20,
|
|
max_overflow=40,
|
|
echo=settings.DEBUG,
|
|
)
|
|
|
|
# 创建会话工厂
|
|
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
|
|
|
# 创建基类
|
|
Base = declarative_base()
|
|
|
|
|
|
@contextmanager
|
|
def get_db():
|
|
"""获取数据库会话的上下文管理器"""
|
|
db = SessionLocal()
|
|
try:
|
|
yield db
|
|
db.commit()
|
|
except Exception as e:
|
|
db.rollback()
|
|
logger.error(f"Database error: {e}")
|
|
raise
|
|
finally:
|
|
db.close()
|
|
|
|
|
|
def init_db():
|
|
"""初始化数据库表"""
|
|
from . import virtual_user, interaction, token_usage, system_config, ai_model, news_cache
|
|
Base.metadata.create_all(bind=engine)
|
|
logger.info("Database tables created successfully")
|