create_calendar_records.sql 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. -- 日历内容记录表DDL脚本
  2. -- 用于存储用户的日历内容记录信息
  3. create table public.calendar_records
  4. (
  5. id serial
  6. primary key,
  7. openid varchar(255) not null,
  8. month_key varchar(7) not null,
  9. calendar_content jsonb not null,
  10. created_at timestamp with time zone default current_timestamp not null,
  11. updated_at timestamp with time zone default current_timestamp not null
  12. );
  13. comment on table public.calendar_records is '日历内容记录表';
  14. comment on column public.calendar_records.id is '主键ID';
  15. comment on column public.calendar_records.openid is '微信用户openid';
  16. comment on column public.calendar_records.month_key is '月份标识,格式为YYYY-MM';
  17. comment on column public.calendar_records.calendar_content is '日历内容,JSON数组格式';
  18. comment on column public.calendar_records.created_at is '记录创建时间';
  19. comment on column public.calendar_records.updated_at is '记录更新时间';
  20. -- 创建索引以提高查询性能
  21. create index idx_calendar_records_openid on public.calendar_records(openid);
  22. create index idx_calendar_records_month_key on public.calendar_records(month_key);
  23. create index idx_calendar_records_openid_month on public.calendar_records(openid, month_key);
  24. create index idx_calendar_records_created_at on public.calendar_records(created_at);
  25. create index idx_calendar_records_updated_at on public.calendar_records(updated_at);
  26. -- 创建更新时间触发器函数
  27. create or replace function update_calendar_records_updated_at()
  28. returns trigger as $$
  29. begin
  30. new.updated_at = current_timestamp;
  31. return new;
  32. end;
  33. $$ language plpgsql;
  34. -- 创建触发器
  35. create trigger trigger_update_calendar_records_updated_at
  36. before update on public.calendar_records
  37. for each row
  38. execute function update_calendar_records_updated_at();
  39. -- 创建唯一约束(一个用户在同一个月份只能有一条记录)
  40. create unique index idx_calendar_records_openid_month_unique
  41. on public.calendar_records(openid, month_key);
  42. -- 添加约束检查月份格式
  43. alter table public.calendar_records
  44. add constraint chk_calendar_records_month_format
  45. check (month_key ~ '^\d{4}-\d{2}$');
  46. -- 添加约束检查openid格式(微信openid通常是28位字符串)
  47. alter table public.calendar_records
  48. add constraint chk_calendar_records_openid_format
  49. check (length(openid) = 28 and openid ~ '^[a-zA-Z0-9_-]+$');
  50. -- 添加约束检查JSON内容不为空
  51. alter table public.calendar_records
  52. add constraint chk_calendar_records_content_not_empty
  53. check (jsonb_array_length(calendar_content) >= 0);