AI files
ai-filesFiles and documents for AI chats: a private bucket whose policies only accept an upload a reserved record expects, provider file references with expiry, versioned documents with suggested edits, and a purge that hands back the objects to remove.
AImanagedcustom
Which deals close this month?
AI
3 deals, €42k in total.
Install
The command also installs updated-at, memberships, permissions, versions, the modules it needs.
npx better-supabase add ai-filesConfigure
The blocks entries in your config, with the default mode.
import { defineConfig } from "better-supabase/config";
export default defineConfig({
blocks: {
// Required by ai-files; add installs them too.
"updated-at": {},
memberships: {},
permissions: {},
versions: {},
// Modes: "managed", "custom". The default is "managed".
"ai-files": { mode: "managed" },
},
});Migrations
The files
npx better-supabase add ai-files writes into your declarative schema with the default layout.11 files
supabase/schemas/900_better_supabase_048_ai_files.sqlschema992 lines-- better-supabase module: ai-files
-- @bsb-block ai-files@3 managed
-- @bsb-hash sha256:5278334fc9a82891b24fa6722e39633708b5b6a45abdf95263724c82b28a547c
-- Files and documents for AI chats: a private bucket whose policies only accept an upload a reserved record expects, provider file references with expiry, versioned documents with suggested edits, and a purge that hands back the objects to remove.
-- 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.
-- Files for AI chats: uploads, generated images and audio, and what a
-- provider's file API returned for them. Objects live in the private
-- ai-files bucket at {organization_id}/{owner_id}/{id}/{filename}; the record is
-- reserved first, so the storage policies only accept the upload it expects.
create table "better_supabase"."ai_files" (
"id" uuid primary key default gen_random_uuid(),
"tenant_id" uuid not null,
"owner_id" uuid not null references auth.users (id) on delete cascade,
"chat_id" uuid,
"project_id" uuid,
"bucket" text not null,
"filename" text not null constraint bsb_ai_files_filename_check check (length("filename") >= 1 and length("filename") <= 255 and "filename" !~ '[/\\]' and "filename" not in ('.', '..')),
"path" text generated always as ("tenant_id"::text || '/' || "owner_id"::text || '/' || "id"::text || '/' || "filename") stored,
"media_type" text not null constraint bsb_ai_files_media_type_check check ("media_type" ~ '^[a-z0-9.+-]+/[a-z0-9.+-]+$'),
"byte_size" bigint not null constraint bsb_ai_files_byte_size_check check ("byte_size" >= 0 and "byte_size" <= 52428800),
"sha256" text constraint bsb_ai_files_sha256_check check ("sha256" ~ '^[0-9a-f]{64}$'),
"status" text not null default 'pending' constraint bsb_ai_files_status_check check ("status" in ('pending', 'ready', 'failed')),
"source" text not null default 'upload' constraint bsb_ai_files_source_check check ("source" in ('upload', 'generated', 'provider')),
"created_at" timestamptz not null default now(),
"uploaded_at" timestamptz,
"expires_at" timestamptz
);
create unique index ai_files_object_idx on "better_supabase"."ai_files" ("bucket", "path");
create index ai_files_owner_idx on "better_supabase"."ai_files" ("owner_id");
create index ai_files_tenant_idx on "better_supabase"."ai_files" ("tenant_id");
create index ai_files_chat_idx on "better_supabase"."ai_files" ("chat_id") where "chat_id" is not null;
create index ai_files_pending_idx on "better_supabase"."ai_files" ("created_at") where "status" = 'pending';
alter table "better_supabase"."ai_files" enable row level security;
revoke all on "better_supabase"."ai_files" from public, anon, authenticated;
grant select on "better_supabase"."ai_files" to authenticated;
grant all on "better_supabase"."ai_files" to service_role;
create policy bsb_ai_files_read on "better_supabase"."ai_files"
for select to authenticated
using (("owner_id" = (select auth.uid()) or "tenant_id" in (select better_supabase.tenant_ids_with('ai_files.manage')) or false));
-- What a provider's file API returned for a file (an OpenAI file id, a
-- Gemini file URI), so the next call reuses it until it expires.
create table "better_supabase"."ai_provider_files" (
"file_id" uuid not null references "better_supabase"."ai_files" ("id") on delete cascade,
"provider" text not null constraint bsb_ai_provider_files_provider_check check (length("provider") >= 1 and length("provider") <= 100),
"reference" text not null constraint bsb_ai_provider_files_reference_check check (length("reference") >= 1 and length("reference") <= 2000),
"expires_at" timestamptz,
"created_at" timestamptz not null default now(),
primary key ("file_id", "provider")
);
create index ai_provider_files_expires_idx on "better_supabase"."ai_provider_files" ("expires_at") where "expires_at" is not null;
alter table "better_supabase"."ai_provider_files" enable row level security;
revoke all on "better_supabase"."ai_provider_files" from public, anon, authenticated;
grant all on "better_supabase"."ai_provider_files" to service_role;
-- Documents an assistant writes and the user edits beside the chat (text,
-- code, sheets, images). Their versions live in the versions block, which
-- keeps the newest ones by its keep option.
create table "better_supabase"."ai_documents" (
"id" uuid primary key default gen_random_uuid(),
"tenant_id" uuid not null,
"owner_id" uuid not null references auth.users (id) on delete cascade,
"chat_id" uuid,
"kind" text not null constraint bsb_ai_documents_kind_check check ("kind" in ('text', 'code', 'sheet', 'image', 'spec')),
"title" text not null constraint bsb_ai_documents_title_check check (length("title") >= 1 and length("title") <= 500),
"current_version" integer not null default 1 constraint bsb_ai_documents_current_version_check check ("current_version" >= 1),
"created_at" timestamptz not null default now(),
"updated_at" timestamptz not null default now()
);
create index ai_documents_owner_idx on "better_supabase"."ai_documents" ("owner_id");
create index ai_documents_tenant_idx on "better_supabase"."ai_documents" ("tenant_id");
create index ai_documents_chat_idx on "better_supabase"."ai_documents" ("chat_id") where "chat_id" is not null;
alter table "better_supabase"."ai_documents" enable row level security;
revoke all on "better_supabase"."ai_documents" from public, anon, authenticated;
grant select on "better_supabase"."ai_documents" to authenticated;
grant all on "better_supabase"."ai_documents" to service_role;
create policy bsb_ai_documents_read on "better_supabase"."ai_documents"
for select to authenticated
using (("owner_id" = (select auth.uid()) or "tenant_id" in (select better_supabase.tenant_ids_with('ai_files.manage')) or false));
-- A document's versions live in the versions block (subject type
-- ai_document); they go with the document.
create or replace function "better_supabase"."ai_document_purge_versions"()
returns trigger
language plpgsql
security definer
set search_path = ''
as $$
begin
delete from "better_supabase"."versions" x where x."subject_type" = 'ai_document' and x."subject_id" = old."id"::text;
return old;
end;
$$;
revoke execute on function "better_supabase"."ai_document_purge_versions"() from public, anon, authenticated;
create trigger "bsb_ai_document_purge_versions"
after delete on "better_supabase"."ai_documents"
for each row execute function "better_supabase"."ai_document_purge_versions"();
create table "better_supabase"."ai_suggestions" (
"id" uuid primary key default gen_random_uuid(),
"document_id" uuid not null references "better_supabase"."ai_documents" ("id") on delete cascade,
"version" integer not null,
"original_text" text not null,
"suggested_text" text not null,
"description" text,
"created_by" uuid references auth.users (id) on delete set null,
"created_at" timestamptz not null default now(),
"resolved_at" timestamptz,
"accepted" boolean
);
create index ai_suggestions_document_idx on "better_supabase"."ai_suggestions" ("document_id");
create index ai_suggestions_created_by_idx on "better_supabase"."ai_suggestions" ("created_by") where "created_by" is not null;
alter table "better_supabase"."ai_suggestions" enable row level security;
revoke all on "better_supabase"."ai_suggestions" from public, anon, authenticated;
grant select on "better_supabase"."ai_suggestions" to authenticated;
grant all on "better_supabase"."ai_suggestions" to service_role;
create policy bsb_ai_suggestions_read on "better_supabase"."ai_suggestions"
for select to authenticated
using (exists (select 1 from "better_supabase"."ai_documents" doc where doc."id" = "document_id"));
-- Whether the caller may run action (insert, select or delete) on the
-- object at path in bucket: an upload needs the caller's pending record, a
-- read the owner, an ai_chat admin or a reader of the file's chat, a delete
-- the owner or an admin. It reads the table as its owner, so the storage
-- policies don't depend on the table's own policies.
create or replace function "better_supabase"."ai_file_object_allowed"(bucket text, path text, action text)
returns boolean
language sql
stable
security definer
set search_path = ''
as $$
select exists (
select 1 from "better_supabase"."ai_files" a
where a."bucket" = ai_file_object_allowed.bucket and a."path" = ai_file_object_allowed.path
and case ai_file_object_allowed.action
when 'insert' then a."status" = 'pending' and a."owner_id" = auth.uid()
when 'select' then a."owner_id" = auth.uid() or coalesce(better_supabase.can('tenant', a."tenant_id", 'ai_files.manage'), false) or false
when 'delete' then a."owner_id" = auth.uid() or coalesce(better_supabase.can('tenant', a."tenant_id", 'ai_files.manage'), false)
else false
end
)
$$;
revoke execute on function "better_supabase"."ai_file_object_allowed"(text, text, text) from public, anon;
grant execute on function "better_supabase"."ai_file_object_allowed"(text, text, text) to authenticated, service_role;
create policy bsb_ai_files_insert on storage.objects
for insert to authenticated
with check ((bucket_id = 'ai-files' and "better_supabase"."ai_file_object_allowed"(bucket_id, name, 'insert')) and (select better_supabase.actor_may_write()));
create policy bsb_ai_files_select on storage.objects
for select to authenticated
using (bucket_id = 'ai-files' and "better_supabase"."ai_file_object_allowed"(bucket_id, name, 'select'));
create policy bsb_ai_files_delete on storage.objects
for delete to authenticated
using ((bucket_id = 'ai-files' and "better_supabase"."ai_file_object_allowed"(bucket_id, name, 'delete')) and (select better_supabase.actor_may_write()));
-- Reserves a file for the caller, who then uploads to its path (a signed
-- upload URL, or TUS for large files). The size and type are checked here
-- and again by the bucket.
create or replace function "better_supabase"."reserve_ai_file"(
tenant uuid,
filename text,
media_type text,
byte_size bigint,
chat_id uuid default null,
project_id uuid default null
)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
declare
v_row "better_supabase"."ai_files"%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 auth.uid() is null or not coalesce(better_supabase.can('tenant', reserve_ai_file.tenant, 'ai_files.upload'), false) then
raise exception 'you may not upload files here' using errcode = '42501', hint = 'AI_FILE_FORBIDDEN';
end if;
if byte_size < 0 or byte_size > 52428800 then
raise exception 'files are limited to % bytes', 52428800 using errcode = '22023', hint = 'AI_FILE_TOO_LARGE';
end if;
insert into "better_supabase"."ai_files" ("tenant_id", "owner_id", "chat_id", "project_id", "bucket", "filename", "media_type", "byte_size")
values (reserve_ai_file.tenant, auth.uid(), reserve_ai_file.chat_id, reserve_ai_file.project_id, 'ai-files', reserve_ai_file.filename, lower(reserve_ai_file.media_type), reserve_ai_file.byte_size)
returning * into v_row;
return jsonb_build_object('id', v_row."id", 'organization_id', v_row."tenant_id", 'owner_id', v_row."owner_id", 'chat_id', v_row."chat_id", 'project_id', v_row."project_id", 'bucket', v_row."bucket", 'path', v_row."path", 'media_type', v_row."media_type", 'filename', v_row."filename", 'byte_size', v_row."byte_size", 'sha256', v_row."sha256", 'status', v_row."status", 'source', v_row."source", 'created_at', v_row."created_at", 'uploaded_at', v_row."uploaded_at", 'expires_at', v_row."expires_at");
end;
$$;
revoke execute on function "better_supabase"."reserve_ai_file"(uuid, text, text, bigint, uuid, uuid) from public, anon;
grant execute on function "better_supabase"."reserve_ai_file"(uuid, text, text, bigint, uuid, uuid) to authenticated, service_role;
-- Marks an upload done once its object exists, taking the stored size.
create or replace function "better_supabase"."confirm_ai_file"(file_id uuid, sha256 text default null)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
declare
v_row "better_supabase"."ai_files"%rowtype;
v_size bigint;
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"."ai_files" x where x."id" = confirm_ai_file.file_id for update;
if not found or not (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or coalesce(v_row."owner_id" = auth.uid(), false)) then
raise exception 'file % not found', file_id using errcode = 'P0002', hint = 'AI_FILE_NOT_FOUND';
end if;
if v_row."status" <> 'pending' then
return jsonb_build_object('id', v_row."id", 'organization_id', v_row."tenant_id", 'owner_id', v_row."owner_id", 'chat_id', v_row."chat_id", 'project_id', v_row."project_id", 'bucket', v_row."bucket", 'path', v_row."path", 'media_type', v_row."media_type", 'filename', v_row."filename", 'byte_size', v_row."byte_size", 'sha256', v_row."sha256", 'status', v_row."status", 'source', v_row."source", 'created_at', v_row."created_at", 'uploaded_at', v_row."uploaded_at", 'expires_at', v_row."expires_at");
end if;
select (o.metadata ->> 'size')::bigint into v_size
from storage.objects o where o.bucket_id = v_row."bucket" and o.name = v_row."path";
if not found then
raise exception 'file % has no uploaded object yet', file_id using errcode = 'P0001', hint = 'AI_FILE_NOT_UPLOADED';
end if;
update "better_supabase"."ai_files" x set
"status" = 'ready',
"uploaded_at" = now(),
"byte_size" = coalesce(v_size, x."byte_size"),
"sha256" = coalesce(lower(confirm_ai_file.sha256), x."sha256")
where x."id" = v_row."id"
returning * into v_row;
return jsonb_build_object('id', v_row."id", 'organization_id', v_row."tenant_id", 'owner_id', v_row."owner_id", 'chat_id', v_row."chat_id", 'project_id', v_row."project_id", 'bucket', v_row."bucket", 'path', v_row."path", 'media_type', v_row."media_type", 'filename', v_row."filename", 'byte_size', v_row."byte_size", 'sha256', v_row."sha256", 'status', v_row."status", 'source', v_row."source", 'created_at', v_row."created_at", 'uploaded_at', v_row."uploaded_at", 'expires_at', v_row."expires_at");
end;
$$;
revoke execute on function "better_supabase"."confirm_ai_file"(uuid, text) from public, anon;
grant execute on function "better_supabase"."confirm_ai_file"(uuid, text) to authenticated, service_role;
-- A file the caller may read, by id or by object path; null otherwise.
create or replace function "better_supabase"."get_ai_file"(file_id uuid)
returns jsonb
language sql
stable
security invoker
set search_path = ''
as $$
select jsonb_build_object('id', x."id", 'organization_id', x."tenant_id", 'owner_id', x."owner_id", 'chat_id', x."chat_id", 'project_id', x."project_id", 'bucket', x."bucket", 'path', x."path", 'media_type', x."media_type", 'filename', x."filename", 'byte_size', x."byte_size", 'sha256', x."sha256", 'status', x."status", 'source', x."source", 'created_at', x."created_at", 'uploaded_at', x."uploaded_at", 'expires_at', x."expires_at") from "better_supabase"."ai_files" x where x."id" = get_ai_file.file_id
$$;
revoke execute on function "better_supabase"."get_ai_file"(uuid) from public, anon;
grant execute on function "better_supabase"."get_ai_file"(uuid) to authenticated, service_role;
create or replace function "better_supabase"."get_ai_file_by_path"(bucket text, path text)
returns jsonb
language sql
stable
security invoker
set search_path = ''
as $$
select jsonb_build_object('id', x."id", 'organization_id', x."tenant_id", 'owner_id', x."owner_id", 'chat_id', x."chat_id", 'project_id', x."project_id", 'bucket', x."bucket", 'path', x."path", 'media_type', x."media_type", 'filename', x."filename", 'byte_size', x."byte_size", 'sha256', x."sha256", 'status', x."status", 'source', x."source", 'created_at', x."created_at", 'uploaded_at', x."uploaded_at", 'expires_at', x."expires_at") from "better_supabase"."ai_files" x
where x."bucket" = get_ai_file_by_path.bucket and x."path" = get_ai_file_by_path.path
$$;
revoke execute on function "better_supabase"."get_ai_file_by_path"(text, text) from public, anon;
grant execute on function "better_supabase"."get_ai_file_by_path"(text, text) to authenticated, service_role;
-- The files of a chat the caller can read, oldest first.
create or replace function "better_supabase"."list_ai_files"(chat_id uuid)
returns jsonb
language sql
stable
security invoker
set search_path = ''
as $$
select coalesce(jsonb_agg(jsonb_build_object('id', x."id", 'organization_id', x."tenant_id", 'owner_id', x."owner_id", 'chat_id', x."chat_id", 'project_id', x."project_id", 'bucket', x."bucket", 'path', x."path", 'media_type', x."media_type", 'filename', x."filename", 'byte_size', x."byte_size", 'sha256', x."sha256", 'status', x."status", 'source', x."source", 'created_at', x."created_at", 'uploaded_at', x."uploaded_at", 'expires_at', x."expires_at") order by x."created_at"), '[]'::jsonb)
from "better_supabase"."ai_files" x where x."chat_id" = list_ai_files.chat_id
$$;
revoke execute on function "better_supabase"."list_ai_files"(uuid) from public, anon;
grant execute on function "better_supabase"."list_ai_files"(uuid) to authenticated, service_role;
-- The files of a tenant the caller can read as a keyset page (ADR 1077),
-- oldest first. filters is { chatId (one uuid), status, source, mediaType (a
-- value or a list), search (filename), sort (createdAt, filename, size),
-- direction, facet, count, limit, after, offset, paged, total, totalCap }.
create or replace function "better_supabase"."page_ai_files"(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_ai_files.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_chat text := nullif(coalesce(v_filters #>> '{chatId,0}', v_filters ->> 'chatId'), '');
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 exists (select 1 from jsonb_array_elements_text(case when jsonb_typeof(v_filters -> 'chatId') = 'array' then v_filters -> 'chatId' when jsonb_typeof(v_filters -> 'chatId') in ('string', 'number') then jsonb_build_array(v_filters -> 'chatId') else '[]'::jsonb end) s where s !~ '^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$') then
raise exception 'chatId is a uuid' using errcode = '22023', hint = 'AI_FILE_INVALID';
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 = 'AI_FILE_INVALID';
end if;
if v_facet is not null then
if v_facet not in ('status', 'source', 'mediaType') then
raise exception 'facet is one of status, source, mediaType' using errcode = '22023', hint = 'AI_FILE_INVALID';
end if;
with s as (
select (case v_facet when 'status' then (x."status")::text when 'source' then (x."source")::text when 'mediaType' then (x."media_type")::text end) as v
from "better_supabase"."ai_files" x
where x."tenant_id" = page_ai_files.tenant
and (v_chat is null or x."chat_id" = v_chat::uuid)
and (not (v_filters -> 'status' is not null and jsonb_typeof(v_filters -> 'status') <> 'null' and not (jsonb_typeof(v_filters -> 'status') = 'array' and jsonb_array_length(v_filters -> 'status') = 0)) or x."status"::text = any((case when jsonb_typeof(v_filters -> 'status') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'status')) else array[v_filters ->> 'status'] end)::text[]))
and (not (v_filters -> 'source' is not null and jsonb_typeof(v_filters -> 'source') <> 'null' and not (jsonb_typeof(v_filters -> 'source') = 'array' and jsonb_array_length(v_filters -> 'source') = 0)) or x."source"::text = any((case when jsonb_typeof(v_filters -> 'source') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'source')) else array[v_filters ->> 'source'] end)::text[]))
and (not (v_filters -> 'mediaType' is not null and jsonb_typeof(v_filters -> 'mediaType') <> 'null' and not (jsonb_typeof(v_filters -> 'mediaType') = 'array' and jsonb_array_length(v_filters -> 'mediaType') = 0)) or (x."media_type")::text = any((case when jsonb_typeof(v_filters -> 'mediaType') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'mediaType')) else array[v_filters ->> 'mediaType'] end)::text[]))
and (v_search is null or x."filename" 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"."ai_files" x
where x."tenant_id" = page_ai_files.tenant
and (v_chat is null or x."chat_id" = v_chat::uuid)
and (not (v_filters -> 'status' is not null and jsonb_typeof(v_filters -> 'status') <> 'null' and not (jsonb_typeof(v_filters -> 'status') = 'array' and jsonb_array_length(v_filters -> 'status') = 0)) or x."status"::text = any((case when jsonb_typeof(v_filters -> 'status') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'status')) else array[v_filters ->> 'status'] end)::text[]))
and (not (v_filters -> 'source' is not null and jsonb_typeof(v_filters -> 'source') <> 'null' and not (jsonb_typeof(v_filters -> 'source') = 'array' and jsonb_array_length(v_filters -> 'source') = 0)) or x."source"::text = any((case when jsonb_typeof(v_filters -> 'source') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'source')) else array[v_filters ->> 'source'] end)::text[]))
and (not (v_filters -> 'mediaType' is not null and jsonb_typeof(v_filters -> 'mediaType') <> 'null' and not (jsonb_typeof(v_filters -> 'mediaType') = 'array' and jsonb_array_length(v_filters -> 'mediaType') = 0)) or (x."media_type")::text = any((case when jsonb_typeof(v_filters -> 'mediaType') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'mediaType')) else array[v_filters ->> 'mediaType'] end)::text[]))
and (v_search is null or x."filename" 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 ('createdAt', 'filename', 'size') then
raise exception 'sort is one of createdAt, filename, size' using errcode = '22023', hint = 'AI_FILE_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 = 'AI_FILE_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 = 'AI_FILE_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", 'organization_id', x."tenant_id", 'owner_id', x."owner_id", 'chat_id', x."chat_id", 'project_id', x."project_id", 'bucket', x."bucket", 'path', x."path", 'media_type', x."media_type", 'filename', x."filename", 'byte_size', x."byte_size", 'sha256', x."sha256", 'status', x."status", 'source', x."source", 'created_at', x."created_at", 'uploaded_at', x."uploaded_at", 'expires_at', x."expires_at") as j, jsonb_build_array((x."created_at")::text, (x."id")::text) as k
from (
select * from "better_supabase"."ai_files" x
where x."tenant_id" = page_ai_files.tenant
and (v_chat is null or x."chat_id" = v_chat::uuid)
and (not (v_filters -> 'status' is not null and jsonb_typeof(v_filters -> 'status') <> 'null' and not (jsonb_typeof(v_filters -> 'status') = 'array' and jsonb_array_length(v_filters -> 'status') = 0)) or x."status"::text = any((case when jsonb_typeof(v_filters -> 'status') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'status')) else array[v_filters ->> 'status'] end)::text[]))
and (not (v_filters -> 'source' is not null and jsonb_typeof(v_filters -> 'source') <> 'null' and not (jsonb_typeof(v_filters -> 'source') = 'array' and jsonb_array_length(v_filters -> 'source') = 0)) or x."source"::text = any((case when jsonb_typeof(v_filters -> 'source') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'source')) else array[v_filters ->> 'source'] end)::text[]))
and (not (v_filters -> 'mediaType' is not null and jsonb_typeof(v_filters -> 'mediaType') <> 'null' and not (jsonb_typeof(v_filters -> 'mediaType') = 'array' and jsonb_array_length(v_filters -> 'mediaType') = 0)) or (x."media_type")::text = any((case when jsonb_typeof(v_filters -> 'mediaType') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'mediaType')) else array[v_filters ->> 'mediaType'] end)::text[]))
and (v_search is null or x."filename" 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 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 = 'AI_FILE_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", 'organization_id', x."tenant_id", 'owner_id', x."owner_id", 'chat_id', x."chat_id", 'project_id', x."project_id", 'bucket', x."bucket", 'path', x."path", 'media_type', x."media_type", 'filename', x."filename", 'byte_size', x."byte_size", 'sha256', x."sha256", 'status', x."status", 'source', x."source", 'created_at', x."created_at", 'uploaded_at', x."uploaded_at", 'expires_at', x."expires_at") as j, jsonb_build_array((x."created_at")::text, (x."id")::text) as k
from (
select * from "better_supabase"."ai_files" x
where x."tenant_id" = page_ai_files.tenant
and (v_chat is null or x."chat_id" = v_chat::uuid)
and (not (v_filters -> 'status' is not null and jsonb_typeof(v_filters -> 'status') <> 'null' and not (jsonb_typeof(v_filters -> 'status') = 'array' and jsonb_array_length(v_filters -> 'status') = 0)) or x."status"::text = any((case when jsonb_typeof(v_filters -> 'status') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'status')) else array[v_filters ->> 'status'] end)::text[]))
and (not (v_filters -> 'source' is not null and jsonb_typeof(v_filters -> 'source') <> 'null' and not (jsonb_typeof(v_filters -> 'source') = 'array' and jsonb_array_length(v_filters -> 'source') = 0)) or x."source"::text = any((case when jsonb_typeof(v_filters -> 'source') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'source')) else array[v_filters ->> 'source'] end)::text[]))
and (not (v_filters -> 'mediaType' is not null and jsonb_typeof(v_filters -> 'mediaType') <> 'null' and not (jsonb_typeof(v_filters -> 'mediaType') = 'array' and jsonb_array_length(v_filters -> 'mediaType') = 0)) or (x."media_type")::text = any((case when jsonb_typeof(v_filters -> 'mediaType') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'mediaType')) else array[v_filters ->> 'mediaType'] end)::text[]))
and (v_search is null or x."filename" 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 = 'createdAt' 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 = 'AI_FILE_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", 'organization_id', x."tenant_id", 'owner_id', x."owner_id", 'chat_id', x."chat_id", 'project_id', x."project_id", 'bucket', x."bucket", 'path', x."path", 'media_type', x."media_type", 'filename', x."filename", 'byte_size', x."byte_size", 'sha256', x."sha256", 'status', x."status", 'source', x."source", 'created_at', x."created_at", 'uploaded_at', x."uploaded_at", 'expires_at', x."expires_at") as j, jsonb_build_array((x."created_at")::text, (x."id")::text) as k
from (
select * from "better_supabase"."ai_files" x
where x."tenant_id" = page_ai_files.tenant
and (v_chat is null or x."chat_id" = v_chat::uuid)
and (not (v_filters -> 'status' is not null and jsonb_typeof(v_filters -> 'status') <> 'null' and not (jsonb_typeof(v_filters -> 'status') = 'array' and jsonb_array_length(v_filters -> 'status') = 0)) or x."status"::text = any((case when jsonb_typeof(v_filters -> 'status') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'status')) else array[v_filters ->> 'status'] end)::text[]))
and (not (v_filters -> 'source' is not null and jsonb_typeof(v_filters -> 'source') <> 'null' and not (jsonb_typeof(v_filters -> 'source') = 'array' and jsonb_array_length(v_filters -> 'source') = 0)) or x."source"::text = any((case when jsonb_typeof(v_filters -> 'source') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'source')) else array[v_filters ->> 'source'] end)::text[]))
and (not (v_filters -> 'mediaType' is not null and jsonb_typeof(v_filters -> 'mediaType') <> 'null' and not (jsonb_typeof(v_filters -> 'mediaType') = 'array' and jsonb_array_length(v_filters -> 'mediaType') = 0)) or (x."media_type")::text = any((case when jsonb_typeof(v_filters -> 'mediaType') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'mediaType')) else array[v_filters ->> 'mediaType'] end)::text[]))
and (v_search is null or x."filename" 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, '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 = 'AI_FILE_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", 'organization_id', x."tenant_id", 'owner_id', x."owner_id", 'chat_id', x."chat_id", 'project_id', x."project_id", 'bucket', x."bucket", 'path', x."path", 'media_type', x."media_type", 'filename', x."filename", 'byte_size', x."byte_size", 'sha256', x."sha256", 'status', x."status", 'source', x."source", 'created_at', x."created_at", 'uploaded_at', x."uploaded_at", 'expires_at', x."expires_at") as j, jsonb_build_array((x."created_at")::text, (x."id")::text) as k
from (
select * from "better_supabase"."ai_files" x
where x."tenant_id" = page_ai_files.tenant
and (v_chat is null or x."chat_id" = v_chat::uuid)
and (not (v_filters -> 'status' is not null and jsonb_typeof(v_filters -> 'status') <> 'null' and not (jsonb_typeof(v_filters -> 'status') = 'array' and jsonb_array_length(v_filters -> 'status') = 0)) or x."status"::text = any((case when jsonb_typeof(v_filters -> 'status') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'status')) else array[v_filters ->> 'status'] end)::text[]))
and (not (v_filters -> 'source' is not null and jsonb_typeof(v_filters -> 'source') <> 'null' and not (jsonb_typeof(v_filters -> 'source') = 'array' and jsonb_array_length(v_filters -> 'source') = 0)) or x."source"::text = any((case when jsonb_typeof(v_filters -> 'source') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'source')) else array[v_filters ->> 'source'] end)::text[]))
and (not (v_filters -> 'mediaType' is not null and jsonb_typeof(v_filters -> 'mediaType') <> 'null' and not (jsonb_typeof(v_filters -> 'mediaType') = 'array' and jsonb_array_length(v_filters -> 'mediaType') = 0)) or (x."media_type")::text = any((case when jsonb_typeof(v_filters -> 'mediaType') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'mediaType')) else array[v_filters ->> 'mediaType'] end)::text[]))
and (v_search is null or x."filename" 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 = 'filename' 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 = 'AI_FILE_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", 'organization_id', x."tenant_id", 'owner_id', x."owner_id", 'chat_id', x."chat_id", 'project_id', x."project_id", 'bucket', x."bucket", 'path', x."path", 'media_type', x."media_type", 'filename', x."filename", 'byte_size', x."byte_size", 'sha256', x."sha256", 'status', x."status", 'source', x."source", 'created_at', x."created_at", 'uploaded_at', x."uploaded_at", 'expires_at', x."expires_at") as j, jsonb_build_array((lower(x."filename"))::text, (x."id")::text) as k
from (
select * from "better_supabase"."ai_files" x
where x."tenant_id" = page_ai_files.tenant
and (v_chat is null or x."chat_id" = v_chat::uuid)
and (not (v_filters -> 'status' is not null and jsonb_typeof(v_filters -> 'status') <> 'null' and not (jsonb_typeof(v_filters -> 'status') = 'array' and jsonb_array_length(v_filters -> 'status') = 0)) or x."status"::text = any((case when jsonb_typeof(v_filters -> 'status') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'status')) else array[v_filters ->> 'status'] end)::text[]))
and (not (v_filters -> 'source' is not null and jsonb_typeof(v_filters -> 'source') <> 'null' and not (jsonb_typeof(v_filters -> 'source') = 'array' and jsonb_array_length(v_filters -> 'source') = 0)) or x."source"::text = any((case when jsonb_typeof(v_filters -> 'source') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'source')) else array[v_filters ->> 'source'] end)::text[]))
and (not (v_filters -> 'mediaType' is not null and jsonb_typeof(v_filters -> 'mediaType') <> 'null' and not (jsonb_typeof(v_filters -> 'mediaType') = 'array' and jsonb_array_length(v_filters -> 'mediaType') = 0)) or (x."media_type")::text = any((case when jsonb_typeof(v_filters -> 'mediaType') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'mediaType')) else array[v_filters ->> 'mediaType'] end)::text[]))
and (v_search is null or x."filename" ilike v_search)
and (v_after is null or (lower(x."filename"), x."id") > ((v_after ->> 0)::text, (v_after ->> 1)::uuid))
order by lower(x."filename") asc, x."id" asc
limit v_limit + 1 offset v_offset
) x
) p;
elsif v_sort = 'filename' 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 = 'AI_FILE_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", 'organization_id', x."tenant_id", 'owner_id', x."owner_id", 'chat_id', x."chat_id", 'project_id', x."project_id", 'bucket', x."bucket", 'path', x."path", 'media_type', x."media_type", 'filename', x."filename", 'byte_size', x."byte_size", 'sha256', x."sha256", 'status', x."status", 'source', x."source", 'created_at', x."created_at", 'uploaded_at', x."uploaded_at", 'expires_at', x."expires_at") as j, jsonb_build_array((lower(x."filename"))::text, (x."id")::text) as k
from (
select * from "better_supabase"."ai_files" x
where x."tenant_id" = page_ai_files.tenant
and (v_chat is null or x."chat_id" = v_chat::uuid)
and (not (v_filters -> 'status' is not null and jsonb_typeof(v_filters -> 'status') <> 'null' and not (jsonb_typeof(v_filters -> 'status') = 'array' and jsonb_array_length(v_filters -> 'status') = 0)) or x."status"::text = any((case when jsonb_typeof(v_filters -> 'status') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'status')) else array[v_filters ->> 'status'] end)::text[]))
and (not (v_filters -> 'source' is not null and jsonb_typeof(v_filters -> 'source') <> 'null' and not (jsonb_typeof(v_filters -> 'source') = 'array' and jsonb_array_length(v_filters -> 'source') = 0)) or x."source"::text = any((case when jsonb_typeof(v_filters -> 'source') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'source')) else array[v_filters ->> 'source'] end)::text[]))
and (not (v_filters -> 'mediaType' is not null and jsonb_typeof(v_filters -> 'mediaType') <> 'null' and not (jsonb_typeof(v_filters -> 'mediaType') = 'array' and jsonb_array_length(v_filters -> 'mediaType') = 0)) or (x."media_type")::text = any((case when jsonb_typeof(v_filters -> 'mediaType') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'mediaType')) else array[v_filters ->> 'mediaType'] end)::text[]))
and (v_search is null or x."filename" ilike v_search)
and (v_after is null or (lower(x."filename") <= (v_after ->> 0)::text and ((lower(x."filename") < (v_after ->> 0)::text) or (lower(x."filename") = (v_after ->> 0)::text and x."id" > (v_after ->> 1)::uuid))))
order by lower(x."filename") desc, x."id" asc
limit v_limit + 1 offset v_offset
) x
) p;
elsif v_sort = 'size' 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 = 'AI_FILE_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", 'organization_id', x."tenant_id", 'owner_id', x."owner_id", 'chat_id', x."chat_id", 'project_id', x."project_id", 'bucket', x."bucket", 'path', x."path", 'media_type', x."media_type", 'filename', x."filename", 'byte_size', x."byte_size", 'sha256', x."sha256", 'status', x."status", 'source', x."source", 'created_at', x."created_at", 'uploaded_at', x."uploaded_at", 'expires_at', x."expires_at") as j, jsonb_build_array((x."byte_size")::text, (x."id")::text) as k
from (
select * from "better_supabase"."ai_files" x
where x."tenant_id" = page_ai_files.tenant
and (v_chat is null or x."chat_id" = v_chat::uuid)
and (not (v_filters -> 'status' is not null and jsonb_typeof(v_filters -> 'status') <> 'null' and not (jsonb_typeof(v_filters -> 'status') = 'array' and jsonb_array_length(v_filters -> 'status') = 0)) or x."status"::text = any((case when jsonb_typeof(v_filters -> 'status') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'status')) else array[v_filters ->> 'status'] end)::text[]))
and (not (v_filters -> 'source' is not null and jsonb_typeof(v_filters -> 'source') <> 'null' and not (jsonb_typeof(v_filters -> 'source') = 'array' and jsonb_array_length(v_filters -> 'source') = 0)) or x."source"::text = any((case when jsonb_typeof(v_filters -> 'source') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'source')) else array[v_filters ->> 'source'] end)::text[]))
and (not (v_filters -> 'mediaType' is not null and jsonb_typeof(v_filters -> 'mediaType') <> 'null' and not (jsonb_typeof(v_filters -> 'mediaType') = 'array' and jsonb_array_length(v_filters -> 'mediaType') = 0)) or (x."media_type")::text = any((case when jsonb_typeof(v_filters -> 'mediaType') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'mediaType')) else array[v_filters ->> 'mediaType'] end)::text[]))
and (v_search is null or x."filename" ilike v_search)
and (v_after is null or (x."byte_size", x."id") > ((v_after ->> 0)::bigint, (v_after ->> 1)::uuid))
order by x."byte_size" asc, x."id" asc
limit v_limit + 1 offset v_offset
) x
) p;
elsif v_sort = 'size' 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 = 'AI_FILE_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", 'organization_id', x."tenant_id", 'owner_id', x."owner_id", 'chat_id', x."chat_id", 'project_id', x."project_id", 'bucket', x."bucket", 'path', x."path", 'media_type', x."media_type", 'filename', x."filename", 'byte_size', x."byte_size", 'sha256', x."sha256", 'status', x."status", 'source', x."source", 'created_at', x."created_at", 'uploaded_at', x."uploaded_at", 'expires_at', x."expires_at") as j, jsonb_build_array((x."byte_size")::text, (x."id")::text) as k
from (
select * from "better_supabase"."ai_files" x
where x."tenant_id" = page_ai_files.tenant
and (v_chat is null or x."chat_id" = v_chat::uuid)
and (not (v_filters -> 'status' is not null and jsonb_typeof(v_filters -> 'status') <> 'null' and not (jsonb_typeof(v_filters -> 'status') = 'array' and jsonb_array_length(v_filters -> 'status') = 0)) or x."status"::text = any((case when jsonb_typeof(v_filters -> 'status') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'status')) else array[v_filters ->> 'status'] end)::text[]))
and (not (v_filters -> 'source' is not null and jsonb_typeof(v_filters -> 'source') <> 'null' and not (jsonb_typeof(v_filters -> 'source') = 'array' and jsonb_array_length(v_filters -> 'source') = 0)) or x."source"::text = any((case when jsonb_typeof(v_filters -> 'source') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'source')) else array[v_filters ->> 'source'] end)::text[]))
and (not (v_filters -> 'mediaType' is not null and jsonb_typeof(v_filters -> 'mediaType') <> 'null' and not (jsonb_typeof(v_filters -> 'mediaType') = 'array' and jsonb_array_length(v_filters -> 'mediaType') = 0)) or (x."media_type")::text = any((case when jsonb_typeof(v_filters -> 'mediaType') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'mediaType')) else array[v_filters ->> 'mediaType'] end)::text[]))
and (v_search is null or x."filename" ilike v_search)
and (v_after is null or (x."byte_size" <= (v_after ->> 0)::bigint and ((x."byte_size" < (v_after ->> 0)::bigint) or (x."byte_size" = (v_after ->> 0)::bigint and x."id" > (v_after ->> 1)::uuid))))
order by x."byte_size" 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"."ai_files" x
where x."tenant_id" = page_ai_files.tenant
and (v_chat is null or x."chat_id" = v_chat::uuid)
and (not (v_filters -> 'status' is not null and jsonb_typeof(v_filters -> 'status') <> 'null' and not (jsonb_typeof(v_filters -> 'status') = 'array' and jsonb_array_length(v_filters -> 'status') = 0)) or x."status"::text = any((case when jsonb_typeof(v_filters -> 'status') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'status')) else array[v_filters ->> 'status'] end)::text[]))
and (not (v_filters -> 'source' is not null and jsonb_typeof(v_filters -> 'source') <> 'null' and not (jsonb_typeof(v_filters -> 'source') = 'array' and jsonb_array_length(v_filters -> 'source') = 0)) or x."source"::text = any((case when jsonb_typeof(v_filters -> 'source') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'source')) else array[v_filters ->> 'source'] end)::text[]))
and (not (v_filters -> 'mediaType' is not null and jsonb_typeof(v_filters -> 'mediaType') <> 'null' and not (jsonb_typeof(v_filters -> 'mediaType') = 'array' and jsonb_array_length(v_filters -> 'mediaType') = 0)) or (x."media_type")::text = any((case when jsonb_typeof(v_filters -> 'mediaType') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'mediaType')) else array[v_filters ->> 'mediaType'] end)::text[]))
and (v_search is null or x."filename" 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_ai_files"(uuid, jsonb) from public, anon;
grant execute on function "better_supabase"."page_ai_files"(uuid, jsonb) to authenticated, service_role;
-- Deletes the record; returns { bucket, path } for the Storage API to
-- remove the object, or null when the caller may not delete it.
create or replace function "better_supabase"."delete_ai_file"(file_id uuid)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
declare
v_row "better_supabase"."ai_files"%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"."ai_files" x where x."id" = delete_ai_file.file_id;
if not found or not (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or coalesce(v_row."owner_id" = auth.uid(), false) or coalesce(better_supabase.can('tenant', v_row."tenant_id", 'ai_files.manage'), false)) then
return null;
end if;
delete from "better_supabase"."ai_files" x where x."id" = v_row."id";
return jsonb_build_object('bucket', v_row."bucket", 'path', v_row."path");
end;
$$;
revoke execute on function "better_supabase"."delete_ai_file"(uuid) from public, anon;
grant execute on function "better_supabase"."delete_ai_file"(uuid) to authenticated, service_role;
-- A ready file the server writes itself (a generated image, speech, a file
-- a provider returned), owned by owner; the caller uploads to its path.
create or replace function "better_supabase"."store_ai_file"(
tenant uuid,
owner uuid,
filename text,
media_type text,
byte_size bigint,
chat_id uuid default null,
source text default 'generated',
sha256 text default null
)
returns jsonb
language plpgsql
set search_path = ''
as $$
declare
v_row "better_supabase"."ai_files"%rowtype;
begin
insert into "better_supabase"."ai_files" ("tenant_id", "owner_id", "chat_id", "bucket", "filename", "media_type", "byte_size", "status", "source", "sha256", "uploaded_at")
values (store_ai_file.tenant, store_ai_file.owner, store_ai_file.chat_id, 'ai-files', store_ai_file.filename, lower(store_ai_file.media_type), store_ai_file.byte_size, 'ready', coalesce(store_ai_file.source, 'generated'), lower(store_ai_file.sha256), now())
returning * into v_row;
return jsonb_build_object('id', v_row."id", 'organization_id', v_row."tenant_id", 'owner_id', v_row."owner_id", 'chat_id', v_row."chat_id", 'project_id', v_row."project_id", 'bucket', v_row."bucket", 'path', v_row."path", 'media_type', v_row."media_type", 'filename', v_row."filename", 'byte_size', v_row."byte_size", 'sha256', v_row."sha256", 'status', v_row."status", 'source', v_row."source", 'created_at', v_row."created_at", 'uploaded_at', v_row."uploaded_at", 'expires_at', v_row."expires_at");
end;
$$;
revoke execute on function "better_supabase"."store_ai_file"(uuid, uuid, text, text, bigint, uuid, text, text) from public, anon, authenticated;
grant execute on function "better_supabase"."store_ai_file"(uuid, uuid, text, text, bigint, uuid, text, text) to service_role;
create or replace function "better_supabase"."set_ai_provider_file"(file_id uuid, provider text, reference text, expires_at timestamptz default null)
returns boolean
language sql
set search_path = ''
as $$
insert into "better_supabase"."ai_provider_files" ("file_id", "provider", "reference", "expires_at")
values (set_ai_provider_file.file_id, set_ai_provider_file.provider, set_ai_provider_file.reference, set_ai_provider_file.expires_at)
on conflict ("file_id", "provider") do update
set "reference" = excluded."reference", "expires_at" = excluded."expires_at", "created_at" = now()
returning true
$$;
revoke execute on function "better_supabase"."set_ai_provider_file"(uuid, text, text, timestamptz) from public, anon, authenticated;
grant execute on function "better_supabase"."set_ai_provider_file"(uuid, text, text, timestamptz) to service_role;
-- The provider's reference while it is still valid, or null.
create or replace function "better_supabase"."get_ai_provider_file"(file_id uuid, provider text)
returns jsonb
language sql
stable
set search_path = ''
as $$
select jsonb_build_object('file_id', p."file_id", 'provider', p."provider", 'reference', p."reference", 'expires_at', p."expires_at")
from "better_supabase"."ai_provider_files" p
where p."file_id" = get_ai_provider_file.file_id and p."provider" = get_ai_provider_file.provider
and (p."expires_at" is null or p."expires_at" > now())
$$;
revoke execute on function "better_supabase"."get_ai_provider_file"(uuid, text) from public, anon, authenticated;
grant execute on function "better_supabase"."get_ai_provider_file"(uuid, text) to service_role;
-- Provider references that expire within horizon, for a refresh job.
create or replace function "better_supabase"."expiring_ai_provider_files"(horizon interval default '1 day', batch integer default 100)
returns jsonb
language sql
stable
set search_path = ''
as $$
select coalesce(jsonb_agg(jsonb_build_object('file_id', p."file_id", 'provider', p."provider", 'reference', p."reference", 'expires_at', p."expires_at")), '[]'::jsonb)
from (
select * from "better_supabase"."ai_provider_files"
where "expires_at" is not null and "expires_at" <= now() + coalesce(horizon, interval '1 day')
order by "expires_at"
limit greatest(coalesce(batch, 100), 1)
) p
$$;
revoke execute on function "better_supabase"."expiring_ai_provider_files"(interval, integer) from public, anon, authenticated;
grant execute on function "better_supabase"."expiring_ai_provider_files"(interval, integer) to service_role;
-- Deletes pending uploads older than older_than, expired files and, with
-- ai-chat installed, the files of deleted chats. Returns the { bucket, path }
-- objects for the Storage API to remove.
create or replace function "better_supabase"."purge_ai_files"(older_than interval default '1 day', batch integer default 500)
returns jsonb
language plpgsql
set search_path = ''
as $$
declare
v_removed jsonb;
begin
with doomed as (
select x."id" from "better_supabase"."ai_files" x
where (x."status" = 'pending' and x."created_at" <= now() - coalesce(older_than, interval '1 day'))
or x."expires_at" <= now()
limit greatest(coalesce(batch, 500), 1)
),
gone as (
delete from "better_supabase"."ai_files" x using doomed where x."id" = doomed."id"
returning x."bucket" as bucket, x."path" as path
)
select coalesce(jsonb_agg(jsonb_build_object('bucket', gone.bucket, 'path', gone.path)), '[]'::jsonb) into v_removed from gone;
return v_removed;
end;
$$;
revoke execute on function "better_supabase"."purge_ai_files"(interval, integer) from public, anon, authenticated;
grant execute on function "better_supabase"."purge_ai_files"(interval, integer) to service_role;
-- A document with its first version. The caller needs upload rights in the
-- organization; the service role writes for an owner.
create or replace function "better_supabase"."create_ai_document"(
tenant uuid,
kind text,
title text,
content text default null,
chat_id uuid default null,
message_id text default null,
owner uuid default null,
storage_path text default null
)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
declare
v_owner uuid := case when coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') then create_ai_document.owner else auth.uid() end;
v_row "better_supabase"."ai_documents"%rowtype;
v_version jsonb;
begin
if not (better_supabase.actor_may_write()) then
raise exception 'This session is read-only' using errcode = '42501', hint = 'ACTOR_READ_ONLY';
end if;
if v_owner is null or not (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or coalesce(better_supabase.can('tenant', create_ai_document.tenant, 'ai_files.upload'), false)) then
raise exception 'you may not create documents here' using errcode = '42501', hint = 'AI_DOCUMENT_FORBIDDEN';
end if;
insert into "better_supabase"."ai_documents" ("tenant_id", "owner_id", "chat_id", "kind", "title")
values (create_ai_document.tenant, v_owner, create_ai_document.chat_id, create_ai_document.kind, create_ai_document.title)
returning * into v_row;
v_version := "better_supabase"."version_insert"(v_row."tenant_id", 'ai_document', v_row."id"::text, jsonb_build_object('text', create_ai_document.content, 'messageId', create_ai_document.message_id), create_ai_document.storage_path, null, 'manual', false, v_owner);
update "better_supabase"."ai_documents" x set "current_version" = (v_version ->> 'number')::integer
where x."id" = v_row."id"
returning * into v_row;
return jsonb_build_object('id', v_row."id", 'organization_id', v_row."tenant_id", 'owner_id', v_row."owner_id", 'chat_id', v_row."chat_id", 'kind', v_row."kind", 'title', v_row."title", 'current_version', v_row."current_version", 'created_at', v_row."created_at", 'updated_at', v_row."updated_at");
end;
$$;
revoke execute on function "better_supabase"."create_ai_document"(uuid, text, text, text, uuid, text, uuid, text) from public, anon;
grant execute on function "better_supabase"."create_ai_document"(uuid, text, text, text, uuid, text, uuid, text) to authenticated, service_role;
-- A new version of the document. expected_version guards against two
-- writers: when it is set and not the current version, nothing changes.
create or replace function "better_supabase"."update_ai_document"(
document_id uuid,
content text default null,
title text default null,
message_id text default null,
expected_version integer default null,
storage_path text default null
)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
declare
v_row "better_supabase"."ai_documents"%rowtype;
v_version jsonb;
begin
if not (better_supabase.actor_may_write()) then
raise exception 'This session is read-only' using errcode = '42501', hint = 'ACTOR_READ_ONLY';
end if;
select * into v_row from "better_supabase"."ai_documents" x where x."id" = update_ai_document.document_id for update;
if not found or not (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or coalesce(v_row."owner_id" = auth.uid(), false) or coalesce(better_supabase.can('tenant', v_row."tenant_id", 'ai_files.manage'), false)) then
raise exception 'document % not found', document_id using errcode = 'P0002', hint = 'AI_DOCUMENT_NOT_FOUND';
end if;
if expected_version is not null and expected_version <> v_row."current_version" then
raise exception 'document % is at version %', document_id, v_row."current_version" using errcode = '40001', hint = 'AI_DOCUMENT_CONFLICT';
end if;
v_version := "better_supabase"."version_insert"(v_row."tenant_id", 'ai_document', v_row."id"::text, jsonb_build_object('text', update_ai_document.content, 'messageId', update_ai_document.message_id), update_ai_document.storage_path, null, 'manual', false, auth.uid());
update "better_supabase"."ai_documents" x set
"current_version" = (v_version ->> 'number')::integer,
"title" = coalesce(update_ai_document.title, x."title"),
"updated_at" = now()
where x."id" = v_row."id"
returning * into v_row;
return jsonb_build_object('id', v_row."id", 'organization_id', v_row."tenant_id", 'owner_id', v_row."owner_id", 'chat_id', v_row."chat_id", 'kind', v_row."kind", 'title', v_row."title", 'current_version', v_row."current_version", 'created_at', v_row."created_at", 'updated_at', v_row."updated_at");
end;
$$;
revoke execute on function "better_supabase"."update_ai_document"(uuid, text, text, text, integer, text) from public, anon;
grant execute on function "better_supabase"."update_ai_document"(uuid, text, text, text, integer, text) to authenticated, service_role;
-- Writes version as the newest version again.
create or replace function "better_supabase"."rollback_ai_document"(document_id uuid, version integer)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
declare
v_row "better_supabase"."ai_documents"%rowtype;
v_content jsonb;
v_storage_path text;
v_version jsonb;
begin
if not (better_supabase.actor_may_write()) then
raise exception 'This session is read-only' using errcode = '42501', hint = 'ACTOR_READ_ONLY';
end if;
select * into v_row from "better_supabase"."ai_documents" x where x."id" = rollback_ai_document.document_id for update;
if not found or not (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or coalesce(v_row."owner_id" = auth.uid(), false) or coalesce(better_supabase.can('tenant', v_row."tenant_id", 'ai_files.manage'), false)) then
raise exception 'document % not found', document_id using errcode = 'P0002', hint = 'AI_DOCUMENT_NOT_FOUND';
end if;
select x."content", x."storage_path" into v_content, v_storage_path
from "better_supabase"."versions" x where x."subject_type" = 'ai_document' and x."subject_id" = v_row."id"::text and x."number" = rollback_ai_document.version;
if not found then
raise exception 'document % has no version %', document_id, rollback_ai_document.version using errcode = 'P0002', hint = 'AI_DOCUMENT_VERSION_NOT_FOUND';
end if;
v_version := "better_supabase"."version_insert"(v_row."tenant_id", 'ai_document', v_row."id"::text, jsonb_build_object('text', v_content ->> 'text', 'messageId', null::text), v_storage_path, null, 'restore', false, auth.uid());
update "better_supabase"."ai_documents" x set "current_version" = (v_version ->> 'number')::integer, "updated_at" = now()
where x."id" = v_row."id"
returning * into v_row;
return jsonb_build_object('id', v_row."id", 'organization_id', v_row."tenant_id", 'owner_id', v_row."owner_id", 'chat_id', v_row."chat_id", 'kind', v_row."kind", 'title', v_row."title", 'current_version', v_row."current_version", 'created_at', v_row."created_at", 'updated_at', v_row."updated_at");
end;
$$;
revoke execute on function "better_supabase"."rollback_ai_document"(uuid, integer) from public, anon;
grant execute on function "better_supabase"."rollback_ai_document"(uuid, integer) to authenticated, service_role;
-- The document with its current version's content, for a reader of it.
create or replace function "better_supabase"."get_ai_document"(document_id uuid)
returns jsonb
language plpgsql
stable
security definer
set search_path = ''
as $$
declare
v_row "better_supabase"."ai_documents"%rowtype;
v_content jsonb;
v_storage_path text;
begin
select * into v_row from "better_supabase"."ai_documents" x where x."id" = get_ai_document.document_id;
if not found or not (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or (v_row."owner_id" = (select auth.uid()) or coalesce(better_supabase.can('tenant', v_row."tenant_id", 'ai_files.manage'), false) or false)) then
return null;
end if;
select x."content", x."storage_path" into v_content, v_storage_path
from "better_supabase"."versions" x where x."subject_type" = 'ai_document' and x."subject_id" = v_row."id"::text and x."number" = v_row."current_version";
return jsonb_build_object('id', v_row."id", 'organization_id', v_row."tenant_id", 'owner_id', v_row."owner_id", 'chat_id', v_row."chat_id", 'kind', v_row."kind", 'title', v_row."title", 'current_version', v_row."current_version", 'created_at', v_row."created_at", 'updated_at', v_row."updated_at") || jsonb_build_object('content', v_content ->> 'text', 'storage_path', v_storage_path);
end;
$$;
revoke execute on function "better_supabase"."get_ai_document"(uuid) from public, anon;
grant execute on function "better_supabase"."get_ai_document"(uuid) to authenticated, service_role;
-- Every version of a document the caller can read, newest first.
create or replace function "better_supabase"."list_ai_document_versions"(document_id uuid)
returns jsonb
language plpgsql
stable
security definer
set search_path = ''
as $$
declare
v_row "better_supabase"."ai_documents"%rowtype;
v_versions jsonb;
begin
select * into v_row from "better_supabase"."ai_documents" x where x."id" = list_ai_document_versions.document_id;
if not found or not (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or (v_row."owner_id" = (select auth.uid()) or coalesce(better_supabase.can('tenant', v_row."tenant_id", 'ai_files.manage'), false) or false)) then
return '[]'::jsonb;
end if;
select coalesce(jsonb_agg(jsonb_build_object('document_id', x."subject_id"::uuid, 'version', x."number", 'content', x."content" ->> 'text', 'storage_path', x."storage_path", 'created_by_message_id', x."content" ->> 'messageId', 'created_by', x."created_by", 'created_at', x."created_at") order by x."number" desc), '[]'::jsonb) into v_versions
from "better_supabase"."versions" x where x."subject_type" = 'ai_document' and x."subject_id" = v_row."id"::text;
return v_versions;
end;
$$;
revoke execute on function "better_supabase"."list_ai_document_versions"(uuid) from public, anon;
grant execute on function "better_supabase"."list_ai_document_versions"(uuid) to authenticated, service_role;
-- A suggested edit on the current version; the assistant or a reader of the
-- document writes it, the owner resolves it.
create or replace function "better_supabase"."suggest_ai_document_edit"(document_id uuid, original_text text, suggested_text text, description text default null)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
declare
v_doc "better_supabase"."ai_documents"%rowtype;
v_row "better_supabase"."ai_suggestions"%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_doc from "better_supabase"."ai_documents" x where x."id" = suggest_ai_document_edit.document_id;
if not found or not (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or (v_doc."owner_id" = (select auth.uid()) or coalesce(better_supabase.can('tenant', v_doc."tenant_id", 'ai_files.manage'), false) or false)) then
raise exception 'document % not found', document_id using errcode = 'P0002', hint = 'AI_DOCUMENT_NOT_FOUND';
end if;
insert into "better_supabase"."ai_suggestions" ("document_id", "version", "original_text", "suggested_text", "description", "created_by")
values (v_doc."id", v_doc."current_version", suggest_ai_document_edit.original_text, suggest_ai_document_edit.suggested_text, suggest_ai_document_edit.description, auth.uid())
returning * into v_row;
return jsonb_build_object('id', v_row."id", 'document_id', v_row."document_id", 'version', v_row."version", 'original_text', v_row."original_text", 'suggested_text', v_row."suggested_text", 'description', v_row."description", 'created_by', v_row."created_by", 'created_at', v_row."created_at", 'resolved_at', v_row."resolved_at", 'accepted', v_row."accepted");
end;
$$;
revoke execute on function "better_supabase"."suggest_ai_document_edit"(uuid, text, text, text) from public, anon;
grant execute on function "better_supabase"."suggest_ai_document_edit"(uuid, text, text, text) to authenticated, service_role;
create or replace function "better_supabase"."list_ai_suggestions"(document_id uuid, open_only boolean default true)
returns jsonb
language sql
stable
security invoker
set search_path = ''
as $$
select coalesce(jsonb_agg(jsonb_build_object('id', x."id", 'document_id', x."document_id", 'version', x."version", 'original_text', x."original_text", 'suggested_text', x."suggested_text", 'description', x."description", 'created_by', x."created_by", 'created_at', x."created_at", 'resolved_at', x."resolved_at", 'accepted', x."accepted") order by x."created_at"), '[]'::jsonb)
from "better_supabase"."ai_suggestions" x
where x."document_id" = list_ai_suggestions.document_id
and (not coalesce(open_only, true) or x."resolved_at" is null)
$$;
revoke execute on function "better_supabase"."list_ai_suggestions"(uuid, boolean) from public, anon;
grant execute on function "better_supabase"."list_ai_suggestions"(uuid, boolean) to authenticated, service_role;
-- Accepts or rejects a suggestion; accepting doesn't edit the document, the
-- client writes the new version with update_ai_document.
create or replace function "better_supabase"."resolve_ai_suggestion"(suggestion_id uuid, accepted boolean)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
declare
v_row "better_supabase"."ai_suggestions"%rowtype;
v_doc "better_supabase"."ai_documents"%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"."ai_suggestions" x where x."id" = resolve_ai_suggestion.suggestion_id for update;
if found then
select * into v_doc from "better_supabase"."ai_documents" x where x."id" = v_row."document_id";
end if;
if v_doc."id" is null or not (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or coalesce(v_doc."owner_id" = auth.uid(), false) or coalesce(better_supabase.can('tenant', v_doc."tenant_id", 'ai_files.manage'), false)) then
raise exception 'suggestion % not found', suggestion_id using errcode = 'P0002', hint = 'AI_SUGGESTION_NOT_FOUND';
end if;
update "better_supabase"."ai_suggestions" x set "resolved_at" = now(), "accepted" = resolve_ai_suggestion.accepted
where x."id" = v_row."id"
returning * into v_row;
return jsonb_build_object('id', v_row."id", 'document_id', v_row."document_id", 'version', v_row."version", 'original_text', v_row."original_text", 'suggested_text', v_row."suggested_text", 'description', v_row."description", 'created_by', v_row."created_by", 'created_at', v_row."created_at", 'resolved_at', v_row."resolved_at", 'accepted', v_row."accepted");
end;
$$;
revoke execute on function "better_supabase"."resolve_ai_suggestion"(uuid, boolean) from public, anon;
grant execute on function "better_supabase"."resolve_ai_suggestion"(uuid, boolean) to authenticated, service_role;
-- Deletes a document and, through its trigger, its versions; true when the
-- caller could.
create or replace function "better_supabase"."delete_ai_document"(document_id uuid)
returns boolean
language plpgsql
security definer
set search_path = ''
as $$
declare
v_row "better_supabase"."ai_documents"%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"."ai_documents" x where x."id" = delete_ai_document.document_id;
if not found or not (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or coalesce(v_row."owner_id" = auth.uid(), false) or coalesce(better_supabase.can('tenant', v_row."tenant_id", 'ai_files.manage'), false)) then
return false;
end if;
delete from "better_supabase"."ai_documents" x where x."id" = v_row."id";
return true;
end;
$$;
revoke execute on function "better_supabase"."delete_ai_document"(uuid) from public, anon;
grant execute on function "better_supabase"."delete_ai_document"(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"."ai_files" as restrictive
for select to public
using (
"tenant_id" in (select better_supabase.member_organization_ids())
or (("owner_id" = (select auth.uid()) or "tenant_id" in (select better_supabase.tenant_ids_with('ai_files.manage')) or false))
);
create policy bsb_tenant_scope_insert on "better_supabase"."ai_files" 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"."ai_files" 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"."ai_files" 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"."ai_documents" as restrictive
for select to public
using (
"tenant_id" in (select better_supabase.member_organization_ids())
or (("owner_id" = (select auth.uid()) or "tenant_id" in (select better_supabase.tenant_ids_with('ai_files.manage')) or false))
);
create policy bsb_tenant_scope_insert on "better_supabase"."ai_documents" 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"."ai_documents" 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"."ai_documents" 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/ai-files, which runs on the server.
Events
With the outbox installed, the module writes these in the same transaction as the change.
This module writes no outbox events.
Dependencies
- Required: the install command adds it too
- Works with: optional
Requires
Works with
Recipes
No UI recipe uses it yet. See all recipes.
More in AI
Vector searchvector-search search_<table>(query, k) for each table in vectorSearch: the k nearest rows the caller can read, with pgvector iterative index scans so RLS filters still return k rows. AI chatai-chat Chats, projects, participants and a message tree (or one linear list) in the canonical AI message format or the SDK's own parts, with runs (and the id of a durable engine's run), run steps for progress, a compare-and-set stream claim, harness sessions, tool approvals and policies, pending inputs, cited sources, feedback, hashed share links, a model catalog per plan, moderation events and private Realtime topics per chat and per user.React hooks Knowledgeknowledge Documents and chunks for retrieval with an embedding and a tsvector each, scoped to an organization, agent, project, chat, user or record (subject) and grouped into collections with a visibility, a priority and grants, plus system documents shared with every tenant; hybrid search with reciprocal rank fusion, chunks that keep their embedding when unchanged, and an embed job per document when jobs is installed. With ai-files and jobs, queue_knowledge_file ingests a file through a job. Memorymemory Memory for AI assistants: core memory as files under /memories edited with view, create, str_replace, insert, delete and rename with version checks; archival facts with hybrid similarity search; message embeddings to recall earlier chats, skipped for temporary chats; and versioned documents under an opaque scope key for agent runtimes such as eve. Agentsagents Custom assistants with instructions, a model, tools, connectors, knowledge scopes and starters; private until published to the organization or the public store, with installs, ratings and provider skills. AI scheduled tasksai-schedules Prompts a user schedules on a cron, with a run per occurrence; the scheduler claims due tasks, queues an ai_task_run job when jobs is installed, and fails runs that stall.