Files
iAs/migrations/20260601000012_fix_chat_dedup.sql
wunianxiao dcfaf47809 fix: token统计+聊天记录入库静默失败, 列名/类型/去重不匹配
根因:insert_llm_usage / insert_chat_record 因旧 iPet 遗留列 (kind/entry NOT NULL,
context_token_present boolean→context_token text) 导致 INSERT 静默失败,
四个调用点 let _ = 吞掉错误。ias usage 显示 token 总量为 0。

修复:
- llm_usage: 迁移 0010 ADD COLUMN IF NOT EXISTS + 条件 DROP NOT NULL,
  insert_llm_usage 写入 kind/entry 默认值
- chat_records: 迁移 0011 列名 context_token_present→context_token 类型转换+重命名,
  迁移 0012 清理存量重复→partial UNIQUE index→恢复 ON CONFLICT
- main.rs: 所有 let _ = insert_* 改为 if let Err(e) 日志输出,
  message_id 缺失时归为 '' 而非 '0'
2026-06-02 16:31:48 +08:00

13 lines
544 B
SQL

-- 聊天记录去重:清理存量重复 → 建 partial UNIQUE 索引支持 ON CONFLICT
-- 1) 删除重复记录(保留每个 message_id 最早的那条)
DELETE FROM chat_records a
USING chat_records b
WHERE a.message_id = b.message_id
AND a.message_id NOT IN ('', '0')
AND a.id > b.id;
-- 2) 替换旧普通索引为 UNIQUE partial index(排除空和占位值)
DROP INDEX IF EXISTS idx_chat_records_message_id;
CREATE UNIQUE INDEX idx_chat_records_message_id
ON chat_records (message_id) WHERE message_id NOT IN ('', '0');