Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(delegate): support _count select of base fields #1937

Merged
merged 3 commits into from
Jan 6, 2025
Merged

Conversation

ymc9
Copy link
Member

@ymc9 ymc9 commented Jan 5, 2025

fixes #1467

Copy link
Contributor

coderabbitai bot commented Jan 5, 2025

📝 Walkthrough

Walkthrough

The pull request introduces modifications to the delegate model's query handling, specifically in the DelegateProxyHandler class within the runtime package. The changes focus on improving the flexibility of handling selections and inclusions, particularly for inherited models and count-based queries. A new regression test has been added to validate the behavior of count queries on inherited models, addressing a specific issue with nested field selection.

Changes

File Change Summary
packages/runtime/src/enhancements/node/delegate.ts - Updated injectSelectIncludeHierarchy method with a more structured selector function approach.
- Modified injectBaseFieldSelect to include new forCount parameter.
- Refined argument handling for count and nested selections.
tests/regression/tests/issue-1467.test.ts - Added new regression test for count queries on inherited models.
- Created test schema with User, Container, and Drink/Beer models.
- Implemented test case verifying count selection behavior.
tests/integration/tests/enhancements/with-delegate/enhanced-client.test.ts - Added test case for counting related records in a polymorphic schema.

Assessment against linked issues

