- domain:市场数据实体(Stock / 交易日历 / 日线 / 复权 / 财务含 announce_date)+ Repository 与 MarketDataProvider Protocol
- 数据源:TushareProvider(归一化、重试、鉴权错误归类)、SinaProvider(备用,明确前复权口径与能力边界)、FailoverProvider + SyncLog 审计(禁止静默切换)
- 持久化:SQLAlchemy 2.x Models + Repository 实现(按业务键幂等 upsert、as_of_date 防未来函数过滤)+ Alembic 迁移
- CLI:uv run python -m app.cli.sync {basic|calendar|daily|financial|verify},支持 --resume 断点续传
- 真实 Tushare 验证:stock 5556 / 交易日历 366 / daily+factor 242 / 财务 55;sync_log 审计完整
- 测试:38 passed(domain / provider / failover / repository / 未来函数 / 迁移),ruff clean
70 lines
2.0 KiB
Python
70 lines
2.0 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 import models as _models # noqa: F401 —— 注册全部表
|
|
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)
|
|
|
|
# alembic.ini 中显式 sqlalchemy.url 优先(测试/运维可注入);否则用应用配置
|
|
_db_url = config.get_main_option("sqlalchemy.url")
|
|
if not _db_url:
|
|
_db_url = get_settings().database_url
|
|
config.set_main_option("sqlalchemy.url", _db_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()
|