-- ============================================================ -- Migration 051: RLS Performance Fixes -- Addresses all Supabase linter warnings: -- 1. auth_rls_initplan: wrap auth.uid() in (select auth.uid()) -- 2. multiple_permissive_policies: consolidate overlapping policies -- ============================================================ -- ============================================================ -- PART 1: Fix auth_rls_initplan -- Replace auth.uid() with (select auth.uid()) in ALL RLS policies -- using a dynamic DO block that reads pg_policies catalog -- ============================================================ DO $$ DECLARE r record; qual_new text; check_new text; cmd_parts text[]; sql_cmd text; BEGIN FOR r IN SELECT schemaname, tablename, policyname, permissive, roles, cmd AS policy_cmd, qual, with_check FROM pg_policies WHERE schemaname = 'public' AND ( qual ~ 'auth\.uid\(\)' AND qual !~ '\(\s*select\s+auth\.uid\(\)\s*\)' OR with_check ~ 'auth\.uid\(\)' AND with_check !~ '\(\s*select\s+auth\.uid\(\)\s*\)' ) LOOP -- Replace auth.uid() with (select auth.uid()) in USING clause qual_new := r.qual; IF qual_new IS NOT NULL THEN -- Avoid double-wrapping: only replace bare auth.uid() not already in (select ...) qual_new := regexp_replace(qual_new, '(?