Files
iAs/migrations/20260601000010_fix_llm_usage_legacy_columns.sql
T
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

19 lines
874 B
SQL

-- 修复 llm_usage 表兼容性:旧库有 iPet 遗留的 kind/entry 列 (NOT NULL),新库没有
-- kind/entry 保留为兼容字段,新代码写入默认值 ("llm_call" / null)
-- 1) 添加列(如果不存在)
ALTER TABLE llm_usage ADD COLUMN IF NOT EXISTS kind TEXT;
ALTER TABLE llm_usage ADD COLUMN IF NOT EXISTS entry JSONB;
-- 2) 只在列存在且 NOT NULL 时解除约束
DO $$
BEGIN
IF EXISTS (SELECT 1 FROM information_schema.columns
WHERE table_name = 'llm_usage' AND column_name = 'kind' AND is_nullable = 'NO') THEN
ALTER TABLE llm_usage ALTER COLUMN kind DROP NOT NULL;
END IF;
IF EXISTS (SELECT 1 FROM information_schema.columns
WHERE table_name = 'llm_usage' AND column_name = 'entry' AND is_nullable = 'NO') THEN
ALTER TABLE llm_usage ALTER COLUMN entry DROP NOT NULL;
END IF;
END;
$$;