Files
group_fqcd_jr/app/model/profile.py
T

66 lines
3.3 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.
"""画像与用户事实的 ORM 映射。
只映射既有表结构,**不改变任何字段**(`AGENTS.md` 第 3/4 条)。两处与常见表不同的设计在
这里显式标注,避免后续有人按直觉写入而踩坑:
1. `user_facts.id` 在库里**没有 auto_increment**,插入时必须由应用显式提供主键;
2. `profile_snapshots.current_customer_id` 是**生成列**(`IF(is_current=1, customer_id, NULL)`),
与唯一键 `uk_profile_snapshot_current` 共同保证「每个客户最多一条当前快照」。生成列由数据库
维护,因此这里只映射为只读计算列,写入时不会提供该字段。
"""
from datetime import datetime
from typing import Any
from sqlalchemy import CHAR, JSON, BigInteger, Boolean, Computed, DateTime, Float, String
from sqlalchemy.orm import Mapped, mapped_column
from app.model.base import Base
class UserFact(Base):
"""用户事实(user_facts):由中期记忆提升而来的稳定事实,供画像组装读取。
表上**没有** (customer_id, fact_key) 唯一键(只有两个普通索引),因此"同一事实只保留一条"
必须由服务层用"先查后写"保证,不能依赖数据库约束。
"""
__tablename__ = "user_facts"
# 注意:库中该列无 auto_increment,主键由服务层显式赋值(单调递增)
id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=False)
customer_id: Mapped[int] = mapped_column(BigInteger, nullable=False)
fact_key: Mapped[str] = mapped_column(String(128), nullable=False)
fact_value: Mapped[Any] = mapped_column(JSON, nullable=False)
source_portal: Mapped[str] = mapped_column(String(16), nullable=False)
source_episode_id: Mapped[int | None] = mapped_column(BigInteger)
confidence: Mapped[float] = mapped_column(Float, nullable=False, default=1.0)
is_critical: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False)
class ProfileSnapshot(Base):
"""画像快照(profile_snapshots):画像的版本化留痕。
存在意义是回答"当时依据的是什么"——风控复盘与合规检查都需要它,所以画像变更
**只新增版本、不原地覆盖**。
"""
__tablename__ = "profile_snapshots"
id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=True)
profile_uuid: Mapped[str | None] = mapped_column(CHAR(36), unique=True)
customer_id: Mapped[int] = mapped_column(BigInteger, nullable=False)
version: Mapped[int] = mapped_column(BigInteger, nullable=False)
snapshot: Mapped[Any] = mapped_column(JSON, nullable=False)
generation_basis: Mapped[Any | None] = mapped_column(JSON)
snapshot_hash: Mapped[str | None] = mapped_column(CHAR(64))
is_current: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
generated_at: Mapped[datetime | None] = mapped_column(DateTime)
created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False)
updated_at: Mapped[datetime] = mapped_column(DateTime, nullable=False)
# 生成列由数据库维护;映射为只读计算列,便于按当前快照查询,不参与 INSERT/UPDATE。
current_customer_id: Mapped[int | None] = mapped_column(
BigInteger, Computed("IF(is_current = 1, customer_id, NULL)")
)