Skip to content

feat: convert InsightsBookingService to use Prisma.sql raw queries#5

Open
everettbu wants to merge 1 commit into
insights-query-foundationfrom
insights-performance-optimization
Open

feat: convert InsightsBookingService to use Prisma.sql raw queries#5
everettbu wants to merge 1 commit into
insights-query-foundationfrom
insights-performance-optimization

Conversation

@everettbu

@everettbu everettbu commented Jul 28, 2025

Copy link
Copy Markdown

Test 5

Summary by CodeRabbit

  • Refactor

    • Authorization and filter logic for bookings now use raw SQL conditions for improved precision.
    • Simplified and updated internal service options and method signatures.
    • Integration tests updated to match new SQL-based condition handling.
    • Caching-related tests have been removed.
  • New Features

    • Enhanced support for complex authorization and filter combinations using SQL logic.

…22345)

* fix: use raw query at InsightsBookingService

* feat: convert InsightsBookingService to use Prisma.sql raw queries

- Convert auth conditions from Prisma object notation to Prisma.sql
- Convert filter conditions from Prisma object notation to Prisma.sql
- Update return types from Prisma.BookingTimeStatusDenormalizedWhereInput to Prisma.Sql
- Fix type error in isOrgOwnerOrAdmin method
- Follow same pattern as InsightsRoutingService conversion

Co-Authored-By: eunjae@cal.com <hey@eunjae.dev>

* feat: convert InsightsBookingService to use Prisma.sql raw queries

- Convert auth conditions from Prisma object notation to Prisma.sql
- Convert filter conditions from Prisma object notation to Prisma.sql
- Update return types from Prisma.BookingTimeStatusDenormalizedWhereInput to Prisma.Sql
- Fix type error in isOrgOwnerOrAdmin method
- Follow same pattern as InsightsRoutingService conversion

Co-Authored-By: eunjae@cal.com <hey@eunjae.dev>

* fix: update InsightsBookingService integration tests for Prisma.sql format

- Replace Prisma object notation expectations with Prisma.sql template literals
- Add NOTHING_CONDITION constant for consistency with InsightsRoutingService
- Update all test cases to use direct Prisma.sql comparisons
- Use $queryRaw for actual database integration testing
- Follow same testing patterns as InsightsRoutingService

Co-Authored-By: eunjae@cal.com <hey@eunjae.dev>

* fix: exclude intentionally skipped jobs from required CI check failure

- Remove 'skipped' from failure condition in pr.yml and all-checks.yml
- Allow E2E jobs to be skipped without failing the required check
- Only actual failures and cancelled jobs will cause required check to fail

Co-Authored-By: eunjae@cal.com <hey@eunjae.dev>

* fix tests

* Revert "fix: exclude intentionally skipped jobs from required CI check failure"

This reverts commit 6ff44fc9a8f14ad657f7bba7c2e454e192b66c8f.

* clean up tests

* address feedback

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@coderabbitai

coderabbitai Bot commented Jul 28, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

The InsightsBookingService and its integration tests were refactored to replace Prisma's typed where input objects with raw SQL condition fragments using Prisma.sql. The service now constructs, combines, and returns SQL fragments for authorization and filter logic. The tests were updated to assert against these SQL fragments. The previous findMany method was removed.

Changes

Cohort / File(s) Change Summary
Service Refactor to SQL Fragments
packages/lib/server/service/insightsBooking.ts
Replaced all Prisma where input object logic with raw SQL fragments using Prisma.sql. Introduced NOTHING_CONDITION as Prisma.sql\1=0`. Added a public options type. Refactored the class to build and return SQL fragments for authorization and filter conditions. Removed findMany, added getBaseConditions. Updated all relevant method signatures to return or operate on Prisma.Sql`. Simplified internal logic for role checks and SQL composition.
Test Refactor for SQL Assertions
packages/lib/server/service/__tests__/insightsBooking.integration-test.ts
Refactored integration tests to expect and assert against Prisma SQL fragments instead of plain JS objects. Introduced NOTHING_CONDITION in tests. Updated all assertions to match SQL logic, including complex combinations with logical operators and array handling. Removed the "Caching" test suite. Renamed and restructured the main test suite to focus on getBaseConditions, executing raw SQL queries and comparing results directly. Maintained but reordered cleanup steps.

Sequence Diagram(s)

sequenceDiagram
    participant Test
    participant InsightsBookingService
    participant Database

    Test->>InsightsBookingService: new InsightsBookingService(options)
    Test->>InsightsBookingService: getBaseConditions()
    InsightsBookingService->>InsightsBookingService: getAuthorizationConditions()
    InsightsBookingService->>InsightsBookingService: getFilterConditions()
    InsightsBookingService->>InsightsBookingService: Combine SQL fragments (AND/NOTHING_CONDITION)
    InsightsBookingService-->>Test: return Prisma.Sql condition
    Test->>Database: Execute raw SQL with returned condition
    Database-->>Test: Return result rows
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~40 minutes

Poem

