0015_usage_events.sql 1.2 KB

1234567891011121314151617181920212223242526
  1. -- usage_events — hourly rollups, one row per (project, hour, metric).
  2. -- The aggregation cron writes here every hour; the Polar metering push
  3. -- worker reads pending rows and POSTs them to Polar's meter API.
  4. -- Survives function_logs retention (free tier prunes at 7 days) so
  5. -- historical usage queries beyond the log window still resolve.
  6. CREATE TABLE IF NOT EXISTS "usage_events" (
  7. "id" text PRIMARY KEY NOT NULL,
  8. "project_id" text NOT NULL,
  9. "metric" text NOT NULL,
  10. "period_start" timestamp with time zone NOT NULL,
  11. "value" text NOT NULL,
  12. "polar_push_status" text NOT NULL DEFAULT 'pending',
  13. "polar_pushed_at" timestamp with time zone,
  14. "created_at" timestamp with time zone DEFAULT now() NOT NULL
  15. );
  16. -- One row per (project, hour, metric). Idempotent re-runs of the cron
  17. -- overwrite the same row instead of stacking duplicates.
  18. CREATE UNIQUE INDEX IF NOT EXISTS "usage_events_project_period_metric_idx"
  19. ON "usage_events" USING btree ("project_id", "period_start", "metric");
  20. -- Partial index for the Polar push worker — only scans pending rows.
  21. CREATE INDEX IF NOT EXISTS "usage_events_pending_idx"
  22. ON "usage_events" USING btree ("polar_push_status", "period_start")
  23. WHERE "polar_push_status" = 'pending';