Skip to content

feat: implement caching for the directory search endpoint (#926) - #2829

Merged
krushit1307 merged 4 commits into
krushit1307:mainfrom
Neel-2606:feat/issue-926-directory-search-cache
Aug 9, 2026
Merged

krushit1307 merged 4 commits into
krushit1307:mainfrom
Neel-2606:feat/issue-926-directory-search-cache

Conversation

@Neel-2606

@Neel-2606 Neel-2606 commented Aug 9, 2026 •

Copy link
Copy Markdown
Contributor

Closes #926

📝 Context

This PR updates the application's backend GraphQL layer to add an in-memory cache for the directory search (profiles query endpoint) to reduce database hits for common page and sort configurations.

🐛/✨ Problem / Request

Before this change, the profiles query fetched data directly from the Supabase Postgres instance on every page load and search request, which could lead to redundant database hits, especially for the initial "top 20" search results.

✅ Solution

  • Instantiated a new LRUCache instance (profilesCache) in graphql/resolvers/index.ts.
  • Updated the profiles query to utilize a compound cache key based on the paginated request parameters (limit:offset:sortBy:sortOrder).
  • Set up a real-time postgres_changes channel subscription in Supabase to invalidate the profilesCache automatically whenever the underlying profiles table is modified, ensuring that the directory cache never gets stale.

Summary by CodeRabbit

  • New Features

    • Added paginated club browsing with “Load More Clubs” support.
    • Search, category, and tag filters now work together, including AND-based tag filtering.
    • Empty states provide clearer messaging for filtered results.
  • Bug Fixes

    • Improved error reporting by removing sensitive information from displayed and logged errors.
    • Account merges and dormant-account cleanup now preserve records through soft deletion.
  • Performance

    • Improved profile and club data loading through caching and server-side filtering.

@github-actions github-actions Bot added ECSoC26 Elite Coders Summer Of Code'26 - Open Source Program enhancement New feature or request feature labels Aug 9, 2026
@coderabbitai

coderabbitai Bot commented Aug 9, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

The pull request adds paginated server-side club filtering, profile resolver caching, sanitized error telemetry, and soft-deletion with authentication bans for merged and dormant accounts.

Changes

Club directory pagination

Layer / File(s) Summary
Filtered clubs RPC
supabase/migrations/20260810000001_clubs_pagination_rpc.sql
Adds get_filtered_clubs with search, category, AND-based tag filtering, deleted-club exclusion, ordering, and public execution grants.
Paginated club loading and rendering
src/routes/clubs.index.tsx
Replaces client-side filtering with useInfiniteQuery, server-side filters, 12-item pages, flattened results, HoverLink cards, profile prefetching, and a “Load More Clubs” button.

Profile resolver caching

Layer / File(s) Summary
Profile cache and invalidation
graphql/resolvers/index.ts
Adds a 50-entry LRU cache keyed by pagination and sorting parameters. Supabase realtime events clear the cache when profiles changes.

Error telemetry sanitization

Layer / File(s) Summary
Sanitized error reporting
src/components/ErrorBoundary.tsx
Redacts sensitive values from errors and stacks before React logging, OpenTelemetry recording, and route status reporting.

Account retention changes

Layer / File(s) Summary
Merge account cleanup
supabase/migrations/20260729200000_merge_user_accounts_rpc.sql, supabase/functions/merge-accounts/index.ts
Removes leftover secondary-account rows, soft-deletes the secondary profile, and bans the secondary authentication account for 876000 hours.
Dormant account cleanup
supabase/functions/purge-dormant-accounts/index.ts, supabase/functions/globals.d.ts
Soft-deletes dormant profiles and bans their authentication users. Adds Deno and module-specifier declarations for Supabase functions.

Estimated code review effort: 4 (Complex) | ~60 minutes

Sequence Diagram(s)

sequenceDiagram
  participant ClubsPage
  participant get_filtered_clubs
  participant ClubsTable
  ClubsPage->>get_filtered_clubs: Request a filtered page
  get_filtered_clubs->>ClubsTable: Apply search, category, and tag filters
  ClubsTable-->>get_filtered_clubs: Return ordered clubs
  get_filtered_clubs-->>ClubsPage: Return the page
  ClubsPage->>ClubsPage: Render results or fetch the next page
Loading

Possibly related PRs

Suggested labels: backend, optimization, performance

Suggested reviewers: ayush-0918, aryanbuha890

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Out of Scope Changes check ⚠️ Warning The PR also changes error sanitization, club pagination, account lifecycle handling, and TypeScript declarations unrelated to [#926]. Move unrelated changes into separate pull requests, and keep this PR focused on directory search caching.
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly identifies the primary change: caching for the directory search endpoint.
Linked Issues check ✅ Passed The PR adds an in-memory LRU cache with parameter-based keys and profile-change invalidation, satisfying the caching objective in [#926].
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@Neel-2606
Neel-2606 force-pushed the feat/issue-926-directory-search-cache branch from 9d5aafd to 60c5396 Compare August 9, 2026 20:26

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 13

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@graphql/resolvers/index.ts`:
- Line 592: Remove the trailing whitespace at the affected blank line in the
resolver file, preserving all surrounding code and behavior so the configured
Prettier ESLint rule passes.
- Around line 574-579: In the profiles resolver, normalize sortBy and sortOrder
into actualSortBy and actualSortOrder before constructing or reading the cache
key. Build the structured key from these effective values so invalid inputs
sharing the same normalized query reuse the same cache entry, while preserving
the existing cache lookup and return behavior.
- Around line 592-595: Update the profile query flow around profilesCache.set so
it tracks an invalidation generation before awaiting the database query,
increments that generation when profile-change invalidation clears the cache,
and only stores result when the generation is unchanged. Preserve returning the
query result while preventing an in-flight request from repopulating an
invalidated cache.
- Around line 147-160: Add bounded-staleness handling around the profilesCache
and the profiles-cache-invalidation subscription: apply a TTL to profile cache
entries, inspect subscription status, and handle CHANNEL_ERROR, TIMED_OUT, and
CLOSED by logging/reporting the failure and preventing profile cache hits until
the channel becomes healthy. Keep clubsCache invalidation behavior unchanged and
ensure successful profile channel recovery re-enables caching.

In `@src/components/ErrorBoundary.tsx`:
- Line 8: Format the SENSITIVE_PATTERN declaration according to Prettier by
inserting the required line break in the regular-expression declaration, without
changing the pattern or behavior.
- Around line 245-250: Update RouteErrorBoundary’s route-error handling to
sanitize routeError before both console.error and telemetry. Reuse the existing
safeError or safeMessage value in the console logging path so the original
routeError is never logged, while preserving the current telemetry behavior.
- Around line 8-22: Broaden SENSITIVE_PATTERN and sanitizeErrorMsg to match
compound sensitive keys such as authentication, credentials, and session_id, and
redact complete quoted values including embedded spaces while preserving
unquoted-value handling. Add regression cases in ErrorBoundary.test.tsx covering
these key forms and quoted secrets, verifying no sensitive value remains
exposed.

In `@src/routes/clubs.index.tsx`:
- Around line 71-100: Run the repository formatter on src/routes/clubs.index.tsx
to resolve Prettier issues: format the infinite-query declaration and RPC call
at lines 71-100, format the tag-label query at lines 104-110, format the club
card wrapper at line 222, and remove trailing whitespace at line 267.

In `@supabase/functions/merge-accounts/index.ts`:
- Around line 92-102: Make account cleanup idempotent and retryable across
merge-accounts and purge-dormant-accounts: in merge-accounts, ensure the Auth
ban via updateUserById completes successfully before returning, or persist a
pending_admin_removal/needs_auth_ban marker after the profile merge; in
purge-dormant-accounts, replace the broad cleanup catch with per-user result
handling and retry failed Auth updates through the scheduled workflow. Apply the
corresponding changes in supabase/functions/merge-accounts/index.ts (lines
92-102) and supabase/functions/purge-dormant-accounts/index.ts (lines 31-35).

In `@supabase/migrations/20260729200000_merge_user_accounts_rpc.sql`:
- Around line 87-88: Move the merge-user-accounts function definition containing
the secondary-profile UPDATE to a migration that runs after the deleted_at
schema migration, preserving its behavior. Update merge_user_accounts.test.sql
to assert that the secondary profile remains present with deleted_at set, rather
than asserting it is absent.
- Around line 76-85: Extend the account-merge RPC around the existing
secondary-profile cleanup statements to cover all remaining profile-related
tables affected by the soft-delete cascade change. For each relation, merge or
copy rows where business rules permit, soft-delete entities that follow
soft-deletion semantics, and explicitly delete dependent rows that previously
relied on hard-delete cascading; preserve conflict handling and ensure no
secondary-profile references remain.

In `@supabase/migrations/20260810000001_clubs_pagination_rpc.sql`:
- Around line 11-55: Update get_filtered_clubs to accept validated p_limit and
p_offset parameters, applying them as LIMIT and OFFSET in both the search and
non-search RETURN QUERY branches after filtering and ordering. Update the route
that calls this RPC to pass pageParam * PAGE_SIZE as the offset and PAGE_SIZE as
the limit, while preserving existing filters.
- Around line 21-54: Update the pagination query branches in the clubs RPC to
apply deterministic ordering before pagination. In the search branch using
public.search_clubs, compute and order by an explicit relevance metric with c.id
as the final tie-breaker; in the non-search branch’s ORDER BY, append c.id after
c.name ASC to stabilize duplicate-name ordering.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 523b7c84-78b2-4404-ae28-01c4798f38ab

📥 Commits

Reviewing files that changed from the base of the PR and between c242a96 and 60c5396.

📒 Files selected for processing (8)
  • graphql/resolvers/index.ts
  • src/components/ErrorBoundary.tsx
  • src/routes/clubs.index.tsx
  • supabase/functions/globals.d.ts
  • supabase/functions/merge-accounts/index.ts
  • supabase/functions/purge-dormant-accounts/index.ts
  • supabase/migrations/20260729200000_merge_user_accounts_rpc.sql
  • supabase/migrations/20260810000001_clubs_pagination_rpc.sql

Comment on lines 147 to +160
if (typeof supabase.channel === "function") {
supabase
.channel("clubs-cache-invalidation")
.on("postgres_changes", { event: "*", schema: "public", table: "clubs" }, () => {
clubsCache.delete(CLUBS_CACHE_KEY);
})
.subscribe();

supabase
.channel("profiles-cache-invalidation")
.on("postgres_changes", { event: "*", schema: "public", table: "profiles" }, () => {
profilesCache.clear();
})
.subscribe();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

# Expect: profiles is in supabase_realtime and the intended subscriber can observe invalidating changes.
rg -n -C 8 \
  'supabase_realtime|ALTER PUBLICATION|CREATE PUBLICATION|profiles|CREATE POLICY|ENABLE ROW LEVEL SECURITY' \
  supabase --glob '*.sql'

Repository: krushit1307/CampusConnect

Length of output: 50382


🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

echo "== candidate files =="
fd -a 'index\.ts$|profiles|cache|cache.*' . | sed 's#^\./##' | head -100

echo
echo "== resolver cache subscription area =="
fd -a 'index\.ts$' graphql | xargs -r rg -n -C 10 'profilesCache|clubsCache|CHANNEL_ERROR|TIMED_OUT|subscribe\(|cache.*profiles|profilesCache\.clear|CLUBS_CACHE_KEY|profiles'

Repository: krushit1307/CampusConnect

Length of output: 26313


🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

echo "== publication/RLS focused search =="
rg -n --no-heading -C 3 \
  '(^|\s)(ALTER|CREATE)\s+PUBLICATION\b|TABLES?\s+|\*\b|INSERT|UPDATE|DELETE|public\.profiles|is_soft_deleted|deleted|enable_row_level_security|ENABLE ROW LEVEL SECURITY' \
  supabase --glob '*.sql' | head -250

Repository: krushit1307/CampusConnect

Length of output: 22736


🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

echo "== files with exact supabase_realtime/add public references =="
rg -n --no-heading -C 4 \
  'supabase_realtime|ADD TABLE( .*)?public\.(clubs|profiles|posts|comments|events)|ALTER TABLE (public\.clubs|public\.profiles|public\.posts|public\.comments|public\.events) ENABLE ROW LEVEL SECURITY|CREATE? TABLE (public\.clubs|public\.profiles|public\.posts|public\.comments|public\.events)' \
  supabase/graphql graphql supabase --glob '*.sql'

Repository: krushit1307/CampusConnect

Length of output: 29221


🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

echo "== profile mutations/deletions =="
rg -n --no-heading -C 5 \
  'profiles\.(update|delete|insert)|from\("profiles"\)\.update\(|from\("profiles"\)\.delete\(|is_soft_deleted|deleted_at profiles|UPDATE profiles|DELETE FROM .*profiles|drop.*profiles|CREATE POLICY .*profiles' \
  . --glob '!node_modules/**' --glob '!dist/**' --glob '!build/**' | head -300

Repository: krushit1307/CampusConnect

Length of output: 17298


🌐 Web query:

Supabase JavaScript subscribe status callback postgis realtime CHANNEL_ERROR TIMED_OUT documentation

💡 Result:

In the Supabase JavaScript client, the subscribe callback provides a status string—such as SUBSCRIBED, CHANNEL_ERROR, TIMED_OUT, or CLOSED—and an optional error object to help manage real-time connections [1][2]. Subscription Status Callbacks When calling.subscribe((status, err) =>...), you can handle specific states [1]: - SUBSCRIBED: The client has successfully joined the channel [3][4]. - CHANNEL_ERROR: An error occurred during the subscription process or due to a transport-level failure [2][5]. The err argument (if present) often contains a descriptive message or the original cause (e.g., a CloseEvent) [5]. - TIMED_OUT: The server failed to respond to the subscription request within the allocated time [1][3]. This is frequently related to environment-specific issues, such as using older Node.js versions (e.g., below v22) with newer library versions [6]. - CLOSED: The channel was unexpectedly closed [3][4]. PostGIS and Realtime While the Supabase Realtime SDK does not have specific, unique configurations for PostGIS data, it handles database changes (CDC) via the postgres_changes event [4][7]. PostGIS data types are transmitted in the JSON payload returned by Realtime [8]. To ensure complex types are handled correctly or that you do not miss initial events, ensure your database's publication is correctly configured and that your client library is up to date, as historical race conditions regarding subscription readiness have been addressed [9][10]. Troubleshooting Tips If you encounter frequent TIMED_OUT errors, verify that your Node.js environment is up to date (LTS recommended) or consider explicitly setting the WebSocket transport [6]. For CHANNEL_ERROR, logging the full err object—specifically checking its cause and message properties—is recommended, as recent updates to the SDK provide more detailed error information to help debug connection drops [1][5].

Citations:


Add bounded-staleness protection for profile cache invalidation.

profilesCache lives indefinitely, and both .subscribe() calls ignore status and errors. If profiles-cache-invalidation fails, times out, or is not subscribed, directory queries can keep deleted or soft-deleted rows in cache since profiles RLS filters deletes after cache hits. Add a TTL for invalidation keys and handle CHANNEL_ERROR, TIMED_OUT, and CLOSED; log/report the failure and avoid stale profile pages until the channel is healthy.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@graphql/resolvers/index.ts` around lines 147 - 160, Add bounded-staleness
handling around the profilesCache and the profiles-cache-invalidation
subscription: apply a TTL to profile cache entries, inspect subscription status,
and handle CHANNEL_ERROR, TIMED_OUT, and CLOSED by logging/reporting the failure
and preventing profile cache hits until the channel becomes healthy. Keep
clubsCache invalidation behavior unchanged and ensure successful profile channel
recovery re-enables caching.

Source: MCP tools

Comment on lines +574 to +579
const cacheKey = `profiles:${limit}:${offset}:${sortBy}:${sortOrder}`;
const cached = profilesCache.get(cacheKey);
if (cached) {
return cached;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🚀 Performance & Scalability | 🟡 Minor | ⚡ Quick win

Construct the key from the effective query.

The resolver normalizes sortBy and sortOrder after the cache lookup. Every distinct invalid value can therefore create a different cache entry even when the query uses the same full_name and asc values. This reduces cache hits and can evict useful pages.

Compute actualSortBy and actualSortOrder first, then use those normalized values in a structured key.

Proposed key construction
-      const cacheKey = `profiles:${limit}:${offset}:${sortBy}:${sortOrder}`;
-      const cached = profilesCache.get(cacheKey);
-      if (cached) {
-        return cached;
-      }
-
       let query = supabase.from("profiles").select("*");

       const allowedColumns = ["id", "full_name", "handle", "role", "is_banned"];
       const actualSortBy = allowedColumns.includes(sortBy) ? sortBy : "full_name";
       const actualSortOrder = sortOrder === "desc" ? "desc" : "asc";
+      const cacheKey = JSON.stringify([
+        "profiles",
+        limit,
+        offset,
+        actualSortBy,
+        actualSortOrder,
+      ]);
+      const cached = profilesCache.get(cacheKey);
+      if (cached) {
+        return cached;
+      }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@graphql/resolvers/index.ts` around lines 574 - 579, In the profiles resolver,
normalize sortBy and sortOrder into actualSortBy and actualSortOrder before
constructing or reading the cache key. Build the structured key from these
effective values so invalid inputs sharing the same normalized query reuse the
same cache entry, while preserving the existing cache lookup and return
behavior.

const { data, error } = await query;
if (error) throw error;
return data || [];

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Remove the lint-blocking trailing whitespace.

ESLint prettier/prettier reports extra spaces at Line 592. Remove the whitespace so the file passes the configured formatter.

🧰 Tools
🪛 ESLint

[error] 592-592: Delete ······

(prettier/prettier)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@graphql/resolvers/index.ts` at line 592, Remove the trailing whitespace at
the affected blank line in the resolver file, preserving all surrounding code
and behavior so the configured Prettier ESLint rule passes.

Source: Linters/SAST tools

Comment on lines +592 to +595

const result = data || [];
profilesCache.set(cacheKey, result);
return result;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Prevent an in-flight query from repopulating a cleared cache.

The database query completes after an await. A profile-change callback can clear profilesCache during that wait, but this code then unconditionally stores the pre-invalidation result. The cache can remain stale until another profile event.

Track an invalidation generation and only cache the result when the generation is unchanged.

Generation-based invalidation
+let profilesCacheGeneration = 0;
+
       profilesCache.clear();
+      profilesCacheGeneration += 1;
...
+      const generation = profilesCacheGeneration;
       const { data, error } = await query;
       if (error) throw error;

       const result = data || [];
-      profilesCache.set(cacheKey, result);
+      if (generation === profilesCacheGeneration) {
+        profilesCache.set(cacheKey, result);
+      }
       return result;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const result = data || [];
profilesCache.set(cacheKey, result);
return result;
const result = data || [];
if (generation === profilesCacheGeneration) {
profilesCache.set(cacheKey, result);
}
return result;
🧰 Tools
🪛 ESLint

[error] 592-592: Delete ······

(prettier/prettier)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@graphql/resolvers/index.ts` around lines 592 - 595, Update the profile query
flow around profilesCache.set so it tracks an invalidation generation before
awaiting the database query, increments that generation when profile-change
invalidation clears the cache, and only stores result when the generation is
unchanged. Preserve returning the query result while preventing an in-flight
request from repopulating an invalidated cache.

import React from "react";
import { NotFoundPage } from "./NotFoundPage";

const SENSITIVE_PATTERN = /(password|token|secret|key|auth|credential|bearer|session)([\s"':=]+)([^\s,;}]+)/gi;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Apply the required Prettier line break.

Prettier reports Insert ⏎· at Line 8. Split the regular-expression declaration across lines before merging.

🧰 Tools
🪛 ESLint

[error] 8-8: Insert ⏎·

(prettier/prettier)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/components/ErrorBoundary.tsx` at line 8, Format the SENSITIVE_PATTERN
declaration according to Prettier by inserting the required line break in the
regular-expression declaration, without changing the pattern or behavior.

Source: Linters/SAST tools

Comment on lines +92 to +102
// Initialize admin client to ban the secondary auth.users account
const adminClient = createClient(supabaseUrl, supabaseServiceKey);

const { error: deleteError } = await adminClient.auth.admin.deleteUser(secondary_id);
const { error: deleteError } = await adminClient.auth.admin.updateUserById(secondary_id, {
ban_duration: '876000h'
});

if (deleteError) {
return new Response(
JSON.stringify({
error: "Failed to delete secondary account from auth.users",
error: "Failed to ban secondary account from auth.users",

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔒 Security & Privacy | 🟠 Major | 🏗️ Heavy lift

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

ast-grep outline supabase/functions/merge-accounts/index.ts --items all
ast-grep outline supabase/functions/purge-dormant-accounts/index.ts --items all

rg -n -C 5 \
  'updateUserById|deleted_at|merge_user_accounts|processed|error' \
  supabase/functions supabase/tests

Repository: krushit1307/CampusConnect

Length of output: 50382


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '--- merge-accounts outline ---\n'
ast-grep outline supabase/functions/merge-accounts/index.ts --items all || true
printf '\n--- merge-accounts relevant lines ---\n'
sed -n '1,180p' supabase/functions/merge-accounts/index.ts | cat -n

printf '\n--- purge-dormant-accounts outline ---\n'
ast-grep outline supabase/functions/purge-dormant-accounts/index.ts --items all || true
printf '\n--- purge-dormant-accounts relevant lines ---\n'
sed -n '1,140p' supabase/functions/purge-dormant-accounts/index.ts | cat -n

printf '\n--- targeted references ---\n'
rg -n 'merge-accounts|purge-dormant-accounts|updateUserById|deleted_at|merge_user_accounts|pending|retry|processed' supabase/functions supabase/tests --glob '!**/node_modules/**'

Repository: krushit1307/CampusConnect

Length of output: 254


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- merge-accounts outline ---'
ast-grep outline supabase/functions/merge-accounts/index.ts --items all || true

printf '%s\n' ''
printf '%s\n' '--- merge-accounts relevant lines ---'
sed -n '1,180p' supabase/functions/merge-accounts/index.ts | cat -n

printf '%s\n' ''
printf '%s\n' '--- purge-dormant-accounts outline ---'
ast-grep outline supabase/functions/purge-dormant-accounts/index.ts --items all || true

printf '%s\n' ''
printf '%s\n' '--- purge-dormant-accounts relevant lines ---'
sed -n '1,140p' supabase/functions/purge-dormant-accounts/index.ts | cat -n

printf '%s\n' ''
printf '%s\n' '--- targeted references ---'
rg -n 'merge-accounts|purge-dormant-accounts|updateUserById|deleted_at|merge_user_accounts|pending|retry|processed' supabase/functions supabase/tests --glob '!**/node_modules/**'

Repository: krushit1307/CampusConnect

Length of output: 24824


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- RPC definition ---'
rg -n -C 3 'FUNCTION.*merge_user_accounts|create function.*merge_user_accounts|merge_user_accounts' supabase --glob '*.sql'

printf '%s\n' ''
printf '%s\n' '--- purge function test coverage ---'
ls -la supabase/functions/purge-dormant-accounts/ || true
rg -n 'purge-dormant-accounts|purge_dormant|listUsers|ban|deleted_at' supabase/tests supabase/functions --glob '*.sql' --glob '*.ts'

printf '%s\n' ''
python3 - <<'PY'
from pathlib import Path
p = Path('supabase/functions/purge-dormant-accounts/index.ts')
text = p.read_text()
print('profile_update_contains_await:', 'await supabase.from("profiles").update({ deleted_at :' in text)
print('profile_update_error_assignment:', 'supabase.from("profiles").update({ deleted_at' in text and '.then(({ error' not in text and '{ data, error }' not in text)
print('ban_update_contains_await:', 'await supabase.auth.admin.updateUserById(user.id, { ban_duration' in text)
print('ban_update_error_assignment:', 'supabase.auth.admin.updateUserById(user.id, { ban_duration' in text and '{ data, error }' not in text and '.then(({ error' not in text)
print('catch_nearby:', 'catch (e)' in text and 'Failed to purge' in text)
PY

Repository: krushit1307/CampusConnect

Length of output: 11435


Make account cleanup an idempotent, retryable workflow.

merge-accounts records the database merge successfully and returns before the Auth ban completes. purge-dormant-accounts also runs both cleanup steps under a single broad catch with no per-user return-value handling. Either keep the auth ban before returning from profile cleanup, or mark the user as pending_admin_removal/needs_auth_ban after the profile change and use a scheduled retry worker for failed Auth updates.

📍 Affects 2 files
  • supabase/functions/merge-accounts/index.ts#L92-L102 (this comment)
  • supabase/functions/purge-dormant-accounts/index.ts#L31-L35
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@supabase/functions/merge-accounts/index.ts` around lines 92 - 102, Make
account cleanup idempotent and retryable across merge-accounts and
purge-dormant-accounts: in merge-accounts, ensure the Auth ban via
updateUserById completes successfully before returning, or persist a
pending_admin_removal/needs_auth_ban marker after the profile merge; in
purge-dormant-accounts, replace the broad cleanup catch with per-user result
handling and retry failed Auth updates through the scheduled workflow. Apply the
corresponding changes in supabase/functions/merge-accounts/index.ts (lines
92-102) and supabase/functions/purge-dormant-accounts/index.ts (lines 31-35).

Comment on lines +76 to +85
DELETE FROM public.club_members WHERE user_id = secondary_id;
DELETE FROM public.event_rsvps WHERE user_id = secondary_id;
DELETE FROM public.saved_events WHERE user_id = secondary_id;
DELETE FROM public.post_reactions WHERE user_id = secondary_id;
DELETE FROM public.profile_achievements WHERE profile_id = secondary_id;
DELETE FROM public.event_waitlist WHERE user_id = secondary_id;
DELETE FROM public.event_feedbacks WHERE user_id = secondary_id;
DELETE FROM public.daily_active_users WHERE user_id = secondary_id;
DELETE FROM public.post_likes WHERE user_id = secondary_id;
DELETE FROM public.reports WHERE reporter_id = secondary_id;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect profile foreign keys and merge cleanup behavior in migrations and tests.
rg -n -C 4 --glob '*.sql' \
  'REFERENCES\s+(public\.)?profiles|FOREIGN KEY.*profiles|ON DELETE CASCADE|merge_user_accounts|secondary_id' \
  supabase/migrations supabase/tests

Repository: krushit1307/CampusConnect

Length of output: 50382


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# List current SUPABASE_DIR/env if present, then compare migration ordering and FK handling.
printf 'SUPABASE_DIR/ENV:\n'
printf 'SUPABASE_DIR=%s\n' "${SUPABASE_DIR:-<unset>}"
printf 'SUPABASE_DB_URL=%s\n' "${SUPABASE_DB_URL:-<unset>}"
printf '\nRelevant migration files:\n'
for f in \
  supabase/migrations/20260728000006_cascade_delete_profile_fks.sql \
  supabase/migrations/20260803000000_soft_delete_users_events_global.sql \
  supabase/migrations/20260729200000_merge_user_accounts_rpc.sql
do
  if [ -f "$f" ]; then
    echo "--- $f"
    wc -l "$f"
    sed -n '1,220p' "$f"
  else
    echo "MISSING: $f"
  fi
done

printf '\nProfile FK cleanup operations across migrations:\n'
rg -n -E 'public\.profiles|profiles\(id\)|ON DELETE (CASCADE|SET NULL)|DELETE FROM|ALTER TABLE .*profiles|created_by|user_id|profile_id|author_id|recorded_by|reviewed_by|created_by|reviewed_by' supabase/migrations --glob '*.sql' | rg -i 'profiles|created_by|user_id|profile_id|author_id|recorded_by|reviewed_by|reports|club_members|event_rsvps|saved_events|post_reactions|profile_achievements|event_waitlist|event_feedbacks|daily_active_users|post_likes|reports|notifications|audit_logs|event_attendance_logs|handle_history|certificates|comments|posts|events|clubs' || true

Repository: krushit1307/CampusConnect

Length of output: 11510


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Build a deterministic map of current public.profile references and whether the merge RPC or soft-delete trigger covers them.
python3 - <<'PY'
from pathlib import Path
import re

merge_rpc = Path('supabase/migrations/20260729200000_merge_user_accounts_rpc.sql').read_text()
soft_del = Path('supabase/migrations/20260803000000_soft_delete_users_events_global.sql').read_text()

print('handle_profile_soft_delete_cascade rows:')
m = re.search(r'CREATE\s+OR\s+REPLACE\s+FUNCTION\s+public\.handle_profile_soft_delete_cascade\(\).*?RETURN\s+NEW;', soft_del, re.S)
print(m.group(0) if m else 'MISSING')

# Find profile FKs in CREATE/ALTER statements without assuming schema prefix.
sql = (Path('supabase/migrations').glob('*.sql'))
fk_lines = []
for p in sql:
    text = p.read_text(errors='ignore')
    for i, line in enumerate(text.splitlines(), 1):
        if (re.search(r'REFERENCE[?S\s]+\bprofiles\b|\bprofile_id\b.*\bREFERENCES\s+(public\.)?profiles', line, re.I)
            or re.search(r'\bREFERENCES\s+(public\.)?profiles\b', line, re.I)):
            fk_lines.append((p, i, line.strip()))

covered_by_update = re.findall(r'UPDATE\s+(?:public\.)?(\w+)\s+SET[\s\S]*?WHERE[\s\S]*?(?:id|author_id|user_id|recorded_by|profile_id|reporter_id|created_by)=(?:\s*secondary_id|\$1)', merge_rpc, re.I)
covered_by_trigger = re.findall(r'UPDATE\s+(?:public\.)?(\w+)\s+SET\s+deleted_at\s*=.*WHERE\s+(?:author_id|[a-z_]+_id)\s*=\s*NEW\.id', m.group(0) if m else '', re.I)
covered_by_union = set(covered_by_update) | set(covered_by_trigger)

# Find user/profile relation columns and whether they are in update coverage or merge deletes or trigger.
relation_cols = []
for p in sql:
    text = p.read_text(errors='ignore')
    for i, line in enumerate(text.splitlines(), 1):
        lower = line.lower()
        ref = re.search(r'REFERENCE[?S\s]+\bprofiles\b|\bprofile_id\b.*\bREFERENCES\s+(public\.)?profiles|\bREFERENCES\s+(public\.)?profiles\b', line, re.I)
        if ref and ('user_id' in lower or 'profile_id' in lower or 'author_id' in lower or 'recorded_by' in lower or 'reporter_id' in lower or 'created_by' in lower):
            table = lower.split()[0].lstrip('public.'; splitlines=False) if lower.startswith('create table') or lower.startswith('alter table') else None
            # approximate table from CREATE table ... or ALTER TABLE ...
            m = re.search(r'\b(?:CREATE\s+TABLE\s+|ALTER\s+TABLE\s+)(?:public\.)?(\w+)', line, re.I)
            table = m.group(1) if m else 'unknown'
            col = re.search(r'\b((?:user|profile|author|recorded|reporter|created|reviewed)_id)\b', line, re.I)
            col_name = col.group(1) if col else 'unknown'
            relation_cols.append((p, i, table, col_name, line.strip()))

print('\nprofile FK columns in migrations:')
for row in sorted(relation_cols, key=lambda r: (str(r[0]), r[1])):
    covered = row[3] in covered_by_update or row[3] in covered_by_trigger or row[2] in covered_by_union or row[3] in covered_by_union
    print(f"{row[0]}:{row[1]} table={row[2]} col={row[3]} covered_by_update_or_trigger_or_table={covered}: {row[4]}")

print('\nmerge RPC update target tables:', sorted(set(c.lower() for c in covered_by_update)))
print('soft delete trigger update target tables:', sorted(set(c.lower() for c in covered_by_trigger)))

# Check whether reports unique constraint matches the merge update and delete.
unique_reports = []
for p in sql:
    text = p.read_text(errors='ignore')
    for i, line in enumerate(text.splitlines(), 1):
        if 'create unique index' in line.lower() and 'reports' in line.lower():
            unique_reports.append((p, i, line.strip()))
print('\nreports unique index definitions:')
for row in unique_reports:
    print(f"{row[0]}:{row[1]} {row[2]}")
PY

Repository: krushit1307/CampusConnect

Length of output: 410


🏁 Script executed:

#!/bin/bash
set -euo pipefail

python3 - <<'PY'
from pathlib import Path
import re

merge_rpc = Path('supabase/migrations/20260729200000_merge_user_accounts_rpc.sql').read_text()
soft_del = Path('supabase/migrations/20260803000000_soft_delete_users_events_global.sql').read_text()

print('handle_profile_soft_delete_cascade rows:')
m = re.search(r'CREATE\s+OR\s+REPLACE\s+FUNCTION\s+public\.handle_profile_soft_delete_cascade\(\).*?RETURN\s+NEW;', soft_del, re.S)
print(m.group(0) if m else 'MISSING')

sql_list = list(Path('supabase/migrations').glob('*.sql'))
covered_by_update = re.findall(r'UPDATE\s+(?:public\.)?(\w+)', merge_rpc, re.I)
covered_by_update = set(c.lower() for c in covered_by_update)

# Extract profile FKs from CREATE TABLE and ALTER TABLE profile-related statements.
for p in sql_list:
    text = p.read_text(errors='ignore')
    lines = text.splitlines()
    for i, line in enumerate(lines, 1):
        low = line.lower()
        if not (low.startswith('create table') or low.startswith('alter table') or low.startswith('create unique') or low.startswith('add unique')):
            continue
        if not re.search(r'reference[s]?\s+(public\.)?profiles\b|\bprofile_id\b.*\breferences\s+(public\.)?profiles\b', low, re.I):
            continue
        table = 'unknown'
        mk = re.search(r'\b(?:create\s+table\s+|alter\s+table\s+)(?:public\.)?(\w+)', low, re.I)
        if mk:
            table = mk.group(1).lower()
        cols = re.findall(r'\b([a-z_]*_id)\b', low)
        action = '[FK]'
        if 'create unique' in low:
            action = '[unique idx]'
        print(f"{p}:{i} table={table} cols={cols} action={action}: {line.strip()}")

# Find profile FK columns in all SQL lines for broader coverage check.
print('\nAll profile-referencing columns:')
for p in sql_list:
    text = p.read_text(errors='ignore')
    for i, line in enumerate(text.splitlines(), 1):
        low = line.lower()
        if re.search(r'reference[s]?\b\s+(public\.)?profiles\b|\bprofile_id\b.*\breferences\s+(public\.)?profiles\b|\bREFERENCES\s+(public\.)?profiles\b', low, re.I):
            table = 'unknown'
            mk = None
            for j in range(max(1, i-4), i):
                mk = re.search(r'\b(?:create\s+table\s+|alter\s+table\s+)(?:public\.)?(\w+)', text.splitlines()[j-1], re.I)
                if mk:
                    table = mk.group(1).lower()
                    break
            cols = []
            for col in ['user_id', 'profile_id', 'author_id', 'recorded_by', 'reporter_id', 'created_by', 'reviewed_by']:
                if re.search(r'\b' + col + r'\b', line, re.I):
                    cols.append(col)
            covered = table in covered_by_update or any(c in covered_by_update for c in cols)
            print(f"{p}:{i} table={table} cols={cols or []} merge_table_covered={covered}: {line.strip()}")
PY

Repository: krushit1307/CampusConnect

Length of output: 15720


Handle profile relations that soft deletes no longer cascade.

The soft-delete trigger only soft-deletes posts and comments, while merge conflicts still delete rows directly in the RPC. Add coverage for other secondary-profile relations that need the same fate: merge/copy rows where business-logic allows, soft-delete where consistent, or delete rows that hard-delete would have removed.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@supabase/migrations/20260729200000_merge_user_accounts_rpc.sql` around lines
76 - 85, Extend the account-merge RPC around the existing secondary-profile
cleanup statements to cover all remaining profile-related tables affected by the
soft-delete cascade change. For each relation, merge or copy rows where business
rules permit, soft-delete entities that follow soft-deletion semantics, and
explicitly delete dependent rows that previously relied on hard-delete
cascading; preserve conflict handling and ensure no secondary-profile references
remain.

Comment on lines +87 to +88
-- Soft-delete the secondary profile
UPDATE public.profiles SET deleted_at = NOW() WHERE id = secondary_id;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🔴 Critical | ⚡ Quick win

Apply this function change after the deleted_at schema migration.

20260729200000_merge_user_accounts_rpc.sql runs before 20260803000000_soft_delete_users_events_global.sql, which adds profiles.deleted_at. A fresh migration run fails at Line 88 because the column does not exist yet.

Move this function definition to a migration after the column addition. Update supabase/tests/merge_user_accounts.test.sql to assert that the secondary profile is soft-deleted instead of absent.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@supabase/migrations/20260729200000_merge_user_accounts_rpc.sql` around lines
87 - 88, Move the merge-user-accounts function definition containing the
secondary-profile UPDATE to a migration that runs after the deleted_at schema
migration, preserving its behavior. Update merge_user_accounts.test.sql to
assert that the secondary profile remains present with deleted_at set, rather
than asserting it is absent.

Comment on lines +11 to +55
CREATE OR REPLACE FUNCTION public.get_filtered_clubs(
p_search TEXT DEFAULT NULL,
p_category TEXT DEFAULT NULL,
p_tags TEXT[] DEFAULT NULL
) RETURNS SETOF public.clubs
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = public
AS $$
BEGIN
IF p_search IS NOT NULL AND TRIM(p_search) <> '' THEN
-- Leverage the existing fuzzy search RPC which already handles ordering by relevance
RETURN QUERY
SELECT c.*
FROM public.search_clubs(p_search) c
WHERE
(c.deleted_at IS NULL) AND
(p_category IS NULL OR c.category ILIKE p_category) AND
(
p_tags IS NULL OR array_length(p_tags, 1) IS NULL OR
p_tags <@ (
SELECT coalesce(array_agg(lower(ctl.name)), '{}'::text[])
FROM public.club_tags ct
JOIN public.club_tag_labels ctl ON ct.tag_id = ctl.id
WHERE ct.club_id = c.id
)
);
ELSE
RETURN QUERY
SELECT c.*
FROM public.clubs c
WHERE
(c.deleted_at IS NULL) AND
(p_category IS NULL OR c.category ILIKE p_category) AND
(
p_tags IS NULL OR array_length(p_tags, 1) IS NULL OR
p_tags <@ (
SELECT coalesce(array_agg(lower(ctl.name)), '{}'::text[])
FROM public.club_tags ct
JOIN public.club_tag_labels ctl ON ct.tag_id = ctl.id
WHERE ct.club_id = c.id
)
)
ORDER BY c.name ASC;
END IF;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🚀 Performance & Scalability | 🟠 Major | 🏗️ Heavy lift

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== candidate files =="
fd -a 'clubs_pagination_rpc.sql|clubs.index.tsx|.*clubs.*' . | sed 's#^\./##' | head -200

echo
echo "== migration file excerpt =="
if [ -f supabase/migrations/20260810000001_clubs_pagination_rpc.sql ]; then
  cat -n supabase/migrations/20260810000001_clubs_pagination_rpc.sql
else
  echo "migration file missing"
fi

echo
echo "== route references =="
rg -n "get_filtered_clubs|search_clubs|\.range\(|count:" -S . --glob '!node_modules' --glob '!dist' --glob '!build' | head -300

Repository: krushit1307/CampusConnect

Length of output: 50381


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== POSTGRES version =="
psql --version 2>/dev/null || true

echo
echo "== route clubs pagination excerpt =="
sed -n '1,140p' src/routes/clubs.index.tsx | cat -n

echo
echo "== related club migrations/functions =="
for f in \
  supabase/migrations/20260810000001_clubs_pagination_rpc.sql \
  supabase/migrations/$(ls -1 supabase/migrations | grep 'search_clubs' | head -1) \
  supabase/migrations/$(ls -1 supabase/migrations | grep -E '(fuzzy|trigram)' | tail -1)
do
  if [ -f "$f" ]; then
    echo "--- $f"
    sed -n '1,180p' "$f" | cat -n
    echo
  fi
done

echo
echo "== deterministic pg query-plan shape tests =="
python3 - <<'PY'
from pathlib import Path
files = ["supabase/migrations/20260810000001_clubs_pagination_rpc.sql"]
for path in files:
    s = Path(path).read_text()
    for stmt in s.split(";"):
        stmt = stmt.strip()
        if stmt.startswith("CREATE OR REPLACE FUNCTION"):
            print(path, "contains RETURN QUERY:", "RETURN QUERY" in stmt)
            print(path, "contains function LIMIT:", "LIMIT" in stmt)
            print(path, "contains function OFFSET:", "OFFSET" in stmt)
print("route uses exact count: ", ".rpc('get_filtered_clubs', { ..., { count: 'exact' }" in Path("src/routes/clubs.index.tsx").read_text())
print("route applies .range after rpc: ", ".range((pageParam as number) * PAGE_SIZE" in Path("src/routes/clubs.index.tsx").read_text())
PY

Repository: krushit1307/CampusConnect

Length of output: 14238


🌐 Web query:

PostgreSQL RETURN QUERY materializes entire result set before caller applies LIMIT documentation

💡 Result:

In PostgreSQL, when you use the RETURN QUERY statement within a PL/pgSQL function, the PL/pgSQL engine executes the specified query to completion and stores the entire result set into a tuplestore before returning control to the caller [1][2][3]. Because the function must fully process the RETURN QUERY statement to build this internal result set, applying a LIMIT clause to the function call itself (e.g., SELECT * FROM my_func LIMIT 10) does not prevent the internal query from executing entirely [1][2][4]. If the query inside the function is expensive or produces a very large result set, this behavior can cause significant performance issues, as the database will generate all rows even if the caller only requests a small fraction of them [1][2][4]. To mitigate this, you can: 1. Include the LIMIT clause directly within the RETURN QUERY statement inside the function [5][4]. This allows the query optimizer to incorporate the limit into the execution plan of the inner query, which can substantially improve performance [6][4]. 2. Use an SQL-language function instead of a PL/pgSQL function whenever possible, as SQL functions are often better candidates for inlining by the PostgreSQL query optimizer, allowing the outer LIMIT to be pushed down into the function's logic [4].

Citations:


Move pagination into get_filtered_clubs.

RETURN QUERY completes the function's query before PostgREST applies .range(), so PAGE_SIZE = 12 can still materialize every matching club. count: "exact" adds another full-count operation. Add validated p_limit and p_offset parameters, apply LIMIT/OFFSET on both branches, and have the route pass pageParam * PAGE_SIZE / PAGE_SIZE.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@supabase/migrations/20260810000001_clubs_pagination_rpc.sql` around lines 11
- 55, Update get_filtered_clubs to accept validated p_limit and p_offset
parameters, applying them as LIMIT and OFFSET in both the search and non-search
RETURN QUERY branches after filtering and ordering. Update the route that calls
this RPC to pass pageParam * PAGE_SIZE as the offset and PAGE_SIZE as the limit,
while preserving existing filters.

Comment on lines +21 to +54
IF p_search IS NOT NULL AND TRIM(p_search) <> '' THEN
-- Leverage the existing fuzzy search RPC which already handles ordering by relevance
RETURN QUERY
SELECT c.*
FROM public.search_clubs(p_search) c
WHERE
(c.deleted_at IS NULL) AND
(p_category IS NULL OR c.category ILIKE p_category) AND
(
p_tags IS NULL OR array_length(p_tags, 1) IS NULL OR
p_tags <@ (
SELECT coalesce(array_agg(lower(ctl.name)), '{}'::text[])
FROM public.club_tags ct
JOIN public.club_tag_labels ctl ON ct.tag_id = ctl.id
WHERE ct.club_id = c.id
)
);
ELSE
RETURN QUERY
SELECT c.*
FROM public.clubs c
WHERE
(c.deleted_at IS NULL) AND
(p_category IS NULL OR c.category ILIKE p_category) AND
(
p_tags IS NULL OR array_length(p_tags, 1) IS NULL OR
p_tags <@ (
SELECT coalesce(array_agg(lower(ctl.name)), '{}'::text[])
FROM public.club_tags ct
JOIN public.club_tag_labels ctl ON ct.tag_id = ctl.id
WHERE ct.club_id = c.id
)
)
ORDER BY c.name ASC;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect the search RPC return shape and ordering before defining the outer order.
rg -n -C 12 'CREATE( OR REPLACE)? FUNCTION public\.search_clubs|search_clubs\(' supabase

Repository: krushit1307/CampusConnect

Length of output: 26321


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "Migration file:"
cat -n supabase/migrations/20260810000001_clubs_pagination_rpc.sql

echo
echo "Latest search_clubs definition from migrations:"
sed -n '1,135p' supabase/migrations/20260805120000_trigram_fuzzy_search.sql

echo
echo "Supabase schema search_clubs definition:"
sed -n '1393,1435p' supabase/schema.sql

echo
echo "All references to pagination offset/limit in migrations:"
rg -n "limit|offset|FETCH|SKIP|pg_graphql|rpc|search_clubs|pagination|ORDER BY" supabase/migrations supabase/schema.sql

Repository: krushit1307/CampusConnect

Length of output: 38912


🏁 Script executed:

#!/bin/bash
set -euo pipefail

python3 - <<'PY'
from pathlib import Path
import re

pagination = Path('supabase/migrations/20260810000001_clubs_pagination_rpc.sql').read_text()
schema = Path('supabase/schema.sql').read_text()

def between(text, end, start='CREATE OR REPLACE FUNCTION public.search_clubs'):
    i = text.index(start)
    j = text.index(end, i)
    return text[i:j]

search = between(schema, 'GRANT EXECUTE ON FUNCTION public.search_clubs(TEXT) TO authenticated, anon;')

print("Pagination RPC search branch has outer ORDER BY:", bool(re.search(r'\bORDER\s+BY\b', pagination[21:37])))
print("Schema search_clubs RETURNS:", re.search(r'RETURNS\s+(.+?)\s+LANGUAGE', search, re.S).group(1).strip())
print("Schema search_clubs select:", re.search(r'RETURN\s+QUERY\n\s*SELECT\s+(.+?)\n\s*FROM', search, re.S).group(1).strip())
print("Schema search_clubs end ORDER BY:", re.search(r'\bORDER\s+BY\s+([\s\S]*?)\n\s*END;', search, re.S).group(1).strip())
print("Schema search_clubs has id tie-breaker:", bool(re.search(r'\bORDER\s+BY\b[\s\S]*\bc\.?id\b', search, re.S)))
print("Pagination non-search branch ORDER BY:", re.search(r'\bORDER\s+BY\s+([\s\S]*?)\n\s*END;', pagination[37:180], re.S).group(1).strip())
print("Pagination non-search branch has id tie-breaker:", bool(re.search(r'\bORDER\s+BY\b[\s\S]*\bc\.?id\b', pagination[37:180], re.S)))
PY

Repository: krushit1307/CampusConnect

Length of output: 306


🏁 Script executed:

#!/bin/bash
set -euo pipefail

python3 - <<'PY'
from pathlib import Path
import re

pagination = Path('supabase/migrations/20260810000001_clubs_pagination_rpc.sql').read_text()
schema = Path('supabase/schema.sql').read_text()

search_signature = 'CREATE OR REPLACE FUNCTION public.search_clubs(search_term TEXT)'
grant_signature = "GRANT EXECUTE ON FUNCTION public.search_clubs(TEXT) TO authenticated, anon;"
start = schema.index(search_signature)
end = schema.index(grant_signature, start)
search = schema[start:end]

def has(text, word):
    return bool(re.search(r'\b' + word + r'\b', text))
def extract_order(text):
    return re.search(r'\bORDER\s+BY\s+([\s\S]*?)\n\s*END;', text, re.S).group(1).strip()

if has(pagination, "IF p_search IS NOT NULL AND TRIM(p_search) <> '' THEN"):
    search_branch = pagination[
        pagination.index("IF p_search IS NOT NULL AND TRIM(p_search) <> '' THEN") :
        pagination.index("    ELSE", pagination.index("IF p_search IS NOT NULL"))
    ]
else:
    search_branch = ""

print("Pagination RPC search branch has outer ORDER BY:", has(search_branch, "ORDER BY"))
print("Schema search_clubs RETURNS:", re.search(r'RETURNS\s+(.+?)\s+LANGUAGE', search, re.S).group(1).strip())
print("Schema search_clubs select:", re.search(r'RETURN\s+QUERY\n\s*SELECT\s+(.+?)\n\s*FROM', search, re.S).group(1).strip())
print("Schema search_clubs ORDER BY:", extract_order(search))
print("Schema search_clubs has id tie-breaker:", has(search, "id"))
print("Pagination non-search ORDER BY:", extract_order(pagination[37:180]))
print("Pagination non-search branch has id tie-breaker:", has(pagination[37:180], "id"))
PY

Repository: krushit1307/CampusConnect

Length of output: 269


🏁 Script executed:

#!/bin/bash
set -euo pipefail

python3 - <<'PY'
from pathlib import Path
import re

pagination = Path('supabase/migrations/20260810000001_clubs_pagination_rpc.sql').read_text()
schema = Path('supabase/schema.sql').read_text()

print("Pagination has search branch:", "IF p_search IS NOT NULL AND TRIM(p_search) <> '' THEN" in pagination)
search_start_indices = [i for i in range(len(schema)) if schema.startswith('CREATE OR REPLACE FUNCTION public.search_clubs(search_term TEXT)', i)]
grant_start_indices = [i for i in range(len(schema)) if schema.startswith("GRANT EXECUTE ON FUNCTION public.search_clubs(TEXT) TO authenticated, anon;", i)]
print("search_clubs indices:", search_start_indices)
print("grant indices:", grant_start_indices)
PY

Repository: krushit1307/CampusConnect

Length of output: 246


🏁 Script executed:

#!/bin/bash
set -euo pipefail

python3 - <<'PY'
from pathlib import Path
import re

pagination = Path('supabase/migrations/20260810000001_clubs_pagination_rpc.sql').read_text()
schema = Path('supabase/schema.sql').read_text()

search = schema[49699:49699+1200]
search_branch = pagination[pagination.index("IF p_search IS NOT NULL AND TRIM(p_search) <> '' THEN"):pagination.index("    ELSE", pagination.index("IF p_search IS NOT NULL"))]
non_search = pagination[pagination.index("    ELSE:"):pagination.index("    END IF")]

print("Schema search_clubs:\n", search[:500])
print("Search branch outer ORDER BY:", bool(re.search(r'ORDER\s+BY', search_branch)))
print("Search branch:\n", search_branch)
print("Non-search branch:\n", non_search[:300])
print("Non-search branch outer ORDER BY:", bool(re.search(r'ORDER\s+BY', non_search[non_search.index('RETURN QUERY'):])) )
PY

Repository: krushit1307/CampusConnect

Length of output: 268


Define a stable outer order before applying pagination.

public.search_clubs returns only SETOF public.clubs, so this wrapper cannot reference its ranking. The search branch now has no guaranteed order, and the non-search branch uses only c.name ASC as a tie-breaker, which can reorder clubs with duplicate names across pages. Order the search branch by an explicit relevance metric plus c.id, and add c.id to the non-search ORDER BY.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@supabase/migrations/20260810000001_clubs_pagination_rpc.sql` around lines 21
- 54, Update the pagination query branches in the clubs RPC to apply
deterministic ordering before pagination. In the search branch using
public.search_clubs, compute and order by an explicit relevance metric with c.id
as the final tie-breaker; in the non-search branch’s ORDER BY, append c.id after
c.name ASC to stabilize duplicate-name ordering.

@krushit1307
krushit1307 merged commit b850b66 into krushit1307:main Aug 9, 2026
4 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ECSoC26-SPAM ECSoC26 Elite Coders Summer Of Code'26 - Open Source Program enhancement New feature or request feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Implement caching for the directory search

2 participants