Files
sub2api/backend/migrations/usage_log_api_key_cost_index_test.go
T
hezhaoqian1andClaude Opus 5.5 b8de5e1700 perf(keys): API 密钥列表不再等待 30 天用量统计,并为其加覆盖索引
/keys 页面要等密钥列表和每个 key 的用量统计都返回,才撤掉表格骨架屏。
用量统计(POST /usage/dashboard/api-keys-usage)按 api_key_id 汇总近 30 天的
usage_logs.actual_cost。数据量大时,要逐行回表读取几十万到上百万行,接口耗时
十几到三十几秒,甚至超时,页面就一直停在骨架屏。

- 前端:列表返回就渲染表格,用量列单独显示加载占位;统计失败时回落为 $0.0000。
- 后端:新增覆盖索引 (api_key_id, created_at) INCLUDE (actual_cost),使该统计可以
  index-only scan,不再回表。迁移采用 CONCURRENTLY 建索引;与其他 usage_logs
  索引迁移一样,重试前会先清理中断构建留下的 INVALID 索引。

Refs #5858

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 11:16:54 +08:00

19 lines
542 B
Go

package migrations
import (
"strings"
"testing"
"github.com/stretchr/testify/require"
)
func TestUsageLogAPIKeyCostIndexMigration(t *testing.T) {
content, err := FS.ReadFile("249_add_usage_logs_api_key_cost_index_notx.sql")
require.NoError(t, err)
sql := strings.Join(strings.Fields(string(content)), " ")
require.Contains(t, sql, "CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_usage_logs_api_key_created_cost")
require.Contains(t, sql, "ON usage_logs (api_key_id, created_at)")
require.Contains(t, sql, "INCLUDE (actual_cost)")
}