236_group_model_allowlist_repair.sql 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. -- 236: 收敛 groups 的模型白名单列,修复 235 未落地却已被记账的实例。
  2. --
  3. -- 235 只在「models_list_config 存在且 model_allowlist 不存在」时执行重命名,
  4. -- 而迁移一旦写入 schema_migrations 就会按「文件名 + checksum」整份跳过,不再重跑。
  5. -- 因此只要数据库在 235 之后回到了旧结构——例如为了回滚到旧版本镜像而手工把列名
  6. -- 改回 models_list_config,或者用旧结构的备份做了部分恢复——应用依旧能正常启动,
  7. -- 但每个关联 groups 的查询都会失败:
  8. -- pq: column groups.model_allowlist does not exist
  9. -- 表现为「API 密钥」「我的订阅」「管理端订阅列表」等页面加载失败(issue #6780)。
  10. --
  11. -- 本迁移可重放,并且用 regclass 解析表(跟随 search_path),不再假定 schema 为 public:
  12. -- 1) 只有旧列 -> 重命名,数据原样保留;
  13. -- 2) 两列并存 -> 新列仍是默认空值时,把旧列里的配置回填过来,旧列保留不动;
  14. -- 3) 两列都没有 -> 按默认值补建新列。
  15. -- 结束后保证 groups.model_allowlist 一定存在,且为 NOT NULL DEFAULT '{}'。
  16. DO $$
  17. BEGIN
  18. IF EXISTS (
  19. SELECT 1 FROM pg_attribute
  20. WHERE attrelid = 'groups'::regclass
  21. AND attname = 'models_list_config'
  22. AND NOT attisdropped
  23. ) THEN
  24. IF NOT EXISTS (
  25. SELECT 1 FROM pg_attribute
  26. WHERE attrelid = 'groups'::regclass
  27. AND attname = 'model_allowlist'
  28. AND NOT attisdropped
  29. ) THEN
  30. ALTER TABLE groups RENAME COLUMN models_list_config TO model_allowlist;
  31. ELSE
  32. EXECUTE $backfill$
  33. UPDATE groups
  34. SET model_allowlist = models_list_config
  35. WHERE COALESCE(model_allowlist, '{}'::jsonb) = '{}'::jsonb
  36. AND COALESCE(models_list_config, '{}'::jsonb) <> '{}'::jsonb
  37. $backfill$;
  38. END IF;
  39. END IF;
  40. END
  41. $$;
  42. ALTER TABLE groups
  43. ADD COLUMN IF NOT EXISTS model_allowlist JSONB NOT NULL DEFAULT '{}'::jsonb;
  44. UPDATE groups SET model_allowlist = '{}'::jsonb WHERE model_allowlist IS NULL;
  45. ALTER TABLE groups ALTER COLUMN model_allowlist SET DEFAULT '{}'::jsonb;
  46. ALTER TABLE groups ALTER COLUMN model_allowlist SET NOT NULL;
  47. COMMENT ON COLUMN groups.model_allowlist IS
  48. 'Group model allowlist: constrains both model listing responses and request admission';