Data lifecycle
data-lifecycleData exports per user or organization from every installed module's tables and the app's, written to a private bucket by the app's export job, and organization deletion with a grace period that disables the tenant before a purge job deletes its rows.
Admin & compliancemanagedcustom
Signups this week+18%
flag new-onboarding at 25%
Install
The command also installs updated-at, memberships, permissions, the modules it needs.
npx better-supabase add data-lifecycleConfigure
The blocks entries in your config, with the default mode.
import { defineConfig } from "better-supabase/config";
export default defineConfig({
blocks: {
// Required by data-lifecycle; add installs them too.
"updated-at": {},
memberships: {},
permissions: {},
// Modes: "managed", "custom". The default is "managed".
"data-lifecycle": { mode: "managed" },
},
});Migrations
The files
npx better-supabase add data-lifecycle writes into your declarative schema with the default layout.9 files
supabase/schemas/900_better_supabase_035_data_lifecycle.sqlschema1763 lines-- better-supabase module: data-lifecycle
-- @bsb-block data-lifecycle@9 managed
-- @bsb-hash sha256:575efd0209e79e22cb132acd3b498a298acb01f88640eedc9e8fddc7906d52a8
-- Data exports per user or organization from every installed module's tables and the app's, written to a private bucket by the app's export job, and organization deletion with a grace period that disables the tenant before a purge job deletes its rows.
-- Managed by `better-supabase add`; re-running it rewrites this file unless it was edited by hand.
-- Change it through `blocks` in better-supabase.config.ts and the module's SQL hooks.
-- Exports of a user's or an organization's data, written by the app's
-- export job as one NDJSON file per table under {id}/ in the data-exports bucket.
create table "better_supabase"."data_exports" (
"id" uuid primary key default gen_random_uuid(),
"subject" text not null,
"user_id" uuid references auth.users (id) on delete cascade,
"tenant_id" uuid,
"status" text not null default 'pending' constraint bsb_data_exports_status_check check ("status" in ('pending', 'running', 'ready', 'failed')),
"bucket" text not null default 'data-exports',
"files" text[] not null default '{}',
"error" text,
"requested_by" uuid references auth.users (id) on delete set null default auth.uid(),
"requested_at" timestamptz not null default now(),
"completed_at" timestamptz,
"expires_at" timestamptz
);
alter table "better_supabase"."data_exports" add column "subject_type" text;
alter table "better_supabase"."data_exports" add column "subject_id" text;
alter table "better_supabase"."data_exports" add column "format" text;
alter table "better_supabase"."data_exports" add constraint "bsb_data_exports_subject" check (case "subject"
when 'user' then "user_id" is not null and "tenant_id" is null and "subject_type" is null and "subject_id" is null
when 'organization' then "tenant_id" is not null and "user_id" is null and "subject_type" is null and "subject_id" is null
when 'record' then "subject_type" is not null and "subject_id" is not null and "user_id" is null
else false
end);
alter table "better_supabase"."data_exports" add constraint "bsb_data_exports_format" check ("format" is null or "format" in ('ndjson', 'csv'));
create unique index "data_exports_open_record_idx" on "better_supabase"."data_exports" ("subject_type", "subject_id", "requested_by") where "status" in ('pending', 'running') and "subject" = 'record';
create unique index data_exports_open_user_idx on "better_supabase"."data_exports" ("user_id") where "status" in ('pending', 'running') and "subject" = 'user';
create unique index data_exports_open_tenant_idx on "better_supabase"."data_exports" ("tenant_id") where "status" in ('pending', 'running') and "subject" = 'organization';
create index data_exports_requested_by_idx on "better_supabase"."data_exports" ("requested_by");
create index data_exports_user_idx on "better_supabase"."data_exports" ("user_id") where "user_id" is not null;
alter table "better_supabase"."data_exports" enable row level security;
revoke all on "better_supabase"."data_exports" from public, anon, authenticated;
grant select on "better_supabase"."data_exports" to authenticated;
grant all on "better_supabase"."data_exports" to service_role;
create policy bsb_data_exports_read on "better_supabase"."data_exports"
for select to authenticated
using ("requested_by" = (select auth.uid()) or "tenant_id" in (select better_supabase.tenant_ids_with('data_lifecycle.export')));
-- Organizations waiting for their purge. Requesting disables the tenant
-- through the access contract; cancelling enables it again unless it was
-- disabled before.
create table "better_supabase"."organization_deletions" (
"tenant_id" uuid primary key,
"requested_by" uuid references auth.users (id) on delete set null default auth.uid(),
"requested_at" timestamptz not null default now(),
"purge_at" timestamptz not null,
"cancelled_at" timestamptz,
"purged_at" timestamptz,
"previously_disabled" boolean not null default false
);
create index organization_deletions_due_idx on "better_supabase"."organization_deletions" ("purge_at") where "cancelled_at" is null and "purged_at" is null;
create index organization_deletions_requested_by_idx on "better_supabase"."organization_deletions" ("requested_by") where "requested_by" is not null;
alter table "better_supabase"."organization_deletions" enable row level security;
revoke all on "better_supabase"."organization_deletions" from public, anon, authenticated;
grant all on "better_supabase"."organization_deletions" to service_role;
-- How long each kind of record is kept: for one tenant, for the tenants
-- on a plan, or for every tenant (both null). A purge keeps a row while
-- retention_for says so, whatever its own older_than argument.
create table "better_supabase"."retention_policies" (
"id" uuid primary key default gen_random_uuid(),
"tenant_id" uuid,
"plan" text,
"kind" text not null constraint bsb_retention_policies_kind_check check ("kind" ~ '^[a-z][a-z0-9_]{0,62}$'),
"keep" interval not null constraint bsb_retention_policies_keep_check check ("keep" > interval '0'),
"updated_at" timestamptz not null default now(),
constraint bsb_retention_policies_check check ("tenant_id" is null or "plan" is null),
unique nulls not distinct ("kind", "tenant_id", "plan")
);
create index retention_policies_tenant_idx on "better_supabase"."retention_policies" ("tenant_id") where "tenant_id" is not null;
alter table "better_supabase"."retention_policies" enable row level security;
revoke all on "better_supabase"."retention_policies" from public, anon, authenticated;
grant all on "better_supabase"."retention_policies" to service_role;
-- Legal holds: while one is active (released_at null), no purge deletes
-- the records it covers. A null tenant holds every tenant, a null kind
-- every kind.
create table "better_supabase"."legal_holds" (
"id" uuid primary key default gen_random_uuid(),
"tenant_id" uuid,
"kind" text constraint bsb_legal_holds_kind_check check ("kind" ~ '^[a-z][a-z0-9_]{0,62}$'),
"reason" text not null constraint bsb_legal_holds_reason_check check (length("reason") >= 1 and length("reason") <= 1000),
"placed_by" uuid references auth.users (id) on delete set null default auth.uid(),
"placed_at" timestamptz not null default now(),
"released_by" uuid references auth.users (id) on delete set null,
"released_at" timestamptz
);
create index legal_holds_active_idx on "better_supabase"."legal_holds" ("tenant_id", "kind") where "released_at" is null;
create index legal_holds_placed_by_idx on "better_supabase"."legal_holds" ("placed_by") where "placed_by" is not null;
create index legal_holds_released_by_idx on "better_supabase"."legal_holds" ("released_by") where "released_by" is not null;
alter table "better_supabase"."legal_holds" enable row level security;
revoke all on "better_supabase"."legal_holds" from public, anon, authenticated;
grant all on "better_supabase"."legal_holds" to service_role;
-- The tenant's policy for a kind, else its plan's (the shortest when it has
-- several plans), else the policy for every tenant; null without one.
create or replace function "better_supabase"."retention_for"(kind text, tenant text default null)
returns interval
language plpgsql
stable
security definer
set search_path = ''
as $$
declare
v_keep interval;
begin
if retention_for.tenant is not null then
select x."keep" into v_keep from "better_supabase"."retention_policies" x
where x."kind" = retention_for.kind and x."tenant_id"::text = retention_for.tenant;
if v_keep is not null then
return v_keep;
end if;
end if;
select x."keep" into v_keep from "better_supabase"."retention_policies" x
where x."kind" = retention_for.kind and x."tenant_id" is null and x."plan" is null;
return v_keep;
end;
$$;
-- The shortest time any policy keeps a kind, so a purge can bound its scan
-- on the timestamp index before it asks retention_for per row.
create or replace function "better_supabase"."retention_floor"(kind text)
returns interval
language sql
stable
security definer
set search_path = ''
as $$
select min(x."keep") from "better_supabase"."retention_policies" x where x."kind" = retention_floor.kind
$$;
-- Whether an active hold covers the kind for the tenant. A null tenant (a
-- row that belongs to no tenant) is covered only by a hold on every tenant.
create or replace function "better_supabase"."is_held"(kind text, tenant text default null)
returns boolean
language sql
stable
security definer
set search_path = ''
as $$
select exists (
select 1 from "better_supabase"."legal_holds" x
where x."released_at" is null
and (x."kind" is null or x."kind" = is_held.kind)
and (x."tenant_id" is null or x."tenant_id"::text = is_held.tenant)
)
$$;
-- retention_for and is_held for a purge's where clause: answered once per
-- tenant and statement, kept in a transaction-local setting under the
-- statement's timestamp, so a purge of a million rows asks the policy tables once
-- per tenant instead of once per row. A later statement in the same transaction
-- reads the tables again.
create or replace function "better_supabase"."retention_for_memo"(kind text, tenant text default null)
returns interval
language plpgsql
volatile
security invoker
set search_path = ''
as $$
declare
v_key text := 'rf' || md5(statement_timestamp()::text || retention_for_memo.kind || coalesce(retention_for_memo.tenant, ''));
v_memo text := better_supabase.memo_slot_get(v_key);
v_keep interval;
begin
if v_memo is not null then
return nullif(v_memo, '-')::interval;
end if;
v_keep := "better_supabase"."retention_for"(retention_for_memo.kind, retention_for_memo.tenant);
perform better_supabase.memo_slot_set(v_key, coalesce(v_keep::text, '-'));
return v_keep;
end;
$$;
create or replace function "better_supabase"."is_held_memo"(kind text, tenant text default null)
returns boolean
language plpgsql
volatile
security invoker
set search_path = ''
as $$
declare
v_key text := 'ih' || md5(statement_timestamp()::text || is_held_memo.kind || coalesce(is_held_memo.tenant, ''));
v_memo text := better_supabase.memo_slot_get(v_key);
v_held boolean;
begin
if v_memo is not null then
return v_memo = 't';
end if;
v_held := "better_supabase"."is_held"(is_held_memo.kind, is_held_memo.tenant);
perform better_supabase.memo_slot_set(v_key, case when v_held then 't' else 'f' end);
return v_held;
end;
$$;
-- Before when every tenant's rows of a kind may go, so a purge can drop a
-- whole partition: null while any hold covers the kind, else the longest
-- policy or the fallback, whichever keeps more.
create or replace function "better_supabase"."retention_cutoff"(kind text, fallback interval)
returns timestamptz
language sql
stable
security definer
set search_path = ''
as $$
select case when exists (
select 1 from "better_supabase"."legal_holds" x
where x."released_at" is null
and (x."kind" is null or x."kind" = retention_cutoff.kind)
) then null else now() - greatest(
fallback,
(select max(x."keep") from "better_supabase"."retention_policies" x where x."kind" = retention_cutoff.kind)
) end
$$;
create or replace function "better_supabase"."set_retention_policy"(kind text, keep interval, tenant uuid default null, plan text default null)
returns jsonb
language plpgsql
security invoker
set search_path = ''
as $$
#variable_conflict use_column
declare
v_row "better_supabase"."retention_policies";
begin
if not (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin')) then
raise exception 'Only the service role sets retention policies' using errcode = '42501', hint = 'RETENTION_FORBIDDEN';
end if;
insert into "better_supabase"."retention_policies" as x ("kind", "keep", "tenant_id", "plan")
values (set_retention_policy.kind, set_retention_policy.keep, set_retention_policy.tenant, set_retention_policy.plan)
on conflict ("kind", "tenant_id", "plan") do update set
"keep" = excluded."keep",
"updated_at" = now()
returning * into v_row;
return to_jsonb(v_row);
end;
$$;
create or replace function "better_supabase"."delete_retention_policy"(kind text, tenant uuid default null, plan text default null)
returns boolean
language plpgsql
security invoker
set search_path = ''
as $$
begin
if not (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin')) then
raise exception 'Only the service role removes retention policies' using errcode = '42501', hint = 'RETENTION_FORBIDDEN';
end if;
delete from "better_supabase"."retention_policies" x
where x."kind" = delete_retention_policy.kind
and x."tenant_id" is not distinct from delete_retention_policy.tenant
and x."plan" is not distinct from delete_retention_policy.plan;
return found;
end;
$$;
create or replace function "better_supabase"."list_retention_policies"(kind text default null)
returns jsonb
language sql
stable
security invoker
set search_path = ''
as $$
select coalesce(jsonb_agg(to_jsonb(x.*) order by x."kind", x."tenant_id" nulls first, x."plan" nulls first), '[]'::jsonb)
from "better_supabase"."retention_policies" x
where list_retention_policies.kind is null or x."kind" = list_retention_policies.kind
$$;
create or replace function "better_supabase"."place_legal_hold"(reason text, tenant uuid default null, kind text default null)
returns jsonb
language plpgsql
security invoker
set search_path = ''
as $$
declare
v_row "better_supabase"."legal_holds";
begin
if not (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin')) then
raise exception 'Only the service role places legal holds' using errcode = '42501', hint = 'LEGAL_HOLD_FORBIDDEN';
end if;
insert into "better_supabase"."legal_holds" ("reason", "tenant_id", "kind", "placed_by")
values (place_legal_hold.reason, place_legal_hold.tenant, place_legal_hold.kind, auth.uid())
returning * into v_row;
null;
return to_jsonb(v_row);
end;
$$;
-- Releasing keeps the row, so the holds stay on record.
create or replace function "better_supabase"."release_legal_hold"(id uuid)
returns jsonb
language plpgsql
security invoker
set search_path = ''
as $$
declare
v_row "better_supabase"."legal_holds";
begin
if not (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin')) then
raise exception 'Only the service role releases legal holds' using errcode = '42501', hint = 'LEGAL_HOLD_FORBIDDEN';
end if;
update "better_supabase"."legal_holds" x set "released_at" = now(), "released_by" = auth.uid()
where x."id" = release_legal_hold.id and x."released_at" is null
returning * into v_row;
if v_row."id" is null then
return null;
end if;
null;
return to_jsonb(v_row);
end;
$$;
create or replace function "better_supabase"."list_legal_holds"(include_released boolean default false)
returns jsonb
language sql
stable
security invoker
set search_path = ''
as $$
select coalesce(jsonb_agg(to_jsonb(x.*) order by x."placed_at" desc, x."id"), '[]'::jsonb)
from "better_supabase"."legal_holds" x
where list_legal_holds.include_released or x."released_at" is null
$$;
revoke execute on function "better_supabase"."retention_for"(text, text) from public, anon, authenticated;
revoke execute on function "better_supabase"."retention_floor"(text) from public, anon, authenticated;
revoke execute on function "better_supabase"."is_held"(text, text) from public, anon, authenticated;
revoke execute on function "better_supabase"."retention_for_memo"(text, text) from public, anon, authenticated;
revoke execute on function "better_supabase"."is_held_memo"(text, text) from public, anon, authenticated;
revoke execute on function "better_supabase"."retention_cutoff"(text, interval) from public, anon, authenticated;
revoke execute on function "better_supabase"."set_retention_policy"(text, interval, uuid, text) from public, anon, authenticated;
revoke execute on function "better_supabase"."delete_retention_policy"(text, uuid, text) from public, anon, authenticated;
revoke execute on function "better_supabase"."list_retention_policies"(text) from public, anon, authenticated;
revoke execute on function "better_supabase"."place_legal_hold"(text, uuid, text) from public, anon, authenticated;
revoke execute on function "better_supabase"."release_legal_hold"(uuid) from public, anon, authenticated;
revoke execute on function "better_supabase"."list_legal_holds"(boolean) from public, anon, authenticated;
grant execute on function "better_supabase"."retention_for"(text, text) to service_role;
grant execute on function "better_supabase"."retention_floor"(text) to service_role;
grant execute on function "better_supabase"."is_held"(text, text) to service_role;
grant execute on function "better_supabase"."retention_for_memo"(text, text) to service_role;
grant execute on function "better_supabase"."is_held_memo"(text, text) to service_role;
grant execute on function "better_supabase"."retention_cutoff"(text, interval) to service_role;
grant execute on function "better_supabase"."set_retention_policy"(text, interval, uuid, text) to service_role;
grant execute on function "better_supabase"."delete_retention_policy"(text, uuid, text) to service_role;
grant execute on function "better_supabase"."list_retention_policies"(text) to service_role;
grant execute on function "better_supabase"."place_legal_hold"(text, uuid, text) to service_role;
grant execute on function "better_supabase"."release_legal_hold"(uuid) to service_role;
grant execute on function "better_supabase"."list_legal_holds"(boolean) to service_role;
-- One row per data subject request (GDPR Arts. 15 to 20). due_at is 30 days
-- after receipt; extended_at records the single extension of two months.
create table "better_supabase"."data_subject_requests" (
"id" uuid primary key default gen_random_uuid(),
"tenant_id" uuid not null,
"kind" text not null constraint bsb_data_subject_requests_kind_check check ("kind" in ('access', 'erasure', 'rectification', 'portability')),
"requester" text not null constraint bsb_data_subject_requests_requester_check check (length("requester") >= 1 and length("requester") <= 320),
"subject_type" text,
"subject_id" text,
"details" text constraint bsb_data_subject_requests_details_check check ("details" is null or length("details") <= 5000),
"status" text not null default 'received' constraint bsb_data_subject_requests_status_check check ("status" in ('received', 'verified', 'fulfilled', 'refused')),
"received_at" timestamptz not null default now(),
"received_by" uuid,
"due_at" timestamptz not null,
"extended_at" timestamptz,
"extension_reason" text,
"verified_at" timestamptz,
"verified_by" uuid,
"verification_method" text,
"export_id" uuid,
"resolution" text,
"closed_at" timestamptz,
"closed_by" uuid,
constraint bsb_data_subject_requests_check check (("subject_type" is null) = ("subject_id" is null))
);
create index data_subject_requests_open_idx on "better_supabase"."data_subject_requests" ("tenant_id", "due_at") where "closed_at" is null;
alter table "better_supabase"."data_subject_requests" enable row level security;
revoke all on "better_supabase"."data_subject_requests" from public, anon, authenticated;
grant all on "better_supabase"."data_subject_requests" to service_role;
-- Opens a request: kind is access, erasure, rectification or portability;
-- requester says who asked (an email address or a name). A request about a
-- record names it with subject_type and subject_id, which an access or
-- portability request needs to be fulfilled through the record export.
create or replace function "better_supabase"."open_data_subject_request"(tenant uuid, kind text, requester text, subject_type text default null, subject_id text default null, details text default null)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
#variable_conflict use_column
declare
v_row "better_supabase"."data_subject_requests";
begin
if not (better_supabase.actor_may_write()) then
raise exception 'This session is read-only' using errcode = '42501', hint = 'ACTOR_READ_ONLY';
end if;
if not (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or coalesce(better_supabase.can('tenant', open_data_subject_request.tenant, 'data_lifecycle.export'), false)) then
raise exception 'You may not handle data subject requests here' using errcode = '42501', hint = 'DSAR_FORBIDDEN';
end if;
if open_data_subject_request.kind is null or open_data_subject_request.kind not in ('access', 'erasure', 'rectification', 'portability') then
raise exception 'kind must be access, erasure, rectification or portability' using errcode = '22023', hint = 'DSAR_INVALID';
end if;
if open_data_subject_request.requester is null or length(trim(open_data_subject_request.requester)) = 0 then
raise exception 'requester is required' using errcode = '22023', hint = 'DSAR_INVALID';
end if;
if (open_data_subject_request.subject_type is null) <> (open_data_subject_request.subject_id is null) then
raise exception 'subject_type and subject_id go together' using errcode = '22023', hint = 'DSAR_INVALID';
end if;
insert into "better_supabase"."data_subject_requests" ("tenant_id", "kind", "requester", "subject_type", "subject_id", "details", "received_by", "due_at")
values (open_data_subject_request.tenant, open_data_subject_request.kind, trim(open_data_subject_request.requester), open_data_subject_request.subject_type, open_data_subject_request.subject_id, open_data_subject_request.details, auth.uid(), now() + interval '30 days')
returning * into v_row;
null;
return to_jsonb(v_row);
end;
$$;
-- Records that the requester's identity was checked (Art. 12(6)); method says
-- how, for example "signed in" or "ID document".
create or replace function "better_supabase"."verify_data_subject_request"(id uuid, method text)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
#variable_conflict use_column
declare
v_row "better_supabase"."data_subject_requests";
begin
if not (better_supabase.actor_may_write()) then
raise exception 'This session is read-only' using errcode = '42501', hint = 'ACTOR_READ_ONLY';
end if;
select * into v_row from "better_supabase"."data_subject_requests" x where x."id" = verify_data_subject_request.id for update;
if v_row."id" is null then
raise exception 'request not found' using errcode = 'P0002', hint = 'DSAR_NOT_FOUND';
end if;
if not (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or coalesce(better_supabase.can('tenant', v_row."tenant_id", 'data_lifecycle.export'), false)) then
raise exception 'You may not handle data subject requests here' using errcode = '42501', hint = 'DSAR_FORBIDDEN';
end if;
if v_row."closed_at" is not null then
raise exception 'the request is already fulfilled or refused' using errcode = '55000', hint = 'DSAR_CLOSED';
end if;
if verify_data_subject_request.method is null or length(trim(verify_data_subject_request.method)) = 0 then
raise exception 'method is required' using errcode = '22023', hint = 'DSAR_INVALID';
end if;
update "better_supabase"."data_subject_requests" x set "status" = 'verified', "verified_at" = now(), "verified_by" = auth.uid(), "verification_method" = trim(verify_data_subject_request.method)
where x."id" = v_row."id"
returning * into v_row;
null;
return to_jsonb(v_row);
end;
$$;
-- Extends the due date by two months, once, when the request is complex or
-- there are many of them (Art. 12(3)). The reason is kept for the requester.
create or replace function "better_supabase"."extend_data_subject_request"(id uuid, reason text)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
#variable_conflict use_column
declare
v_row "better_supabase"."data_subject_requests";
begin
if not (better_supabase.actor_may_write()) then
raise exception 'This session is read-only' using errcode = '42501', hint = 'ACTOR_READ_ONLY';
end if;
select * into v_row from "better_supabase"."data_subject_requests" x where x."id" = extend_data_subject_request.id for update;
if v_row."id" is null then
raise exception 'request not found' using errcode = 'P0002', hint = 'DSAR_NOT_FOUND';
end if;
if not (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or coalesce(better_supabase.can('tenant', v_row."tenant_id", 'data_lifecycle.export'), false)) then
raise exception 'You may not handle data subject requests here' using errcode = '42501', hint = 'DSAR_FORBIDDEN';
end if;
if v_row."closed_at" is not null then
raise exception 'the request is already fulfilled or refused' using errcode = '55000', hint = 'DSAR_CLOSED';
end if;
if v_row."extended_at" is not null then
raise exception 'the due date was already extended once' using errcode = 'PT409', hint = 'DSAR_EXTENDED';
end if;
if extend_data_subject_request.reason is null or length(trim(extend_data_subject_request.reason)) = 0 then
raise exception 'reason is required' using errcode = '22023', hint = 'DSAR_INVALID';
end if;
update "better_supabase"."data_subject_requests" x set "due_at" = x."received_at" + interval '3 months', "extended_at" = now(), "extension_reason" = trim(extend_data_subject_request.reason)
where x."id" = v_row."id"
returning * into v_row;
null;
return to_jsonb(v_row);
end;
$$;
-- Fulfils a verified request. Access and portability start the NDJSON export
-- of the named record (request_subject_export) and keep its id; the export job
-- writes the files. Erasure refuses while a legal hold covers every kind of
-- record and otherwise records that the app deleted or anonymized the data;
-- rectification records what changed. resolution is required for both.
create or replace function "better_supabase"."fulfil_data_subject_request"(id uuid, resolution text default null)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
#variable_conflict use_column
declare
v_row "better_supabase"."data_subject_requests";
v_export jsonb;
v_export_id uuid;
begin
if not (better_supabase.actor_may_write()) then
raise exception 'This session is read-only' using errcode = '42501', hint = 'ACTOR_READ_ONLY';
end if;
select * into v_row from "better_supabase"."data_subject_requests" x where x."id" = fulfil_data_subject_request.id for update;
if v_row."id" is null then
raise exception 'request not found' using errcode = 'P0002', hint = 'DSAR_NOT_FOUND';
end if;
if not (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or coalesce(better_supabase.can('tenant', v_row."tenant_id", 'data_lifecycle.export'), false)) then
raise exception 'You may not handle data subject requests here' using errcode = '42501', hint = 'DSAR_FORBIDDEN';
end if;
if v_row."closed_at" is not null then
raise exception 'the request is already fulfilled or refused' using errcode = '55000', hint = 'DSAR_CLOSED';
end if;
if v_row."verified_at" is null then
raise exception 'verify the requester''s identity first' using errcode = '55000', hint = 'DSAR_UNVERIFIED';
end if;
if v_row."kind" in ('access', 'portability') then
if v_row."subject_type" is null then
raise exception 'an access or portability request names the record to export' using errcode = '22023', hint = 'DSAR_INVALID';
end if;
v_export := "better_supabase"."request_subject_export"(v_row."subject_type", v_row."subject_id", 'ndjson');
v_export_id := (v_export ->> 'id')::uuid;
else
if fulfil_data_subject_request.resolution is null or length(trim(fulfil_data_subject_request.resolution)) = 0 then
raise exception 'resolution is required' using errcode = '22023', hint = 'DSAR_INVALID';
end if;
if v_row."kind" = 'erasure' and "better_supabase"."is_held"('data_subject_request', v_row."tenant_id"::text) then
raise exception 'a legal hold stops the erasure; refuse the request with its reason' using errcode = '55000', hint = 'DSAR_HELD';
end if;
end if;
update "better_supabase"."data_subject_requests" x set "status" = 'fulfilled', "closed_at" = now(), "closed_by" = auth.uid(), "export_id" = v_export_id, "resolution" = nullif(trim(fulfil_data_subject_request.resolution), '')
where x."id" = v_row."id"
returning * into v_row;
null;
return to_jsonb(v_row);
end;
$$;
-- Refuses a request with its reason (Art. 12(4)): the requester gets it with
-- the right to complain to the supervisory authority.
create or replace function "better_supabase"."refuse_data_subject_request"(id uuid, reason text)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
#variable_conflict use_column
declare
v_row "better_supabase"."data_subject_requests";
begin
if not (better_supabase.actor_may_write()) then
raise exception 'This session is read-only' using errcode = '42501', hint = 'ACTOR_READ_ONLY';
end if;
select * into v_row from "better_supabase"."data_subject_requests" x where x."id" = refuse_data_subject_request.id for update;
if v_row."id" is null then
raise exception 'request not found' using errcode = 'P0002', hint = 'DSAR_NOT_FOUND';
end if;
if not (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or coalesce(better_supabase.can('tenant', v_row."tenant_id", 'data_lifecycle.export'), false)) then
raise exception 'You may not handle data subject requests here' using errcode = '42501', hint = 'DSAR_FORBIDDEN';
end if;
if v_row."closed_at" is not null then
raise exception 'the request is already fulfilled or refused' using errcode = '55000', hint = 'DSAR_CLOSED';
end if;
if refuse_data_subject_request.reason is null or length(trim(refuse_data_subject_request.reason)) = 0 then
raise exception 'reason is required' using errcode = '22023', hint = 'DSAR_INVALID';
end if;
update "better_supabase"."data_subject_requests" x set "status" = 'refused', "closed_at" = now(), "closed_by" = auth.uid(), "resolution" = trim(refuse_data_subject_request.reason)
where x."id" = v_row."id"
returning * into v_row;
null;
return to_jsonb(v_row);
end;
$$;
-- The organization's requests, the nearest due date first. status filters by
-- status; open_only leaves out fulfilled and refused ones. overdue is true for
-- an open request past its due date.
create or replace function "better_supabase"."list_data_subject_requests"(tenant uuid, status text default null, open_only boolean default false)
returns jsonb
language plpgsql
stable
security definer
set search_path = ''
as $$
#variable_conflict use_column
begin
if not (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or coalesce(better_supabase.can('tenant', list_data_subject_requests.tenant, 'data_lifecycle.export'), false)) then
raise exception 'You may not handle data subject requests here' using errcode = '42501', hint = 'DSAR_FORBIDDEN';
end if;
return coalesce((
select jsonb_agg(to_jsonb(x.*) || jsonb_build_object('overdue', x."closed_at" is null and x."due_at" < now()) order by x."due_at", x."id")
from "better_supabase"."data_subject_requests" x
where x."tenant_id" = list_data_subject_requests.tenant
and (list_data_subject_requests.status is null or x."status" = list_data_subject_requests.status)
and (not list_data_subject_requests.open_only or x."closed_at" is null)
), '[]'::jsonb);
end;
$$;
revoke execute on function "better_supabase"."open_data_subject_request"(uuid, text, text, text, text, text) from public, anon;
revoke execute on function "better_supabase"."verify_data_subject_request"(uuid, text) from public, anon;
revoke execute on function "better_supabase"."extend_data_subject_request"(uuid, text) from public, anon;
revoke execute on function "better_supabase"."fulfil_data_subject_request"(uuid, text) from public, anon;
revoke execute on function "better_supabase"."refuse_data_subject_request"(uuid, text) from public, anon;
-- The organization's data subject requests as a keyset page, the nearest due date first (ADR 1077). filters is { status, kind (each a value or a list), open (true leaves out fulfilled and refused ones), overdue (true keeps the open ones past their due date), search (subject id and requester), sort (dueAt, receivedAt), direction, facet, count, limit, after, offset, paged, total, totalCap }.
create or replace function "better_supabase"."page_data_subject_requests"(tenant uuid, filters jsonb default '{}')
returns jsonb
language plpgsql
stable
security definer
set search_path = ''
as $$
#variable_conflict use_variable
declare
v_filters jsonb := coalesce(page_data_subject_requests.filters, '{}'::jsonb);
v_search text := case when nullif(trim(v_filters ->> 'search'), '') is null then null
else '%' || replace(replace(replace(trim(v_filters ->> 'search'), '\', '\\'), '%', '\%'), '_', '\_') || '%' end;
v_limit integer := least(greatest(coalesce((v_filters ->> 'limit')::integer, 50), 1), 200);
v_offset integer := greatest(coalesce((v_filters ->> 'offset')::integer, 0), 0);
v_after jsonb := v_filters -> 'after';
v_paged boolean := coalesce((v_filters ->> 'paged')::boolean, false);
v_total_cap integer := least(greatest(coalesce((v_filters ->> 'totalCap')::integer, 10000), 1), 100000);
v_items jsonb;
v_more boolean;
v_next jsonb;
v_total integer;
v_sort text := nullif(v_filters ->> 'sort', '');
v_dir text := nullif(v_filters ->> 'direction', '');
v_facet text := nullif(v_filters ->> 'facet', '');
v_count boolean := coalesce((v_filters ->> 'count')::boolean, false);
v_result jsonb;
begin
if not (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or coalesce(better_supabase.can('tenant', page_data_subject_requests.tenant, 'data_lifecycle.export'), false)) then
raise exception 'You may not handle data subject requests here' using errcode = '42501', hint = 'DSAR_FORBIDDEN';
end if;
if v_filters ? 'after' and v_filters ? 'offset' then
raise exception 'after and offset are two ways to page; pass one' using errcode = '22023', hint = 'DSAR_INVALID';
end if;
if v_facet is not null then
if v_facet not in ('status', 'kind') then
raise exception 'facet is one of status, kind' using errcode = '22023', hint = 'DSAR_INVALID';
end if;
with s as (
select (case v_facet when 'status' then (x."status"::text)::text when 'kind' then (x."kind"::text)::text end) as v
from "better_supabase"."data_subject_requests" x
where x."tenant_id" = page_data_subject_requests.tenant
and (not (v_filters -> 'status' is not null and jsonb_typeof(v_filters -> 'status') <> 'null' and not (jsonb_typeof(v_filters -> 'status') = 'array' and jsonb_array_length(v_filters -> 'status') = 0)) or x."status"::text = any((case when jsonb_typeof(v_filters -> 'status') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'status')) else array[v_filters ->> 'status'] end)::text[]))
and (not (v_filters -> 'kind' is not null and jsonb_typeof(v_filters -> 'kind') <> 'null' and not (jsonb_typeof(v_filters -> 'kind') = 'array' and jsonb_array_length(v_filters -> 'kind') = 0)) or x."kind"::text = any((case when jsonb_typeof(v_filters -> 'kind') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'kind')) else array[v_filters ->> 'kind'] end)::text[]))
and (not coalesce(nullif(coalesce(v_filters #>> '{open,0}', v_filters ->> 'open'), '') = 'true', false) or x."closed_at" is null)
and (not coalesce(nullif(coalesce(v_filters #>> '{overdue,0}', v_filters ->> 'overdue'), '') = 'true', false) or (x."closed_at" is null and x."due_at" < now()))
and (v_search is null or x."subject_id" ilike v_search or x."requester"::text ilike v_search)
limit v_total_cap + 1
)
select jsonb_build_object('facet', v_facet, 'values', coalesce(jsonb_agg(jsonb_build_object('value', g.v, 'count', jsonb_build_object('value', g.n, 'exact', g.exact)) order by g.n desc, g.v), '[]'::jsonb))
into v_result
from (
select s.v, count(*) as n, (select count(*) from s) <= v_total_cap as exact
from s where s.v is not null group by s.v order by n desc, s.v limit 100
) g;
return v_result;
end if;
if v_count then
select count(*) into v_total from (
select 1 from "better_supabase"."data_subject_requests" x
where x."tenant_id" = page_data_subject_requests.tenant
and (not (v_filters -> 'status' is not null and jsonb_typeof(v_filters -> 'status') <> 'null' and not (jsonb_typeof(v_filters -> 'status') = 'array' and jsonb_array_length(v_filters -> 'status') = 0)) or x."status"::text = any((case when jsonb_typeof(v_filters -> 'status') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'status')) else array[v_filters ->> 'status'] end)::text[]))
and (not (v_filters -> 'kind' is not null and jsonb_typeof(v_filters -> 'kind') <> 'null' and not (jsonb_typeof(v_filters -> 'kind') = 'array' and jsonb_array_length(v_filters -> 'kind') = 0)) or x."kind"::text = any((case when jsonb_typeof(v_filters -> 'kind') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'kind')) else array[v_filters ->> 'kind'] end)::text[]))
and (not coalesce(nullif(coalesce(v_filters #>> '{open,0}', v_filters ->> 'open'), '') = 'true', false) or x."closed_at" is null)
and (not coalesce(nullif(coalesce(v_filters #>> '{overdue,0}', v_filters ->> 'overdue'), '') = 'true', false) or (x."closed_at" is null and x."due_at" < now()))
and (v_search is null or x."subject_id" ilike v_search or x."requester"::text ilike v_search)
limit v_total_cap + 1
) c;
return jsonb_build_object('value', least(v_total, v_total_cap), 'exact', v_total <= v_total_cap);
end if;
if v_sort is not null and v_sort not in ('dueAt', 'receivedAt') then
raise exception 'sort is one of dueAt, receivedAt' using errcode = '22023', hint = 'DSAR_INVALID';
end if;
if v_dir is not null and v_dir not in ('asc', 'desc') then
raise exception 'direction is asc or desc' using errcode = '22023', hint = 'DSAR_INVALID';
end if;
if v_sort is null and coalesce(v_dir, 'asc') = 'asc' then
if v_after is not null and (jsonb_typeof(v_after) <> 'array' or jsonb_array_length(v_after) <> 2) then
raise exception 'after is the nextCursor of the previous page' using errcode = '22023', hint = 'DSAR_INVALID';
end if;
select coalesce(jsonb_agg(p.j order by p.n) filter (where p.n <= v_limit), '[]'::jsonb),
count(*) > v_limit,
(array_agg(p.k order by p.n) filter (where p.n = v_limit))[1]
into v_items, v_more, v_next
from (
select row_number() over () as n, to_jsonb(x.*) || jsonb_build_object('overdue', x."closed_at" is null and x."due_at" < now()) as j, jsonb_build_array((x."due_at")::text, (x."id")::text) as k
from (
select * from "better_supabase"."data_subject_requests" x
where x."tenant_id" = page_data_subject_requests.tenant
and (not (v_filters -> 'status' is not null and jsonb_typeof(v_filters -> 'status') <> 'null' and not (jsonb_typeof(v_filters -> 'status') = 'array' and jsonb_array_length(v_filters -> 'status') = 0)) or x."status"::text = any((case when jsonb_typeof(v_filters -> 'status') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'status')) else array[v_filters ->> 'status'] end)::text[]))
and (not (v_filters -> 'kind' is not null and jsonb_typeof(v_filters -> 'kind') <> 'null' and not (jsonb_typeof(v_filters -> 'kind') = 'array' and jsonb_array_length(v_filters -> 'kind') = 0)) or x."kind"::text = any((case when jsonb_typeof(v_filters -> 'kind') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'kind')) else array[v_filters ->> 'kind'] end)::text[]))
and (not coalesce(nullif(coalesce(v_filters #>> '{open,0}', v_filters ->> 'open'), '') = 'true', false) or x."closed_at" is null)
and (not coalesce(nullif(coalesce(v_filters #>> '{overdue,0}', v_filters ->> 'overdue'), '') = 'true', false) or (x."closed_at" is null and x."due_at" < now()))
and (v_search is null or x."subject_id" ilike v_search or x."requester"::text ilike v_search)
and (v_after is null or (x."due_at", x."id") > ((v_after ->> 0)::timestamptz, (v_after ->> 1)::uuid))
order by x."due_at" asc, x."id" asc
limit v_limit + 1 offset v_offset
) x
) p;
elsif v_sort is null and coalesce(v_dir, 'asc') = 'desc' then
if v_after is not null and (jsonb_typeof(v_after) <> 'array' or jsonb_array_length(v_after) <> 2) then
raise exception 'after is the nextCursor of the previous page' using errcode = '22023', hint = 'DSAR_INVALID';
end if;
select coalesce(jsonb_agg(p.j order by p.n) filter (where p.n <= v_limit), '[]'::jsonb),
count(*) > v_limit,
(array_agg(p.k order by p.n) filter (where p.n = v_limit))[1]
into v_items, v_more, v_next
from (
select row_number() over () as n, to_jsonb(x.*) || jsonb_build_object('overdue', x."closed_at" is null and x."due_at" < now()) as j, jsonb_build_array((x."due_at")::text, (x."id")::text) as k
from (
select * from "better_supabase"."data_subject_requests" x
where x."tenant_id" = page_data_subject_requests.tenant
and (not (v_filters -> 'status' is not null and jsonb_typeof(v_filters -> 'status') <> 'null' and not (jsonb_typeof(v_filters -> 'status') = 'array' and jsonb_array_length(v_filters -> 'status') = 0)) or x."status"::text = any((case when jsonb_typeof(v_filters -> 'status') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'status')) else array[v_filters ->> 'status'] end)::text[]))
and (not (v_filters -> 'kind' is not null and jsonb_typeof(v_filters -> 'kind') <> 'null' and not (jsonb_typeof(v_filters -> 'kind') = 'array' and jsonb_array_length(v_filters -> 'kind') = 0)) or x."kind"::text = any((case when jsonb_typeof(v_filters -> 'kind') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'kind')) else array[v_filters ->> 'kind'] end)::text[]))
and (not coalesce(nullif(coalesce(v_filters #>> '{open,0}', v_filters ->> 'open'), '') = 'true', false) or x."closed_at" is null)
and (not coalesce(nullif(coalesce(v_filters #>> '{overdue,0}', v_filters ->> 'overdue'), '') = 'true', false) or (x."closed_at" is null and x."due_at" < now()))
and (v_search is null or x."subject_id" ilike v_search or x."requester"::text ilike v_search)
and (v_after is null or (x."due_at" <= (v_after ->> 0)::timestamptz and ((x."due_at" < (v_after ->> 0)::timestamptz) or (x."due_at" = (v_after ->> 0)::timestamptz and x."id" > (v_after ->> 1)::uuid))))
order by x."due_at" desc, x."id" asc
limit v_limit + 1 offset v_offset
) x
) p;
elsif v_sort = 'dueAt' and coalesce(v_dir, 'asc') = 'asc' then
if v_after is not null and (jsonb_typeof(v_after) <> 'array' or jsonb_array_length(v_after) <> 2) then
raise exception 'after is the nextCursor of the previous page' using errcode = '22023', hint = 'DSAR_INVALID';
end if;
select coalesce(jsonb_agg(p.j order by p.n) filter (where p.n <= v_limit), '[]'::jsonb),
count(*) > v_limit,
(array_agg(p.k order by p.n) filter (where p.n = v_limit))[1]
into v_items, v_more, v_next
from (
select row_number() over () as n, to_jsonb(x.*) || jsonb_build_object('overdue', x."closed_at" is null and x."due_at" < now()) as j, jsonb_build_array((x."due_at")::text, (x."id")::text) as k
from (
select * from "better_supabase"."data_subject_requests" x
where x."tenant_id" = page_data_subject_requests.tenant
and (not (v_filters -> 'status' is not null and jsonb_typeof(v_filters -> 'status') <> 'null' and not (jsonb_typeof(v_filters -> 'status') = 'array' and jsonb_array_length(v_filters -> 'status') = 0)) or x."status"::text = any((case when jsonb_typeof(v_filters -> 'status') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'status')) else array[v_filters ->> 'status'] end)::text[]))
and (not (v_filters -> 'kind' is not null and jsonb_typeof(v_filters -> 'kind') <> 'null' and not (jsonb_typeof(v_filters -> 'kind') = 'array' and jsonb_array_length(v_filters -> 'kind') = 0)) or x."kind"::text = any((case when jsonb_typeof(v_filters -> 'kind') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'kind')) else array[v_filters ->> 'kind'] end)::text[]))
and (not coalesce(nullif(coalesce(v_filters #>> '{open,0}', v_filters ->> 'open'), '') = 'true', false) or x."closed_at" is null)
and (not coalesce(nullif(coalesce(v_filters #>> '{overdue,0}', v_filters ->> 'overdue'), '') = 'true', false) or (x."closed_at" is null and x."due_at" < now()))
and (v_search is null or x."subject_id" ilike v_search or x."requester"::text ilike v_search)
and (v_after is null or (x."due_at", x."id") > ((v_after ->> 0)::timestamptz, (v_after ->> 1)::uuid))
order by x."due_at" asc, x."id" asc
limit v_limit + 1 offset v_offset
) x
) p;
elsif v_sort = 'dueAt' and coalesce(v_dir, 'asc') = 'desc' then
if v_after is not null and (jsonb_typeof(v_after) <> 'array' or jsonb_array_length(v_after) <> 2) then
raise exception 'after is the nextCursor of the previous page' using errcode = '22023', hint = 'DSAR_INVALID';
end if;
select coalesce(jsonb_agg(p.j order by p.n) filter (where p.n <= v_limit), '[]'::jsonb),
count(*) > v_limit,
(array_agg(p.k order by p.n) filter (where p.n = v_limit))[1]
into v_items, v_more, v_next
from (
select row_number() over () as n, to_jsonb(x.*) || jsonb_build_object('overdue', x."closed_at" is null and x."due_at" < now()) as j, jsonb_build_array((x."due_at")::text, (x."id")::text) as k
from (
select * from "better_supabase"."data_subject_requests" x
where x."tenant_id" = page_data_subject_requests.tenant
and (not (v_filters -> 'status' is not null and jsonb_typeof(v_filters -> 'status') <> 'null' and not (jsonb_typeof(v_filters -> 'status') = 'array' and jsonb_array_length(v_filters -> 'status') = 0)) or x."status"::text = any((case when jsonb_typeof(v_filters -> 'status') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'status')) else array[v_filters ->> 'status'] end)::text[]))
and (not (v_filters -> 'kind' is not null and jsonb_typeof(v_filters -> 'kind') <> 'null' and not (jsonb_typeof(v_filters -> 'kind') = 'array' and jsonb_array_length(v_filters -> 'kind') = 0)) or x."kind"::text = any((case when jsonb_typeof(v_filters -> 'kind') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'kind')) else array[v_filters ->> 'kind'] end)::text[]))
and (not coalesce(nullif(coalesce(v_filters #>> '{open,0}', v_filters ->> 'open'), '') = 'true', false) or x."closed_at" is null)
and (not coalesce(nullif(coalesce(v_filters #>> '{overdue,0}', v_filters ->> 'overdue'), '') = 'true', false) or (x."closed_at" is null and x."due_at" < now()))
and (v_search is null or x."subject_id" ilike v_search or x."requester"::text ilike v_search)
and (v_after is null or (x."due_at" <= (v_after ->> 0)::timestamptz and ((x."due_at" < (v_after ->> 0)::timestamptz) or (x."due_at" = (v_after ->> 0)::timestamptz and x."id" > (v_after ->> 1)::uuid))))
order by x."due_at" desc, x."id" asc
limit v_limit + 1 offset v_offset
) x
) p;
elsif v_sort = 'receivedAt' and coalesce(v_dir, 'desc') = 'asc' then
if v_after is not null and (jsonb_typeof(v_after) <> 'array' or jsonb_array_length(v_after) <> 2) then
raise exception 'after is the nextCursor of the previous page' using errcode = '22023', hint = 'DSAR_INVALID';
end if;
select coalesce(jsonb_agg(p.j order by p.n) filter (where p.n <= v_limit), '[]'::jsonb),
count(*) > v_limit,
(array_agg(p.k order by p.n) filter (where p.n = v_limit))[1]
into v_items, v_more, v_next
from (
select row_number() over () as n, to_jsonb(x.*) || jsonb_build_object('overdue', x."closed_at" is null and x."due_at" < now()) as j, jsonb_build_array((x."received_at")::text, (x."id")::text) as k
from (
select * from "better_supabase"."data_subject_requests" x
where x."tenant_id" = page_data_subject_requests.tenant
and (not (v_filters -> 'status' is not null and jsonb_typeof(v_filters -> 'status') <> 'null' and not (jsonb_typeof(v_filters -> 'status') = 'array' and jsonb_array_length(v_filters -> 'status') = 0)) or x."status"::text = any((case when jsonb_typeof(v_filters -> 'status') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'status')) else array[v_filters ->> 'status'] end)::text[]))
and (not (v_filters -> 'kind' is not null and jsonb_typeof(v_filters -> 'kind') <> 'null' and not (jsonb_typeof(v_filters -> 'kind') = 'array' and jsonb_array_length(v_filters -> 'kind') = 0)) or x."kind"::text = any((case when jsonb_typeof(v_filters -> 'kind') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'kind')) else array[v_filters ->> 'kind'] end)::text[]))
and (not coalesce(nullif(coalesce(v_filters #>> '{open,0}', v_filters ->> 'open'), '') = 'true', false) or x."closed_at" is null)
and (not coalesce(nullif(coalesce(v_filters #>> '{overdue,0}', v_filters ->> 'overdue'), '') = 'true', false) or (x."closed_at" is null and x."due_at" < now()))
and (v_search is null or x."subject_id" ilike v_search or x."requester"::text ilike v_search)
and (v_after is null or (x."received_at", x."id") > ((v_after ->> 0)::timestamptz, (v_after ->> 1)::uuid))
order by x."received_at" asc, x."id" asc
limit v_limit + 1 offset v_offset
) x
) p;
elsif v_sort = 'receivedAt' and coalesce(v_dir, 'desc') = 'desc' then
if v_after is not null and (jsonb_typeof(v_after) <> 'array' or jsonb_array_length(v_after) <> 2) then
raise exception 'after is the nextCursor of the previous page' using errcode = '22023', hint = 'DSAR_INVALID';
end if;
select coalesce(jsonb_agg(p.j order by p.n) filter (where p.n <= v_limit), '[]'::jsonb),
count(*) > v_limit,
(array_agg(p.k order by p.n) filter (where p.n = v_limit))[1]
into v_items, v_more, v_next
from (
select row_number() over () as n, to_jsonb(x.*) || jsonb_build_object('overdue', x."closed_at" is null and x."due_at" < now()) as j, jsonb_build_array((x."received_at")::text, (x."id")::text) as k
from (
select * from "better_supabase"."data_subject_requests" x
where x."tenant_id" = page_data_subject_requests.tenant
and (not (v_filters -> 'status' is not null and jsonb_typeof(v_filters -> 'status') <> 'null' and not (jsonb_typeof(v_filters -> 'status') = 'array' and jsonb_array_length(v_filters -> 'status') = 0)) or x."status"::text = any((case when jsonb_typeof(v_filters -> 'status') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'status')) else array[v_filters ->> 'status'] end)::text[]))
and (not (v_filters -> 'kind' is not null and jsonb_typeof(v_filters -> 'kind') <> 'null' and not (jsonb_typeof(v_filters -> 'kind') = 'array' and jsonb_array_length(v_filters -> 'kind') = 0)) or x."kind"::text = any((case when jsonb_typeof(v_filters -> 'kind') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'kind')) else array[v_filters ->> 'kind'] end)::text[]))
and (not coalesce(nullif(coalesce(v_filters #>> '{open,0}', v_filters ->> 'open'), '') = 'true', false) or x."closed_at" is null)
and (not coalesce(nullif(coalesce(v_filters #>> '{overdue,0}', v_filters ->> 'overdue'), '') = 'true', false) or (x."closed_at" is null and x."due_at" < now()))
and (v_search is null or x."subject_id" ilike v_search or x."requester"::text ilike v_search)
and (v_after is null or (x."received_at" <= (v_after ->> 0)::timestamptz and ((x."received_at" < (v_after ->> 0)::timestamptz) or (x."received_at" = (v_after ->> 0)::timestamptz and x."id" > (v_after ->> 1)::uuid))))
order by x."received_at" desc, x."id" asc
limit v_limit + 1 offset v_offset
) x
) p;
end if;
if not v_paged then
return v_items;
end if;
if coalesce((v_filters ->> 'total')::boolean, false) then
select count(*) into v_total from (
select 1 from "better_supabase"."data_subject_requests" x
where x."tenant_id" = page_data_subject_requests.tenant
and (not (v_filters -> 'status' is not null and jsonb_typeof(v_filters -> 'status') <> 'null' and not (jsonb_typeof(v_filters -> 'status') = 'array' and jsonb_array_length(v_filters -> 'status') = 0)) or x."status"::text = any((case when jsonb_typeof(v_filters -> 'status') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'status')) else array[v_filters ->> 'status'] end)::text[]))
and (not (v_filters -> 'kind' is not null and jsonb_typeof(v_filters -> 'kind') <> 'null' and not (jsonb_typeof(v_filters -> 'kind') = 'array' and jsonb_array_length(v_filters -> 'kind') = 0)) or x."kind"::text = any((case when jsonb_typeof(v_filters -> 'kind') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'kind')) else array[v_filters ->> 'kind'] end)::text[]))
and (not coalesce(nullif(coalesce(v_filters #>> '{open,0}', v_filters ->> 'open'), '') = 'true', false) or x."closed_at" is null)
and (not coalesce(nullif(coalesce(v_filters #>> '{overdue,0}', v_filters ->> 'overdue'), '') = 'true', false) or (x."closed_at" is null and x."due_at" < now()))
and (v_search is null or x."subject_id" ilike v_search or x."requester"::text ilike v_search)
limit v_total_cap + 1
) c;
end if;
return jsonb_build_object('items', v_items, 'hasMore', v_more, 'nextCursor', case when v_more then v_next end)
|| case when v_total is null then '{}'::jsonb
else jsonb_build_object('total', least(v_total, v_total_cap), 'totalCapped', v_total > v_total_cap) end;
end;
$$;
revoke execute on function "better_supabase"."page_data_subject_requests"(uuid, jsonb) from public, anon;
grant execute on function "better_supabase"."page_data_subject_requests"(uuid, jsonb) to authenticated, service_role;
-- One data subject request, or a not-found error. Needs the export permission.
create or replace function "better_supabase"."get_data_subject_request"(request_id uuid)
returns jsonb
language plpgsql
stable
security definer
set search_path = ''
as $$
#variable_conflict use_variable
declare
v_row "better_supabase"."data_subject_requests"%rowtype;
begin
select * into v_row from "better_supabase"."data_subject_requests" x where x."id" = get_data_subject_request.request_id;
if not found then
raise exception 'data subject request not found' using errcode = 'P0002', hint = 'DSAR_NOT_FOUND';
end if;
if not (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or coalesce(better_supabase.can('tenant', v_row."tenant_id", 'data_lifecycle.export'), false)) then
raise exception 'You may not handle data subject requests here' using errcode = '42501', hint = 'DSAR_FORBIDDEN';
end if;
return to_jsonb(v_row) || jsonb_build_object('overdue', v_row."closed_at" is null and v_row."due_at" < now());
end;
$$;
revoke execute on function "better_supabase"."get_data_subject_request"(uuid) from public, anon;
grant execute on function "better_supabase"."get_data_subject_request"(uuid) to authenticated, service_role;
revoke execute on function "better_supabase"."list_data_subject_requests"(uuid, text, boolean) from public, anon;
grant execute on function "better_supabase"."open_data_subject_request"(uuid, text, text, text, text, text) to authenticated, service_role;
grant execute on function "better_supabase"."verify_data_subject_request"(uuid, text) to authenticated, service_role;
grant execute on function "better_supabase"."extend_data_subject_request"(uuid, text) to authenticated, service_role;
grant execute on function "better_supabase"."fulfil_data_subject_request"(uuid, text) to authenticated, service_role;
grant execute on function "better_supabase"."refuse_data_subject_request"(uuid, text) to authenticated, service_role;
grant execute on function "better_supabase"."list_data_subject_requests"(uuid, text, boolean) to authenticated, service_role;
-- Erases the data of the request's person across the modules' tables that
-- declare a lifecycle erase mode (ADR 0903). delete removes the rows, anonymize
-- sets the personal columns to null and keeps the row, keep leaves it. A table
-- under an active legal hold is untouched and listed under held. The request
-- must be a verified, open erasure; fulfil_data_subject_request closes it.
create or replace function "better_supabase"."erase_data_subject"(request_id uuid)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
#variable_conflict use_column
declare
v_row "better_supabase"."data_subject_requests";
v_count bigint;
v_removed jsonb := '{}'::jsonb;
v_blanked jsonb := '{}'::jsonb;
v_kept jsonb := '{}'::jsonb;
v_held jsonb := '{}'::jsonb;
begin
select * into v_row from "better_supabase"."data_subject_requests" x where x."id" = erase_data_subject.request_id for update;
if v_row."id" is null then
raise exception 'request not found' using errcode = 'P0002', hint = 'DSAR_NOT_FOUND';
end if;
if not (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or coalesce(better_supabase.can('tenant', v_row."tenant_id", 'data_lifecycle.export'), false)) then
raise exception 'You may not handle data subject requests here' using errcode = '42501', hint = 'DSAR_FORBIDDEN';
end if;
if v_row."kind" <> 'erasure' then
raise exception 'only an erasure request is executed' using errcode = '22023', hint = 'DSAR_INVALID';
end if;
if v_row."closed_at" is not null then
raise exception 'the request is already fulfilled or refused' using errcode = 'PT409', hint = 'DSAR_CLOSED';
end if;
if v_row."verified_at" is null then
raise exception 'verify the requester''s identity first' using errcode = '55000', hint = 'DSAR_UNVERIFIED';
end if;
if v_row."subject_type" is null then
raise exception 'an erasure request names the record to erase' using errcode = '22023', hint = 'DSAR_INVALID';
end if;
if "better_supabase"."is_held"('audit', v_row."tenant_id"::text) then
select count(*) into v_count from "better_supabase"."data_subject_requests" x where x."tenant_id"::text = v_row."tenant_id"::text and x."subject_type" = v_row."subject_type" and x."subject_id" = v_row."subject_id";
v_held := v_held || jsonb_build_object('better_supabase.data_subject_requests', v_count);
else
select count(*) into v_count from "better_supabase"."data_subject_requests" x where x."tenant_id"::text = v_row."tenant_id"::text and x."subject_type" = v_row."subject_type" and x."subject_id" = v_row."subject_id";
v_kept := v_kept || jsonb_build_object('better_supabase.data_subject_requests', v_count);
end if;
return jsonb_build_object('removed', v_removed, 'blanked', v_blanked, 'kept', v_kept, 'held', v_held);
end;
$$;
revoke execute on function "better_supabase"."erase_data_subject"(uuid) from public, anon;
grant execute on function "better_supabase"."erase_data_subject"(uuid) to authenticated, service_role;
-- The tables a restore may write, from the same list an export reads. Each
-- entry: name, tenantColumn, columns (writable and not omitted from exports),
-- keyColumns (the primary key without the tenant column) and references (the
-- listed tables its foreign keys point at).
create or replace function "better_supabase"."data_restore_tables"()
returns jsonb
language plpgsql
stable
set search_path = ''
as $$
begin
return (
with listed as (
select t.name, t.tbl, t.col, t.omit, to_regclass(t.tbl) as oid
from "better_supabase"."data_lifecycle_tables"() t
where t.subject = 'organization' and t.exported and to_regclass(t.tbl) is not null
and t.name <> all (array['better_supabase.memberships', 'better_supabase.permission_overrides']::text[])
)
select coalesce(jsonb_agg(jsonb_build_object(
'name', l.name,
'tenantColumn', l.col,
'columns', (
select coalesce(jsonb_agg(a.attname order by a.attnum), '[]'::jsonb)
from pg_catalog.pg_attribute a
where a.attrelid = l.oid and a.attnum > 0 and not a.attisdropped
and a.attgenerated = '' and a.attidentity <> 'a'
and a.attname <> all (coalesce(l.omit, '{}'))
),
'keyColumns', (
select coalesce(jsonb_agg(a.attname order by k.ord), '[]'::jsonb)
from pg_catalog.pg_constraint c
cross join lateral unnest(c.conkey) with ordinality as k(attnum, ord)
join pg_catalog.pg_attribute a on a.attrelid = c.conrelid and a.attnum = k.attnum
where c.conrelid = l.oid and c.contype = 'p' and a.attname <> l.col
),
'references', (
select coalesce(jsonb_agg(distinct o.name), '[]'::jsonb)
from pg_catalog.pg_constraint c
join listed o on o.oid = c.confrelid
where c.conrelid = l.oid and c.contype = 'f' and c.confrelid <> c.conrelid
)
) order by l.name), '[]'::jsonb)
from listed l
);
end
$$;
revoke execute on function "better_supabase"."data_restore_tables"() from public, anon, authenticated;
grant execute on function "better_supabase"."data_restore_tables"() to service_role;
-- The write function of the data_lifecycle_row import target: item.data is
-- { table, row }. The row goes into the importing organization (its tenant
-- column is replaced) and updates the row with the same primary key, unless
-- that row belongs to another organization.
create or replace function "better_supabase"."restore_data_row"(run uuid, item jsonb, subject_id text)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
#variable_conflict use_column
declare
v_name text := item #>> '{data,table}';
v_row jsonb := item #> '{data,row}';
v_tenant text := item ->> 'tenant';
v_table jsonb;
v_tbl text;
v_tenant_col text;
v_columns text[];
v_keys text[];
v_given text[];
v_cols text[];
v_pk text[];
v_sets text[];
v_sql text;
v_count bigint;
v_creator uuid;
begin
if not (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin')) then
raise exception 'Only the service role restores data' using errcode = '42501', hint = 'DATA_RESTORE_FORBIDDEN';
end if;
if v_name is null or jsonb_typeof(v_row) is distinct from 'object' then
raise exception 'an item needs data.table and a data.row object' using errcode = '22023', hint = 'DATA_RESTORE_ROW_INVALID';
end if;
select x.value into v_table
from jsonb_array_elements("better_supabase"."data_restore_tables"()) x
where x.value ->> 'name' = v_name;
if v_table is null then
raise exception 'The restore has no table %', v_name using errcode = '22023', hint = 'DATA_RESTORE_TABLE';
end if;
select t.tbl into v_tbl from "better_supabase"."data_lifecycle_tables"() t
where t.subject = 'organization' and t.name = v_name and t.exported;
v_tenant_col := v_table ->> 'tenantColumn';
select coalesce(array_agg(c.value), '{}') into v_columns from jsonb_array_elements_text(v_table -> 'columns') c;
select coalesce(array_agg(c.value), '{}') into v_keys from jsonb_array_elements_text(v_table -> 'keyColumns') c;
select coalesce(array_agg(k.key), '{}') into v_given from jsonb_object_keys(v_row) k(key);
if exists (select 1 from unnest(v_given) g where g <> all (v_columns)) then
raise exception 'The table % has no column %', v_name, (select g from unnest(v_given) g where g <> all (v_columns) limit 1) using errcode = '22023', hint = 'DATA_RESTORE_COLUMN';
end if;
select array_agg(distinct c) into v_cols from unnest(v_given || array[v_tenant_col]) c;
v_row := v_row || pg_catalog.jsonb_build_object(v_tenant_col, v_tenant);
v_pk := v_keys || case when v_tenant_col = any (
select a.attname from pg_catalog.pg_constraint c
cross join lateral unnest(c.conkey) k(attnum)
join pg_catalog.pg_attribute a on a.attrelid = c.conrelid and a.attnum = k.attnum
where c.conrelid = to_regclass(v_tbl) and c.contype = 'p'
) then array[v_tenant_col] else '{}'::text[] end;
v_sql := pg_catalog.format(
'insert into %s as t (%s) select %s from jsonb_populate_record(null::%s, $1) r',
v_tbl,
(select string_agg(pg_catalog.format('%I', c), ', ') from unnest(v_cols) c),
(select string_agg(pg_catalog.format('r.%I', c), ', ') from unnest(v_cols) c),
v_tbl
);
if cardinality(v_pk) > 0 then
select array_agg(pg_catalog.format('%I = excluded.%I', c, c)) into v_sets
from unnest(v_cols) c where c <> all (v_pk);
v_sql := v_sql || pg_catalog.format(
' on conflict ' || '(%s) do update set %s where t.%I::text = excluded.%I::text',
(select string_agg(pg_catalog.format('%I', c), ', ') from unnest(v_pk) c),
coalesce(array_to_string(v_sets, ', '), pg_catalog.format('%I = excluded.%I', v_pk[1], v_pk[1])),
v_tenant_col, v_tenant_col
);
end if;
execute v_sql using v_row;
get diagnostics v_count = row_count;
if v_count = 0 then
raise exception 'The row of % belongs to another organization', v_name using errcode = '23505', hint = 'DATA_RESTORE_ROW_CONFLICT';
end if;
return pg_catalog.jsonb_build_object('subjectId', item ->> 'key', 'subjectType', 'data_lifecycle_row');
end;
$$;
revoke execute on function "better_supabase"."restore_data_row"(uuid, jsonb, text) from public, anon, authenticated;
grant execute on function "better_supabase"."restore_data_row"(uuid, jsonb, text) to service_role;
-- What an export reads and the purge clears: subject, display name,
-- quoted table, column and whether the purge deletes it.
create or replace function "better_supabase"."data_lifecycle_tables"()
returns table (subject text, name text, tbl text, col text, purge boolean, omit text[], exported boolean)
language sql
immutable
set search_path = ''
as $$
select * from (values
('user', 'better_supabase.memberships', '"better_supabase"."memberships"', 'user_id', true, '{}'::text[], true),
('user', 'better_supabase.platform_roles', '"better_supabase"."platform_roles"', 'user_id', true, '{}'::text[], true),
('organization', 'better_supabase.memberships', '"better_supabase"."memberships"', 'organization_id', true, '{}'::text[], true),
('organization', 'better_supabase.permission_overrides', '"better_supabase"."permission_overrides"', 'tenant_id', true, '{}'::text[], true),
('organization', 'better_supabase.retention_policies', '"better_supabase"."retention_policies"', 'tenant_id', true, '{}'::text[], false),
('organization', 'better_supabase.data_subject_requests', '"better_supabase"."data_subject_requests"', 'tenant_id', true, '{}'::text[], false)
) as t(subject, name, tbl, col, purge, omit, exported)
$$;
-- The credential_ref columns of module tables: display name, quoted table,
-- column and the user column a ref is revoked for (null for the app).
create or replace function "better_supabase"."data_lifecycle_credentials"()
returns table (name text, tbl text, col text, user_col text)
language sql
immutable
set search_path = ''
as $$
select null::text, null::text, null::text, null::text where false
$$;
-- The credential_refs in the rows a due purge deletes (service role), for
-- the purger to revoke through its CredentialProvider first. in_tenant is
-- false for a ref that doesn't carry the organization; those stay unrevoked.
create or replace function "better_supabase"."organization_credential_refs"(tenant uuid)
returns jsonb
language plpgsql
stable
security invoker
set search_path = ''
as $$
declare
v_entry record;
v_type text;
v_refs jsonb;
v_all jsonb := '[]'::jsonb;
begin
if not (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin')) then
raise exception 'Only the service role purges organizations' using errcode = '42501', hint = 'ORGANIZATION_DELETION_FORBIDDEN';
end if;
if not exists (
select 1 from "better_supabase"."organization_deletions" x
where x."tenant_id" = organization_credential_refs.tenant and x."cancelled_at" is null
and x."purged_at" is null and x."purge_at" <= now()
) then
raise exception 'No due deletion for this organization' using errcode = 'P0002', hint = 'ORGANIZATION_DELETION_NOT_DUE';
end if;
if exists (
select 1 from "better_supabase"."legal_holds" x
where x."released_at" is null
and (x."tenant_id" is null or x."tenant_id" = organization_credential_refs.tenant)
) then
raise exception 'A legal hold covers this organization, so it can''t be purged' using errcode = 'P0001', hint = 'ORGANIZATION_LEGAL_HOLD';
end if;
for v_entry in
select c.name, c.tbl, c.col, c.user_col, t.col as tenant_col
from "better_supabase"."data_lifecycle_credentials"() c
join "better_supabase"."data_lifecycle_tables"() t on t.subject = 'organization' and t.name = c.name and t.purge
where to_regclass(c.tbl) is not null
order by c.name, c.col
loop
select pg_catalog.format_type(a.atttypid, a.atttypmod) into v_type
from pg_catalog.pg_attribute a
where a.attrelid = to_regclass(v_entry.tbl) and a.attname = v_entry.tenant_col and not a.attisdropped;
execute format(
'select coalesce(jsonb_agg(jsonb_build_object(''table'', $2, ''column'', $3, ''ref'', r.ref, ''user_id'', r.user_id, ''in_tenant'', not (jsonb_typeof(r.ref -> ''tenant'') is distinct from ''string'' or (r.ref ->> ''tenant'') is distinct from ($1)::text))), ''[]''::jsonb)
from (select t.%I as ref, %s as user_id from %s t where t.%I = $1::%s) r
where jsonb_typeof(r.ref) = ''object''',
v_entry.col,
case when v_entry.user_col is null then 'null::text' else format('t.%I::text', v_entry.user_col) end,
v_entry.tbl, v_entry.tenant_col, v_type
) into v_refs
using organization_credential_refs.tenant::text, v_entry.name, v_entry.col;
v_all := v_all || v_refs;
end loop;
return v_all;
end;
$$;
revoke execute on function "better_supabase"."data_lifecycle_credentials"() from public, anon, authenticated;
revoke execute on function "better_supabase"."organization_credential_refs"(uuid) from public, anon, authenticated;
grant execute on function "better_supabase"."data_lifecycle_credentials"() to service_role;
grant execute on function "better_supabase"."organization_credential_refs"(uuid) to service_role;
create or replace function "better_supabase"."data_export_object_allowed"(path text)
returns boolean
language sql
stable
security definer
set search_path = ''
as $$
-- Files sit under <export id>/, so the primary key finds the one export.
select exists (
select 1 from "better_supabase"."data_exports" x
where x."id" = case when split_part(path, '/', 1) ~* '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' then split_part(path, '/', 1)::uuid end
and x."bucket" = 'data-exports'
and x."status" = 'ready'
and (x."expires_at" is null or x."expires_at" > now())
and path = any (x."files")
and (x."requested_by" = auth.uid() or (x."tenant_id" is not null and coalesce(better_supabase.can('tenant', x."tenant_id", 'data_lifecycle.export'), false)))
)
$$;
revoke execute on function "better_supabase"."data_export_object_allowed"(text) from public, anon;
grant execute on function "better_supabase"."data_export_object_allowed"(text) to authenticated, service_role;
create policy bsb_data_exports_select on storage.objects
for select to authenticated
using (bucket_id = 'data-exports' and "better_supabase"."data_export_object_allowed"(name));
-- The caller's own data (subject 'user') or a tenant's (needs the export
-- permission). An open export for the same subject is returned instead
-- of a second one.
create or replace function "better_supabase"."request_data_export"(subject text default 'user', tenant uuid default null)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
declare
v_row "better_supabase"."data_exports";
begin
if not (better_supabase.actor_may_write()) then
raise exception 'This session is read-only' using errcode = '42501', hint = 'ACTOR_READ_ONLY';
end if;
if auth.uid() is null then
raise exception 'Sign in to export data' using errcode = '42501', hint = 'DATA_EXPORT_FORBIDDEN';
end if;
if request_data_export.subject = 'organization' then
if request_data_export.tenant is null or not coalesce(better_supabase.can('tenant', request_data_export.tenant, 'data_lifecycle.export'), false) then
raise exception 'You may not export this organization''s data' using errcode = '42501', hint = 'DATA_EXPORT_FORBIDDEN';
end if;
select * into v_row from "better_supabase"."data_exports" x where x."tenant_id" = request_data_export.tenant and x."subject" = 'organization' and x."status" in ('pending', 'running');
if v_row."id" is null then
insert into "better_supabase"."data_exports" ("subject", "tenant_id") values ('organization', request_data_export.tenant) returning * into v_row;
null;
end if;
elsif request_data_export.subject = 'user' then
select * into v_row from "better_supabase"."data_exports" x where x."user_id" = auth.uid() and x."subject" = 'user' and x."status" in ('pending', 'running');
if v_row."id" is null then
insert into "better_supabase"."data_exports" ("subject", "user_id") values ('user', auth.uid()) returning * into v_row;
null;
end if;
else
raise exception 'subject must be user or organization' using errcode = '22023', hint = 'DATA_EXPORT_SUBJECT';
end if;
return to_jsonb(v_row);
end;
$$;
-- A record export's rows, from request_subject_export until the export job
-- writes them: parts maps each file name to its rows.
create table "better_supabase"."data_export_contents" (
"export_id" uuid primary key references "better_supabase"."data_exports" ("id") on delete cascade,
"parts" jsonb not null default '{}'::jsonb
);
alter table "better_supabase"."data_export_contents" enable row level security;
revoke all on "better_supabase"."data_export_contents" from public, anon, authenticated;
grant all on "better_supabase"."data_export_contents" to service_role;
-- One record's data (subject 'record'): its own row, decrypted through its
-- table's reveal function as the caller, and every installed module's rows
-- attached to it. Needs the export permission in the record's tenant or the
-- record's manage action. An open export of the record by the caller is
-- returned instead of a second one.
create or replace function "better_supabase"."request_subject_export"(subject_type text, subject_id text, format text default 'ndjson')
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
declare
v_row "better_supabase"."data_exports";
v_tenant uuid;
v_record jsonb;
v_name text;
v_reveal text;
v_reveal_schema text;
v_proc text;
v_arg text;
v_sealed text[];
v_plain jsonb;
v_rows jsonb;
v_parts jsonb := '{}'::jsonb;
begin
if not (better_supabase.actor_may_write()) then
raise exception 'This session is read-only' using errcode = '42501', hint = 'ACTOR_READ_ONLY';
end if;
if auth.uid() is null then
raise exception 'Sign in to export data' using errcode = '42501', hint = 'DATA_EXPORT_FORBIDDEN';
end if;
if request_subject_export.format is null or request_subject_export.format not in ('ndjson', 'csv') then
raise exception 'format must be ndjson or csv' using errcode = '22023', hint = 'DATA_EXPORT_FORMAT';
end if;
raise exception 'No record type can be exported' using errcode = '22023', hint = 'DATA_EXPORT_SUBJECT';
if v_record is null or not ((v_tenant is not null and coalesce(better_supabase.can('tenant', v_tenant, 'data_lifecycle.export'), false))) then
raise exception 'You may not export this record' using errcode = '42501', hint = 'DATA_EXPORT_FORBIDDEN';
end if;
select * into v_row from "better_supabase"."data_exports" x
where x."subject" = 'record' and x."subject_type" = request_subject_export.subject_type
and x."subject_id" = request_subject_export.subject_id and x."requested_by" = auth.uid()
and x."status" in ('pending', 'running');
if v_row."id" is not null then
return to_jsonb(v_row);
end if;
-- Only the owner's reveal function, so one another role created never runs
-- with this function's rights.
select pg_catalog.format('%I.%I', n.nspname, p.proname), pg_catalog.format_type(p.proargtypes[0], null),
array(select a.name from unnest(p.proargnames, p.proargmodes::text[]) with ordinality a(name, mode, n)
where a.mode = 't' order by a.n offset 1)
into v_proc, v_arg, v_sealed
from pg_catalog.pg_proc p
join pg_catalog.pg_namespace n on n.oid = p.pronamespace
where n.nspname = v_reveal_schema and p.proname = v_reveal and p.pronargs = 1
and p.proowner = (select r.oid from pg_catalog.pg_roles r where r.rolname = current_user)
limit 1;
-- The stored ciphertext never leaves: a caller the reveal returns no row
-- for gets the record without its encrypted columns.
if v_proc is not null then
execute format('select to_jsonb(r.*) from %s(array[$1]::%s) r', v_proc, v_arg) into v_plain
using request_subject_export.subject_id;
v_record := (v_record - coalesce(v_sealed, '{}'::text[])) || coalesce(v_plain, '{}'::jsonb);
end if;
v_parts := jsonb_build_object(v_name, jsonb_build_array(v_record));
insert into "better_supabase"."data_exports" ("subject", "tenant_id", "subject_type", "subject_id", "format")
values ('record', v_tenant, request_subject_export.subject_type, request_subject_export.subject_id, request_subject_export.format)
returning * into v_row;
insert into "better_supabase"."data_export_contents" ("export_id", "parts") values (v_row."id", v_parts);
null;
return to_jsonb(v_row);
end;
$$;
revoke execute on function "better_supabase"."request_subject_export"(text, text, text) from public, anon;
grant execute on function "better_supabase"."request_subject_export"(text, text, text) to authenticated, service_role;
create or replace function "better_supabase"."list_data_exports"(tenant uuid default null)
returns jsonb
language sql
stable
security invoker
set search_path = ''
as $$
select coalesce(jsonb_agg(to_jsonb(x.*) order by x."requested_at" desc, x."id"), '[]'::jsonb)
from "better_supabase"."data_exports" x
where case when list_data_exports.tenant is null
then (x."subject" = 'user' and x."user_id" = auth.uid()) or (x."subject" = 'record' and x."tenant_id" is null and x."requested_by" = auth.uid())
else x."tenant_id" = list_data_exports.tenant
end
$$;
create or replace function "better_supabase"."get_data_export"(id uuid)
returns jsonb
language sql
stable
security invoker
set search_path = ''
as $$
select to_jsonb(x.*) from "better_supabase"."data_exports" x where x."id" = get_data_export.id
$$;
-- Starts a pending (or failed) export and returns it with the tables to
-- read (service role).
create or replace function "better_supabase"."claim_data_export"(id uuid)
returns jsonb
language plpgsql
security invoker
set search_path = ''
as $$
declare
v_row "better_supabase"."data_exports";
begin
if not (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin')) then
raise exception 'Only the service role runs exports' using errcode = '42501', hint = 'DATA_EXPORT_FORBIDDEN';
end if;
update "better_supabase"."data_exports" x set "status" = 'running', "error" = null
where x."id" = claim_data_export.id and x."status" in ('pending', 'failed')
returning * into v_row;
if v_row."id" is null then
return null;
end if;
return to_jsonb(v_row) || jsonb_build_object('tables', case when v_row."subject"::text = 'record' then (select coalesce(jsonb_agg(k.key order by k.key), '[]'::jsonb)
from "better_supabase"."data_export_contents" c, jsonb_object_keys(c."parts") k(key)
where c."export_id" = v_row."id") else (
select coalesce(jsonb_agg(t.name order by t.name), '[]'::jsonb)
from "better_supabase"."data_lifecycle_tables"() t
where t.subject = v_row."subject" and t.exported and to_regclass(t.tbl) is not null
) end);
end;
$$;
-- A page of the subject's rows in one table, after the ctid `after`
-- (service role): { rows, after }, with after null on the last page.
create or replace function "better_supabase"."data_export_rows"(id uuid, table_name text, after text default null, page_size integer default 1000)
returns jsonb
language plpgsql
security invoker
set search_path = ''
as $$
declare
v_row "better_supabase"."data_exports";
v_table record;
v_type text;
v_rows jsonb;
v_after text;
v_offset integer;
begin
if not (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin')) then
raise exception 'Only the service role runs exports' using errcode = '42501', hint = 'DATA_EXPORT_FORBIDDEN';
end if;
select * into v_row from "better_supabase"."data_exports" x where x."id" = data_export_rows.id and x."status" = 'running';
if v_row."id" is null then
raise exception 'No running export has this id' using errcode = 'P0002', hint = 'DATA_EXPORT_NOT_FOUND';
end if;
if v_row."subject"::text = 'record' then
select c."parts" -> data_export_rows.table_name into v_rows
from "better_supabase"."data_export_contents" c where c."export_id" = v_row."id";
if v_rows is null or jsonb_typeof(v_rows) <> 'array' then
raise exception 'The export has no table %', data_export_rows.table_name using errcode = '22023', hint = 'DATA_EXPORT_TABLE';
end if;
v_offset := coalesce(nullif(data_export_rows.after, '')::integer, 0);
return jsonb_build_object(
'rows', (select coalesce(jsonb_agg(r.value order by r.n), '[]'::jsonb)
from jsonb_array_elements(v_rows) with ordinality r(value, n)
where r.n > v_offset and r.n <= v_offset + greatest(1, least(data_export_rows.page_size, 10000))),
'after', case when v_offset + greatest(1, least(data_export_rows.page_size, 10000)) < jsonb_array_length(v_rows) then (v_offset + greatest(1, least(data_export_rows.page_size, 10000)))::text end
);
end if;
select * into v_table from "better_supabase"."data_lifecycle_tables"() t
where t.subject = v_row."subject" and t.name = data_export_rows.table_name and t.exported;
if v_table.tbl is null or to_regclass(v_table.tbl) is null then
raise exception 'The export has no table %', data_export_rows.table_name using errcode = '22023', hint = 'DATA_EXPORT_TABLE';
end if;
select pg_catalog.format_type(a.atttypid, a.atttypmod) into v_type
from pg_catalog.pg_attribute a
where a.attrelid = to_regclass(v_table.tbl) and a.attname = v_table.col and not a.attisdropped;
execute format(
'select coalesce(jsonb_agg((to_jsonb(p.*) - ''_ctid'') - $4::text[] order by p._ctid), ''[]''::jsonb), max(p._ctid)::text, count(*)
from (select t.ctid as _ctid, t.* from %s t where t.%I = $1::%s and ($2::tid is null or t.ctid > $2::tid) order by t.ctid limit $3) p',
v_table.tbl, v_table.col, v_type
) into v_rows, v_after
using case when v_row."subject" = 'user' then v_row."user_id"::text else v_row."tenant_id"::text end,
data_export_rows.after, greatest(1, least(data_export_rows.page_size, 10000)), coalesce(v_table.omit, '{}');
return jsonb_build_object(
'rows', v_rows,
'after', case when jsonb_array_length(v_rows) < greatest(1, least(data_export_rows.page_size, 10000)) then null else v_after end
);
end;
$$;
create or replace function "better_supabase"."complete_data_export"(id uuid, files text[])
returns jsonb
language plpgsql
security invoker
set search_path = ''
as $$
declare
v_row "better_supabase"."data_exports";
begin
if not (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin')) then
raise exception 'Only the service role runs exports' using errcode = '42501', hint = 'DATA_EXPORT_FORBIDDEN';
end if;
update "better_supabase"."data_exports" x set "status" = 'ready', "files" = complete_data_export.files,
"completed_at" = now(), "expires_at" = now() + '7 days'::interval
where x."id" = complete_data_export.id and x."status" = 'running'
returning * into v_row;
if v_row."id" is null then
raise exception 'No running export has this id' using errcode = 'P0002', hint = 'DATA_EXPORT_NOT_FOUND';
end if;
delete from "better_supabase"."data_export_contents" c where c."export_id" = v_row."id";
null;
return to_jsonb(v_row);
end;
$$;
create or replace function "better_supabase"."fail_data_export"(id uuid, error text)
returns jsonb
language plpgsql
security invoker
set search_path = ''
as $$
declare
v_row "better_supabase"."data_exports";
begin
if not (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin')) then
raise exception 'Only the service role runs exports' using errcode = '42501', hint = 'DATA_EXPORT_FORBIDDEN';
end if;
update "better_supabase"."data_exports" x set "status" = 'failed', "error" = fail_data_export.error, "completed_at" = now()
where x."id" = fail_data_export.id and x."status" = 'running'
returning * into v_row;
if v_row."id" is null then
return null;
end if;
null;
return to_jsonb(v_row);
end;
$$;
-- Schedules the purge after the grace period and disables the tenant.
-- Needs the delete permission; requesting again moves the purge date.
create or replace function "better_supabase"."request_organization_deletion"(tenant uuid, grace interval default '30 days'::interval)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
declare
v_row "better_supabase"."organization_deletions";
v_disabled boolean;
begin
if not (better_supabase.actor_may_write()) then
raise exception 'This session is read-only' using errcode = '42501', hint = 'ACTOR_READ_ONLY';
end if;
if not (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin')) and not coalesce(better_supabase.can('tenant', request_organization_deletion.tenant, 'organization.delete'), false) then
raise exception 'You may not delete this organization' using errcode = '42501', hint = 'ORGANIZATION_DELETION_FORBIDDEN';
end if;
if request_organization_deletion.grace < interval '0' then
raise exception 'grace must not be negative' using errcode = '22023', hint = 'ORGANIZATION_DELETION_GRACE';
end if;
if exists (select 1 from "better_supabase"."organization_deletions" x where x."tenant_id" = request_organization_deletion.tenant and x."purged_at" is not null) then
raise exception 'The organization was already purged' using errcode = 'P0002', hint = 'ORGANIZATION_PURGED';
end if;
v_disabled := false;
insert into "better_supabase"."organization_deletions" as x ("tenant_id", "requested_by", "purge_at", "previously_disabled")
values (request_organization_deletion.tenant, auth.uid(), now() + request_organization_deletion.grace, coalesce(v_disabled, false))
on conflict ("tenant_id") do update set
"requested_by" = excluded."requested_by",
"requested_at" = now(),
"purge_at" = excluded."purge_at",
"previously_disabled" = case when x."cancelled_at" is null then x."previously_disabled" else excluded."previously_disabled" end,
"cancelled_at" = null
returning * into v_row;
null;
return to_jsonb(v_row);
end;
$$;
-- The requester, a member holding the cancelDelete permission or the service
-- role cancels a pending purge. The tenant is disabled meanwhile, so this
-- asks member_can_while_deleting, which skips the disabled-tenant check.
create or replace function "better_supabase"."cancel_organization_deletion"(tenant uuid)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
declare
v_row "better_supabase"."organization_deletions";
begin
if not (better_supabase.actor_may_write()) then
raise exception 'This session is read-only' using errcode = '42501', hint = 'ACTOR_READ_ONLY';
end if;
select * into v_row from "better_supabase"."organization_deletions" x
where x."tenant_id" = cancel_organization_deletion.tenant and x."cancelled_at" is null and x."purged_at" is null
for update;
if v_row."tenant_id" is null then
return null;
end if;
if not (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or coalesce(v_row."requested_by" = auth.uid(), false) or coalesce(better_supabase.member_can_while_deleting(auth.uid(), cancel_organization_deletion.tenant, 'organization.delete'), false)) then
raise exception 'You may not cancel this deletion' using errcode = '42501', hint = 'ORGANIZATION_DELETION_FORBIDDEN';
end if;
update "better_supabase"."organization_deletions" x set "cancelled_at" = now()
where x."tenant_id" = v_row."tenant_id"
returning * into v_row;
null;
return to_jsonb(v_row);
end;
$$;
-- The pending deletion, for the organization's members.
create or replace function "better_supabase"."organization_deletion"(tenant uuid)
returns jsonb
language sql
stable
security definer
set search_path = ''
as $$
select to_jsonb(x.*) from "better_supabase"."organization_deletions" x
where x."tenant_id" = organization_deletion.tenant
and x."cancelled_at" is null
and (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or exists (select 1 from "better_supabase"."memberships" mm where mm."organization_id" = organization_deletion.tenant and mm."user_id" = auth.uid()))
$$;
create or replace function "better_supabase"."due_organization_deletions"(max_rows integer default 100)
returns jsonb
language sql
stable
security invoker
set search_path = ''
as $$
select coalesce(jsonb_agg(to_jsonb(x.*) order by x."purge_at"), '[]'::jsonb)
from (
select * from "better_supabase"."organization_deletions" y
where y."purge_at" <= now() and y."cancelled_at" is null and y."purged_at" is null
order by y."purge_at"
limit greatest(1, least(due_organization_deletions.max_rows, 1000))
) x
$$;
-- Deletes a due organization's rows (service role): the app's
-- on_organization_purge(tenant) hook first, then each purged table, then
-- the organization. Returns { organizationId, deleted: { table: rows } }.
create or replace function "better_supabase"."purge_organization"(tenant uuid)
returns jsonb
language plpgsql
security invoker
set search_path = ''
as $$
declare
v_row "better_supabase"."organization_deletions";
v_table record;
v_type text;
v_count bigint;
v_deleted jsonb := '{}'::jsonb;
v_pending text[];
v_left text[];
v_name text;
v_pass integer;
begin
if not (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin')) then
raise exception 'Only the service role purges organizations' using errcode = '42501', hint = 'ORGANIZATION_DELETION_FORBIDDEN';
end if;
select * into v_row from "better_supabase"."organization_deletions" x
where x."tenant_id" = purge_organization.tenant and x."cancelled_at" is null and x."purged_at" is null
for update;
if v_row."tenant_id" is null or v_row."purge_at" > now() then
raise exception 'No due deletion for this organization' using errcode = 'P0002', hint = 'ORGANIZATION_DELETION_NOT_DUE';
end if;
if exists (
select 1 from "better_supabase"."legal_holds" x
where x."released_at" is null
and (x."tenant_id" is null or x."tenant_id" = purge_organization.tenant)
) then
raise exception 'A legal hold covers this organization, so it can''t be purged' using errcode = 'P0001', hint = 'ORGANIZATION_LEGAL_HOLD';
end if;
declare
v_hook regprocedure := to_regprocedure('"public"."on_organization_purge"(uuid)');
begin
if v_hook is not null then
execute format('select %s($1::uuid)', v_hook::oid::regproc)
using purge_organization.tenant;
end if;
end;
-- Tables go in reverse order; a table whose rows another table still
-- references (a restricting foreign key) waits for a later pass.
v_pending := array(
select t.name from "better_supabase"."data_lifecycle_tables"() t
where t.subject = 'organization' and t.purge and to_regclass(t.tbl) is not null
and to_regclass(t.tbl) <> to_regclass('"better_supabase"."organization_deletions"')
order by (row_number() over ()) desc
);
perform set_config('better_supabase.purge_tenant', purge_organization.tenant::text, true);
for v_pass in 1..10 loop
exit when cardinality(v_pending) = 0;
v_left := '{}';
foreach v_name in array v_pending loop
select * into v_table from "better_supabase"."data_lifecycle_tables"() t
where t.subject = 'organization' and t.name = v_name;
select pg_catalog.format_type(a.atttypid, a.atttypmod) into v_type
from pg_catalog.pg_attribute a
where a.attrelid = to_regclass(v_table.tbl) and a.attname = v_table.col and not a.attisdropped;
begin
execute format('delete from %s t where t.%I = $1::%s', v_table.tbl, v_table.col, v_type)
using purge_organization.tenant::text;
get diagnostics v_count = row_count;
v_deleted := v_deleted || jsonb_build_object(v_name, coalesce((v_deleted ->> v_name)::bigint, 0) + v_count);
exception when foreign_key_violation or restrict_violation or check_violation then
-- Another table's rows still point here (or a set null action breaks
-- a check on them): try again after the other tables.
v_left := v_left || v_name;
end;
end loop;
if v_left = v_pending then
raise exception 'Rows in % still have references the purge does not delete', array_to_string(v_left, ', ')
using errcode = '23503', hint = 'ORGANIZATION_PURGE_BLOCKED';
end if;
v_pending := v_left;
end loop;
perform set_config('better_supabase.purge_tenant', '', true);
update "better_supabase"."organization_deletions" x set "purged_at" = now() where x."tenant_id" = v_row."tenant_id" returning * into v_row;
null;
return jsonb_build_object('organizationId', v_row."tenant_id"::text, 'deleted', v_deleted);
end;
$$;
-- Exports past expires_at, oldest first, with their files, for the purger to
-- remove from Storage before forget_data_exports drops the rows.
create or replace function "better_supabase"."expired_data_exports"(max_rows integer default 100)
returns jsonb
language sql
stable
security definer
set search_path = ''
as $$
select coalesce(jsonb_agg(jsonb_build_object('id', x."id", 'bucket', x."bucket", 'files', to_jsonb(x."files")) order by x."expires_at"), '[]'::jsonb)
from (
select * from "better_supabase"."data_exports" y
where y."expires_at" < now()
order by y."expires_at"
limit greatest(1, least(coalesce(max_rows, 100), 1000))
) x
$$;
-- Deletes the export rows (their files are already gone); returns how many.
create or replace function "better_supabase"."forget_data_exports"(ids uuid[])
returns integer
language sql
security definer
set search_path = ''
as $$
with removed as (
delete from "better_supabase"."data_exports" x where x."id" = any (forget_data_exports.ids) and x."expires_at" < now() returning 1
)
select count(*)::integer from removed
$$;
revoke execute on function "better_supabase"."expired_data_exports"(integer) from public, anon, authenticated;
revoke execute on function "better_supabase"."forget_data_exports"(uuid[]) from public, anon, authenticated;
grant execute on function "better_supabase"."expired_data_exports"(integer) to service_role;
-- Anonymizes the rows blocks.data-lifecycle.options.anonymize names once
-- their time is up (service role): at most max_rows per rule, each row once,
-- marked with the time. Returns { table: rows }.
create or replace function "better_supabase"."anonymize_due"(max_rows integer default 1000)
returns jsonb
language plpgsql
security invoker
set search_path = ''
as $$
declare
v_done jsonb := '{}'::jsonb;
begin
if not (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin')) then
raise exception 'Only the service role anonymizes rows' using errcode = '42501', hint = 'DATA_ANONYMIZE_FORBIDDEN';
end if;
return v_done;
end;
$$;
revoke execute on function "better_supabase"."anonymize_due"(integer) from public, anon, authenticated;
grant execute on function "better_supabase"."anonymize_due"(integer) to service_role;
grant execute on function "better_supabase"."forget_data_exports"(uuid[]) to service_role;
revoke execute on function "better_supabase"."data_lifecycle_tables"() from public, anon, authenticated;
revoke execute on function "better_supabase"."request_data_export"(text, uuid) from public, anon;
revoke execute on function "better_supabase"."list_data_exports"(uuid) from public, anon;
revoke execute on function "better_supabase"."get_data_export"(uuid) from public, anon;
revoke execute on function "better_supabase"."claim_data_export"(uuid) from public, anon, authenticated;
revoke execute on function "better_supabase"."data_export_rows"(uuid, text, text, integer) from public, anon, authenticated;
revoke execute on function "better_supabase"."complete_data_export"(uuid, text[]) from public, anon, authenticated;
revoke execute on function "better_supabase"."fail_data_export"(uuid, text) from public, anon, authenticated;
revoke execute on function "better_supabase"."request_organization_deletion"(uuid, interval) from public, anon;
revoke execute on function "better_supabase"."cancel_organization_deletion"(uuid) from public, anon;
revoke execute on function "better_supabase"."organization_deletion"(uuid) from public, anon;
revoke execute on function "better_supabase"."due_organization_deletions"(integer) from public, anon, authenticated;
revoke execute on function "better_supabase"."purge_organization"(uuid) from public, anon, authenticated;
grant execute on function "better_supabase"."data_lifecycle_tables"() to service_role;
grant execute on function "better_supabase"."request_data_export"(text, uuid) to authenticated, service_role;
grant execute on function "better_supabase"."list_data_exports"(uuid) to authenticated, service_role;
grant execute on function "better_supabase"."get_data_export"(uuid) to authenticated, service_role;
grant execute on function "better_supabase"."claim_data_export"(uuid) to service_role;
grant execute on function "better_supabase"."data_export_rows"(uuid, text, text, integer) to service_role;
grant execute on function "better_supabase"."complete_data_export"(uuid, text[]) to service_role;
grant execute on function "better_supabase"."fail_data_export"(uuid, text) to service_role;
grant execute on function "better_supabase"."request_organization_deletion"(uuid, interval) to authenticated, service_role;
grant execute on function "better_supabase"."cancel_organization_deletion"(uuid) to authenticated, service_role;
grant execute on function "better_supabase"."organization_deletion"(uuid) to authenticated, service_role;
grant execute on function "better_supabase"."due_organization_deletions"(integer) to service_role;
grant execute on function "better_supabase"."purge_organization"(uuid) to service_role;
Client
This block has no React entry yet. Its TypeScript side is in better-supabase/blocks/data-lifecycle, which runs on the server.
Events
With the outbox installed, the module writes these in the same transaction as the change.
- data_export.completed
- data_export.failed
- data_export.requested
- data_subject_request.extended
- data_subject_request.fulfilled
- data_subject_request.received
- data_subject_request.refused
- data_subject_request.verified
- legal_hold.placed
- legal_hold.released
- organization.deletion_cancelled
- organization.deletion_requested
- organization.purged
Dependencies
- Required: the install command adds it too
- Works with: optional
Requires
Works with
- every module
- imports
Recipes
More in Admin & compliance
Audit logaudit Records inserts, updates and deletes with the actor and changed columns for tables you register, plus semantic events through audit_event(), with redaction, an append-only guard, a tenant read policy and per-tenant retention as options.React hooks Support sessionsimpersonation Lets platform staff view the app as a user: time-limited, read-only by default, gated by is_platform() and a second admin's approval, recorded in the audit log, with the target's claims built by your access token hook. Metricsmetrics Metrics declared with defineMetric over a table (count, sum or avg per time bucket and dimension), rolled up into metric_points or read from the table, with metric_series and metric_value checked against a permission in the tenant. Compliance controlscompliance Compliance frameworks and their controls, evidence linked to controls (attachments or notes, with a validity date), recurring evidence tasks with assignees and an overdue state, a status rollup per framework, and policies published as frozen versions that members acknowledge through the acknowledgements block. Consentsconsents Consent per record and purpose: the purposes an organization asks consent for with their lawful basis and version, each decision with who made it (the person or a representative) and its signature, form or file as evidence, withdrawals and expiry. consent_active() answers whether processing may go ahead.