Teams
teamsTenant teams and their members. Inbox assignment uses these rows instead of its own team tables.
Tenancy & accountsmanagedcustom
organizationsRLS on
tenantroleupdated_atacmeowner2m agoglobexadmin1h agoinitechmember3d ago
Install
The command also installs updated-at, memberships, permissions, the modules it needs.
npx better-supabase add teamsConfigure
The blocks entries in your config, with the default mode.
import { defineConfig } from "better-supabase/config";
export default defineConfig({
blocks: {
// Required by teams; add installs them too.
"updated-at": {},
memberships: {},
permissions: {},
// Modes: "managed", "custom". The default is "managed".
teams: { mode: "managed" },
},
});Migrations
The files
npx better-supabase add teams writes into your declarative schema with the default layout.9 files
supabase/schemas/900_better_supabase_058_teams.sqlschema651 lines-- better-supabase module: teams
-- @bsb-block teams@3 managed
-- @bsb-hash sha256:4d2e5bf8b205e1f09e3a8a2e5006c46b4558f70947483be6c7c61e9f6329afd9
-- Tenant teams and their members. Inbox assignment uses these rows instead of its own team tables.
-- 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.
-- Teams belong to a tenant. Inbox assignment uses these rows when inbox is installed.
create table "better_supabase"."teams" (
"id" uuid primary key default gen_random_uuid(),
"tenant_id" uuid not null,
"name" text not null constraint bsb_teams_name_check check (length("name") >= 1 and length("name") <= 200),
"slug" text not null constraint bsb_teams_slug_check check ("slug" ~ '^[a-z0-9]+(?:-[a-z0-9]+)*$'),
"description" text,
"status" text not null default 'active' constraint bsb_teams_status_check check ("status" in ('active', 'archived')),
"created_by" uuid,
"created_at" timestamptz not null default now(),
"updated_at" timestamptz not null default now(),
unique ("tenant_id", "slug")
);
create unique index "bsb_teams_tenant_id_key" on "better_supabase"."teams" ("tenant_id", "id");
alter table "better_supabase"."teams" enable row level security;
revoke all on "better_supabase"."teams" from public, anon, authenticated;
grant select on "better_supabase"."teams" to authenticated;
grant all on "better_supabase"."teams" to service_role;
create policy bsb_teams_read on "better_supabase"."teams"
for select to authenticated
using ("tenant_id" in (select better_supabase.tenant_ids_with('teams.read')));
create table "better_supabase"."team_members" (
"team_id" uuid not null references "better_supabase"."teams" ("id") on delete cascade,
"user_id" uuid not null references auth.users (id) on delete cascade,
"tenant_id" uuid not null,
"created_at" timestamptz not null default now(),
primary key ("team_id", "user_id")
);
create index team_members_user_idx on "better_supabase"."team_members" ("user_id");
create index team_members_membership_idx on "better_supabase"."team_members" ("tenant_id", "user_id");
alter table "better_supabase"."team_members" enable row level security;
revoke all on "better_supabase"."team_members" from public, anon, authenticated;
grant select on "better_supabase"."team_members" to authenticated;
grant all on "better_supabase"."team_members" to service_role;
create policy bsb_team_members_read on "better_supabase"."team_members"
for select to authenticated
using ("tenant_id" in (select better_supabase.tenant_ids_with('teams.read')));
alter table "better_supabase"."team_members"
add constraint team_members_membership_fkey
foreign key ("tenant_id", "user_id")
references "better_supabase"."memberships" ("organization_id", "user_id")
on delete cascade;
alter table "better_supabase"."team_members"
add constraint team_members_team_tenant_fkey
foreign key ("tenant_id", "team_id")
references "better_supabase"."teams" ("tenant_id", "id")
on delete cascade;
create index team_members_tenant_team_idx on "better_supabase"."team_members" ("tenant_id", "team_id");
-- A signed-in caller may only read their own teams; the service role and
-- direct database sessions (no request role) may read anyone's.
create or replace function "better_supabase"."team_ids_of"(member uuid)
returns setof uuid
language plpgsql
stable
security definer
set search_path = ''
as $$
begin
if team_ids_of.member is distinct from (select auth.uid())
and coalesce((select auth.jwt() ->> 'role'), 'service_role') <> 'service_role' then
raise exception 'team_ids_of reads only the caller''s teams' using errcode = '42501', hint = 'TEAM_FORBIDDEN';
end if;
return query select "team_id" from "better_supabase"."team_members" where "user_id" = team_ids_of.member;
end;
$$;
revoke execute on function "better_supabase"."team_ids_of"(uuid) from public, anon;
grant execute on function "better_supabase"."team_ids_of"(uuid) to authenticated, service_role;
-- fields: the extra columns (columns your schema files add) to set.
create or replace function "better_supabase"."create_team"(tenant uuid, name text, description text)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
declare
v_id uuid;
v_slug text := trim(both '-' from regexp_replace(lower(create_team.name), '[^a-z0-9]+', '-', 'g'));
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', create_team.tenant, 'teams.manage'), false)) then
raise exception 'not allowed to manage teams' using errcode = '42501', hint = 'TEAM_FORBIDDEN';
end if;
if v_slug is null or v_slug = '' then
raise exception 'team name needs a slug' using errcode = '22023', hint = 'TEAM_SLUG_INVALID';
end if;
declare
v_hook regprocedure := to_regprocedure('"public"."before_team_create"(uuid, text)');
begin
if v_hook is not null then
execute format('select %s($1::uuid, $2::text)', v_hook::oid::regproc)
using create_team.tenant, v_slug;
end if;
end;
insert into "better_supabase"."teams" ("tenant_id", "name", "slug", "description", "created_by")
values (create_team.tenant, create_team.name, v_slug, create_team.description, auth.uid())
returning "id" into v_id;
null;
declare
v_hook regprocedure := to_regprocedure('"public"."after_team_create"(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, create_team.tenant;
end if;
end;
return jsonb_build_object('id', v_id, 'slug', v_slug);
end;
$$;
revoke execute on function "better_supabase"."create_team"(uuid, text, text) from public, anon;
grant execute on function "better_supabase"."create_team"(uuid, text, text) to authenticated, service_role;
create or replace function "better_supabase"."update_team"(team uuid, name text, description text)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
declare
v_tenant 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 "tenant_id" into v_tenant from "better_supabase"."teams" where "id" = update_team.team;
if not found then
raise exception 'team not found' using errcode = 'P0002', hint = 'TEAM_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, 'teams.manage'), false)) then
raise exception 'not allowed to manage teams' using errcode = '42501', hint = 'TEAM_FORBIDDEN';
end if;
update "better_supabase"."teams" as t
set "name" = coalesce(update_team.name, t."name"),
"description" = coalesce(update_team.description, t."description"),
"updated_at" = now()
where t."id" = update_team.team;
null;
return (select jsonb_build_object('id', x."id", 'name', x."name", 'slug', x."slug", 'description', x."description", 'status', x."status") from "better_supabase"."teams" x where x."id" = update_team.team);
end;
$$;
revoke execute on function "better_supabase"."update_team"(uuid, text, text) from public, anon;
grant execute on function "better_supabase"."update_team"(uuid, text, text) to authenticated, service_role;
create or replace function "better_supabase"."archive_team"(team uuid)
returns boolean
language plpgsql
security definer
set search_path = ''
as $$
declare
v_tenant 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 "tenant_id" into v_tenant from "better_supabase"."teams" where "id" = archive_team.team;
if not found then
raise exception 'team not found' using errcode = 'P0002', hint = 'TEAM_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, 'teams.manage'), false)) then
raise exception 'not allowed to manage teams' using errcode = '42501', hint = 'TEAM_FORBIDDEN';
end if;
update "better_supabase"."teams" set "status" = 'archived', "updated_at" = now() where "id" = archive_team.team;
null;
return true;
end;
$$;
revoke execute on function "better_supabase"."archive_team"(uuid) from public, anon;
grant execute on function "better_supabase"."archive_team"(uuid) to authenticated, service_role;
create or replace function "better_supabase"."purge_team"(team uuid)
returns boolean
language plpgsql
security definer
set search_path = ''
as $$
declare
v_tenant 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 "tenant_id" into v_tenant from "better_supabase"."teams" where "id" = purge_team.team;
if not found then
raise exception 'team not found' using errcode = 'P0002', hint = 'TEAM_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, 'teams.manage'), false)) then
raise exception 'not allowed to manage teams' using errcode = '42501', hint = 'TEAM_FORBIDDEN';
end if;
delete from "better_supabase"."teams" where "id" = purge_team.team;
null;
return true;
end;
$$;
revoke execute on function "better_supabase"."purge_team"(uuid) from public, anon;
grant execute on function "better_supabase"."purge_team"(uuid) to authenticated, service_role;
-- purge_team for each of team_ids in one call, all or nothing; returns how many
-- it purged.
create or replace function "better_supabase"."purge_teams"(team_ids uuid[])
returns integer
language plpgsql
security definer
set search_path = ''
as $$
declare
v_team uuid;
v_count integer := 0;
begin
if coalesce(cardinality(purge_teams.team_ids), 0) > 1000 then
raise exception 'purge at most 1000 teams in one call' using errcode = '22023', hint = 'TEAM_INVALID';
end if;
for v_team in select distinct x from unnest(purge_teams.team_ids) x where x is not null loop
perform "better_supabase"."purge_team"(v_team);
v_count := v_count + 1;
end loop;
return v_count;
end;
$$;
revoke execute on function "better_supabase"."purge_teams"(uuid[]) from public, anon;
grant execute on function "better_supabase"."purge_teams"(uuid[]) to authenticated, service_role;
create or replace function "better_supabase"."create_team_member"(team uuid, member uuid)
returns boolean
language plpgsql
security definer
set search_path = ''
as $$
declare
v_tenant 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 "tenant_id" into v_tenant from "better_supabase"."teams" where "id" = create_team_member.team;
if not found then
raise exception 'team not found' using errcode = 'P0002', hint = 'TEAM_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, 'teams.manage'), false)) then
raise exception 'not allowed to manage teams' using errcode = '42501', hint = 'TEAM_FORBIDDEN';
end if;
if not exists (
select 1 from "better_supabase"."memberships" m
where m."organization_id" = v_tenant
and m."user_id" = create_team_member.member
) then
raise exception 'user is not a member of the tenant' using errcode = '22023', hint = 'TEAM_MEMBER_INVALID';
end if;
insert into "better_supabase"."team_members" ("team_id", "user_id", "tenant_id")
values (create_team_member.team, create_team_member.member, v_tenant)
on conflict do nothing;
null;
return true;
end;
$$;
revoke execute on function "better_supabase"."create_team_member"(uuid, uuid) from public, anon;
grant execute on function "better_supabase"."create_team_member"(uuid, uuid) to authenticated, service_role;
create or replace function "better_supabase"."delete_team_member"(team uuid, member uuid)
returns boolean
language plpgsql
security definer
set search_path = ''
as $$
declare
v_tenant 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 "tenant_id" into v_tenant from "better_supabase"."teams" where "id" = delete_team_member.team;
if not found then
raise exception 'team not found' using errcode = 'P0002', hint = 'TEAM_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, 'teams.manage'), false)) then
raise exception 'not allowed to manage teams' using errcode = '42501', hint = 'TEAM_FORBIDDEN';
end if;
delete from "better_supabase"."team_members"
where "team_id" = delete_team_member.team and "user_id" = delete_team_member.member;
null;
return found;
end;
$$;
revoke execute on function "better_supabase"."delete_team_member"(uuid, uuid) from public, anon;
grant execute on function "better_supabase"."delete_team_member"(uuid, uuid) to authenticated, service_role;
-- Teams as a keyset page, by name unless sort says otherwise (ADR 1077).
-- filters may hold status (a value or a list), search, sort (name,
-- createdAt), direction, facet, count, limit and after. Without paged it
-- returns the plain array, at most 200.
create or replace function "better_supabase"."list_teams"(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(list_teams.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', list_teams.tenant, 'teams.read'), false)) then
raise exception 'not allowed to read teams' using errcode = '42501', hint = 'TEAM_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 = 'TEAM_INVALID';
end if;
if v_facet is not null then
if v_facet not in ('status') then
raise exception 'facet is one of status' using errcode = '22023', hint = 'TEAM_INVALID';
end if;
with s as (
select (case v_facet when 'status' then (x."status")::text end) as v
from "better_supabase"."teams" x
where x."tenant_id" = list_teams.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 (v_search is null or x."name" ilike v_search or x."slug" ilike v_search or coalesce(x."description", '') 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"."teams" x
where x."tenant_id" = list_teams.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 (v_search is null or x."name" ilike v_search or x."slug" ilike v_search or coalesce(x."description", '') 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 ('name', 'createdAt') then
raise exception 'sort is one of name, createdAt' using errcode = '22023', hint = 'TEAM_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 = 'TEAM_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 = 'TEAM_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",
'name', x."name",
'slug', x."slug",
'description', x."description",
'status', x."status",
'member_ids', coalesce((
select jsonb_agg(m."user_id" order by m."created_at")
from "better_supabase"."team_members" m
where m."team_id" = x."id"
), '[]'::jsonb)
) as j, jsonb_build_array((lower(x."name"))::text, (x."id")::text) as k
from (
select * from "better_supabase"."teams" x
where x."tenant_id" = list_teams.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 (v_search is null or x."name" ilike v_search or x."slug" ilike v_search or coalesce(x."description", '') ilike v_search)
and (v_after is null or (lower(x."name"), x."id") > ((v_after ->> 0)::text, (v_after ->> 1)::uuid))
order by lower(x."name") 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 = 'TEAM_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",
'name', x."name",
'slug', x."slug",
'description', x."description",
'status', x."status",
'member_ids', coalesce((
select jsonb_agg(m."user_id" order by m."created_at")
from "better_supabase"."team_members" m
where m."team_id" = x."id"
), '[]'::jsonb)
) as j, jsonb_build_array((lower(x."name"))::text, (x."id")::text) as k
from (
select * from "better_supabase"."teams" x
where x."tenant_id" = list_teams.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 (v_search is null or x."name" ilike v_search or x."slug" ilike v_search or coalesce(x."description", '') ilike v_search)
and (v_after is null or (lower(x."name") <= (v_after ->> 0)::text and ((lower(x."name") < (v_after ->> 0)::text) or (lower(x."name") = (v_after ->> 0)::text and x."id" > (v_after ->> 1)::uuid))))
order by lower(x."name") desc, x."id" asc
limit v_limit + 1 offset v_offset
) x
) p;
elsif v_sort = 'name' 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 = 'TEAM_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",
'name', x."name",
'slug', x."slug",
'description', x."description",
'status', x."status",
'member_ids', coalesce((
select jsonb_agg(m."user_id" order by m."created_at")
from "better_supabase"."team_members" m
where m."team_id" = x."id"
), '[]'::jsonb)
) as j, jsonb_build_array((lower(x."name"))::text, (x."id")::text) as k
from (
select * from "better_supabase"."teams" x
where x."tenant_id" = list_teams.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 (v_search is null or x."name" ilike v_search or x."slug" ilike v_search or coalesce(x."description", '') ilike v_search)
and (v_after is null or (lower(x."name"), x."id") > ((v_after ->> 0)::text, (v_after ->> 1)::uuid))
order by lower(x."name") asc, x."id" asc
limit v_limit + 1 offset v_offset
) x
) p;
elsif v_sort = 'name' 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 = 'TEAM_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",
'name', x."name",
'slug', x."slug",
'description', x."description",
'status', x."status",
'member_ids', coalesce((
select jsonb_agg(m."user_id" order by m."created_at")
from "better_supabase"."team_members" m
where m."team_id" = x."id"
), '[]'::jsonb)
) as j, jsonb_build_array((lower(x."name"))::text, (x."id")::text) as k
from (
select * from "better_supabase"."teams" x
where x."tenant_id" = list_teams.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 (v_search is null or x."name" ilike v_search or x."slug" ilike v_search or coalesce(x."description", '') ilike v_search)
and (v_after is null or (lower(x."name") <= (v_after ->> 0)::text and ((lower(x."name") < (v_after ->> 0)::text) or (lower(x."name") = (v_after ->> 0)::text and x."id" > (v_after ->> 1)::uuid))))
order by lower(x."name") desc, x."id" asc
limit v_limit + 1 offset v_offset
) x
) p;
elsif v_sort = 'createdAt' 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 = 'TEAM_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",
'name', x."name",
'slug', x."slug",
'description', x."description",
'status', x."status",
'member_ids', coalesce((
select jsonb_agg(m."user_id" order by m."created_at")
from "better_supabase"."team_members" m
where m."team_id" = x."id"
), '[]'::jsonb)
) as j, jsonb_build_array((x."created_at")::text, (x."id")::text) as k
from (
select * from "better_supabase"."teams" x
where x."tenant_id" = list_teams.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 (v_search is null or x."name" ilike v_search or x."slug" ilike v_search or coalesce(x."description", '') ilike v_search)
and (v_after is null or (x."created_at", x."id") > ((v_after ->> 0)::timestamptz, (v_after ->> 1)::uuid))
order by x."created_at" asc, x."id" asc
limit v_limit + 1 offset v_offset
) x
) p;
elsif v_sort = 'createdAt' 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 = 'TEAM_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",
'name', x."name",
'slug', x."slug",
'description', x."description",
'status', x."status",
'member_ids', coalesce((
select jsonb_agg(m."user_id" order by m."created_at")
from "better_supabase"."team_members" m
where m."team_id" = x."id"
), '[]'::jsonb)
) as j, jsonb_build_array((x."created_at")::text, (x."id")::text) as k
from (
select * from "better_supabase"."teams" x
where x."tenant_id" = list_teams.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 (v_search is null or x."name" ilike v_search or x."slug" ilike v_search or coalesce(x."description", '') ilike v_search)
and (v_after is null or (x."created_at" <= (v_after ->> 0)::timestamptz and ((x."created_at" < (v_after ->> 0)::timestamptz) or (x."created_at" = (v_after ->> 0)::timestamptz and x."id" > (v_after ->> 1)::uuid))))
order by x."created_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"."teams" x
where x."tenant_id" = list_teams.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 (v_search is null or x."name" ilike v_search or x."slug" ilike v_search or coalesce(x."description", '') 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"."list_teams"(uuid, jsonb) from public, anon;
grant execute on function "better_supabase"."list_teams"(uuid, jsonb) to authenticated, service_role;
-- One team the caller may read, or null.
create or replace function "better_supabase"."get_team"(team uuid)
returns jsonb
language plpgsql
stable
security definer
set search_path = ''
as $$
#variable_conflict use_variable
declare
v_tenant uuid;
v_row jsonb;
begin
select x."tenant_id", jsonb_build_object(
'id', x."id",
'name', x."name",
'slug', x."slug",
'description', x."description",
'status', x."status",
'member_ids', coalesce((
select jsonb_agg(m."user_id" order by m."created_at")
from "better_supabase"."team_members" m
where m."team_id" = x."id"
), '[]'::jsonb)
)
into v_tenant, v_row
from "better_supabase"."teams" x
where x."id" = get_team.team;
if v_row 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, 'teams.read'), false)) then
raise exception 'not allowed to read teams' using errcode = '42501', hint = 'TEAM_FORBIDDEN';
end if;
return v_row;
end;
$$;
revoke execute on function "better_supabase"."get_team"(uuid) from public, anon;
grant execute on function "better_supabase"."get_team"(uuid) 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"."teams" 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('teams.read')))
);
create policy bsb_tenant_scope_insert on "better_supabase"."teams" 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"."teams" 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"."teams" as restrictive
for delete to public
using ("tenant_id" in (select better_supabase.member_organization_ids()));
create policy bsb_tenant_scope_select on "better_supabase"."team_members" 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('teams.read')))
);
create policy bsb_tenant_scope_insert on "better_supabase"."team_members" 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"."team_members" 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"."team_members" 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/teams, which runs on the server.
Events
With the outbox installed, the module writes these in the same transaction as the change.
- team.archived
- team.created
- team.purged
- team.updated
- team_member.added
- team_member.deleted
Dependencies
- Required: the install command adds it too
- Works with: optional
Requires
Recipes
More in Tenancy & accounts
Tenant memberships and permission helpermemberships Memberships with roles, member_organization_ids() and has_organization_role() for RLS policies, and membership_claims() for the access token hook. Adopt an existing memberships table through blocks.memberships. Invitationsinvitations invite_member(tenant, email, role) returns a single-use token whose hash is stored; accept_invitation(token) checks the signed-in user's confirmed email and, again, the inviter's authority. Roles follow the access model; a null tenant invites to a platform role, stored in platform_invitations. Reserved slugsreserved-slugs A slug format and length check and a list of reserved words (admin, api, www, ...), enforced by a trigger. Organizationsorganizations create_organization(attrs) with slug rules and an after-create hook, a deferred owner check, an assignment ceiling, and member functions (role change, remove, leave, transfer ownership) on the access contract.React hooks Profilesprofiles A profile per user, created on sign-up from auth metadata with a unique username, an email mirror, column-level update grants and a guard on columns the service owns. Settingssettings Per-user, per-organization and platform-wide settings as key-value jsonb rows. Users read and write their own; organization settings check settings.read and settings.update; platform settings check a platform permission per key. Keys with a JSON Schema in options.schemas get a pg_jsonschema check.React hooks