0002_usage_daily.sql 1.5 KB

123456789101112131415161718192021222324252627
  1. CREATE TABLE `usage_daily` (
  2. `date` text NOT NULL,
  3. `source` text NOT NULL,
  4. `provider` text NOT NULL,
  5. `model` text NOT NULL,
  6. `runs` integer DEFAULT 0 NOT NULL,
  7. `failed` integer DEFAULT 0 NOT NULL,
  8. `interrupted` integer DEFAULT 0 NOT NULL,
  9. `input_tokens` integer DEFAULT 0 NOT NULL,
  10. `output_tokens` integer DEFAULT 0 NOT NULL,
  11. `cache_read_tokens` integer DEFAULT 0 NOT NULL,
  12. `cache_write_tokens` integer DEFAULT 0 NOT NULL,
  13. `cost_usd` real DEFAULT 0 NOT NULL,
  14. `duration_ms` integer DEFAULT 0 NOT NULL,
  15. PRIMARY KEY(`date`, `source`, `provider`, `model`)
  16. );
  17. --> statement-breakpoint
  18. -- 数据迁移:用现有的 Run 记录补齐历史用量(按服务器本地日期)
  19. INSERT INTO `usage_daily` (`date`, `source`, `provider`, `model`, `runs`, `failed`, `interrupted`, `input_tokens`, `output_tokens`, `cache_read_tokens`, `cache_write_tokens`, `cost_usd`, `duration_ms`)
  20. SELECT date(coalesce(r.`started_at`, r.`created_at`), 'localtime'), s.`source`, s.`provider`, s.`model`,
  21. count(*), sum(r.`status` = 'failed'), sum(r.`status` = 'interrupted'),
  22. coalesce(sum(r.`input_tokens`), 0), coalesce(sum(r.`output_tokens`), 0), coalesce(sum(r.`cache_read_tokens`), 0), coalesce(sum(r.`cache_write_tokens`), 0),
  23. coalesce(sum(r.`cost_usd`), 0),
  24. coalesce(sum(CASE WHEN r.`started_at` IS NOT NULL AND r.`ended_at` IS NOT NULL THEN cast((julianday(r.`ended_at`) - julianday(r.`started_at`)) * 86400000 AS integer) END), 0)
  25. FROM `runs` r JOIN `sessions` s ON s.`id` = r.`session_id`
  26. WHERE r.`status` IN ('completed', 'failed', 'interrupted')
  27. GROUP BY 1, 2, 3, 4;