Skip to content

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

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

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

Conversation

@ShashankFC

@ShashankFC ShashankFC commented Feb 4, 2026

Copy link
Copy Markdown

Test 5nn

Summary by CodeRabbit

  • Refactor

    • Internal refactoring of booking insights authorization and filtering logic to improve performance and maintainability.
  • Tests

    • Updated integration tests to reflect changes in condition handling.

✏️ Tip: You can customize this high-level summary in your review settings.

nn---n*Replicated from [ai-code-review-evaluation/cal.com-coderabbit#5](https://github.com/ai-code-review-evaluation/cal.com-coderabbit/pull/5)*

EntelligenceAI PR Summary

Refactored InsightsBookingService from Prisma's type-safe query builder to raw SQL queries for improved performance and flexibility.

  • Replaced all condition-building methods to return Prisma.Sql instead of Prisma.BookingTimeStatusDenormalizedWhereInput
  • Removed findMany method and introduced getBaseConditions method that returns combined SQL conditions
  • Changed NOTHING pattern from { id: -1 } object to NOTHING_CONDITION SQL fragment (1=0)
  • Updated integration tests to validate SQL template literals using $queryRaw instead of findMany
  • Removed caching-related test suites from integration tests
  • Implemented parameterized SQL queries using template literals and ANY operator for array comparisons

…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>

@entelligence-ai-pr-reviews entelligence-ai-pr-reviews 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.

Walkthrough

This PR refactors the InsightsBookingService from using Prisma's type-safe query builder to raw SQL queries. The core change replaces object-based query conditions (Prisma.BookingTimeStatusDenormalizedWhereInput) with SQL template literals (Prisma.Sql) throughout the service. The findMany method is removed and replaced with getBaseConditions that returns combined SQL conditions. The NOTHING constant pattern changes from { id: -1 } to a SQL fragment (1=0). Integration tests are updated to validate SQL conditions using $queryRaw instead of findMany, with caching-related test suites removed entirely. Authorization and filter methods now construct parameterized SQL queries using template literals and the ANY operator for array comparisons.

Changes

File(s) Summary
packages/lib/server/service/insightsBooking.ts Refactored service to use raw SQL queries (Prisma.Sql) instead of Prisma's query builder; replaced NOTHING constant with NOTHING_CONDITION SQL fragment; removed findMany method and added getBaseConditions method returning combined SQL conditions; updated all condition-building methods to return Prisma.Sql with template literals and ANY operator for arrays; changed Prisma import from type-only to regular; introduced InsightsBookingServicePublicOptions type.
packages/lib/server/service/__tests__/insightsBooking.integration-test.ts Updated test assertions to expect raw SQL conditions using Prisma.sql instead of object-based queries; introduced NOTHING_CONDITION constant (Prisma.sql1=0); removed 'Caching' test suites; renamed 'findMany' suite to 'getBaseConditions' and updated to use $queryRaw with SQL-based conditions; all authorization and filter assertions now validate SQL template literals with parameterized values.

Sequence Diagram

This diagram shows the interactions between components:

sequenceDiagram
    participant Test as Test Suite
    participant Service as InsightsBookingService
    participant Prisma as Prisma Client
    participant DB as Database

    Note over Test,DB: Authorization Conditions Flow

    Test->>Service: new InsightsBookingService(options)
    activate Service
    Service-->>Test: service instance
    deactivate Service

    Test->>Service: getAuthorizationConditions()
    activate Service
    Service->>Service: Build SQL conditions based on user role
    alt No user/team access
        Service-->>Test: NOTHING_CONDITION (1=0)
    else User scope (owner/admin)
        Service-->>Test: Prisma.sql with userId and teamId filters
    else Team member scope
        Service-->>Test: Prisma.sql with OR conditions for team/user bookings
    else Organization admin scope
        Service-->>Test: Prisma.sql with multiple team/user IDs using ANY()
    end
    deactivate Service

    Note over Test,DB: Filter Conditions Flow

    Test->>Service: getFilterConditions()
    activate Service
    Service->>Service: Build SQL filters from options
    alt EventType filter
        Service-->>Test: Prisma.sql with eventTypeId OR eventParentId
    else User filter
        Service-->>Test: Prisma.sql with userId
    else Combined filters
        Service-->>Test: Prisma.sql with AND conditions
    end
    deactivate Service

    Note over Test,DB: Combined Query Flow

    Test->>Service: getBaseConditions()
    activate Service
    Service->>Service: getAuthorizationConditions()
    Service->>Service: getFilterConditions()
    Service->>Service: Combine auth + filter SQL
    Service-->>Test: Combined Prisma.sql conditions
    deactivate Service

    Test->>Prisma: $queryRaw with SQL conditions
    activate Prisma
    Prisma->>DB: Execute raw SQL query
    DB-->>Prisma: Query results
    Prisma-->>Test: Booking records
    deactivate Prisma

    Test->>Test: Assert results match expected data
Loading

🔗 Cross-Repository Impact Analysis

Enable automatic detection of breaking changes across your dependent repositories. → Set up now

Learn more about Cross-Repository Analysis

What It Does

  • Automatically identifies repositories that depend on this code
  • Analyzes potential breaking changes across your entire codebase
  • Provides risk assessment before merging to prevent cross-repo issues

How to Enable

  1. Visit Settings → Code Management
  2. Configure repository dependencies
  3. Future PRs will automatically include cross-repo impact analysis!

Benefits

  • 🛡️ Prevent breaking changes across repositories
  • 🔍 Catch integration issues before they reach production
  • 📊 Better visibility into your multi-repo architecture

▶️AI Code Reviews for VS Code, Cursor, Windsurf
Install the extension

Note for Windsurf Please change the default marketplace provider to the following in the windsurf settings:

Marketplace Extension Gallery Service URL: https://marketplace.visualstudio.com/_apis/public/gallery

Marketplace Gallery Item URL: https://marketplace.visualstudio.com/items

Entelligence.ai can learn from your feedback. Simply add 👍 / 👎 emojis to teach it your preferences. More shortcuts below

Emoji Descriptions:

  • ⚠️ Potential Issue - May require further investigation.
  • 🔒 Security Vulnerability - Fix to ensure system safety.
  • 💻 Code Improvement - Suggestions to enhance code quality.
  • 🔨 Refactor Suggestion - Recommendations for restructuring code.
  • ℹ️ Others - General comments and information.

Interact with the Bot:

  • Send a message or request using the format:
    @entelligenceai + *your message*
Example: @entelligenceai Can you suggest improvements for this code?
  • Help the Bot learn by providing feedback on its responses.
    @entelligenceai + *feedback*
Example: @entelligenceai Do not comment on `save_auth` function !

Also you can trigger various commands with the bot by doing
@entelligenceai command

The current supported commands are

  1. config - shows the current config
  2. retrigger_review - retriggers the review

More commands to be added soon.

Comment on lines 26 to 38
}),
]);

export type InsightsBookingServicePublicOptions = {
scope: "user" | "org" | "team";
userId: number;
orgId: number;
teamId?: number;
};

export type InsightsBookingServiceOptions = z.infer<typeof insightsBookingServiceOptionsSchema>;

export type InsightsBookingServiceFilterOptions = {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Correctness: The InsightsBookingServicePublicOptions type incorrectly marks teamId as optional. However, the insightsBookingServiceOptionsSchema requires teamId when scope is "team". This mismatch allows the service to be instantiated with a "team" scope but no teamId, which causes the constructor's Zod validation to fail and set this.options to null. Consequently, buildAuthorizationConditions returns NOTHING_CONDITION (1=0), causing the service to silently return no results at runtime despite passing TypeScript checks. Update InsightsBookingServicePublicOptions to be a discriminated union where teamId is required for the team scope.

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.

2 participants