mike/backend/migrations/20260613_01_chats_overview_rpc.sql

39 lines
778 B
PL/PgSQL

-- Migration date: 2026-06-13
-- Global assistant chats overview read model.
-- Returns the user's own chats plus chats under projects they own.
create or replace function public.get_chats_overview(
p_user_id text,
p_limit integer default null
)
returns table (
id uuid,
project_id uuid,
user_id text,
title text,
created_at timestamptz
)
language sql
stable
as $$
select
c.id,
c.project_id,
c.user_id,
c.title,
c.created_at
from public.chats c
where c.user_id = p_user_id
or exists (
select 1
from public.projects p
where p.id = c.project_id
and p.user_id = p_user_id
)
order by c.created_at desc
limit case
when p_limit is null then null
else greatest(1, least(p_limit, 100))
end;
$$;