AssetManager.API/sql/migrate_financial_fields.sql
OpenClaw Agent 19f3cc8679 fix: 历史汇率处理bug + Transaction表增加汇率字段
关键修复:
1. BackfillNavHistoryInternalAsync 汇率处理bug
   - holdings 存储目标币种成本,避免卖出时用当前汇率重转历史成本
   - 优先使用交易时保存的汇率

2. Transaction 表新增字段
   - exchange_rate: 交易时汇率
   - total_amount_base: 本位币金额
   - 创建交易时自动保存汇率

3. CalculateAndSaveDailyNavAsync
   - 优先使用 TotalAmountBase 字段计算成本
   - 回退到当前汇率(兼容历史数据)

4. 新增迁移脚本 sql/migrate_financial_fields.sql
2026-03-25 05:22:50 +00:00

44 lines
1.8 KiB
SQL
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.

-- =============================================
-- 数据库迁移脚本:为金融计算增加关键字段
-- 执行前请备份数据
-- =============================================
-- 1. positions 表添加 total_cost 字段
ALTER TABLE positions ADD COLUMN total_cost DECIMAL(18,4) DEFAULT 0;
-- 初始化 total_costshares * avg_price
UPDATE positions SET total_cost = shares * avg_price WHERE total_cost = 0 OR total_cost IS NULL;
-- 验证 positions 更新
SELECT 'positions' as table_name, COUNT(*) as total,
SUM(CASE WHEN total_cost > 0 THEN 1 ELSE 0 END) as with_cost
FROM positions;
-- =============================================
-- 2. transactions 表添加汇率相关字段
ALTER TABLE transactions ADD COLUMN exchange_rate DECIMAL(18,6) DEFAULT NULL;
ALTER TABLE transactions ADD COLUMN total_amount_base DECIMAL(18,4) DEFAULT NULL;
-- 为已有交易记录填充当前汇率(历史数据只能用当前汇率近似)
-- 注意:这会导致历史净值计算有汇率偏差,建议手动修正重要历史交易
-- UPDATE transactions t
-- JOIN portfolios p ON t.portfolio_id = p.id
-- SET t.exchange_rate = 1.0, t.total_amount_base = t.total_amount
-- WHERE t.currency = p.currency OR t.currency IS NULL;
-- 验证 transactions 更新
SELECT 'transactions' as table_name, COUNT(*) as total,
SUM(CASE WHEN total_amount_base IS NOT NULL THEN 1 ELSE 0 END) as with_base_amount
FROM transactions;
-- =============================================
-- SQLite 版本(如果使用 SQLite
-- ALTER TABLE positions ADD COLUMN total_cost REAL DEFAULT 0;
-- UPDATE positions SET total_cost = shares * avg_price;
-- SQLite 不支持多个 ADD COLUMN需要分开执行
-- ALTER TABLE transactions ADD COLUMN exchange_rate REAL DEFAULT NULL;
-- ALTER TABLE transactions ADD COLUMN total_amount_base REAL DEFAULT NULL;