Files
mtusi2026lab7/migrations/006_message_locks.sql
T

20 lines
918 B
PL/PgSQL

-- Lock rows with the migration owner's privileges without granting business UPDATE.
CREATE FUNCTION lock_chat_member(chat uuid, actor uuid) RETURNS boolean
LANGUAGE sql SECURITY DEFINER SET search_path = pg_catalog, public
AS $$
SELECT EXISTS (
SELECT 1 FROM public.chat_members WHERE chat_id = chat AND user_id = actor FOR KEY SHARE
)
$$;
CREATE FUNCTION lock_chat_attachments(chat uuid, ids uuid[]) RETURNS TABLE(id uuid, status text)
LANGUAGE sql SECURITY DEFINER SET search_path = pg_catalog, public
AS $$
SELECT a.id, a.status FROM public.attachments a
WHERE a.chat_id = chat AND a.id = ANY(ids) ORDER BY a.id FOR SHARE
$$;
REVOKE ALL ON FUNCTION lock_chat_member(uuid, uuid), lock_chat_attachments(uuid, uuid[]) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION lock_chat_member(uuid, uuid), lock_chat_attachments(uuid, uuid[]) TO lab_api;
REVOKE UPDATE (chat_id) ON chat_members FROM lab_api;