- uv 工程(Python 3.12,pyproject + uv.lock,dev: pytest/ruff) - 分层包结构:api / application / domain / infrastructure / quant(qlib_adapter) / agent / core - app.core.config:加载根 config.yaml + .env,sqlite 相对路径解析到项目根 data/ - SQLAlchemy Base + Session 工厂(Infrastructure 层,业务走 Repository) - Alembic 迁移环境就位(env.py 复用应用配置,render_as_batch 兼容 SQLite) - GET /api/health + pytest 冒烟 6 项通过 / ruff clean / uvicorn 启动验证
65 lines
1.7 KiB
Python
65 lines
1.7 KiB
Python
"""Alembic 迁移环境:从应用配置读取 DATABASE_URL 并连接 Base.metadata。
|
|
|
|
用法(cd backend):
|
|
uv run alembic revision --autogenerate -m "add xxx table"
|
|
uv run alembic upgrade head
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from logging.config import fileConfig
|
|
|
|
from alembic import context
|
|
from app.core.config import get_settings
|
|
from app.infrastructure.persistence.sqlalchemy.base import Base
|
|
from sqlalchemy import engine_from_config, pool
|
|
|
|
config = context.config
|
|
|
|
if config.config_file_name is not None:
|
|
fileConfig(config.config_file_name)
|
|
|
|
config.set_main_option("sqlalchemy.url", get_settings().database_url)
|
|
|
|
target_metadata = Base.metadata
|
|
|
|
|
|
def run_migrations_offline() -> None:
|
|
"""离线模式:只生成 SQL,不连接数据库。"""
|
|
url = config.get_main_option("sqlalchemy.url")
|
|
context.configure(
|
|
url=url,
|
|
target_metadata=target_metadata,
|
|
literal_binds=True,
|
|
dialect_opts={"paramstyle": "named"},
|
|
render_as_batch=True, # SQLite 支持 ALTER 需要 batch 模式
|
|
)
|
|
|
|
with context.begin_transaction():
|
|
context.run_migrations()
|
|
|
|
|
|
def run_migrations_online() -> None:
|
|
"""在线模式:连接数据库执行迁移。"""
|
|
connectable = engine_from_config(
|
|
config.get_section(config.config_ini_section, {}),
|
|
prefix="sqlalchemy.",
|
|
poolclass=pool.NullPool,
|
|
)
|
|
|
|
with connectable.connect() as connection:
|
|
context.configure(
|
|
connection=connection,
|
|
target_metadata=target_metadata,
|
|
render_as_batch=True,
|
|
)
|
|
|
|
with context.begin_transaction():
|
|
context.run_migrations()
|
|
|
|
|
|
if context.is_offline_mode():
|
|
run_migrations_offline()
|
|
else:
|
|
run_migrations_online()
|