Templates
templatesTyped, versioned templates (system starters and tenant forks) that create records, with merge fields and workflows started on each record they create.
Content & filesmanagedcustom
BIH1v12
Q4 launch planInstall
The command also installs updated-at, memberships, permissions, recurrence, the modules it needs.
npx better-supabase add templatesConfigure
The blocks entries in your config, with the default mode.
import { defineConfig } from "better-supabase/config";
export default defineConfig({
blocks: {
// Required by templates; add installs them too.
"updated-at": {},
memberships: {},
permissions: {},
recurrence: {},
// Modes: "managed", "custom". The default is "managed".
templates: { mode: "managed" },
},
});Migrations
The files
npx better-supabase add templates writes into your declarative schema with the default layout.11 files
supabase/schemas/900_better_supabase_091_templates.sqlschema1354 lines-- better-supabase module: templates
-- @bsb-block templates@1 managed
-- @bsb-hash sha256:df3d5238801ade6b18de6854f2fe0dc91f21fdb3135c286db998bc6fce37b339
-- Typed, versioned templates (system starters and tenant forks) that create records, with merge fields and workflows started on each record they create.
-- 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 extension if not exists pgcrypto with schema extensions;
-- Templates of a type (an invoice, a project, an email): a tenant's own, or
-- a system starter (no tenant) that sync_templates keeps by key and tenants
-- fork, or with options.brand a starter of one brand. forked_from: the template and version a fork copied.
create table "better_supabase"."templates" (
"id" uuid primary key default gen_random_uuid(),
"tenant_id" uuid,
"scope" text not null default 'tenant' constraint bsb_templates_scope_check check ("scope" in ('tenant', 'system')),
"key" text constraint bsb_templates_key_check check ("key" ~ '^[a-z0-9][a-z0-9_.-]{0,99}$'),
"type" text not null constraint bsb_templates_type_check check ("type" ~ '^[a-z][a-z0-9_.-]{0,63}$'),
"name" text not null constraint bsb_templates_name_check check (length("name") >= 1 and length("name") <= 200),
"language" text not null default 'en' constraint bsb_templates_language_check check ("language" ~ '^[a-z]{2,3}(-[A-Za-z0-9]{1,8})*$'),
"is_default" boolean not null default false,
"settings" jsonb not null default '{}'::jsonb
constraint bsb_templates_settings_check check (jsonb_typeof("settings") = 'object' and pg_column_size("settings") <= 65536),
"forked_from" uuid references "better_supabase"."templates" ("id") on delete set null,
"forked_from_version" integer constraint bsb_templates_forked_from_version_check check ("forked_from_version" > 0),
"created_by" uuid references auth.users (id) on delete set null,
"created_at" timestamptz not null default now(),
"updated_at" timestamptz not null default now(),
constraint bsb_templates_system_check check (("scope" = 'system') = ("tenant_id" is null))
);
create unique index templates_key_idx on "better_supabase"."templates" ("tenant_id", "key") nulls not distinct where "key" is not null;
create unique index templates_default_idx on "better_supabase"."templates" ("tenant_id", "type", "language") nulls not distinct where "is_default";
create index templates_type_idx on "better_supabase"."templates" ("tenant_id", "type");
create index templates_forked_from_idx on "better_supabase"."templates" ("forked_from") where "forked_from" is not null;
create index templates_created_by_idx on "better_supabase"."templates" ("created_by");
alter table "better_supabase"."templates" enable row level security;
revoke all on "better_supabase"."templates" from public, anon, authenticated;
grant select on "better_supabase"."templates" to authenticated;
grant all on "better_supabase"."templates" to service_role;
create policy bsb_templates_read on "better_supabase"."templates"
for select to authenticated
using ("tenant_id" in (select better_supabase.tenant_ids_with('templates.read'))
or ("scope" = 'system' and exists (select better_supabase.tenant_ids_with('templates.read'))));
-- Numbered snapshots of a template's body: at most one draft, and published
-- versions that never change. hash: the SHA-256 of the body as text.
create table "better_supabase"."template_versions" (
"id" uuid primary key default gen_random_uuid(),
"template_id" uuid not null references "better_supabase"."templates" ("id") on delete cascade,
"version" integer not null constraint bsb_template_versions_version_check check ("version" > 0),
"body" jsonb not null constraint bsb_template_versions_body_check check (pg_column_size("body") <= 1048576),
"hash" text not null,
"published_at" timestamptz,
"created_by" uuid references auth.users (id) on delete set null,
"created_at" timestamptz not null default now(),
constraint template_versions_template_version_key unique ("template_id", "version")
);
create unique index template_versions_one_draft_idx on "better_supabase"."template_versions" ("template_id") where "published_at" is null;
create index template_versions_created_by_idx on "better_supabase"."template_versions" ("created_by");
alter table "better_supabase"."template_versions" enable row level security;
revoke all on "better_supabase"."template_versions" from public, anon, authenticated;
grant select on "better_supabase"."template_versions" to authenticated;
grant all on "better_supabase"."template_versions" to service_role;
create policy bsb_template_versions_read on "better_supabase"."template_versions"
for select to authenticated
using (exists (select 1 from "better_supabase"."templates" x where x."id" = "template_id"));
-- Each time a published version created a record, and which one.
create table "better_supabase"."template_applications" (
"id" uuid primary key default gen_random_uuid(),
"template_id" uuid not null references "better_supabase"."templates" ("id") on delete cascade,
"version_id" uuid not null references "better_supabase"."template_versions" ("id") on delete cascade,
"tenant_id" uuid not null,
"subject_type" text not null constraint bsb_template_applications_subject_type_check check (length("subject_type") >= 1 and length("subject_type") <= 100),
"subject_id" text not null constraint bsb_template_applications_subject_id_check check (length("subject_id") >= 1 and length("subject_id") <= 200),
"applied_by" uuid references auth.users (id) on delete set null,
"applied_at" timestamptz not null default now()
);
create index template_applications_tenant_idx on "better_supabase"."template_applications" ("tenant_id", "applied_at" desc);
create index template_applications_template_idx on "better_supabase"."template_applications" ("template_id");
create index template_applications_version_idx on "better_supabase"."template_applications" ("version_id");
create index template_applications_subject_idx on "better_supabase"."template_applications" ("subject_type", "subject_id");
create index template_applications_applied_by_idx on "better_supabase"."template_applications" ("applied_by");
alter table "better_supabase"."template_applications" enable row level security;
revoke all on "better_supabase"."template_applications" from public, anon, authenticated;
grant select on "better_supabase"."template_applications" to authenticated;
grant all on "better_supabase"."template_applications" to service_role;
create policy bsb_template_applications_read on "better_supabase"."template_applications"
for select to authenticated
using ("tenant_id" in (select better_supabase.tenant_ids_with('templates.read')));
-- Creates a template (template_id null) or renames it and replaces its
-- settings. tenant null saves a system template, which only the service
-- role may; a tenant's needs templates.manage there.
-- fields: the extra columns (columns your schema files add) to set.
create or replace function "better_supabase"."upsert_template"(template_id uuid, tenant uuid, type text, name text, language text, settings jsonb)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
#variable_conflict use_variable
declare
v_row "better_supabase"."templates"%rowtype;
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 upsert_template.settings is not null and jsonb_typeof(upsert_template.settings) <> 'object' then
raise exception 'settings must be an object' using errcode = '22023', hint = 'TEMPLATE_INVALID';
end if;
if upsert_template.template_id is not null then
select * into v_row from "better_supabase"."templates" x where x."id" = upsert_template.template_id for update;
if not found or v_row."tenant_id" is distinct from upsert_template.tenant then
raise exception 'No such template' using errcode = 'P0002', hint = 'TEMPLATE_NOT_FOUND';
end if;
end if;
if not (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or (upsert_template.tenant is not null and coalesce(better_supabase.can('tenant', upsert_template.tenant, 'templates.manage'), false))) then
raise exception 'You may not change templates here' using errcode = '42501', hint = 'TEMPLATE_FORBIDDEN';
end if;
if upsert_template.template_id is null and (upsert_template.type is null or upsert_template.type !~ '^[a-z][a-z0-9_.-]{0,63}$') then
raise exception 'type must be lower-case letters, digits, dots, dashes or underscores' using errcode = '22023', hint = 'TEMPLATE_INVALID';
end if;
if upsert_template.template_id is null and upsert_template.name is null then
raise exception 'A template needs a name' using errcode = '22023', hint = 'TEMPLATE_INVALID';
end if;
declare
v_hook regprocedure := to_regprocedure('"public"."before_template_save"(uuid, text, jsonb)');
begin
if v_hook is not null then
execute format('select %s($1::uuid, $2::text, $3::jsonb)', v_hook::oid::regproc)
using upsert_template.tenant, coalesce(upsert_template.type, v_row."type"), upsert_template.settings;
end if;
end;
if upsert_template.template_id is null then
insert into "better_supabase"."templates" ("tenant_id", "scope", "type", "name", "language", "settings", "created_by")
values (
upsert_template.tenant,
case when upsert_template.tenant is null then 'system' else 'tenant' end,
upsert_template.type,
upsert_template.name,
coalesce(upsert_template.language, 'en'),
coalesce(upsert_template.settings, '{}'::jsonb),
(select auth.uid())
)
returning * into v_row;
else
update "better_supabase"."templates" x set
"name" = coalesce(upsert_template.name, x."name"),
"language" = coalesce(upsert_template.language, x."language"),
"settings" = coalesce(upsert_template.settings, x."settings"),
"is_default" = x."is_default" and coalesce(upsert_template.language, x."language") = x."language",
"updated_at" = now()
where x."id" = upsert_template.template_id
returning * into v_row;
end if;
declare
v_hook regprocedure := to_regprocedure('"public"."after_template_save"(uuid)');
begin
if v_hook is not null then
execute format('select %s($1::uuid)', v_hook::oid::regproc)
using v_row."id";
end if;
end;
return jsonb_build_object(
'id', v_row."id",
'tenant', v_row."tenant_id",
'scope', v_row."scope",
'key', v_row."key",
'type', v_row."type",
'name', v_row."name",
'language', v_row."language",
'isDefault', v_row."is_default",
'settings', v_row."settings",
'forkedFrom', v_row."forked_from",
'forkedFromVersion', v_row."forked_from_version",
'publishedVersion', (select y."version" from "better_supabase"."template_versions" y where y."template_id" = v_row."id" and y."published_at" is not null order by y."version" desc limit 1),
'upstreamVersion', case when v_row."forked_from" is not null then (select y."version" from "better_supabase"."template_versions" y where y."template_id" = v_row."forked_from" and y."published_at" is not null order by y."version" desc limit 1) end,
'createdBy', v_row."created_by",
'createdAt', v_row."created_at",
'updatedAt', v_row."updated_at"
);
end;
$$;
revoke execute on function "better_supabase"."upsert_template"(uuid, uuid, text, text, text, jsonb) from public, anon;
grant execute on function "better_supabase"."upsert_template"(uuid, uuid, text, text, text, jsonb) to authenticated, service_role;
-- The tenant's templates and the system ones (only the system ones without
-- a tenant), filtered by type and language, defaults first.
create or replace function "better_supabase"."templates_list"(tenant uuid, type text, language text)
returns jsonb
language sql
stable
security invoker
set search_path = ''
as $$
select coalesce(jsonb_agg(jsonb_build_object(
'id', x."id",
'tenant', x."tenant_id",
'scope', x."scope",
'key', x."key",
'type', x."type",
'name', x."name",
'language', x."language",
'isDefault', x."is_default",
'settings', x."settings",
'forkedFrom', x."forked_from",
'forkedFromVersion', x."forked_from_version",
'publishedVersion', (select y."version" from "better_supabase"."template_versions" y where y."template_id" = x."id" and y."published_at" is not null order by y."version" desc limit 1),
'upstreamVersion', case when x."forked_from" is not null then (select y."version" from "better_supabase"."template_versions" y where y."template_id" = x."forked_from" and y."published_at" is not null order by y."version" desc limit 1) end,
'createdBy', x."created_by",
'createdAt', x."created_at",
'updatedAt', x."updated_at"
)
order by x."is_default" desc, x."scope" desc, x."name", x."id"), '[]'::jsonb)
from "better_supabase"."templates" x
where (x."scope" = 'system' or x."tenant_id" = templates_list.tenant)
and (templates_list.type is null or x."type" = templates_list.type)
and (templates_list.language is null or x."language" = templates_list.language)
$$;
revoke execute on function "better_supabase"."templates_list"(uuid, text, text) from public, anon;
grant execute on function "better_supabase"."templates_list"(uuid, text, text) to authenticated, service_role;
-- A keyset page of the templates the tenant sees: its own, its brand's and the
-- system starters, by name (ADR 1077). Row security decides what the caller
-- sees. filters is { type, language, scope, isDefault (each a value or a list),
-- search, sort (name, createdAt, updatedAt), direction, facet, count, limit,
-- after, offset, paged, total, totalCap }.
create or replace function "better_supabase"."page_templates"(tenant uuid, filters jsonb default '{}')
returns jsonb
language plpgsql
stable
security invoker
set search_path = ''
as $$
#variable_conflict use_variable
declare
v_filters jsonb := coalesce(page_templates.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 v_filters ? 'after' and v_filters ? 'offset' then
raise exception 'after and offset are two ways to page; pass one' using errcode = '22023', hint = 'TEMPLATE_INVALID';
end if;
if v_facet is not null then
if v_facet not in ('type', 'language', 'scope') then
raise exception 'facet is one of type, language, scope' using errcode = '22023', hint = 'TEMPLATE_INVALID';
end if;
with s as (
select (case v_facet when 'type' then (x."type")::text when 'language' then (x."language")::text when 'scope' then (x."scope")::text end) as v
from "better_supabase"."templates" x
where (x."scope" = 'system' or x."tenant_id" = page_templates.tenant)
and (not (v_filters -> 'type' is not null and jsonb_typeof(v_filters -> 'type') <> 'null' and not (jsonb_typeof(v_filters -> 'type') = 'array' and jsonb_array_length(v_filters -> 'type') = 0)) or (x."type")::text = any((case when jsonb_typeof(v_filters -> 'type') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'type')) else array[v_filters ->> 'type'] end)::text[]))
and (not (v_filters -> 'language' is not null and jsonb_typeof(v_filters -> 'language') <> 'null' and not (jsonb_typeof(v_filters -> 'language') = 'array' and jsonb_array_length(v_filters -> 'language') = 0)) or (x."language")::text = any((case when jsonb_typeof(v_filters -> 'language') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'language')) else array[v_filters ->> 'language'] end)::text[]))
and (not (v_filters -> 'scope' is not null and jsonb_typeof(v_filters -> 'scope') <> 'null' and not (jsonb_typeof(v_filters -> 'scope') = 'array' and jsonb_array_length(v_filters -> 'scope') = 0)) or (x."scope")::text = any((case when jsonb_typeof(v_filters -> 'scope') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'scope')) else array[v_filters ->> 'scope'] end)::text[]))
and (not (v_filters -> 'isDefault' is not null and jsonb_typeof(v_filters -> 'isDefault') <> 'null' and not (jsonb_typeof(v_filters -> 'isDefault') = 'array' and jsonb_array_length(v_filters -> 'isDefault') = 0)) or x."is_default"::text = any((case when jsonb_typeof(v_filters -> 'isDefault') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'isDefault')) else array[v_filters ->> 'isDefault'] end)::text[]))
and (v_search is null or x."name" ilike v_search or x."key" 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"."templates" x
where (x."scope" = 'system' or x."tenant_id" = page_templates.tenant)
and (not (v_filters -> 'type' is not null and jsonb_typeof(v_filters -> 'type') <> 'null' and not (jsonb_typeof(v_filters -> 'type') = 'array' and jsonb_array_length(v_filters -> 'type') = 0)) or (x."type")::text = any((case when jsonb_typeof(v_filters -> 'type') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'type')) else array[v_filters ->> 'type'] end)::text[]))
and (not (v_filters -> 'language' is not null and jsonb_typeof(v_filters -> 'language') <> 'null' and not (jsonb_typeof(v_filters -> 'language') = 'array' and jsonb_array_length(v_filters -> 'language') = 0)) or (x."language")::text = any((case when jsonb_typeof(v_filters -> 'language') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'language')) else array[v_filters ->> 'language'] end)::text[]))
and (not (v_filters -> 'scope' is not null and jsonb_typeof(v_filters -> 'scope') <> 'null' and not (jsonb_typeof(v_filters -> 'scope') = 'array' and jsonb_array_length(v_filters -> 'scope') = 0)) or (x."scope")::text = any((case when jsonb_typeof(v_filters -> 'scope') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'scope')) else array[v_filters ->> 'scope'] end)::text[]))
and (not (v_filters -> 'isDefault' is not null and jsonb_typeof(v_filters -> 'isDefault') <> 'null' and not (jsonb_typeof(v_filters -> 'isDefault') = 'array' and jsonb_array_length(v_filters -> 'isDefault') = 0)) or x."is_default"::text = any((case when jsonb_typeof(v_filters -> 'isDefault') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'isDefault')) else array[v_filters ->> 'isDefault'] end)::text[]))
and (v_search is null or x."name" ilike v_search or x."key" 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', 'updatedAt') then
raise exception 'sort is one of name, createdAt, updatedAt' using errcode = '22023', hint = 'TEMPLATE_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 = 'TEMPLATE_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 = 'TEMPLATE_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",
'tenant', x."tenant_id",
'scope', x."scope",
'key', x."key",
'type', x."type",
'name', x."name",
'language', x."language",
'isDefault', x."is_default",
'settings', x."settings",
'forkedFrom', x."forked_from",
'forkedFromVersion', x."forked_from_version",
'publishedVersion', (select y."version" from "better_supabase"."template_versions" y where y."template_id" = x."id" and y."published_at" is not null order by y."version" desc limit 1),
'upstreamVersion', case when x."forked_from" is not null then (select y."version" from "better_supabase"."template_versions" y where y."template_id" = x."forked_from" and y."published_at" is not null order by y."version" desc limit 1) end,
'createdBy', x."created_by",
'createdAt', x."created_at",
'updatedAt', x."updated_at"
) as j, jsonb_build_array((lower(x."name"))::text, (x."id")::text) as k
from (
select * from "better_supabase"."templates" x
where (x."scope" = 'system' or x."tenant_id" = page_templates.tenant)
and (not (v_filters -> 'type' is not null and jsonb_typeof(v_filters -> 'type') <> 'null' and not (jsonb_typeof(v_filters -> 'type') = 'array' and jsonb_array_length(v_filters -> 'type') = 0)) or (x."type")::text = any((case when jsonb_typeof(v_filters -> 'type') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'type')) else array[v_filters ->> 'type'] end)::text[]))
and (not (v_filters -> 'language' is not null and jsonb_typeof(v_filters -> 'language') <> 'null' and not (jsonb_typeof(v_filters -> 'language') = 'array' and jsonb_array_length(v_filters -> 'language') = 0)) or (x."language")::text = any((case when jsonb_typeof(v_filters -> 'language') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'language')) else array[v_filters ->> 'language'] end)::text[]))
and (not (v_filters -> 'scope' is not null and jsonb_typeof(v_filters -> 'scope') <> 'null' and not (jsonb_typeof(v_filters -> 'scope') = 'array' and jsonb_array_length(v_filters -> 'scope') = 0)) or (x."scope")::text = any((case when jsonb_typeof(v_filters -> 'scope') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'scope')) else array[v_filters ->> 'scope'] end)::text[]))
and (not (v_filters -> 'isDefault' is not null and jsonb_typeof(v_filters -> 'isDefault') <> 'null' and not (jsonb_typeof(v_filters -> 'isDefault') = 'array' and jsonb_array_length(v_filters -> 'isDefault') = 0)) or x."is_default"::text = any((case when jsonb_typeof(v_filters -> 'isDefault') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'isDefault')) else array[v_filters ->> 'isDefault'] end)::text[]))
and (v_search is null or x."name" ilike v_search or x."key" 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 = 'TEMPLATE_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",
'tenant', x."tenant_id",
'scope', x."scope",
'key', x."key",
'type', x."type",
'name', x."name",
'language', x."language",
'isDefault', x."is_default",
'settings', x."settings",
'forkedFrom', x."forked_from",
'forkedFromVersion', x."forked_from_version",
'publishedVersion', (select y."version" from "better_supabase"."template_versions" y where y."template_id" = x."id" and y."published_at" is not null order by y."version" desc limit 1),
'upstreamVersion', case when x."forked_from" is not null then (select y."version" from "better_supabase"."template_versions" y where y."template_id" = x."forked_from" and y."published_at" is not null order by y."version" desc limit 1) end,
'createdBy', x."created_by",
'createdAt', x."created_at",
'updatedAt', x."updated_at"
) as j, jsonb_build_array((lower(x."name"))::text, (x."id")::text) as k
from (
select * from "better_supabase"."templates" x
where (x."scope" = 'system' or x."tenant_id" = page_templates.tenant)
and (not (v_filters -> 'type' is not null and jsonb_typeof(v_filters -> 'type') <> 'null' and not (jsonb_typeof(v_filters -> 'type') = 'array' and jsonb_array_length(v_filters -> 'type') = 0)) or (x."type")::text = any((case when jsonb_typeof(v_filters -> 'type') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'type')) else array[v_filters ->> 'type'] end)::text[]))
and (not (v_filters -> 'language' is not null and jsonb_typeof(v_filters -> 'language') <> 'null' and not (jsonb_typeof(v_filters -> 'language') = 'array' and jsonb_array_length(v_filters -> 'language') = 0)) or (x."language")::text = any((case when jsonb_typeof(v_filters -> 'language') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'language')) else array[v_filters ->> 'language'] end)::text[]))
and (not (v_filters -> 'scope' is not null and jsonb_typeof(v_filters -> 'scope') <> 'null' and not (jsonb_typeof(v_filters -> 'scope') = 'array' and jsonb_array_length(v_filters -> 'scope') = 0)) or (x."scope")::text = any((case when jsonb_typeof(v_filters -> 'scope') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'scope')) else array[v_filters ->> 'scope'] end)::text[]))
and (not (v_filters -> 'isDefault' is not null and jsonb_typeof(v_filters -> 'isDefault') <> 'null' and not (jsonb_typeof(v_filters -> 'isDefault') = 'array' and jsonb_array_length(v_filters -> 'isDefault') = 0)) or x."is_default"::text = any((case when jsonb_typeof(v_filters -> 'isDefault') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'isDefault')) else array[v_filters ->> 'isDefault'] end)::text[]))
and (v_search is null or x."name" ilike v_search or x."key" 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 = 'TEMPLATE_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",
'tenant', x."tenant_id",
'scope', x."scope",
'key', x."key",
'type', x."type",
'name', x."name",
'language', x."language",
'isDefault', x."is_default",
'settings', x."settings",
'forkedFrom', x."forked_from",
'forkedFromVersion', x."forked_from_version",
'publishedVersion', (select y."version" from "better_supabase"."template_versions" y where y."template_id" = x."id" and y."published_at" is not null order by y."version" desc limit 1),
'upstreamVersion', case when x."forked_from" is not null then (select y."version" from "better_supabase"."template_versions" y where y."template_id" = x."forked_from" and y."published_at" is not null order by y."version" desc limit 1) end,
'createdBy', x."created_by",
'createdAt', x."created_at",
'updatedAt', x."updated_at"
) as j, jsonb_build_array((lower(x."name"))::text, (x."id")::text) as k
from (
select * from "better_supabase"."templates" x
where (x."scope" = 'system' or x."tenant_id" = page_templates.tenant)
and (not (v_filters -> 'type' is not null and jsonb_typeof(v_filters -> 'type') <> 'null' and not (jsonb_typeof(v_filters -> 'type') = 'array' and jsonb_array_length(v_filters -> 'type') = 0)) or (x."type")::text = any((case when jsonb_typeof(v_filters -> 'type') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'type')) else array[v_filters ->> 'type'] end)::text[]))
and (not (v_filters -> 'language' is not null and jsonb_typeof(v_filters -> 'language') <> 'null' and not (jsonb_typeof(v_filters -> 'language') = 'array' and jsonb_array_length(v_filters -> 'language') = 0)) or (x."language")::text = any((case when jsonb_typeof(v_filters -> 'language') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'language')) else array[v_filters ->> 'language'] end)::text[]))
and (not (v_filters -> 'scope' is not null and jsonb_typeof(v_filters -> 'scope') <> 'null' and not (jsonb_typeof(v_filters -> 'scope') = 'array' and jsonb_array_length(v_filters -> 'scope') = 0)) or (x."scope")::text = any((case when jsonb_typeof(v_filters -> 'scope') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'scope')) else array[v_filters ->> 'scope'] end)::text[]))
and (not (v_filters -> 'isDefault' is not null and jsonb_typeof(v_filters -> 'isDefault') <> 'null' and not (jsonb_typeof(v_filters -> 'isDefault') = 'array' and jsonb_array_length(v_filters -> 'isDefault') = 0)) or x."is_default"::text = any((case when jsonb_typeof(v_filters -> 'isDefault') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'isDefault')) else array[v_filters ->> 'isDefault'] end)::text[]))
and (v_search is null or x."name" ilike v_search or x."key" 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 = 'TEMPLATE_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",
'tenant', x."tenant_id",
'scope', x."scope",
'key', x."key",
'type', x."type",
'name', x."name",
'language', x."language",
'isDefault', x."is_default",
'settings', x."settings",
'forkedFrom', x."forked_from",
'forkedFromVersion', x."forked_from_version",
'publishedVersion', (select y."version" from "better_supabase"."template_versions" y where y."template_id" = x."id" and y."published_at" is not null order by y."version" desc limit 1),
'upstreamVersion', case when x."forked_from" is not null then (select y."version" from "better_supabase"."template_versions" y where y."template_id" = x."forked_from" and y."published_at" is not null order by y."version" desc limit 1) end,
'createdBy', x."created_by",
'createdAt', x."created_at",
'updatedAt', x."updated_at"
) as j, jsonb_build_array((lower(x."name"))::text, (x."id")::text) as k
from (
select * from "better_supabase"."templates" x
where (x."scope" = 'system' or x."tenant_id" = page_templates.tenant)
and (not (v_filters -> 'type' is not null and jsonb_typeof(v_filters -> 'type') <> 'null' and not (jsonb_typeof(v_filters -> 'type') = 'array' and jsonb_array_length(v_filters -> 'type') = 0)) or (x."type")::text = any((case when jsonb_typeof(v_filters -> 'type') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'type')) else array[v_filters ->> 'type'] end)::text[]))
and (not (v_filters -> 'language' is not null and jsonb_typeof(v_filters -> 'language') <> 'null' and not (jsonb_typeof(v_filters -> 'language') = 'array' and jsonb_array_length(v_filters -> 'language') = 0)) or (x."language")::text = any((case when jsonb_typeof(v_filters -> 'language') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'language')) else array[v_filters ->> 'language'] end)::text[]))
and (not (v_filters -> 'scope' is not null and jsonb_typeof(v_filters -> 'scope') <> 'null' and not (jsonb_typeof(v_filters -> 'scope') = 'array' and jsonb_array_length(v_filters -> 'scope') = 0)) or (x."scope")::text = any((case when jsonb_typeof(v_filters -> 'scope') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'scope')) else array[v_filters ->> 'scope'] end)::text[]))
and (not (v_filters -> 'isDefault' is not null and jsonb_typeof(v_filters -> 'isDefault') <> 'null' and not (jsonb_typeof(v_filters -> 'isDefault') = 'array' and jsonb_array_length(v_filters -> 'isDefault') = 0)) or x."is_default"::text = any((case when jsonb_typeof(v_filters -> 'isDefault') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'isDefault')) else array[v_filters ->> 'isDefault'] end)::text[]))
and (v_search is null or x."name" ilike v_search or x."key" 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 = 'TEMPLATE_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",
'tenant', x."tenant_id",
'scope', x."scope",
'key', x."key",
'type', x."type",
'name', x."name",
'language', x."language",
'isDefault', x."is_default",
'settings', x."settings",
'forkedFrom', x."forked_from",
'forkedFromVersion', x."forked_from_version",
'publishedVersion', (select y."version" from "better_supabase"."template_versions" y where y."template_id" = x."id" and y."published_at" is not null order by y."version" desc limit 1),
'upstreamVersion', case when x."forked_from" is not null then (select y."version" from "better_supabase"."template_versions" y where y."template_id" = x."forked_from" and y."published_at" is not null order by y."version" desc limit 1) end,
'createdBy', x."created_by",
'createdAt', x."created_at",
'updatedAt', x."updated_at"
) as j, jsonb_build_array((x."created_at")::text, (x."id")::text) as k
from (
select * from "better_supabase"."templates" x
where (x."scope" = 'system' or x."tenant_id" = page_templates.tenant)
and (not (v_filters -> 'type' is not null and jsonb_typeof(v_filters -> 'type') <> 'null' and not (jsonb_typeof(v_filters -> 'type') = 'array' and jsonb_array_length(v_filters -> 'type') = 0)) or (x."type")::text = any((case when jsonb_typeof(v_filters -> 'type') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'type')) else array[v_filters ->> 'type'] end)::text[]))
and (not (v_filters -> 'language' is not null and jsonb_typeof(v_filters -> 'language') <> 'null' and not (jsonb_typeof(v_filters -> 'language') = 'array' and jsonb_array_length(v_filters -> 'language') = 0)) or (x."language")::text = any((case when jsonb_typeof(v_filters -> 'language') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'language')) else array[v_filters ->> 'language'] end)::text[]))
and (not (v_filters -> 'scope' is not null and jsonb_typeof(v_filters -> 'scope') <> 'null' and not (jsonb_typeof(v_filters -> 'scope') = 'array' and jsonb_array_length(v_filters -> 'scope') = 0)) or (x."scope")::text = any((case when jsonb_typeof(v_filters -> 'scope') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'scope')) else array[v_filters ->> 'scope'] end)::text[]))
and (not (v_filters -> 'isDefault' is not null and jsonb_typeof(v_filters -> 'isDefault') <> 'null' and not (jsonb_typeof(v_filters -> 'isDefault') = 'array' and jsonb_array_length(v_filters -> 'isDefault') = 0)) or x."is_default"::text = any((case when jsonb_typeof(v_filters -> 'isDefault') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'isDefault')) else array[v_filters ->> 'isDefault'] end)::text[]))
and (v_search is null or x."name" ilike v_search or x."key" 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 = 'TEMPLATE_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",
'tenant', x."tenant_id",
'scope', x."scope",
'key', x."key",
'type', x."type",
'name', x."name",
'language', x."language",
'isDefault', x."is_default",
'settings', x."settings",
'forkedFrom', x."forked_from",
'forkedFromVersion', x."forked_from_version",
'publishedVersion', (select y."version" from "better_supabase"."template_versions" y where y."template_id" = x."id" and y."published_at" is not null order by y."version" desc limit 1),
'upstreamVersion', case when x."forked_from" is not null then (select y."version" from "better_supabase"."template_versions" y where y."template_id" = x."forked_from" and y."published_at" is not null order by y."version" desc limit 1) end,
'createdBy', x."created_by",
'createdAt', x."created_at",
'updatedAt', x."updated_at"
) as j, jsonb_build_array((x."created_at")::text, (x."id")::text) as k
from (
select * from "better_supabase"."templates" x
where (x."scope" = 'system' or x."tenant_id" = page_templates.tenant)
and (not (v_filters -> 'type' is not null and jsonb_typeof(v_filters -> 'type') <> 'null' and not (jsonb_typeof(v_filters -> 'type') = 'array' and jsonb_array_length(v_filters -> 'type') = 0)) or (x."type")::text = any((case when jsonb_typeof(v_filters -> 'type') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'type')) else array[v_filters ->> 'type'] end)::text[]))
and (not (v_filters -> 'language' is not null and jsonb_typeof(v_filters -> 'language') <> 'null' and not (jsonb_typeof(v_filters -> 'language') = 'array' and jsonb_array_length(v_filters -> 'language') = 0)) or (x."language")::text = any((case when jsonb_typeof(v_filters -> 'language') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'language')) else array[v_filters ->> 'language'] end)::text[]))
and (not (v_filters -> 'scope' is not null and jsonb_typeof(v_filters -> 'scope') <> 'null' and not (jsonb_typeof(v_filters -> 'scope') = 'array' and jsonb_array_length(v_filters -> 'scope') = 0)) or (x."scope")::text = any((case when jsonb_typeof(v_filters -> 'scope') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'scope')) else array[v_filters ->> 'scope'] end)::text[]))
and (not (v_filters -> 'isDefault' is not null and jsonb_typeof(v_filters -> 'isDefault') <> 'null' and not (jsonb_typeof(v_filters -> 'isDefault') = 'array' and jsonb_array_length(v_filters -> 'isDefault') = 0)) or x."is_default"::text = any((case when jsonb_typeof(v_filters -> 'isDefault') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'isDefault')) else array[v_filters ->> 'isDefault'] end)::text[]))
and (v_search is null or x."name" ilike v_search or x."key" 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;
elsif v_sort = 'updatedAt' 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 = 'TEMPLATE_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",
'tenant', x."tenant_id",
'scope', x."scope",
'key', x."key",
'type', x."type",
'name', x."name",
'language', x."language",
'isDefault', x."is_default",
'settings', x."settings",
'forkedFrom', x."forked_from",
'forkedFromVersion', x."forked_from_version",
'publishedVersion', (select y."version" from "better_supabase"."template_versions" y where y."template_id" = x."id" and y."published_at" is not null order by y."version" desc limit 1),
'upstreamVersion', case when x."forked_from" is not null then (select y."version" from "better_supabase"."template_versions" y where y."template_id" = x."forked_from" and y."published_at" is not null order by y."version" desc limit 1) end,
'createdBy', x."created_by",
'createdAt', x."created_at",
'updatedAt', x."updated_at"
) as j, jsonb_build_array((x."updated_at")::text, (x."id")::text) as k
from (
select * from "better_supabase"."templates" x
where (x."scope" = 'system' or x."tenant_id" = page_templates.tenant)
and (not (v_filters -> 'type' is not null and jsonb_typeof(v_filters -> 'type') <> 'null' and not (jsonb_typeof(v_filters -> 'type') = 'array' and jsonb_array_length(v_filters -> 'type') = 0)) or (x."type")::text = any((case when jsonb_typeof(v_filters -> 'type') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'type')) else array[v_filters ->> 'type'] end)::text[]))
and (not (v_filters -> 'language' is not null and jsonb_typeof(v_filters -> 'language') <> 'null' and not (jsonb_typeof(v_filters -> 'language') = 'array' and jsonb_array_length(v_filters -> 'language') = 0)) or (x."language")::text = any((case when jsonb_typeof(v_filters -> 'language') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'language')) else array[v_filters ->> 'language'] end)::text[]))
and (not (v_filters -> 'scope' is not null and jsonb_typeof(v_filters -> 'scope') <> 'null' and not (jsonb_typeof(v_filters -> 'scope') = 'array' and jsonb_array_length(v_filters -> 'scope') = 0)) or (x."scope")::text = any((case when jsonb_typeof(v_filters -> 'scope') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'scope')) else array[v_filters ->> 'scope'] end)::text[]))
and (not (v_filters -> 'isDefault' is not null and jsonb_typeof(v_filters -> 'isDefault') <> 'null' and not (jsonb_typeof(v_filters -> 'isDefault') = 'array' and jsonb_array_length(v_filters -> 'isDefault') = 0)) or x."is_default"::text = any((case when jsonb_typeof(v_filters -> 'isDefault') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'isDefault')) else array[v_filters ->> 'isDefault'] end)::text[]))
and (v_search is null or x."name" ilike v_search or x."key" ilike v_search)
and (v_after is null or (x."updated_at", x."id") > ((v_after ->> 0)::timestamptz, (v_after ->> 1)::uuid))
order by x."updated_at" asc, x."id" asc
limit v_limit + 1 offset v_offset
) x
) p;
elsif v_sort = 'updatedAt' 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 = 'TEMPLATE_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",
'tenant', x."tenant_id",
'scope', x."scope",
'key', x."key",
'type', x."type",
'name', x."name",
'language', x."language",
'isDefault', x."is_default",
'settings', x."settings",
'forkedFrom', x."forked_from",
'forkedFromVersion', x."forked_from_version",
'publishedVersion', (select y."version" from "better_supabase"."template_versions" y where y."template_id" = x."id" and y."published_at" is not null order by y."version" desc limit 1),
'upstreamVersion', case when x."forked_from" is not null then (select y."version" from "better_supabase"."template_versions" y where y."template_id" = x."forked_from" and y."published_at" is not null order by y."version" desc limit 1) end,
'createdBy', x."created_by",
'createdAt', x."created_at",
'updatedAt', x."updated_at"
) as j, jsonb_build_array((x."updated_at")::text, (x."id")::text) as k
from (
select * from "better_supabase"."templates" x
where (x."scope" = 'system' or x."tenant_id" = page_templates.tenant)
and (not (v_filters -> 'type' is not null and jsonb_typeof(v_filters -> 'type') <> 'null' and not (jsonb_typeof(v_filters -> 'type') = 'array' and jsonb_array_length(v_filters -> 'type') = 0)) or (x."type")::text = any((case when jsonb_typeof(v_filters -> 'type') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'type')) else array[v_filters ->> 'type'] end)::text[]))
and (not (v_filters -> 'language' is not null and jsonb_typeof(v_filters -> 'language') <> 'null' and not (jsonb_typeof(v_filters -> 'language') = 'array' and jsonb_array_length(v_filters -> 'language') = 0)) or (x."language")::text = any((case when jsonb_typeof(v_filters -> 'language') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'language')) else array[v_filters ->> 'language'] end)::text[]))
and (not (v_filters -> 'scope' is not null and jsonb_typeof(v_filters -> 'scope') <> 'null' and not (jsonb_typeof(v_filters -> 'scope') = 'array' and jsonb_array_length(v_filters -> 'scope') = 0)) or (x."scope")::text = any((case when jsonb_typeof(v_filters -> 'scope') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'scope')) else array[v_filters ->> 'scope'] end)::text[]))
and (not (v_filters -> 'isDefault' is not null and jsonb_typeof(v_filters -> 'isDefault') <> 'null' and not (jsonb_typeof(v_filters -> 'isDefault') = 'array' and jsonb_array_length(v_filters -> 'isDefault') = 0)) or x."is_default"::text = any((case when jsonb_typeof(v_filters -> 'isDefault') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'isDefault')) else array[v_filters ->> 'isDefault'] end)::text[]))
and (v_search is null or x."name" ilike v_search or x."key" ilike v_search)
and (v_after is null or (x."updated_at" <= (v_after ->> 0)::timestamptz and ((x."updated_at" < (v_after ->> 0)::timestamptz) or (x."updated_at" = (v_after ->> 0)::timestamptz and x."id" > (v_after ->> 1)::uuid))))
order by x."updated_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"."templates" x
where (x."scope" = 'system' or x."tenant_id" = page_templates.tenant)
and (not (v_filters -> 'type' is not null and jsonb_typeof(v_filters -> 'type') <> 'null' and not (jsonb_typeof(v_filters -> 'type') = 'array' and jsonb_array_length(v_filters -> 'type') = 0)) or (x."type")::text = any((case when jsonb_typeof(v_filters -> 'type') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'type')) else array[v_filters ->> 'type'] end)::text[]))
and (not (v_filters -> 'language' is not null and jsonb_typeof(v_filters -> 'language') <> 'null' and not (jsonb_typeof(v_filters -> 'language') = 'array' and jsonb_array_length(v_filters -> 'language') = 0)) or (x."language")::text = any((case when jsonb_typeof(v_filters -> 'language') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'language')) else array[v_filters ->> 'language'] end)::text[]))
and (not (v_filters -> 'scope' is not null and jsonb_typeof(v_filters -> 'scope') <> 'null' and not (jsonb_typeof(v_filters -> 'scope') = 'array' and jsonb_array_length(v_filters -> 'scope') = 0)) or (x."scope")::text = any((case when jsonb_typeof(v_filters -> 'scope') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'scope')) else array[v_filters ->> 'scope'] end)::text[]))
and (not (v_filters -> 'isDefault' is not null and jsonb_typeof(v_filters -> 'isDefault') <> 'null' and not (jsonb_typeof(v_filters -> 'isDefault') = 'array' and jsonb_array_length(v_filters -> 'isDefault') = 0)) or x."is_default"::text = any((case when jsonb_typeof(v_filters -> 'isDefault') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'isDefault')) else array[v_filters ->> 'isDefault'] end)::text[]))
and (v_search is null or x."name" ilike v_search or x."key" 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_templates"(uuid, jsonb) from public, anon;
grant execute on function "better_supabase"."page_templates"(uuid, jsonb) to authenticated, service_role;
-- One template with its newest published version and its draft, bodies
-- included; null when the caller can't read it.
create or replace function "better_supabase"."template_get"(template_id uuid)
returns jsonb
language sql
stable
security invoker
set search_path = ''
as $$
select jsonb_build_object(
'id', x."id",
'tenant', x."tenant_id",
'scope', x."scope",
'key', x."key",
'type', x."type",
'name', x."name",
'language', x."language",
'isDefault', x."is_default",
'settings', x."settings",
'forkedFrom', x."forked_from",
'forkedFromVersion', x."forked_from_version",
'publishedVersion', (select y."version" from "better_supabase"."template_versions" y where y."template_id" = x."id" and y."published_at" is not null order by y."version" desc limit 1),
'upstreamVersion', case when x."forked_from" is not null then (select y."version" from "better_supabase"."template_versions" y where y."template_id" = x."forked_from" and y."published_at" is not null order by y."version" desc limit 1) end,
'createdBy', x."created_by",
'createdAt', x."created_at",
'updatedAt', x."updated_at"
) || jsonb_build_object(
'published', (select jsonb_build_object(
'id', y."id",
'template', y."template_id",
'version', y."version",
'hash', y."hash",
'publishedAt', y."published_at",
'createdBy', y."created_by",
'createdAt', y."created_at",
'body', y."body"
) from "better_supabase"."template_versions" y
where y."template_id" = x."id" and y."published_at" is not null
order by y."version" desc limit 1),
'draft', (select jsonb_build_object(
'id', y."id",
'template', y."template_id",
'version', y."version",
'hash', y."hash",
'publishedAt', y."published_at",
'createdBy', y."created_by",
'createdAt', y."created_at",
'body', y."body"
) from "better_supabase"."template_versions" y
where y."template_id" = x."id" and y."published_at" is null))
from "better_supabase"."templates" x
where x."id" = template_get.template_id
$$;
revoke execute on function "better_supabase"."template_get"(uuid) from public, anon;
grant execute on function "better_supabase"."template_get"(uuid) to authenticated, service_role;
-- Many templates with their newest published version and draft in one read,
-- in the order requested. One the caller can't read has no entry.
create or replace function "better_supabase"."templates_get_many"(template_ids uuid[])
returns jsonb
language sql
stable
security invoker
set search_path = ''
as $$
select coalesce(jsonb_agg(jsonb_build_object(
'id', x."id",
'tenant', x."tenant_id",
'scope', x."scope",
'key', x."key",
'type', x."type",
'name', x."name",
'language', x."language",
'isDefault', x."is_default",
'settings', x."settings",
'forkedFrom', x."forked_from",
'forkedFromVersion', x."forked_from_version",
'publishedVersion', (select y."version" from "better_supabase"."template_versions" y where y."template_id" = x."id" and y."published_at" is not null order by y."version" desc limit 1),
'upstreamVersion', case when x."forked_from" is not null then (select y."version" from "better_supabase"."template_versions" y where y."template_id" = x."forked_from" and y."published_at" is not null order by y."version" desc limit 1) end,
'createdBy', x."created_by",
'createdAt', x."created_at",
'updatedAt', x."updated_at"
) || jsonb_build_object(
'published', (select jsonb_build_object(
'id', y."id",
'template', y."template_id",
'version', y."version",
'hash', y."hash",
'publishedAt', y."published_at",
'createdBy', y."created_by",
'createdAt', y."created_at",
'body', y."body"
) from "better_supabase"."template_versions" y
where y."template_id" = x."id" and y."published_at" is not null
order by y."version" desc limit 1),
'draft', (select jsonb_build_object(
'id', y."id",
'template', y."template_id",
'version', y."version",
'hash', y."hash",
'publishedAt', y."published_at",
'createdBy', y."created_by",
'createdAt', y."created_at",
'body', y."body"
) from "better_supabase"."template_versions" y
where y."template_id" = x."id" and y."published_at" is null))
order by array_position(templates_get_many.template_ids, x."id")), '[]'::jsonb)
from "better_supabase"."templates" x
where x."id" = any (templates_get_many.template_ids)
$$;
revoke execute on function "better_supabase"."templates_get_many"(uuid[]) from public, anon;
grant execute on function "better_supabase"."templates_get_many"(uuid[]) to authenticated, service_role;
create or replace function "better_supabase"."delete_template"(template_id uuid)
returns boolean
language plpgsql
security definer
set search_path = ''
as $$
#variable_conflict use_variable
declare
v_row "better_supabase"."templates"%rowtype;
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"."templates" x where x."id" = delete_template.template_id;
if not found then
return false;
end if;
if not (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or (v_row."tenant_id" is not null and coalesce(better_supabase.can('tenant', v_row."tenant_id", 'templates.manage'), false))) then
raise exception 'You may not remove this template' using errcode = '42501', hint = 'TEMPLATE_FORBIDDEN';
end if;
delete from "better_supabase"."templates" x where x."id" = delete_template.template_id;
return true;
end;
$$;
revoke execute on function "better_supabase"."delete_template"(uuid) from public, anon;
grant execute on function "better_supabase"."delete_template"(uuid) to authenticated, service_role;
-- Saves body as the template's draft: updates the open one, or opens one
-- numbered after the last version.
create or replace function "better_supabase"."upsert_template_draft"(template_id uuid, body jsonb)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
#variable_conflict use_variable
declare
v_tpl "better_supabase"."templates"%rowtype;
v_row "better_supabase"."template_versions"%rowtype;
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_tpl from "better_supabase"."templates" x where x."id" = upsert_template_draft.template_id for update;
if not found then
raise exception 'No such template' using errcode = 'P0002', hint = 'TEMPLATE_NOT_FOUND';
end if;
if not (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or (v_tpl."tenant_id" is not null and coalesce(better_supabase.can('tenant', v_tpl."tenant_id", 'templates.manage'), false))) then
raise exception 'You may not edit this template' using errcode = '42501', hint = 'TEMPLATE_FORBIDDEN';
end if;
if upsert_template_draft.body is null then
raise exception 'A template version needs a body' using errcode = '22023', hint = 'TEMPLATE_INVALID';
end if;
update "better_supabase"."template_versions" x set
"body" = upsert_template_draft.body,
"hash" = encode(extensions.digest(upsert_template_draft.body::text, 'sha256'), 'hex')
where x."template_id" = upsert_template_draft.template_id and x."published_at" is null
returning * into v_row;
if not found then
insert into "better_supabase"."template_versions" ("template_id", "version", "body", "hash", "created_by")
values (
upsert_template_draft.template_id,
coalesce((select max(y."version") from "better_supabase"."template_versions" y where y."template_id" = upsert_template_draft.template_id), 0) + 1,
upsert_template_draft.body,
encode(extensions.digest(upsert_template_draft.body::text, 'sha256'), 'hex'),
(select auth.uid())
)
returning * into v_row;
end if;
update "better_supabase"."templates" x set "updated_at" = now() where x."id" = upsert_template_draft.template_id;
return jsonb_build_object(
'id', v_row."id",
'template', v_row."template_id",
'version', v_row."version",
'hash', v_row."hash",
'publishedAt', v_row."published_at",
'createdBy', v_row."created_by",
'createdAt', v_row."created_at",
'body', v_row."body"
);
end;
$$;
revoke execute on function "better_supabase"."upsert_template_draft"(uuid, jsonb) from public, anon;
grant execute on function "better_supabase"."upsert_template_draft"(uuid, jsonb) to authenticated, service_role;
-- Publishes the template's draft. Applications use the newest published
-- version; published versions never change.
create or replace function "better_supabase"."publish_template_version"(template_id uuid)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
#variable_conflict use_variable
declare
v_tpl "better_supabase"."templates"%rowtype;
v_row "better_supabase"."template_versions"%rowtype;
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_tpl from "better_supabase"."templates" x where x."id" = publish_template_version.template_id for update;
if not found then
raise exception 'No such template' using errcode = 'P0002', hint = 'TEMPLATE_NOT_FOUND';
end if;
if not (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or (v_tpl."tenant_id" is not null and coalesce(better_supabase.can('tenant', v_tpl."tenant_id", 'templates.manage'), false))) then
raise exception 'You may not publish this template' using errcode = '42501', hint = 'TEMPLATE_FORBIDDEN';
end if;
update "better_supabase"."template_versions" x set "published_at" = now()
where x."template_id" = publish_template_version.template_id and x."published_at" is null
returning * into v_row;
if not found then
raise exception 'This template has no draft to publish' using errcode = 'P0002', hint = 'TEMPLATE_NO_DRAFT';
end if;
update "better_supabase"."templates" x set "updated_at" = now() where x."id" = publish_template_version.template_id;
null;
return jsonb_build_object(
'id', v_row."id",
'template', v_row."template_id",
'version', v_row."version",
'hash', v_row."hash",
'publishedAt', v_row."published_at",
'createdBy', v_row."created_by",
'createdAt', v_row."created_at",
'body', v_row."body"
);
end;
$$;
revoke execute on function "better_supabase"."publish_template_version"(uuid) from public, anon;
grant execute on function "better_supabase"."publish_template_version"(uuid) to authenticated, service_role;
create or replace function "better_supabase"."template_versions_list"(template_id uuid)
returns jsonb
language sql
stable
security invoker
set search_path = ''
as $$
select coalesce(jsonb_agg(jsonb_build_object(
'id', y."id",
'template', y."template_id",
'version', y."version",
'hash', y."hash",
'publishedAt', y."published_at",
'createdBy', y."created_by",
'createdAt', y."created_at"
) order by y."version" desc), '[]'::jsonb)
from "better_supabase"."template_versions" y where y."template_id" = template_versions_list.template_id
$$;
revoke execute on function "better_supabase"."template_versions_list"(uuid) from public, anon;
grant execute on function "better_supabase"."template_versions_list"(uuid) to authenticated, service_role;
-- One default per tenant, type and language.
create or replace function "better_supabase"."set_default_template"(template_id uuid, on_default boolean)
returns boolean
language plpgsql
security definer
set search_path = ''
as $$
#variable_conflict use_variable
declare
v_row "better_supabase"."templates"%rowtype;
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"."templates" x where x."id" = set_default_template.template_id for update;
if not found then
raise exception 'No such template' using errcode = 'P0002', hint = 'TEMPLATE_NOT_FOUND';
end if;
if not (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or (v_row."tenant_id" is not null and coalesce(better_supabase.can('tenant', v_row."tenant_id", 'templates.manage'), false))) then
raise exception 'You may not change this template' using errcode = '42501', hint = 'TEMPLATE_FORBIDDEN';
end if;
if set_default_template.on_default then
update "better_supabase"."templates" x set "is_default" = false, "updated_at" = now()
where (x."tenant_id" = v_row."tenant_id" or (x."tenant_id" is null and v_row."tenant_id" is null))
and x."type" = v_row."type" and x."language" = v_row."language"
and x."is_default" and x."id" <> v_row."id";
end if;
update "better_supabase"."templates" x set "is_default" = coalesce(set_default_template.on_default, false), "updated_at" = now()
where x."id" = set_default_template.template_id;
return true;
end;
$$;
revoke execute on function "better_supabase"."set_default_template"(uuid, boolean) from public, anon;
grant execute on function "better_supabase"."set_default_template"(uuid, boolean) to authenticated, service_role;
-- Copies the newest published version of source (a system template, or one
-- in tenant) into a new template in tenant, published as its version 1, and
-- records the version it copied. templates.manage in tenant.
create or replace function "better_supabase"."fork_template"(source uuid, tenant uuid)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
#variable_conflict use_variable
declare
v_src "better_supabase"."templates"%rowtype;
v_version "better_supabase"."template_versions"%rowtype;
v_row "better_supabase"."templates"%rowtype;
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_src from "better_supabase"."templates" x where x."id" = fork_template.source;
if not found or not (v_src."scope" = 'system' or v_src."tenant_id" = fork_template.tenant) then
raise exception 'No such template' using errcode = 'P0002', hint = 'TEMPLATE_NOT_FOUND';
end if;
if fork_template.tenant is null or not (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or (fork_template.tenant is not null and coalesce(better_supabase.can('tenant', fork_template.tenant, 'templates.manage'), false))) then
raise exception 'You may not create templates here' using errcode = '42501', hint = 'TEMPLATE_FORBIDDEN';
end if;
select * into v_version from "better_supabase"."template_versions" y
where y."template_id" = fork_template.source and y."published_at" is not null
order by y."version" desc limit 1;
if not found then
raise exception 'This template has no published version' using errcode = 'P0002', hint = 'TEMPLATE_NOT_PUBLISHED';
end if;
insert into "better_supabase"."templates" ("tenant_id", "scope", "type", "name", "language", "settings", "forked_from", "forked_from_version", "created_by")
values (fork_template.tenant, 'tenant', v_src."type", v_src."name", v_src."language", v_src."settings", v_src."id", v_version."version", (select auth.uid()))
returning * into v_row;
insert into "better_supabase"."template_versions" ("template_id", "version", "body", "hash", "published_at", "created_by")
values (v_row."id", 1, v_version."body", v_version."hash", now(), (select auth.uid()));
return jsonb_build_object(
'id', v_row."id",
'tenant', v_row."tenant_id",
'scope', v_row."scope",
'key', v_row."key",
'type', v_row."type",
'name', v_row."name",
'language', v_row."language",
'isDefault', v_row."is_default",
'settings', v_row."settings",
'forkedFrom', v_row."forked_from",
'forkedFromVersion', v_row."forked_from_version",
'publishedVersion', (select y."version" from "better_supabase"."template_versions" y where y."template_id" = v_row."id" and y."published_at" is not null order by y."version" desc limit 1),
'upstreamVersion', case when v_row."forked_from" is not null then (select y."version" from "better_supabase"."template_versions" y where y."template_id" = v_row."forked_from" and y."published_at" is not null order by y."version" desc limit 1) end,
'createdBy', v_row."created_by",
'createdAt', v_row."created_at",
'updatedAt', v_row."updated_at"
);
end;
$$;
revoke execute on function "better_supabase"."fork_template"(uuid, uuid) from public, anon;
grant execute on function "better_supabase"."fork_template"(uuid, uuid) to authenticated, service_role;
-- Upserts the system templates by key from starters, a JSON array of
-- { key, type, name, language?, settings?, body }, and publishes a new
-- version of each whose body changed. Returns how many it published.
create or replace function "better_supabase"."sync_templates"(starters jsonb)
returns integer
language plpgsql
security definer
set search_path = ''
as $$
#variable_conflict use_variable
declare
v_starter jsonb;
v_row "better_supabase"."templates"%rowtype;
v_hash text;
v_version "better_supabase"."template_versions"%rowtype;
v_count integer := 0;
begin
if jsonb_typeof(sync_templates.starters) <> 'array' then
raise exception 'starters must be an array' using errcode = '22023', hint = 'TEMPLATE_INVALID';
end if;
for v_starter in select value from jsonb_array_elements(sync_templates.starters) loop
if coalesce(v_starter ->> 'key', '') !~ '^[a-z0-9][a-z0-9_.-]{0,99}$' or not (v_starter ? 'body') then
raise exception 'Each starter needs a key and a body' using errcode = '22023', hint = 'TEMPLATE_INVALID';
end if;
if v_starter ? 'brand' then
raise exception 'this templates table has no brand column' using errcode = '22023', hint = 'TEMPLATE_BRAND_UNSUPPORTED';
end if;
select * into v_row from "better_supabase"."templates" x where x."tenant_id" is null and x."key" = v_starter ->> 'key' for update;
if not found then
insert into "better_supabase"."templates" ("tenant_id", "scope", "key", "type", "name", "language", "settings")
values (null, 'system', v_starter ->> 'key', v_starter ->> 'type', v_starter ->> 'name',
coalesce(v_starter ->> 'language', 'en'), coalesce(v_starter -> 'settings', '{}'::jsonb))
returning * into v_row;
else
update "better_supabase"."templates" x set
"type" = coalesce(v_starter ->> 'type', x."type"),
"name" = coalesce(v_starter ->> 'name', x."name"),
"language" = coalesce(v_starter ->> 'language', x."language"),
"settings" = coalesce(v_starter -> 'settings', x."settings"),
"updated_at" = now()
where x."id" = v_row."id"
returning * into v_row;
end if;
v_hash := encode(extensions.digest((v_starter -> 'body')::text, 'sha256'), 'hex');
if v_hash is distinct from (select y."hash" from "better_supabase"."template_versions" y
where y."template_id" = v_row."id" and y."published_at" is not null
order by y."version" desc limit 1) then
delete from "better_supabase"."template_versions" y where y."template_id" = v_row."id" and y."published_at" is null;
insert into "better_supabase"."template_versions" ("template_id", "version", "body", "hash", "published_at")
values (
v_row."id",
coalesce((select max(y."version") from "better_supabase"."template_versions" y where y."template_id" = v_row."id"), 0) + 1,
v_starter -> 'body',
v_hash,
now()
)
returning * into v_version;
v_count := v_count + 1;
null;
end if;
end loop;
return v_count;
end;
$$;
revoke execute on function "better_supabase"."sync_templates"(jsonb) from public, anon, authenticated;
grant execute on function "better_supabase"."sync_templates"(jsonb) to service_role;
-- What applying template in tenant needs: the template, its newest
-- published version with the body, and the enabled workflow attachments,
-- each input checked against the published version's input_schema
-- (TEMPLATE_WORKFLOW_INPUT_INVALID). templates.apply in tenant.
create or replace function "better_supabase"."template_apply_target"(template_id uuid, tenant uuid)
returns jsonb
language plpgsql
stable
security definer
set search_path = ''
as $$
#variable_conflict use_variable
declare
v_tpl "better_supabase"."templates"%rowtype;
v_version "better_supabase"."template_versions"%rowtype;
v_workflows jsonb := '[]'::jsonb;
begin
if template_apply_target.tenant is null then
raise exception 'Applying a template needs a tenant' using errcode = '22023', hint = 'TEMPLATE_INVALID';
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', template_apply_target.tenant, 'templates.apply'), false)) then
raise exception 'You may not apply templates here' using errcode = '42501', hint = 'TEMPLATE_FORBIDDEN';
end if;
select * into v_tpl from "better_supabase"."templates" x where x."id" = template_apply_target.template_id;
if not found or not (v_tpl."scope" = 'system' or v_tpl."tenant_id" = template_apply_target.tenant) then
raise exception 'No such template' using errcode = 'P0002', hint = 'TEMPLATE_NOT_FOUND';
end if;
select * into v_version from "better_supabase"."template_versions" y
where y."template_id" = v_tpl."id" and y."published_at" is not null
order by y."version" desc limit 1;
if not found then
raise exception 'This template has no published version' using errcode = 'P0002', hint = 'TEMPLATE_NOT_PUBLISHED';
end if;
return jsonb_build_object(
'template', jsonb_build_object(
'id', v_tpl."id",
'tenant', v_tpl."tenant_id",
'scope', v_tpl."scope",
'key', v_tpl."key",
'type', v_tpl."type",
'name', v_tpl."name",
'language', v_tpl."language",
'isDefault', v_tpl."is_default",
'settings', v_tpl."settings",
'forkedFrom', v_tpl."forked_from",
'forkedFromVersion', v_tpl."forked_from_version",
'publishedVersion', (select y."version" from "better_supabase"."template_versions" y where y."template_id" = v_tpl."id" and y."published_at" is not null order by y."version" desc limit 1),
'upstreamVersion', case when v_tpl."forked_from" is not null then (select y."version" from "better_supabase"."template_versions" y where y."template_id" = v_tpl."forked_from" and y."published_at" is not null order by y."version" desc limit 1) end,
'createdBy', v_tpl."created_by",
'createdAt', v_tpl."created_at",
'updatedAt', v_tpl."updated_at"
),
'version', jsonb_build_object(
'id', v_version."id",
'template', v_version."template_id",
'version', v_version."version",
'hash', v_version."hash",
'publishedAt', v_version."published_at",
'createdBy', v_version."created_by",
'createdAt', v_version."created_at",
'body', v_version."body"
),
'workflows', v_workflows
);
end;
$$;
revoke execute on function "better_supabase"."template_apply_target"(uuid, uuid) from public, anon;
grant execute on function "better_supabase"."template_apply_target"(uuid, uuid) to authenticated, service_role;
-- Records that version of template created subject_type/subject_id in
-- tenant. templates.apply in tenant.
create or replace function "better_supabase"."record_template_application"(template_id uuid, version_id uuid, tenant uuid, subject_type text, subject_id text)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
#variable_conflict use_variable
declare
v_tpl "better_supabase"."templates"%rowtype;
v_row "better_supabase"."template_applications"%rowtype;
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 record_template_application.tenant is null then
raise exception 'Applying a template needs a tenant' using errcode = '22023', hint = 'TEMPLATE_INVALID';
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', record_template_application.tenant, 'templates.apply'), false)) then
raise exception 'You may not apply templates here' using errcode = '42501', hint = 'TEMPLATE_FORBIDDEN';
end if;
select * into v_tpl from "better_supabase"."templates" x where x."id" = record_template_application.template_id;
if not found or not (v_tpl."scope" = 'system' or v_tpl."tenant_id" = record_template_application.tenant) then
raise exception 'No such template' using errcode = 'P0002', hint = 'TEMPLATE_NOT_FOUND';
end if;
if not exists (select 1 from "better_supabase"."template_versions" y where y."id" = record_template_application.version_id
and y."template_id" = v_tpl."id" and y."published_at" is not null) then
raise exception 'Not a published version of this template' using errcode = 'P0002', hint = 'TEMPLATE_NOT_PUBLISHED';
end if;
declare
v_hook regprocedure := to_regprocedure('"public"."before_template_apply"(uuid, uuid, text, text)');
begin
if v_hook is not null then
execute format('select %s($1::uuid, $2::uuid, $3::text, $4::text)', v_hook::oid::regproc)
using record_template_application.tenant, v_tpl."id", record_template_application.subject_type, record_template_application.subject_id;
end if;
end;
insert into "better_supabase"."template_applications" ("template_id", "version_id", "tenant_id", "subject_type", "subject_id", "applied_by")
values (v_tpl."id", record_template_application.version_id, record_template_application.tenant,
record_template_application.subject_type, record_template_application.subject_id, (select auth.uid()))
returning * into v_row;
null;
declare
v_hook regprocedure := to_regprocedure('"public"."after_template_apply"(uuid)');
begin
if v_hook is not null then
execute format('select %s($1::uuid)', v_hook::oid::regproc)
using v_row."id";
end if;
end;
return jsonb_build_object(
'id', v_row."id",
'template', v_row."template_id",
'version', v_row."version_id",
'tenant', v_row."tenant_id",
'subjectType', v_row."subject_type",
'subjectId', v_row."subject_id",
'appliedBy', v_row."applied_by",
'appliedAt', v_row."applied_at"
);
end;
$$;
revoke execute on function "better_supabase"."record_template_application"(uuid, uuid, uuid, text, text) from public, anon;
grant execute on function "better_supabase"."record_template_application"(uuid, uuid, uuid, text, text) to authenticated, service_role;
-- The tenant's applications, newest first, of one template or onto one
-- subject when those are given.
create or replace function "better_supabase"."template_applications_list"(tenant uuid, template_id uuid, subject_type text, subject_id text)
returns jsonb
language sql
stable
security invoker
set search_path = ''
as $$
select coalesce(jsonb_agg(r.value order by r.at desc, r.id), '[]'::jsonb)
from (
select jsonb_build_object(
'id', a."id",
'template', a."template_id",
'version', a."version_id",
'tenant', a."tenant_id",
'subjectType', a."subject_type",
'subjectId', a."subject_id",
'appliedBy', a."applied_by",
'appliedAt', a."applied_at"
) as value, a."applied_at" as at, a."id" as id
from "better_supabase"."template_applications" a
where a."tenant_id" = template_applications_list.tenant
and (template_applications_list.template_id is null or a."template_id" = template_applications_list.template_id)
and (template_applications_list.subject_type is null or a."subject_type" = template_applications_list.subject_type)
and (template_applications_list.subject_id is null or a."subject_id" = template_applications_list.subject_id)
order by a."applied_at" desc, a."id"
limit 200
) r
$$;
revoke execute on function "better_supabase"."template_applications_list"(uuid, uuid, text, text) from public, anon;
grant execute on function "better_supabase"."template_applications_list"(uuid, uuid, text, text) to authenticated, service_role;
create or replace function "better_supabase"."clone_row"(target regclass, source uuid, overrides jsonb default null)
returns uuid
language plpgsql
security definer
set search_path = ''
as $$
declare
v_row jsonb;
v_new uuid := gen_random_uuid();
v_template uuid;
v_cols text;
v_vals text;
v_child record;
begin
execute format('select to_jsonb(t) from %s t where t.id = $1', target) into v_row using source;
if v_row is null then
raise exception 'No such row' using errcode = 'P0002', hint = 'TEMPLATE_NOT_FOUND';
end if;
v_template := nullif(v_row ->> 'template_id', '')::uuid;
v_row := v_row || coalesce(overrides, '{}'::jsonb) || jsonb_build_object('id', v_new);
if not (coalesce(overrides, '{}'::jsonb) ? 'template_id') then
v_row := v_row || jsonb_build_object('template_id', null);
end if;
if v_template is not null and not (coalesce(overrides, '{}'::jsonb) ? 'source_template_id') then
v_row := v_row || jsonb_build_object('source_template_id', v_template);
end if;
select string_agg(format('%I', key), ', '), string_agg(format('%L', value), ', ')
into v_cols, v_vals
from jsonb_each_text(v_row);
execute format('insert into %s (%s) values (%s)', target, v_cols, v_vals);
for v_child in
select c.conrelid::regclass as child, a.attname as parent
from pg_catalog.pg_constraint c
join pg_catalog.pg_attribute a on a.attrelid = c.conrelid and a.attnum = c.conkey[1]
where c.confrelid = target and c.contype = 'f' and c.conrelid <> target
loop
execute format(
'insert into %s select (jsonb_populate_record(null::%s, to_jsonb(x) || jsonb_build_object(%L, $1, ''id'', gen_random_uuid()))).* from %s x where x.%I = $2',
v_child.child, v_child.child, v_child.parent, v_child.child, v_child.parent
) using v_new, source;
end loop;
return v_new;
end;
$$;
revoke execute on function "better_supabase"."clone_row"(regclass, uuid, jsonb) from public, anon, authenticated;
grant execute on function "better_supabase"."clone_row"(regclass, uuid, jsonb) to service_role;
create or replace function "better_supabase"."template_table"(target regclass)
returns void
language plpgsql
security definer
set search_path = ''
as $$
begin
execute format('alter table %s add column if not exists template_id uuid unique references "better_supabase"."templates" (id) on delete cascade', target);
execute format('alter table %s add column if not exists source_template_id uuid references "better_supabase"."templates" (id) on delete set null', target);
execute format('drop trigger if exists bsb_template_row on %s', target);
execute format('create trigger bsb_template_row before update of template_id on %s for each row execute function "better_supabase"."template_row_guard"()', target);
end;
$$;
revoke execute on function "better_supabase"."template_table"(regclass) from public, anon, authenticated;
grant execute on function "better_supabase"."template_table"(regclass) to service_role;
create or replace function "better_supabase"."template_row_guard"()
returns trigger
language plpgsql
set search_path = ''
as $$
begin
if new.template_id is distinct from old.template_id then
raise exception 'A row cannot change between a template and a live record' using errcode = '23514', hint = 'TEMPLATE_IMMUTABLE';
end if;
return new;
end;
$$;
revoke execute on function "better_supabase"."template_row_guard"() from public, anon, authenticated;
-- 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"."templates" 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('templates.read'))
or ("scope" = 'system' and exists (select better_supabase.tenant_ids_with('templates.read'))))
);
create policy bsb_tenant_scope_insert on "better_supabase"."templates" 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"."templates" 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"."templates" 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"."template_applications" 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('templates.read')))
);
create policy bsb_tenant_scope_insert on "better_supabase"."template_applications" 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"."template_applications" 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"."template_applications" 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/templates, which runs on the server.
Events
With the outbox installed, the module writes these in the same transaction as the change.
- template.applied
- template.published
Dependencies
- Required: the install command adds it too
- Works with: optional
Recipes
More in Content & files
Collaborative documentsdocuments Yjs documents attached to any subject: an update log, a compacted snapshot, a private realtime topic per document for updates and presence, suggestions that editors accept into the log, and named versions through the versions module. Drivedrive Folders and files on the attachments module: access granted to users, teams or roles and inherited down the tree, enforced by storage policies too; moves and renames with a name-conflict policy; revisions through versions, a bin through trash, starred and recent items through share-links' user state, and folder share links. Drive filesdrive-files The part of the drive module that needs attachments, versions, trash and share-links: file uploads and revisions with an optional usage quota, extracted text, storage policies, the bin, starred and recent items, folder share links and the purge event. Installed with drive. Formsforms Forms with numbered versions (steps and show or skip logic), a JSON Schema 2020-12 per version that validates every submission, drafts, public links through share-links with a rate limit and a bot-check hook, handlers that turn a submission into a record, scoring against an answer key respondents can't read, and NPS rollups.React hooks Signaturessignatures Simple electronic signatures on a frozen version of a record: drawn, typed or click signatures in parallel or in order, a hash that detects edits after signing, and an approval step a signer can decide. Coursescourses Courses of modules and lessons ordered by rank keys, with quiz lessons graded by forms, per-lesson progress, completion and certificates. Each course runs as an enrollment program, so learners enroll through enrollments.