ai-robot-core/ai-service/migrations/003_user_memories.py

76 lines
1.9 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.

"""
Database Migration: User Memories Table.
[AC-IDMP-14] 用户级记忆滚动摘要表
创建时间: 2025-03-08
变更说明:
- 新增 user_memories 表用于存储滚动摘要与事实/偏好/未解决问题
执行方式:
- SQLModel 会自动创建表(通过 init_db
- 此脚本用于手动迁移或回滚
SQL DDL:
```sql
CREATE TABLE user_memories (
id UUID PRIMARY KEY,
tenant_id VARCHAR NOT NULL,
user_id VARCHAR NOT NULL,
summary TEXT,
facts JSON,
preferences JSON,
open_issues JSON,
summary_version INTEGER NOT NULL DEFAULT 1,
last_turn_id VARCHAR,
expires_at TIMESTAMP,
created_at TIMESTAMP NOT NULL DEFAULT NOW(),
updated_at TIMESTAMP NOT NULL DEFAULT NOW()
);
CREATE INDEX ix_user_memories_tenant_user ON user_memories(tenant_id, user_id);
CREATE INDEX ix_user_memories_tenant_user_updated ON user_memories(tenant_id, user_id, updated_at);
```
回滚 SQL:
```sql
DROP TABLE IF EXISTS user_memories;
```
"""
USER_MEMORIES_DDL = """
CREATE TABLE IF NOT EXISTS user_memories (
id UUID PRIMARY KEY,
tenant_id VARCHAR NOT NULL,
user_id VARCHAR NOT NULL,
summary TEXT,
facts JSON,
preferences JSON,
open_issues JSON,
summary_version INTEGER NOT NULL DEFAULT 1,
last_turn_id VARCHAR,
expires_at TIMESTAMP,
created_at TIMESTAMP NOT NULL DEFAULT NOW(),
updated_at TIMESTAMP NOT NULL DEFAULT NOW()
);
"""
USER_MEMORIES_INDEXES = """
CREATE INDEX IF NOT EXISTS ix_user_memories_tenant_user ON user_memories(tenant_id, user_id);
CREATE INDEX IF NOT EXISTS ix_user_memories_tenant_user_updated ON user_memories(tenant_id, user_id, updated_at);
"""
USER_MEMORIES_ROLLBACK = """
DROP TABLE IF EXISTS user_memories;
"""
async def upgrade(conn):
"""执行迁移"""
await conn.execute(USER_MEMORIES_DDL)
await conn.execute(USER_MEMORIES_INDEXES)
async def downgrade(conn):
"""回滚迁移"""
await conn.execute(USER_MEMORIES_ROLLBACK)