142_user_platform_quotas.sql 1.7 KB

123456789101112131415161718192021222324252627282930313233343536
  1. -- 用户平台维度配额表。每个 (user_id, platform) 对独立记录日/周/月三层 USD 限额与用量。
  2. -- nil limit = 不限制(沿用上层默认),0 = 显式禁用,>0 = USD 上限。
  3. -- 软删除:deleted_at IS NULL 的记录为活跃记录,部分唯一索引保证同用户同平台只有一条活跃配额。
  4. CREATE TABLE IF NOT EXISTS user_platform_quotas (
  5. id BIGSERIAL PRIMARY KEY,
  6. user_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
  7. platform VARCHAR(32) NOT NULL CHECK (platform IN ('anthropic', 'openai', 'gemini', 'antigravity')),
  8. -- 日 / 周 / 月 USD 上限:NULL = 不限制,0 = 显式禁用,>0 = 上限
  9. daily_limit_usd DECIMAL(20,10),
  10. weekly_limit_usd DECIMAL(20,10),
  11. monthly_limit_usd DECIMAL(20,10),
  12. -- 当前窗口已用量
  13. daily_usage_usd DECIMAL(20,10) NOT NULL DEFAULT 0,
  14. weekly_usage_usd DECIMAL(20,10) NOT NULL DEFAULT 0,
  15. monthly_usage_usd DECIMAL(20,10) NOT NULL DEFAULT 0,
  16. -- 窗口起点(NULL = 首次尚未初始化)
  17. daily_window_start TIMESTAMPTZ,
  18. weekly_window_start TIMESTAMPTZ,
  19. monthly_window_start TIMESTAMPTZ,
  20. created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  21. updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  22. deleted_at TIMESTAMPTZ
  23. );
  24. -- 软删除友好唯一索引:同用户同平台只允许一条未删除记录
  25. CREATE UNIQUE INDEX IF NOT EXISTS userplatformquota_user_id_platform_uq
  26. ON user_platform_quotas (user_id, platform)
  27. WHERE deleted_at IS NULL;
  28. CREATE INDEX IF NOT EXISTS userplatformquota_user_id
  29. ON user_platform_quotas (user_id);