Files
medical-mall/docs/ops/2026-02-04__db-schema__fix-ak-users-constraints.md
2026-02-05 10:11:09 +08:00

72 lines
3.6 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 操作文档:修复 `ak_users` 表写入协调问题
- **日期**: 2026-02-04
- **范围**: 数据库 Schema (`public.ak_users`)
- **标题**: 修复 `auth.users` -> `ak_users` 自动同步的写入协调问题
## 摘要
本操作通过修改 `public.ak_users` 表的结构,解决了新用户在 Supabase Auth 注册后,无法在业务表 `ak_users` 中自动创建对应记录的问题。核心改动是放宽了 `username``email` 字段的 `NOT NULL` 约束。
## 动机
在当前实现中,`auth.users` 表上存在一个 `on_auth_user_created` 触发器,该触发器在有新用户注册时会调用 `handle_new_user()` 函数,尝试在 `ak_users` 表中插入一条对应的业务用户记录。然而,由于 `ak_users` 表的 `username``email` 字段被设置为 `NOT NULL` 且没有默认值,而 `handle_new_user()` 函数在执行时无法提供这两个值,导致 `INSERT` 操作因违反约束而静默失败。这造成了 `auth.users``public.ak_users` 之间的数据不一致,使得新注册的用户无法被业务系统识别,后续的权限、角色等功能全部失效。
## 影响范围
- **数据库表**: `public.ak_users`
- **数据库函数**: `public.handle_new_user()` (现在可以成功执行)
- **前端逻辑**: `utils/sapi.uts` 中的 `ensureUserProfile` 函数(现在在用户首次登录时,即使触发器失败,它也能成功插入记录)。
- **业务流程**: 新用户注册、首次登录的数据同步流程。
## 变更清单
- **新增文件**:
- `docs/sql/10_schema/user/ak_users_constraints_fix_v1.sql`: 包含了本次 DDL 变更的权威 SQL 脚本。
- `docs/ops/2026-02-04__db-schema__fix-ak-users-constraints.md`: 本操作文档。
- **修改内容**: `public.ak_users` 表结构
- `username` 字段的 `NOT NULL` 约束被移除。
- `email` 字段的 `NOT NULL` 约束被移除。
- `role` 字段的默认值被更新为 `'customer'`
## 兼容性与风险
- **数据兼容性**: 此变更为向下兼容。允许 `username``email` 为空,不会影响现有记录。应用层代码(如 `ensureUserProfile`)会在用户首次登录时尝试填充这些值。
- **风险**: 理论上,现在 `ak_users` 表中可能存在 `username``email` 为空的记录。依赖这两个字段为非空的前端页面或业务逻辑需要做好空值处理,但这符合用户首次登录后才完善资料的常见模式。
## 回滚方案
如果需要撤销此变更,可以执行以下 SQL 命令,将表的约束恢复到之前的状态:
```sql
BEGIN;
ALTER TABLE public.ak_users
ALTER COLUMN username SET NOT NULL,
ALTER COLUMN email SET NOT NULL;
-- 注意:回滚前必须确保表中没有 username 或 email 为 NULL 的记录,否则会失败。
-- 将 role 的默认值恢复为 'student'(如果需要)
ALTER TABLE public.ak_users
ALTER COLUMN role SET DEFAULT 'student';
COMMIT;
```
## 验证方式
1. **执行变更**: 在数据库中执行 `docs/sql/10_schema/user/ak_users_constraints_fix_v1.sql` 的内容。
2. **注册新用户**: 在 App 中注册一个全新的用户(例如 `new_user@example.com`)。
3. **验证 `ak_users` 表**: 在 SQL Editor 中查询,确认 `ak_users` 表中已自动创建了与新用户 `auth_id` 对应的记录。
```sql
SELECT auth_id, email, username, role FROM public.ak_users WHERE email = 'new_user@example.com';
```
4. **验证 `consistency_status`**: 再次执行之前的一致性检查 SQL确认新用户的状态为 `CONSISTENT`。
## 关联文档
- `docs/AGENT_PROJECT_SPEC.md`
- `docs/sql/10_schema/user/ak_users_constraints_fix_v1.sql`