Trash
trashSoft delete through each subject's deletedAt column: trash with children in one batch, restore with unique checks, a list per organization, and purge after a retention period, skipped for subjects under a legal hold.
Database primitivesmanagedcustom
PLATFORM_JOBS
send-invoicedone
sync-crmrunning
webhook.retryqueued
sk_live_••••4f2a
Install
The command also installs updated-at, memberships, permissions, housekeeping, the modules it needs.
npx better-supabase add trashConfigure
The blocks entries in your config, with the default mode.
import { defineConfig } from "better-supabase/config";
export default defineConfig({
blocks: {
// Required by trash; add installs them too.
"updated-at": {},
memberships: {},
permissions: {},
housekeeping: {},
// Modes: "managed", "custom". The default is "managed".
trash: { mode: "managed" },
},
});Migrations
The files
npx better-supabase add trash writes into your declarative schema with the default layout.11 files
supabase/schemas/900_better_supabase_075_trash.sqlschema622 lines-- better-supabase module: trash
-- @bsb-block trash@3 managed
-- @bsb-hash sha256:dca336b30269bb6ad0a9712f55f72bc7dc24290e0244264ea387a2bfae92a206
-- Soft delete through each subject's deletedAt column: trash with children in one batch, restore with unique checks, a list per organization, and purge after a retention period, skipped for subjects under a legal hold.
-- 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.
create table "better_supabase"."trash_items" (
"id" uuid primary key default gen_random_uuid(),
"tenant_id" uuid not null,
"subject_type" text not null,
"subject_id" text not null,
"title" text,
"batch_id" uuid not null,
"depth" integer not null default 0 constraint bsb_trash_items_depth_check check ("depth" >= 0),
"trashed_by" uuid,
"trashed_at" timestamptz not null default now(),
"purge_at" timestamptz,
unique ("subject_type", "subject_id")
);
create index "trash_items_tenant_idx" on "better_supabase"."trash_items" ("tenant_id", "trashed_at" desc);
create index "trash_items_batch_idx" on "better_supabase"."trash_items" ("batch_id");
alter table "better_supabase"."trash_items" enable row level security;
revoke all on "better_supabase"."trash_items" from public, anon, authenticated;
grant select on "better_supabase"."trash_items" to authenticated;
grant all on "better_supabase"."trash_items" to service_role;
create policy bsb_trash_items_read on "better_supabase"."trash_items"
for select to authenticated
using ("tenant_id" in (select better_supabase.tenant_ids_with('trash.read')));
-- Marks one subject row trashed, records it, then trashes the rows the
-- subject's children options point at, in the same batch.
create or replace function "better_supabase"."trash_cascade"(tenant uuid, subject_type text, subject_id text, batch uuid, depth integer, actor uuid)
returns integer
language plpgsql
security definer
set search_path = ''
as $$
declare
v_title text;
v_count integer := 1;
v_child text;
v_item "better_supabase"."trash_items"%rowtype;
begin
raise exception 'this subject type has no deletedAt column' using errcode = '22023', hint = 'TRASH_UNSUPPORTED';
delete from "better_supabase"."trash_items" i
where i."subject_type" = trash_cascade.subject_type and i."subject_id" = trash_cascade.subject_id;
insert into "better_supabase"."trash_items" ("tenant_id", "subject_type", "subject_id", "title", "batch_id", "depth", "trashed_by", "trashed_at", "purge_at")
values (trash_cascade.tenant, trash_cascade.subject_type, trash_cascade.subject_id, v_title, trash_cascade.batch, trash_cascade.depth, trash_cascade.actor, now(), now() + make_interval(days => 30))
returning * into v_item;
null;
return v_count;
end;
$$;
revoke execute on function "better_supabase"."trash_cascade"(uuid, text, text, uuid, integer, uuid) from public, anon, authenticated;
-- fields: the extra columns (columns your schema files add) of the
-- subject's trash item.
create or replace function "better_supabase"."trash"(tenant uuid, subject_type text, subject_id text)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
declare
v_batch uuid := gen_random_uuid();
v_count integer;
v_id uuid;
begin
if not (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or (coalesce(better_supabase.can('tenant', trash.tenant, 'trash.create'), false) and true and true)) then
raise exception 'not allowed to trash this record' using errcode = '42501', hint = 'TRASH_FORBIDDEN';
end if;
declare
v_hook regprocedure := to_regprocedure('"public"."before_trash"(uuid, text, text)');
begin
if v_hook is not null then
execute format('select %s($1::uuid, $2::text, $3::text)', v_hook::oid::regproc)
using trash.tenant, trash.subject_type, trash.subject_id;
end if;
end;
v_count := "better_supabase"."trash_cascade"(trash.tenant, trash.subject_type, trash.subject_id, v_batch, 0, auth.uid());
if v_count = 0 then
raise exception 'no live record to trash' using errcode = 'P0002', hint = 'TRASH_NOT_FOUND';
end if;
select i."id" into v_id from "better_supabase"."trash_items" i
where i."subject_type" = trash.subject_type and i."subject_id" = trash.subject_id;
declare
v_hook regprocedure := to_regprocedure('"public"."after_trash"(uuid, uuid)');
begin
if v_hook is not null then
execute format('select %s($1::uuid, $2::uuid)', v_hook::oid::regproc)
using v_id, v_batch;
end if;
end;
return jsonb_build_object('id', v_id, 'batchId', v_batch, 'count', v_count);
end;
$$;
revoke execute on function "better_supabase"."trash"(uuid, text, text) from public, anon;
grant execute on function "better_supabase"."trash"(uuid, text, text) to authenticated, service_role;
-- Restores every row of a batch, after checking the unique columns. The
-- caller deletes the batch's items, so the read-only guard sees its write.
create or replace function "better_supabase"."trash_restore_batch"(batch uuid)
returns integer
language plpgsql
security definer
set search_path = ''
as $$
declare
v_item "better_supabase"."trash_items"%rowtype;
v_count integer := 0;
begin
for v_item in select * from "better_supabase"."trash_items" where "batch_id" = trash_restore_batch.batch order by "depth" loop
null;
null;
v_count := v_count + 1;
end loop;
return v_count;
end;
$$;
revoke execute on function "better_supabase"."trash_restore_batch"(uuid) from public, anon, authenticated;
create or replace function "better_supabase"."restore_trash"(item_id uuid)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
declare
v_root "better_supabase"."trash_items"%rowtype;
v_count integer;
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 r.* into v_root from "better_supabase"."trash_items" i
join "better_supabase"."trash_items" r on r."batch_id" = i."batch_id" and r."depth" = 0
where i."id" = restore_trash.item_id;
if not found then
raise exception 'trash item not found' using errcode = 'P0002', hint = 'TRASH_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_root."tenant_id", 'trash.restore'), false) and true)) then
raise exception 'not allowed to restore this record' using errcode = '42501', hint = 'TRASH_FORBIDDEN';
end if;
declare
v_hook regprocedure := to_regprocedure('"public"."before_untrash"(uuid)');
begin
if v_hook is not null then
execute format('select %s($1::uuid)', v_hook::oid::regproc)
using v_root."id";
end if;
end;
v_count := "better_supabase"."trash_restore_batch"(v_root."batch_id");
delete from "better_supabase"."trash_items" where "batch_id" = v_root."batch_id";
declare
v_hook regprocedure := to_regprocedure('"public"."after_untrash"(uuid, uuid)');
begin
if v_hook is not null then
execute format('select %s($1::uuid, $2::uuid)', v_hook::oid::regproc)
using v_root."id", v_root."batch_id";
end if;
end;
return jsonb_build_object('id', v_root."id", 'batchId', v_root."batch_id", 'subjectType', v_root."subject_type", 'subjectId', v_root."subject_id", 'count', v_count);
end;
$$;
revoke execute on function "better_supabase"."restore_trash"(uuid) from public, anon;
grant execute on function "better_supabase"."restore_trash"(uuid) to authenticated, service_role;
create or replace function "better_supabase"."list_trash"(tenant uuid, subject_type text default null, page_size integer default 50, before timestamptz default null)
returns jsonb
language plpgsql
stable
security definer
set search_path = ''
as $$
declare
v_rows 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', list_trash.tenant, 'trash.read'), false)) then
raise exception 'not allowed to read this organization''s trash' using errcode = '42501', hint = 'TRASH_FORBIDDEN';
end if;
select coalesce(jsonb_agg(jsonb_build_object('id', t."id", 'subjectType', t."subject_type", 'subjectId', t."subject_id", 'title', t."title", 'batchId', t."batch_id", 'count', t.n, 'trashedBy', t."trashed_by", 'trashedAt', t."trashed_at", 'purgeAfter', t."purge_at") order by t."trashed_at" desc, t."id"), '[]'::jsonb)
into v_rows
from (
select x.*, (select count(*) from "better_supabase"."trash_items" b where b."batch_id" = x."batch_id")::integer as n
from "better_supabase"."trash_items" x
where x."tenant_id" = list_trash.tenant
and x."depth" = 0
and (list_trash.subject_type is null or x."subject_type" = list_trash.subject_type)
and (list_trash.before is null or x."trashed_at" < list_trash.before)
and (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or true)
order by x."trashed_at" desc, x."id"
limit least(greatest(coalesce(list_trash.page_size, 50), 1), 200)
) t;
return v_rows;
end;
$$;
revoke execute on function "better_supabase"."list_trash"(uuid, text, integer, timestamptz) from public, anon;
grant execute on function "better_supabase"."list_trash"(uuid, text, integer, timestamptz) to authenticated, service_role;
-- One trashed batch per row, newest first (ADR 1077). It runs as definer like
-- list_trash and applies the same read checks. filters is { subjectType (a
-- value or a list), search (title), sort (trashedAt, subjectType, purgeAfter),
-- direction, facet, count, limit, after, offset, paged, total, totalCap }.
create or replace function "better_supabase"."page_trash"(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_trash.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_trash.tenant, 'trash.read'), false)) then
raise exception 'not allowed to read this organization''s trash' using errcode = '42501', hint = 'TRASH_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 = 'TRASH_INVALID';
end if;
if v_facet is not null then
if v_facet not in ('subjectType') then
raise exception 'facet is one of subjectType' using errcode = '22023', hint = 'TRASH_INVALID';
end if;
with s as (
select (case v_facet when 'subjectType' then (x."subject_type")::text end) as v
from (select s.*, (select count(*) from "better_supabase"."trash_items" b where b."batch_id" = s."batch_id")::integer as n from "better_supabase"."trash_items" s) x
where x."tenant_id" = page_trash.tenant
and x."depth" = 0
and (not (v_filters -> 'subjectType' is not null and jsonb_typeof(v_filters -> 'subjectType') <> 'null' and not (jsonb_typeof(v_filters -> 'subjectType') = 'array' and jsonb_array_length(v_filters -> 'subjectType') = 0)) or (x."subject_type")::text = any((case when jsonb_typeof(v_filters -> 'subjectType') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'subjectType')) else array[v_filters ->> 'subjectType'] end)::text[]))
and (v_search is null or x."title" ilike v_search)
and (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or true)
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 (select s.*, (select count(*) from "better_supabase"."trash_items" b where b."batch_id" = s."batch_id")::integer as n from "better_supabase"."trash_items" s) x
where x."tenant_id" = page_trash.tenant
and x."depth" = 0
and (not (v_filters -> 'subjectType' is not null and jsonb_typeof(v_filters -> 'subjectType') <> 'null' and not (jsonb_typeof(v_filters -> 'subjectType') = 'array' and jsonb_array_length(v_filters -> 'subjectType') = 0)) or (x."subject_type")::text = any((case when jsonb_typeof(v_filters -> 'subjectType') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'subjectType')) else array[v_filters ->> 'subjectType'] end)::text[]))
and (v_search is null or x."title" ilike v_search)
and (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or true)
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 ('trashedAt', 'subjectType', 'purgeAfter') then
raise exception 'sort is one of trashedAt, subjectType, purgeAfter' using errcode = '22023', hint = 'TRASH_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 = 'TRASH_INVALID';
end if;
if v_sort is null 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 = 'TRASH_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, jsonb_build_object('id', x."id", 'subjectType', x."subject_type", 'subjectId', x."subject_id", 'title', x."title", 'batchId', x."batch_id", 'count', x.n, 'trashedBy', x."trashed_by", 'trashedAt', x."trashed_at", 'purgeAfter', x."purge_at") as j, jsonb_build_array((x."trashed_at")::text, (x."id")::text) as k
from (
select * from (select s.*, (select count(*) from "better_supabase"."trash_items" b where b."batch_id" = s."batch_id")::integer as n from "better_supabase"."trash_items" s) x
where x."tenant_id" = page_trash.tenant
and x."depth" = 0
and (not (v_filters -> 'subjectType' is not null and jsonb_typeof(v_filters -> 'subjectType') <> 'null' and not (jsonb_typeof(v_filters -> 'subjectType') = 'array' and jsonb_array_length(v_filters -> 'subjectType') = 0)) or (x."subject_type")::text = any((case when jsonb_typeof(v_filters -> 'subjectType') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'subjectType')) else array[v_filters ->> 'subjectType'] end)::text[]))
and (v_search is null or x."title" ilike v_search)
and (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or true)
and (v_after is null or (x."trashed_at", x."id") > ((v_after ->> 0)::timestamptz, (v_after ->> 1)::uuid))
order by x."trashed_at" asc, x."id" asc
limit v_limit + 1 offset v_offset
) x
) p;
elsif v_sort is null 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 = 'TRASH_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, jsonb_build_object('id', x."id", 'subjectType', x."subject_type", 'subjectId', x."subject_id", 'title', x."title", 'batchId', x."batch_id", 'count', x.n, 'trashedBy', x."trashed_by", 'trashedAt', x."trashed_at", 'purgeAfter', x."purge_at") as j, jsonb_build_array((x."trashed_at")::text, (x."id")::text) as k
from (
select * from (select s.*, (select count(*) from "better_supabase"."trash_items" b where b."batch_id" = s."batch_id")::integer as n from "better_supabase"."trash_items" s) x
where x."tenant_id" = page_trash.tenant
and x."depth" = 0
and (not (v_filters -> 'subjectType' is not null and jsonb_typeof(v_filters -> 'subjectType') <> 'null' and not (jsonb_typeof(v_filters -> 'subjectType') = 'array' and jsonb_array_length(v_filters -> 'subjectType') = 0)) or (x."subject_type")::text = any((case when jsonb_typeof(v_filters -> 'subjectType') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'subjectType')) else array[v_filters ->> 'subjectType'] end)::text[]))
and (v_search is null or x."title" ilike v_search)
and (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or true)
and (v_after is null or (x."trashed_at" <= (v_after ->> 0)::timestamptz and ((x."trashed_at" < (v_after ->> 0)::timestamptz) or (x."trashed_at" = (v_after ->> 0)::timestamptz and x."id" > (v_after ->> 1)::uuid))))
order by x."trashed_at" desc, x."id" asc
limit v_limit + 1 offset v_offset
) x
) p;
elsif v_sort = 'trashedAt' 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 = 'TRASH_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, jsonb_build_object('id', x."id", 'subjectType', x."subject_type", 'subjectId', x."subject_id", 'title', x."title", 'batchId', x."batch_id", 'count', x.n, 'trashedBy', x."trashed_by", 'trashedAt', x."trashed_at", 'purgeAfter', x."purge_at") as j, jsonb_build_array((x."trashed_at")::text, (x."id")::text) as k
from (
select * from (select s.*, (select count(*) from "better_supabase"."trash_items" b where b."batch_id" = s."batch_id")::integer as n from "better_supabase"."trash_items" s) x
where x."tenant_id" = page_trash.tenant
and x."depth" = 0
and (not (v_filters -> 'subjectType' is not null and jsonb_typeof(v_filters -> 'subjectType') <> 'null' and not (jsonb_typeof(v_filters -> 'subjectType') = 'array' and jsonb_array_length(v_filters -> 'subjectType') = 0)) or (x."subject_type")::text = any((case when jsonb_typeof(v_filters -> 'subjectType') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'subjectType')) else array[v_filters ->> 'subjectType'] end)::text[]))
and (v_search is null or x."title" ilike v_search)
and (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or true)
and (v_after is null or (x."trashed_at", x."id") > ((v_after ->> 0)::timestamptz, (v_after ->> 1)::uuid))
order by x."trashed_at" asc, x."id" asc
limit v_limit + 1 offset v_offset
) x
) p;
elsif v_sort = 'trashedAt' 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 = 'TRASH_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, jsonb_build_object('id', x."id", 'subjectType', x."subject_type", 'subjectId', x."subject_id", 'title', x."title", 'batchId', x."batch_id", 'count', x.n, 'trashedBy', x."trashed_by", 'trashedAt', x."trashed_at", 'purgeAfter', x."purge_at") as j, jsonb_build_array((x."trashed_at")::text, (x."id")::text) as k
from (
select * from (select s.*, (select count(*) from "better_supabase"."trash_items" b where b."batch_id" = s."batch_id")::integer as n from "better_supabase"."trash_items" s) x
where x."tenant_id" = page_trash.tenant
and x."depth" = 0
and (not (v_filters -> 'subjectType' is not null and jsonb_typeof(v_filters -> 'subjectType') <> 'null' and not (jsonb_typeof(v_filters -> 'subjectType') = 'array' and jsonb_array_length(v_filters -> 'subjectType') = 0)) or (x."subject_type")::text = any((case when jsonb_typeof(v_filters -> 'subjectType') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'subjectType')) else array[v_filters ->> 'subjectType'] end)::text[]))
and (v_search is null or x."title" ilike v_search)
and (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or true)
and (v_after is null or (x."trashed_at" <= (v_after ->> 0)::timestamptz and ((x."trashed_at" < (v_after ->> 0)::timestamptz) or (x."trashed_at" = (v_after ->> 0)::timestamptz and x."id" > (v_after ->> 1)::uuid))))
order by x."trashed_at" desc, x."id" asc
limit v_limit + 1 offset v_offset
) x
) p;
elsif v_sort = 'subjectType' 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 = 'TRASH_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, jsonb_build_object('id', x."id", 'subjectType', x."subject_type", 'subjectId', x."subject_id", 'title', x."title", 'batchId', x."batch_id", 'count', x.n, 'trashedBy', x."trashed_by", 'trashedAt', x."trashed_at", 'purgeAfter', x."purge_at") as j, jsonb_build_array((x."subject_type")::text, (x."id")::text) as k
from (
select * from (select s.*, (select count(*) from "better_supabase"."trash_items" b where b."batch_id" = s."batch_id")::integer as n from "better_supabase"."trash_items" s) x
where x."tenant_id" = page_trash.tenant
and x."depth" = 0
and (not (v_filters -> 'subjectType' is not null and jsonb_typeof(v_filters -> 'subjectType') <> 'null' and not (jsonb_typeof(v_filters -> 'subjectType') = 'array' and jsonb_array_length(v_filters -> 'subjectType') = 0)) or (x."subject_type")::text = any((case when jsonb_typeof(v_filters -> 'subjectType') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'subjectType')) else array[v_filters ->> 'subjectType'] end)::text[]))
and (v_search is null or x."title" ilike v_search)
and (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or true)
and (v_after is null or (x."subject_type", x."id") > ((v_after ->> 0)::text, (v_after ->> 1)::uuid))
order by x."subject_type" asc, x."id" asc
limit v_limit + 1 offset v_offset
) x
) p;
elsif v_sort = 'subjectType' 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 = 'TRASH_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, jsonb_build_object('id', x."id", 'subjectType', x."subject_type", 'subjectId', x."subject_id", 'title', x."title", 'batchId', x."batch_id", 'count', x.n, 'trashedBy', x."trashed_by", 'trashedAt', x."trashed_at", 'purgeAfter', x."purge_at") as j, jsonb_build_array((x."subject_type")::text, (x."id")::text) as k
from (
select * from (select s.*, (select count(*) from "better_supabase"."trash_items" b where b."batch_id" = s."batch_id")::integer as n from "better_supabase"."trash_items" s) x
where x."tenant_id" = page_trash.tenant
and x."depth" = 0
and (not (v_filters -> 'subjectType' is not null and jsonb_typeof(v_filters -> 'subjectType') <> 'null' and not (jsonb_typeof(v_filters -> 'subjectType') = 'array' and jsonb_array_length(v_filters -> 'subjectType') = 0)) or (x."subject_type")::text = any((case when jsonb_typeof(v_filters -> 'subjectType') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'subjectType')) else array[v_filters ->> 'subjectType'] end)::text[]))
and (v_search is null or x."title" ilike v_search)
and (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or true)
and (v_after is null or (x."subject_type" <= (v_after ->> 0)::text and ((x."subject_type" < (v_after ->> 0)::text) or (x."subject_type" = (v_after ->> 0)::text and x."id" > (v_after ->> 1)::uuid))))
order by x."subject_type" desc, x."id" asc
limit v_limit + 1 offset v_offset
) x
) p;
elsif v_sort = 'purgeAfter' 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 = 'TRASH_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, jsonb_build_object('id', x."id", 'subjectType', x."subject_type", 'subjectId', x."subject_id", 'title', x."title", 'batchId', x."batch_id", 'count', x.n, 'trashedBy', x."trashed_by", 'trashedAt', x."trashed_at", 'purgeAfter', x."purge_at") as j, jsonb_build_array((coalesce(x."purge_at", 'infinity'::timestamptz))::text, (x."id")::text) as k
from (
select * from (select s.*, (select count(*) from "better_supabase"."trash_items" b where b."batch_id" = s."batch_id")::integer as n from "better_supabase"."trash_items" s) x
where x."tenant_id" = page_trash.tenant
and x."depth" = 0
and (not (v_filters -> 'subjectType' is not null and jsonb_typeof(v_filters -> 'subjectType') <> 'null' and not (jsonb_typeof(v_filters -> 'subjectType') = 'array' and jsonb_array_length(v_filters -> 'subjectType') = 0)) or (x."subject_type")::text = any((case when jsonb_typeof(v_filters -> 'subjectType') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'subjectType')) else array[v_filters ->> 'subjectType'] end)::text[]))
and (v_search is null or x."title" ilike v_search)
and (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or true)
and (v_after is null or (coalesce(x."purge_at", 'infinity'::timestamptz), x."id") > ((v_after ->> 0)::timestamptz, (v_after ->> 1)::uuid))
order by coalesce(x."purge_at", 'infinity'::timestamptz) asc, x."id" asc
limit v_limit + 1 offset v_offset
) x
) p;
elsif v_sort = 'purgeAfter' 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 = 'TRASH_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, jsonb_build_object('id', x."id", 'subjectType', x."subject_type", 'subjectId', x."subject_id", 'title', x."title", 'batchId', x."batch_id", 'count', x.n, 'trashedBy', x."trashed_by", 'trashedAt', x."trashed_at", 'purgeAfter', x."purge_at") as j, jsonb_build_array((coalesce(x."purge_at", 'infinity'::timestamptz))::text, (x."id")::text) as k
from (
select * from (select s.*, (select count(*) from "better_supabase"."trash_items" b where b."batch_id" = s."batch_id")::integer as n from "better_supabase"."trash_items" s) x
where x."tenant_id" = page_trash.tenant
and x."depth" = 0
and (not (v_filters -> 'subjectType' is not null and jsonb_typeof(v_filters -> 'subjectType') <> 'null' and not (jsonb_typeof(v_filters -> 'subjectType') = 'array' and jsonb_array_length(v_filters -> 'subjectType') = 0)) or (x."subject_type")::text = any((case when jsonb_typeof(v_filters -> 'subjectType') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'subjectType')) else array[v_filters ->> 'subjectType'] end)::text[]))
and (v_search is null or x."title" ilike v_search)
and (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or true)
and (v_after is null or (coalesce(x."purge_at", 'infinity'::timestamptz) <= (v_after ->> 0)::timestamptz and ((coalesce(x."purge_at", 'infinity'::timestamptz) < (v_after ->> 0)::timestamptz) or (coalesce(x."purge_at", 'infinity'::timestamptz) = (v_after ->> 0)::timestamptz and x."id" > (v_after ->> 1)::uuid))))
order by coalesce(x."purge_at", 'infinity'::timestamptz) 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 (select s.*, (select count(*) from "better_supabase"."trash_items" b where b."batch_id" = s."batch_id")::integer as n from "better_supabase"."trash_items" s) x
where x."tenant_id" = page_trash.tenant
and x."depth" = 0
and (not (v_filters -> 'subjectType' is not null and jsonb_typeof(v_filters -> 'subjectType') <> 'null' and not (jsonb_typeof(v_filters -> 'subjectType') = 'array' and jsonb_array_length(v_filters -> 'subjectType') = 0)) or (x."subject_type")::text = any((case when jsonb_typeof(v_filters -> 'subjectType') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'subjectType')) else array[v_filters ->> 'subjectType'] end)::text[]))
and (v_search is null or x."title" ilike v_search)
and (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or true)
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_trash"(uuid, jsonb) from public, anon;
grant execute on function "better_supabase"."page_trash"(uuid, jsonb) to authenticated, service_role;
-- One trashed batch by its root item id, or null.
create or replace function "better_supabase"."get_trash"(item_id uuid)
returns jsonb
language plpgsql
stable
security definer
set search_path = ''
as $$
declare
v_row jsonb;
v_tenant uuid;
begin
select x."tenant_id" into v_tenant from "better_supabase"."trash_items" x where x."id" = get_trash.item_id and x."depth" = 0;
if v_tenant 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(better_supabase.can('tenant', v_tenant, 'trash.read'), false)) then
raise exception 'not allowed to read this organization''s trash' using errcode = '42501', hint = 'TRASH_FORBIDDEN';
end if;
select jsonb_build_object('id', t."id", 'subjectType', t."subject_type", 'subjectId', t."subject_id", 'title', t."title", 'batchId', t."batch_id", 'count', t.n, 'trashedBy', t."trashed_by", 'trashedAt', t."trashed_at", 'purgeAfter', t."purge_at")
into v_row
from (
select x.*, (select count(*) from "better_supabase"."trash_items" b where b."batch_id" = x."batch_id")::integer as n
from "better_supabase"."trash_items" x
where x."id" = get_trash.item_id
and (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or true)
) t;
return v_row;
end;
$$;
revoke execute on function "better_supabase"."get_trash"(uuid) from public, anon;
grant execute on function "better_supabase"."get_trash"(uuid) to authenticated, service_role;
-- Deletes a batch's rows for good, children first.
create or replace function "better_supabase"."trash_purge_batch"(batch uuid)
returns integer
language plpgsql
security definer
set search_path = ''
as $$
declare
v_item "better_supabase"."trash_items"%rowtype;
v_count integer := 0;
begin
for v_item in select * from "better_supabase"."trash_items" where "batch_id" = trash_purge_batch.batch order by "depth" desc loop
if (false) then
raise exception 'a record in this batch is under a legal hold' using errcode = '42501', hint = 'TRASH_HELD';
end if;
null;
null;
v_count := v_count + 1;
end loop;
delete from "better_supabase"."trash_items" where "batch_id" = trash_purge_batch.batch;
return v_count;
end;
$$;
revoke execute on function "better_supabase"."trash_purge_batch"(uuid) from public, anon, authenticated;
create or replace function "better_supabase"."purge_trash"(item_id uuid)
returns integer
language plpgsql
security definer
set search_path = ''
as $$
declare
v_tenant uuid;
v_batch uuid;
begin
select "tenant_id", "batch_id" into v_tenant, v_batch from "better_supabase"."trash_items" where "id" = purge_trash.item_id;
if v_batch is null then
raise exception 'trash item not found' using errcode = 'P0002', hint = 'TRASH_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_tenant, 'trash.manage'), false)) then
raise exception 'not allowed to empty the trash' using errcode = '42501', hint = 'TRASH_FORBIDDEN';
end if;
return "better_supabase"."trash_purge_batch"(v_batch);
end;
$$;
revoke execute on function "better_supabase"."purge_trash"(uuid) from public, anon;
grant execute on function "better_supabase"."purge_trash"(uuid) to authenticated, service_role;
-- Purges batches past their retention. Run it nightly, e.g. from pg_cron:
-- select cron.schedule('purge-trash', '15 3 * * *', 'select "better_supabase"."purge_expired_trash"()');
create or replace function "better_supabase"."purge_expired_trash"(max_batches integer default 100)
returns integer
language plpgsql
security definer
set search_path = ''
as $$
declare
v_batch uuid;
v_count integer := 0;
begin
for v_batch in
select t."batch_id" from "better_supabase"."trash_items" t
where t."depth" = 0 and t."purge_at" <= now()
and not false
order by t."purge_at"
limit greatest(coalesce(purge_expired_trash.max_batches, 100), 1)
loop
v_count := v_count + "better_supabase"."trash_purge_batch"(v_batch);
end loop;
return v_count;
end;
$$;
revoke execute on function "better_supabase"."purge_expired_trash"(integer) from public, anon, authenticated;
grant execute on function "better_supabase"."purge_expired_trash"(integer) to service_role;
-- For policies: `using (not "better_supabase"."is_trashed"('doc', id::text))` hides
-- trashed rows where the table's own deletedAt column isn't checked.
create or replace function "better_supabase"."is_trashed"(subject_type text, subject_id text)
returns boolean
language sql
stable
security definer
set search_path = ''
as $$
select exists (
select 1 from "better_supabase"."trash_items"
where "subject_type" = is_trashed.subject_type and "subject_id" = is_trashed.subject_id
)
$$;
revoke execute on function "better_supabase"."is_trashed"(text, text) from public, anon;
grant execute on function "better_supabase"."is_trashed"(text, text) to authenticated, service_role;
-- Tenant isolation (ADR 0099): permissive policies combine with or, so one
-- the app adds would widen the block's. These restrictive policies keep each
-- table to the caller's organizations and what the block's policies grant.
create policy bsb_tenant_scope_select on "better_supabase"."trash_items" as restrictive
for select to public
using (
"tenant_id" in (select better_supabase.member_organization_ids())
or ("tenant_id" in (select better_supabase.tenant_ids_with('trash.read')))
);
create policy bsb_tenant_scope_insert on "better_supabase"."trash_items" as restrictive
for insert to public
with check ("tenant_id" in (select better_supabase.member_organization_ids()));
create policy bsb_tenant_scope_update on "better_supabase"."trash_items" as restrictive
for update to public
using ("tenant_id" in (select better_supabase.member_organization_ids()))
with check ("tenant_id" in (select better_supabase.member_organization_ids()));
create policy bsb_tenant_scope_delete on "better_supabase"."trash_items" as restrictive
for delete to public
using ("tenant_id" in (select better_supabase.member_organization_ids()));
Client
This block has no React entry yet. Its TypeScript side is in better-supabase/blocks/trash, which runs on the server.
Events
With the outbox installed, the module writes these in the same transaction as the change.
- subject.purged
- subject.restored
- subject.trashed
Dependencies
- Required: the install command adds it too
- Works with: optional
Recipes
More in Database primitives
Update timestampsupdated-at Keeps an updated_at column current on every update. Realtime table changesrealtime-tables Broadcasts a change signal (no row data) once per statement on bsb:t:<schema>.<table>[:<tenant>], or bsb:t:<schema>.<table>:u:<user> for realtime.users tables, for live queries. JSON Schema checks for jsonbjsonb-schemas pg_jsonschema check constraints for jsonb columns with a `schema` in the `json` config, so the database enforces the same shape as the types. A trigger reports what failed through jsonschema_validation_errors, which the client maps to a validation error. pgTAP helperspgtap tests.create_user, tests.authenticate_as and catalog checks (every_table_has_rls, policies_use, no_anon_policies, every_table_audited, partitions_have_rls) for `supabase test db`. Written to supabase/tests, never to your schema. Read setsread-sets One `stable` function per `defineReadSet` in `readSets`, so `db.$many(readSet, params)` is a single GET. Number sequencesnumbering Gapless numbers per tenant, entity and period. next_number locks the row in the caller's transaction, and a trigger fills the document column so a separate round trip cannot open a gap.