Skip to content

fix(polymorphism): support orderBy with base fields #1086

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

Merged
merged 2 commits into from
Mar 6, 2024
Merged

Conversation

ymc9
Copy link
Member

@ymc9 ymc9 commented Mar 6, 2024

Summary by CodeRabbit

  • New Features
    • Enhanced handling of orderBy fields to support correct ordering by inherited fields in queries.
  • Tests
    • Added integration test for improved ordering functionality in scenarios involving inheritance.
  • Chores
    • Updated TypeScript compiler options in CLI Plugins Tests for better performance.

Copy link
Contributor

coderabbitai bot commented Mar 6, 2024

Walkthrough

Walkthrough

The recent updates focus on enhancing the management of inherited fields, especially in sorting operations (orderBy). These improvements involve adjustments in the DelegateProxyHandler to ensure accurate handling of base type fields, including within select and include objects, and when constructing hierarchical where conditions. The inclusion of model names as parameters facilitates the correct resolution of inherited fields. Furthermore, a new test case has been added to validate ordering by base fields in various scenarios.

Changes

Files Change Summary
packages/runtime/src/enhancements/delegate.ts Introduced modifications to DelegateProxyHandler for improved handling of orderBy fields, including inherited fields and adjustments in select and include objects. Added model name as a parameter in buildWhereHierarchy.
tests/integration/tests/enhancements/with-delegate/enhanced-client.test.ts Added a test case in the Polymorphism Test suite to verify ordering by base fields in different scenarios.

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:

Note: Auto-reply has been disabled for this repository by the repository owner. 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 tests 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit tests.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

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 as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger a review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • The JSON schema for the configuration file is available here.
  • 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/coderabbit-overrides.v2.json

CodeRabbit Discord Community

Join our Discord Community to get help, request features, and share feedback.

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.

Review Status

Actionable comments generated: 3

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between 6e7993a and d345b80.
Files selected for processing (2)
  • packages/runtime/src/enhancements/delegate.ts (6 hunks)
  • tests/integration/tests/enhancements/with-delegate/enhanced-client.test.ts (1 hunks)
Additional comments: 3
packages/runtime/src/enhancements/delegate.ts (3)
  • 860-868: The modifications to the aggregate method to process cursor, orderBy, and where arguments using the buildWhereHierarchy method are well-aligned with the PR's objectives. These changes ensure that aggregation operations can correctly handle fields inherited from base types, enhancing the support for polymorphic models. As with other methods that manipulate object properties, ensure to guard against prototype pollution risks.
  • 888-892: The updates to the count method to process cursor and where arguments using the buildWhereHierarchy method are consistent with the PR's objectives. These changes ensure that counting operations can correctly handle fields inherited from base types, further enhancing polymorphism support. Continue to be vigilant about prototype pollution risks when manipulating object properties based on user input.
  • 928-928: The modifications to the groupBy method to process the where argument using the buildWhereHierarchy method align with the PR's objectives. These changes ensure that groupBy operations can correctly handle fields inherited from base types. The proactive error handling for by fields inherited from base types is a good practice, clearly communicating the current limitations to the users.

Comment on lines +134 to +146
private buildWhereHierarchy(model: string, where: any) {
if (!where) {
return undefined;
}

where = deepcopy(where);
Object.entries(where).forEach(([field, value]) => {
const fieldInfo = resolveField(this.options.modelMeta, this.model, field);
const fieldInfo = resolveField(this.options.modelMeta, model, field);
if (!fieldInfo?.inheritedFrom) {
return;
}

let base = this.getBaseModel(this.model);
let base = this.getBaseModel(model);
Copy link
Contributor

Choose a reason for hiding this comment

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

The implementation of buildWhereHierarchy method correctly handles the transformation of where conditions to support fields inherited from base types. This is key to achieving the PR's objective of enhancing polymorphism support. However, there's a potential risk of prototype pollution due to direct manipulation of object properties without validating their names against a list of disallowed prototype properties. This could lead to unintended side effects if a user-controlled input is passed directly to this method.

Consider adding a check to ensure that field names do not correspond to prototype properties, or use a Map for handling dynamic keys safely.

Comment on lines +238 to +271
it('order by base fields', async () => {
const { db, user } = await setup();

await expect(
db.video.findMany({
orderBy: { viewCount: 'desc' },
})
).resolves.toHaveLength(1);

await expect(
db.ratedVideo.findMany({
orderBy: { duration: 'asc' },
})
).resolves.toHaveLength(1);

await expect(
db.user.findMany({
orderBy: { assets: { _count: 'desc' } },
})
).resolves.toHaveLength(1);

await expect(
db.user.findUnique({
where: { id: user.id },
include: {
ratedVideos: {
orderBy: {
viewCount: 'desc',
},
},
},
})
).toResolveTruthy();
});
Copy link
Contributor

Choose a reason for hiding this comment

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

The new test case order by base fields correctly tests the functionality of ordering by base fields in different scenarios, which aligns with the PR's objectives to enhance polymorphism support. However, there are a few points to consider for improvement:

  1. Assertion Specificity: The test case uses .resolves.toHaveLength(1) to assert the outcome of the findMany and findUnique operations. While this checks that the query returns a result, it does not verify that the ordering is correctly applied. It would be beneficial to enhance the assertions to check the order of the returned records explicitly, ensuring that the orderBy functionality works as expected.

  2. Error Handling: The test case uses .toResolveTruthy() for the findUnique operation, which is not a standard Jest matcher. This might be a typo or a custom matcher not defined in the provided context. If it's intended to check that the promise resolves successfully, consider using .resolves.toBeTruthy() or another appropriate Jest matcher for clarity and correctness.

  3. Test Coverage: The test case covers ordering by viewCount and duration for video and ratedVideo models, and a count-based order for assets related to a user. To further ensure robustness, consider adding more scenarios that cover edge cases, such as ordering by fields that might have null values, or combining orderBy with other query parameters like where and include to test more complex queries.

  4. Documentation: Adding comments to explain the setup and the specific scenarios being tested can improve the readability and maintainability of the test case. This is especially useful for future developers who might work on this test suite.

Overall, the test case is a good start towards validating the new functionality but could be enhanced for more comprehensive testing and clarity.

  • Consider enhancing the assertions to explicitly check the order of the returned records.
  • Verify the usage of .toResolveTruthy() and replace it with a standard Jest matcher if necessary.
  • Expand the test coverage to include more scenarios and edge cases.
  • Add comments to document the setup and scenarios being tested for better readability and maintainability.

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.

Review Status

Actionable comments generated: 0

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between d345b80 and f85a6a1.
Files selected for processing (1)
  • tests/integration/tests/cli/plugins.test.ts (1 hunks)
Additional comments: 1
tests/integration/tests/cli/plugins.test.ts (1)
  • 119-119: Adding skipLibCheck: true to the TypeScript compiler options can significantly speed up the compilation process by skipping type checking of declaration files. This change is generally acceptable in test environments where speed might be prioritized over the thoroughness of type checks. However, it's important to weigh the trade-offs, as this could potentially mask type errors in third-party libraries or custom type definitions.

Ensure that this change aligns with the overall testing and quality assurance strategy of the project. It might be beneficial to periodically run type checks with skipLibCheck disabled to catch any hidden issues.

Consider periodically running type checks with skipLibCheck disabled in a separate CI job or before releases to ensure that potential type errors in declaration files are not overlooked.

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