Objective Addressed Explanation
Fix _count on inherited model [#1467]
Ensure count queries work across base and inherited models [#1467]

Possibly related PRs


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

‼️ IMPORTANT
Auto-reply has been disabled for this repository in the CodeRabbit settings. The CodeRabbit bot will not respond to your replies unless it is explicitly tagged.

  • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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. (Beta)
  • @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.

Copy link
Contributor

@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: 0

🧹 Nitpick comments (4)
packages/runtime/src/enhancements/node/delegate.ts (4)

183-196: Improve maintainability of unified selector pattern.

This set of array-based selectors for handling normal and count-based selections is clear and modular. As a good-to-have improvement, consider extracting these objects into well-named constants or small helper functions to avoid inlining potentially repetitive logic in other areas.


204-231: Potential improvement for unrecognized fields.

Looping through Object.entries(data) to resolve inherited fields is correct. However, if there is any chance of unexpected or typo-ed fields, consider adding a warning or logging statement when resolveField returns undefined. This would help surface subtle data payload issues more proactively.


245-245: Avoid the delete operator for performance reasons.

Static analysis warns of performance overhead when using the delete operator. Although semantically correct here, consider setting the property to undefined or using Reflect.deleteProperty(args[kind], '_count') if truly necessary to remove the property.

Below is one possible approach:

- delete args[kind]['_count'];
+ args[kind]['_count'] = undefined;
🧰 Tools
🪛 Biome (1.9.4)

[error] 245-245: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)


310-311: Parameter naming consistency.

The parameter forCount is descriptive, but matching similar naming (e.g., isCount) might enhance overall code consistency and reduce confusion.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1956bdb and 99a9835.

📒 Files selected for processing (2)
  • packages/runtime/src/enhancements/node/delegate.ts (3 hunks)
  • tests/regression/tests/issue-1467.test.ts (1 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
packages/runtime/src/enhancements/node/delegate.ts

[error] 245-245: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)

🔇 Additional comments (6)
packages/runtime/src/enhancements/node/delegate.ts (3)

198-202: Guard checks appear solid.

Early returns (skipping processing when the data object doesn't exist) help keep conditional logic concise and prevent errors. This approach looks good.


233-253: Well-handled base-field injection.

Conditionally injecting base field selections is a neat approach. The fallback logic ensures that if the field is inherited from a base model, it’s properly routed. The code accomplishes the PR’s objective to support base field counting.

🧰 Tools
🪛 Biome (1.9.4)

[error] 245-245: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)


338-351: Robust deepmerge usage.

Merging _count objects (line 345-348) is careful and ensures multiple _count specifications are correctly unified. Great job accommodating partial merges.

tests/regression/tests/issue-1467.test.ts (3)

3-33: Well-organized schema definition.

The inheritance from Drink in Beer and usage of @@delegate(type) effectively tests the base field handling. Very clear test structure for verifying delegated model logic.


38-43: Correctly creating test data.

Creating a Beer instance and linking multiple Container records to that instance thoroughly sets up the scenario needed to test _count behaviors on inherited models.


45-49: Good validation of the _count fix.

Selecting _count on the beer model and verifying the container count addresses the core issue reported in #1467. This ensures that base fields and count logic behave as expected.

Copy link
Contributor

@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: 0

🧹 Nitpick comments (1)
tests/integration/tests/enhancements/with-delegate/enhanced-client.test.ts (1)

434-438: Optional: Consider verifying additional relation counts.

You're verifying both B and C counts at the base level. It might be worth also verifying the cs count at the A2 level for completeness, though this is not strictly necessary.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 99a9835 and 0458037.

📒 Files selected for processing (1)
  • tests/integration/tests/enhancements/with-delegate/enhanced-client.test.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: build-test (20.x)
  • GitHub Check: dependency-review
  • GitHub Check: build-test (20.x)
  • GitHub Check: OSSAR-Scan
  • GitHub Check: build-test (20.x)
🔇 Additional comments (3)
tests/integration/tests/enhancements/with-delegate/enhanced-client.test.ts (3)

382-418: Schema definitions look clean and consistent.

The nested inheritance structure (AA1A2) and multiple delegate definitions (@@delegate(type), @@delegate(type1)) are logically consistent. The presence of B and C models referencing A is well-structured for testing the relation counts.


421-425: Great use of _count in creation.

Leveraging Prisma’s _count select immediately upon record creation is a solid approach to verify the relation counts (bs) in a single query.


427-432: Effective check of relation counts for nested records.

Verifying the count fields (bs) returned from findFirst ensures that the _count logic is correct.

Copy link
Contributor

@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: 0

🧹 Nitpick comments (3)
packages/runtime/src/enhancements/node/delegate.ts (3)

193-210: Good separation of concerns using selector functions.

The implementation cleanly separates different selection cases using an array of selector functions, making the code more modular and easier to maintain.

Consider extracting these selectors into a separate constant or class property to improve reusability and testability.

+private readonly selectors = [
+    (payload: any) => ({ data: payload.select, kind: 'select' as const, isCount: false }),
+    // ... other selectors
+];

330-331: Clear parameter documentation needed.

The forCount parameter lacks JSDoc documentation explaining its purpose and usage.

Add JSDoc documentation for better code maintainability:

    private injectBaseFieldSelect(
        model: string,
        field: string,
        value: any,
        selectInclude: any,
        context: 'select' | 'include',
+       /** Indicates if the injection is for a count-based selection */
        forCount = false
    )

358-373: Complex conditional logic for count-based selections.

The implementation correctly handles count-based selections but the nested conditional logic could be simplified.

Consider extracting the count-based selection logic into a separate private method for better readability:

+private injectCountBasedSelection(
+    thisLayer: any,
+    baseRelationName: string,
+    context: 'select' | 'include',
+    field: string,
+    value: any
+) {
+    if (
+        !thisLayer[baseRelationName][context]['_count'] ||
+        typeof thisLayer[baseRelationName][context] !== 'object'
+    ) {
+        thisLayer[baseRelationName][context]['_count'] = {};
+    }
+    thisLayer[baseRelationName][context]['_count'] = deepmerge(
+        thisLayer[baseRelationName][context]['_count'],
+        { select: { [field]: value } }
+    );
+}

Then use it in the main method:

    if (forCount) {
-        if (
-            !thisLayer[baseRelationName][context]['_count'] ||
-            typeof thisLayer[baseRelationName][context] !== 'object'
-        ) {
-            thisLayer[baseRelationName][context]['_count'] = {};
-        }
-        thisLayer[baseRelationName][context]['_count'] = deepmerge(
-            thisLayer[baseRelationName][context]['_count'],
-            { select: { [field]: value } }
-        );
+        this.injectCountBasedSelection(thisLayer, baseRelationName, context, field, value);
    } else {
        thisLayer[baseRelationName][context][field] = value;
    }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0458037 and 98e28cf.

📒 Files selected for processing (1)
  • packages/runtime/src/enhancements/node/delegate.ts (3 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
packages/runtime/src/enhancements/node/delegate.ts

[error] 264-264: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)

⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: OSSAR-Scan
  • GitHub Check: build-test (20.x)
  • GitHub Check: build-test (20.x)
  • GitHub Check: build-test (20.x)
  • GitHub Check: dependency-review
🔇 Additional comments (3)
packages/runtime/src/enhancements/node/delegate.ts (3)

183-191: Well-documented implementation of polymorphic base hierarchy injection.

The comments clearly explain the two cases where base hierarchy injection is needed, making the code more maintainable.


264-264: Performance consideration: Use of delete operator.

While Biome flags the use of the delete operator for potential performance impact, in this case, it's the correct approach as we need to completely remove empty _count payloads to maintain proper query structure.

The alternative of setting to undefined would still keep the property in the object, which is not desired here.

🧰 Tools
🪛 Biome (1.9.4)

[error] 264-264: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)


262-269: Proper cleanup and merging of count selections.

The code correctly handles empty _count payloads and uses deepmerge for combining selections. However, consider the performance implications of deep merging large payloads.

Let's verify the usage of deepmerge in the codebase:

✅ Verification successful

Performance impact of deepmerge usage is acceptable

The codebase shows that deepmerge is used appropriately with small, focused objects during query building. The implementation includes optimizations like custom merge strategies and proper type handling.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for potential performance bottlenecks with deepmerge
# Look for large payloads being merged

# Find all deepmerge usages
rg --type ts "deepmerge\(" -A 5 -B 5

Length of output: 10107

🧰 Tools
🪛 Biome (1.9.4)

[error] 264-264: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)

@ymc9 ymc9 merged commit bcbfb9a into dev Jan 6, 2025
9 checks passed
@ymc9 ymc9 deleted the fix/issue-1467 branch January 6, 2025 07:27
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