Files
yunke/yunke-server/app/db/base.py
T
浅念 00ae13b5c2 feat(deploy): 完成数据迁移与MySQL全链路(14表698k消息100%一致+5方言补丁+bind mount)
- migrate_sqlite_to_mysql.py: 逐表清空重导(幂等),复用repos强转,JSON列
  解析,67万消息按msg_id键集分批,467s跑完14表全一致
- 修4个MySQL实测bug: NULLS LAST语法(compat.py编译补丁)、message.text
  TEXT→MEDIUMTEXT(64KB字节上限,实测20.8万字符车源清单)、URL列
  String(1024)→Text(分享链接超1KB)、垃圾超长member_id源头清理
- compose: media改bind mount(不占C盘Docker虚拟磁盘,实测2.5GB卷把
  C盘撑爆引擎500);mysql不映射宿主机3306
- 前端Dockerfile: npm ci→install(本地/容器npm版本锁漂移)
- 五服务实测:nginx→backend→MySQL全链路返回真实数据(客户6859/A**杰25条
  /搜索56条),媒体49536文件bind mount直读

Co-Authored-By: Claude <noreply@anthropic.com>
2026-08-22 12:40:44 +08:00

56 lines
1.7 KiB
Python

"""Database core: declarative base, async engine, session factory.
Production targets MySQL via `asyncmy` (configured by `Settings.db_url`).
Unit tests build their own in-memory SQLite engines (see `tests/test_db_base.py`)
and only import `Base` / `async_session_maker` from here.
"""
from collections.abc import AsyncIterator
from sqlalchemy.ext.asyncio import (
AsyncSession,
async_sessionmaker,
create_async_engine,
)
from sqlalchemy.orm import DeclarativeBase
from app.config import get_settings
from app.db import compat # noqa: F401,I100 — 注册 MySQL NULLS LAST 编译补丁(导入即生效)
class Base(DeclarativeBase):
"""Common declarative base for all ORM models in the project."""
settings = get_settings()
# SQLite: 写锁竞争时忙等 60s 而不是立刻报 "database is locked"
# (多进程并发写的场景:页面抓取器 × 2 + 后端 API 同时跑,2026-08-19 实测撞锁崩任务)。
_connect_args = {"timeout": 60} if settings.db_url.startswith("sqlite") else {}
async_engine = create_async_engine(
settings.db_url,
pool_pre_ping=True,
pool_recycle=3600, # recycle connections before MySQL wait_timeout (default 8h) closes them
connect_args=_connect_args,
future=True,
)
async_session_maker: async_sessionmaker[AsyncSession] = async_sessionmaker(
async_engine,
expire_on_commit=False,
)
async def get_session() -> AsyncIterator[AsyncSession]:
"""FastAPI dependency that yields an `AsyncSession`.
Usage::
@app.get("/")
async def index(session: AsyncSession = Depends(get_session)):
...
"""
async with async_session_maker() as session:
yield session