File size: 1,269 Bytes
7cc81cb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
-- Additive approval workspace integrity migration.
--
-- This migration brings the existing approval domain in line with the
-- authoritative ORM models and closes the confirmed cross-workspace
-- authorization gap by backfilling approval requests with their owning
-- workflow workspace, enforcing the relationship, and adding an index
-- used by authorization checks.
--
-- Apply after 0013_notification_preferences.sql.

begin;

alter table approval_requests
  add column if not exists workspace_id text;

do $$
begin
  if exists (
    select 1
    from approval_requests
    where workspace_id is null
  ) then
    update approval_requests
    set workspace_id = approval_workflows.workspace_id
    from approval_workflows
    where approval_workflows.id = approval_requests.workflow_id
      and approval_requests.workspace_id is null;
  end if;
end $$;

alter table approval_requests
  alter column workspace_id set not null;

alter table approval_requests
  drop constraint if exists approval_requests_workflow_id_fkey,
  add constraint approval_requests_workflow_id_fkey
    foreign key (workflow_id) references approval_workflows(id) on delete cascade;

create index if not exists ix_approval_requests_workspace
  on approval_requests(workspace_id);

commit;