In fields of SQL, the rabbits hop,
Where Prisma’s objects used to stop.
Now fragments dance in SQL light,
Authorization, filters—just right!
Tests leap along, conditions true,
Refactored code, fresh as dew.
🐇✨ SQL dreams come into view!

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch insights-performance-optimization

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@everettbu

Copy link
Copy Markdown
Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jul 28, 2025

Copy link
Copy Markdown
Contributor
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (2)
packages/lib/server/service/insightsBooking.ts (2)

29-35: Consider removing redundant type definition.

The InsightsBookingServicePublicOptions type appears to be a less strict version of InsightsBookingServiceOptions. Since the constructor immediately validates the options using the schema, this intermediate type may be unnecessary.

Consider using the schema's input type directly:

-export type InsightsBookingServicePublicOptions = {
-  scope: "user" | "org" | "team";
-  userId: number;
-  orgId: number;
-  teamId?: number;
-};
-
 export type InsightsBookingServiceOptions = z.infer<typeof insightsBookingServiceOptionsSchema>;
+export type InsightsBookingServicePublicOptions = z.input<typeof insightsBookingServiceOptionsSchema>;

145-175: Consider performance impact with large organizations.

The implementation is logically correct, but using ANY operator with potentially large arrays might impact query performance.

For organizations with many teams/users, consider:

  1. Adding indexes on teamId and userId columns if not already present
  2. Monitoring query performance with large datasets
  3. Potentially implementing pagination or limiting scope if performance degrades
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 202d248 and 56ff75f.

📒 Files selected for processing (2)
  • packages/lib/server/service/__tests__/insightsBooking.integration-test.ts (10 hunks)
  • packages/lib/server/service/insightsBooking.ts (6 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
packages/lib/server/service/insightsBooking.ts (3)
packages/prisma/index.ts (1)
  • readonlyPrisma (71-75)
packages/lib/server/repository/team.ts (1)
  • TeamRepository (169-336)
packages/platform/libraries/index.ts (1)
  • MembershipRole (98-98)
🔇 Additional comments (9)
packages/lib/server/service/__tests__/insightsBooking.integration-test.ts (4)

2-2: LGTM! Appropriate imports and constant definition.

The addition of the Prisma import and the NOTHING_CONDITION constant are consistent with the service's refactoring to use raw SQL conditions.

Also applies to: 10-11


210-210: Authorization test assertions correctly updated for SQL conditions.

The test expectations accurately reflect the SQL authorization logic:

  • NOTHING_CONDITION for invalid/unauthorized cases
  • Proper SQL fragments with parameterized values for authorized scopes
  • Correct use of ANY operator for array comparisons in team/org scopes

Also applies to: 245-245, 273-273, 295-299, 332-343


384-386: Filter condition tests properly validate SQL generation.

The assertions correctly verify:

  • Event type filtering with OR logic for eventTypeId/eventParentId
  • Simple equality for memberUserId filter
  • Proper AND combination of multiple filter conditions

Also applies to: 407-407, 429-431


437-437: Test suite correctly refactored for getBaseConditions.

The test properly validates the new SQL-based approach:

  • Directly executes the generated SQL conditions
  • Verifies results match expected bookings
  • Good test case using user-scoped data with filters

Also applies to: 480-491

packages/lib/server/service/insightsBooking.ts (5)

49-50: Cache property types correctly updated.

The cache properties now properly store Prisma.Sql types, matching the new method return types.

Also applies to: 58-58


97-123: Filter condition building implemented correctly.

The method properly:

  • Handles each filter type with appropriate SQL conditions
  • Safely parameterizes values using Prisma.sql
  • Combines multiple conditions with AND operator
  • Returns null when no filters are present

125-143: Authorization condition routing implemented correctly.

The method properly:

  • Validates user permissions before building conditions
  • Routes to appropriate scope-specific builders
  • Has proper fallbacks for invalid cases

177-220: Team authorization and permission check implemented correctly.

Both methods properly implement their logic:

  • Security validation that team belongs to organization
  • Consistent SQL generation pattern
  • Simplified and clear role checking

68-81: Critical: Potential authorization bypass when auth returns NOTHING_CONDITION.

When authConditions returns NOTHING_CONDITION (1=0) but filterConditions exists, the current logic returns only the filter conditions, potentially allowing unauthorized access.

Apply this fix to ensure NOTHING_CONDITION always blocks access:

 async getBaseConditions(): Promise<Prisma.Sql> {
   const authConditions = await this.getAuthorizationConditions();
   const filterConditions = await this.getFilterConditions();
 
+  // If authorization explicitly denies access, always return NOTHING
+  if (authConditions === NOTHING_CONDITION) {
+    return NOTHING_CONDITION;
+  }
+
   if (authConditions && filterConditions) {
     return Prisma.sql`(${authConditions}) AND (${filterConditions})`;
   } else if (authConditions) {
     return authConditions;
   } else if (filterConditions) {
     return filterConditions;
   } else {
     return NOTHING_CONDITION;
   }
 }

Likely an incorrect or invalid review comment.

@github-actions

Copy link
Copy Markdown
Contributor

This PR is being marked as stale due to inactivity.

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

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants