Skip to content

⚡ Bolt: [Combine multiple COUNT queries into single query using FILTER in getTicketStats]#227

Open
ldsgroups225 wants to merge 1 commit intomasterfrom
bolt/optimize-ticket-stats-filter-9972217565576460988
Open

⚡ Bolt: [Combine multiple COUNT queries into single query using FILTER in getTicketStats]#227
ldsgroups225 wants to merge 1 commit intomasterfrom
bolt/optimize-ticket-stats-filter-9972217565576460988

Conversation

@ldsgroups225
Copy link
Copy Markdown
Owner

@ldsgroups225 ldsgroups225 commented Mar 31, 2026

💡 What: Refactored getTicketStats to use a single query with PostgreSQL's FILTER (WHERE ...) clause instead of five sequential COUNT() queries. Also parallelized the remaining average calculations using Promise.all().

🎯 Why: The original implementation executed five separate database queries sequentially to count tickets by different statuses, plus two more queries for averages. This caused unnecessary network round trips and multiple table scans (N+1 query pattern).

📊 Impact: Reduces network round trips from 7 sequential calls to 1 concurrent Promise.all() containing 3 queries. Reduces table scans for counts from 5 to 1. Expected to significantly improve response time for the support dashboard metrics.

🔬 Measurement: Run the support dashboard and observe the network tab for the stats endpoint response time. Also verified via pnpm test and pnpm typecheck.


PR created automatically by Jules for task 9972217565576460988 started by @ldsgroups225

Summary by CodeRabbit

  • Performance Improvements
    • Optimized support ticket statistics retrieval to reduce query latency and improve the responsiveness of ticket management operations.

@google-labs-jules
Copy link
Copy Markdown

👋 Jules, reporting for duty! I'm here to lend a hand with this pull request.

When you start a review, I'll add a 👀 emoji to each comment to let you know I've read it. I'll focus on feedback directed at me and will do my best to stay out of conversations between you and other bots or reviewers to keep the noise down.

I'll push a commit with your requested changes shortly after. Please note there might be a delay between these steps, but rest assured I'm on the job!

For more direct control, you can switch me to Reactive Mode. When this mode is on, I will only act on comments where you specifically mention me with @jules. You can find this option in the Pull Request section of your global Jules UI settings. You can always switch back!

New to Jules? Learn more at jules.google/docs.


For security, I will only act on instructions from the user who triggered this task.

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Mar 31, 2026

📝 Walkthrough

Walkthrough

The getTicketStats function was optimized to consolidate five separate database count queries into a single query using COUNT(*) FILTER clauses and execute it concurrently alongside existing queries via Promise.all, reducing database round trips while maintaining equivalent filtering logic.

Changes

Cohort / File(s) Summary
Query Optimization
packages/data-ops/src/queries/support/read-tickets.ts
Consolidated multiple sequential count queries into a single combined query with conditional aggregation; added concurrent query execution via Promise.all for improved database efficiency.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~22 minutes

Poem

🐰 A query walks into a bar—well, five did,
But now they hop together, all as one bid!
Promise.all cheers as the counts unite,
One FILTER per status, oh what a sight!
Faster stats, no extra round-trips in sight!

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
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 (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title is specific and clearly describes the main optimization: combining multiple COUNT queries into a single query using FILTER in the getTicketStats function, which aligns with the primary change in the changeset.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch bolt/optimize-ticket-stats-filter-9972217565576460988

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 and usage tips.

Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@packages/data-ops/src/queries/support/read-tickets.ts`:
- Around line 228-255: The aggregate queries against the supportTickets table
(the three db.select blocks building countsResult, avgTimeResult, and
satisfactionResult) are currently executed without guaranteed tenant scoping and
can return data across schools; update getTicketStats (or the surrounding
function) to require a schoolId parameter or otherwise enforce multi-tenant
isolation by adding eq(supportTickets.schoolId, schoolId) into the where clauses
(i.e., include it in baseConditions or explicitly
and(eq(supportTickets.schoolId, schoolId), ...baseConditions)) so each of the
three selects is always filtered to the requesting school's data, or separate
the all-schools path into an admin-only query.
🪄 Autofix (Beta)

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

Run ID: 67e4fcb8-e711-4fba-a81c-8ad42a45e3c0

📥 Commits

Reviewing files that changed from the base of the PR and between 7e37ef8 and 9178e49.

📒 Files selected for processing (1)
  • packages/data-ops/src/queries/support/read-tickets.ts

Comment on lines +228 to +255
const [[countsResult], [avgTimeResult], [satisfactionResult]] = await Promise.all([
db
.select({
total: count(),
open: sql<number>`COUNT(*) FILTER (WHERE ${supportTickets.status} = 'open')`,
inProgress: sql<number>`COUNT(*) FILTER (WHERE ${supportTickets.status} = 'in_progress')`,
resolved: sql<number>`COUNT(*) FILTER (WHERE ${supportTickets.status} = 'resolved')`,
closed: sql<number>`COUNT(*) FILTER (WHERE ${supportTickets.status} = 'closed')`,
})
.from(supportTickets)
.where(baseConditions.length > 0 ? and(...baseConditions) : undefined),

// Calculate average resolution time (for resolved tickets)
const [avgTimeResult] = await db
.select({
avg: sql<number>`AVG(EXTRACT(EPOCH FROM (${supportTickets.resolvedAt} - ${supportTickets.createdAt})) / 3600)`,
})
.from(supportTickets)
.where(and(eq(supportTickets.status, 'resolved'), ...baseConditions))
// Calculate average resolution time (for resolved tickets)
db
.select({
avg: sql<number>`AVG(EXTRACT(EPOCH FROM (${supportTickets.resolvedAt} - ${supportTickets.createdAt})) / 3600)`,
})
.from(supportTickets)
.where(and(eq(supportTickets.status, 'resolved'), ...baseConditions)),

// Calculate average satisfaction score
const [satisfactionResult] = await db
.select({
avg: sql<number>`AVG(${supportTickets.satisfactionRating})`,
})
.from(supportTickets)
.where(
and(isNotNull(supportTickets.satisfactionRating), ...baseConditions),
)
// Calculate average satisfaction score
db
.select({
avg: sql<number>`AVG(${supportTickets.satisfactionRating})`,
})
.from(supportTickets)
.where(
and(isNotNull(supportTickets.satisfactionRating), ...baseConditions),
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

Always tenant-scope these aggregate queries.

Line 238, Line 246, and Line 255 still run unscoped when schoolId is missing, so getTicketStats() can aggregate every school's tickets. For a school-scoped table, that's a cross-tenant data leak; make schoolId required here or split the all-schools path into a separate admin-only query.

As per coding guidelines, "Every query on school-scoped tables MUST include where(eq(table.schoolId, schoolId)) for multi-tenant isolation".

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/data-ops/src/queries/support/read-tickets.ts` around lines 228 -
255, The aggregate queries against the supportTickets table (the three db.select
blocks building countsResult, avgTimeResult, and satisfactionResult) are
currently executed without guaranteed tenant scoping and can return data across
schools; update getTicketStats (or the surrounding function) to require a
schoolId parameter or otherwise enforce multi-tenant isolation by adding
eq(supportTickets.schoolId, schoolId) into the where clauses (i.e., include it
in baseConditions or explicitly and(eq(supportTickets.schoolId, schoolId),
...baseConditions)) so each of the three selects is always filtered to the
requesting school's data, or separate the all-schools path into an admin-only
query.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant