Files
live-hub-py/web/backend/migrations/versions/20261003_0041_account_events.py
T
yml2213 e88c41385b Merge branch 'main' into dev
# Conflicts:
#	tests/test_migrations.py
2026-10-04 13:17:43 +08:00

108 lines
4.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""账号事件流表,以及审计日志的账号关联列。
## 为什么需要 account_events
`accounts` 存的是**账号当前状态**(积分、余额、开通标记…),这些字段都是覆盖式更新 ——
「什么时候变成这样」没有任何记录。而账号相关的操作散在 `douyu_tasks`(22 万行 / 687MB,
掺着大量例行轮询),既不能直接给用户看,也不适合当历史长期保留。
于是把「发生过什么」独立成一张 append-only 的事件表:`accounts` 是状态,`account_events`
是流水。账号详情页 = 状态卡 + 事件时间线。
**不做历史回填**(2026-10-03 已定):事件从上线起往后累积,既有历史仍去各自的页面查。
## 为什么审计日志要加 account_id
实测 `audit_logs.target` 是自由文本(`冰柳192` / `导入103个` / `douyu_batch:xxx` 混着),
无法可靠关联到账号,导致「谁什么时候分配/改标签/删除了这个账号」进不了账号时间线。
加一列可空的 account_id,账号相关操作写入时带上即可(旧记录保持 NULL)。
"""
from collections.abc import Sequence
import sqlalchemy as sa
from alembic import op
revision: str = "20261002_0040"
down_revision: str | None = "20261002_0039"
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None
def _tables(bind) -> set[str]:
return set(sa.inspect(bind).get_table_names())
def _columns(bind, table: str) -> set[str]:
return {item["name"] for item in sa.inspect(bind).get_columns(table)}
def upgrade() -> None:
bind = op.get_bind()
if "account_events" not in _tables(bind):
op.create_table(
"account_events",
sa.Column("id", sa.BigInteger(), primary_key=True, autoincrement=True),
sa.Column(
"account_id",
sa.Integer(),
sa.ForeignKey("accounts.id"),
nullable=False,
),
# import / login_ok / ck_invalid / relogin_ok / relogin_failed /
# bind_ok / recharge / exchange / points_credit /
# elite_opened / esports_opened / assigned / tag_changed ...
sa.Column("event_type", sa.String(length=32), nullable=False),
sa.Column("occurred_at", sa.DateTime(), nullable=False),
# 直接可展示的一句话,避免前端再各自拼文案
sa.Column(
"title", sa.String(length=256), nullable=False, server_default=""
),
# 变动量(充值/消耗/到账,有符号)与变动后余额
sa.Column("amount", sa.Integer(), nullable=True),
sa.Column("balance_after", sa.Integer(), nullable=True),
# 精简细节(不是原始大 JSON),便于排障与以后扩展
sa.Column("detail", sa.JSON(), nullable=True),
# 来源:login / task / audit / manual
sa.Column(
"source", sa.String(length=24), nullable=False, server_default=""
),
# 幂等键:如 douyu_task:123456、login_task:14166、audit:789。
# 收集器重跑、事件重复发射都靠它兜住,漏了会造出重复时间线。
# **可空且唯一**:MySQL 的唯一索引允许多个 NULL,所以「没有幂等键」的事件
# (如手工记录)存 NULL;不能用空串 —— 空串会互相冲突,第二条就插不进去。
sa.Column("source_ref", sa.String(length=96), nullable=True),
sa.Column("created_at", sa.DateTime(), nullable=False),
)
op.create_index(
"ix_account_events_account_occurred",
"account_events",
["account_id", "occurred_at"],
)
op.create_index(
"ix_account_events_event_type", "account_events", ["event_type"]
)
op.create_index(
"ix_account_events_source_ref",
"account_events",
["source_ref"],
unique=True,
)
if "account_id" not in _columns(bind, "audit_logs"):
op.add_column(
"audit_logs",
sa.Column("account_id", sa.Integer(), nullable=True),
)
op.create_index("ix_audit_logs_account_id", "audit_logs", ["account_id"])
def downgrade() -> None:
bind = op.get_bind()
if "account_id" in _columns(bind, "audit_logs"):
op.drop_column("audit_logs", "account_id")
if "account_events" in _tables(bind):
# 删表会一并删掉索引
op.drop_table("account_events")