Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

.count use same flow as findMany#2163

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 ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Draft
PodkopovP wants to merge2 commits intozenstackhq:main
base:main
Choose a base branch
Loading
fromPodkopovP:main

Conversation

@PodkopovP
Copy link

The current .count implementation (and probably other aggregate functions) create a different .where clause to findMany - this means that doing a .count and .where with the same inputs, could (after zenstacks RLS implementation) cause be looking at different results - i.e. you might end up with 4 results from .findMany, but .count says there should be 10 results.

@coderabbitai
Copy link
Contributor

coderabbitaibot commentedJun 24, 2025
edited
Loading

📝 Walkthrough

Walkthrough

The changes extend theFindOperations type to include the'count' operation and update thedoFind method to handle'count' by modifying its arguments before invoking the Prisma client. Thecount method is refactored to delegate todoFind, aligning its logic with other find operations for consistent policy enforcement.

Changes

FileChange Summary
packages/runtime/src/enhancements/node/policy/handler.tsExtendedFindOperations type to include'count'; updateddoFind to handle'count'; refactoredcount method to delegate todoFind.

Sequence Diagram(s)

sequenceDiagram    participant Caller    participant PolicyProxyHandler    participant PrismaClient    Caller->>PolicyProxyHandler: count(args)    PolicyProxyHandler->>PolicyProxyHandler: doFind('count', args, [])    PolicyProxyHandler->>PrismaClient: count(modified args)    PrismaClient-->>PolicyProxyHandler: result    PolicyProxyHandler-->>Caller: result
Loading
✨ Finishing Touches
  • 📝 Generate Docstrings

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
🪧 Tips

Chat

There are 3 ways to chat withCodeRabbit:

‼️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 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 oursupport 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 togenerate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in 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 theconfiguration 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 ourDocumentation for detailed information on how to use CodeRabbit.
  • Join ourDiscord Community to get help, request features, and share feedback.
  • Follow us onX/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitaicoderabbitaibot 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

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between9596d33 and0de0b7d.

📒 Files selected for processing (1)
  • packages/runtime/src/enhancements/node/policy/handler.ts (3 hunks)
🔇 Additional comments (2)
packages/runtime/src/enhancements/node/policy/handler.ts (2)

38-38:LGTM: Type extension aligns with unified find operations flow.

The extension ofFindOperations to include'count' correctly supports the PR objective of making count operations follow the same policy enforcement flow as other find operations.


147-149:Verify compatibility with Prisma's count API.

Setting_args.select = true for count operations may not be compatible with Prisma's count method, which typically doesn't use select clauses like find operations. This could potentially cause runtime errors or unexpected behavior.

Please verify that this approach works correctly with Prisma's count API:

#!/bin/bash# Search for how count operations are typically structured in Prisma documentation or examplesrg -A 10 -B 5"\.count\(" --type ts

}
returnthis.modelClient.count(args);
});
returncreateDeferredPromise<unknown[]>(()=>this.doFind(args,'count',()=>[]));
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Critical: Incorrect return type and fallback for count operation.

The count method implementation has several issues:

  1. Return type mismatch: Count operations should return a number or count object, notPromise<unknown[]>
  2. Incorrect fallback: The fallback() => [] returns an empty array, but count operations should return0 when no results match
  3. API incompatibility: UsingdoFind for count operations may not work correctly with Prisma's count API

Consider this approach instead:

-count(args: any) {-    return createDeferredPromise<unknown[]>(() => this.doFind(args, 'count', () => []));-}+count(args: any): Promise<number> {+    return createDeferredPromise<number>(async () => {+        const _args = this.policyUtils.safeClone(args);+        if (!this.policyUtils.injectForRead(this.prisma, this.model, _args)) {+            if (this.shouldLogQuery) {+                this.logger.info(`[policy] \`count\` ${this.model}: unconditionally denied`);+            }+            return 0;+        }++        if (this.shouldLogQuery) {+            this.logger.info(`[policy] \`count\` ${this.model}:\n${formatObject(_args)}`);+        }++        return this.modelClient.count(_args);+    });+}
📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
returncreateDeferredPromise<unknown[]>(()=>this.doFind(args,'count',()=>[]));
count(args: any):Promise<number>{
returncreateDeferredPromise<number>(async()=>{
const_args=this.policyUtils.safeClone(args);
if(!this.policyUtils.injectForRead(this.prisma,this.model,_args)){
if(this.shouldLogQuery){
this.logger.info(`[policy] \`count\`${this.model}: unconditionally denied`);
}
return0;
}
if(this.shouldLogQuery){
this.logger.info(`[policy] \`count\`${this.model}:\n${formatObject(_args)}`);
}
returnthis.modelClient.count(_args);
});
}
🤖 Prompt for AI Agents
In packages/runtime/src/enhancements/node/policy/handler.ts at line 1657, thecount method incorrectly returns a Promise of an unknown array and uses an emptyarray as fallback, which is incompatible with expected count results. To fixthis, change the return type to a number or appropriate count object, replacethe fallback with a function returning 0, and avoid using doFind for countoperations by directly invoking Prisma's count API or a method designed forcounting.

@PodkopovP
Copy link
Author

PodkopovP commentedJun 24, 2025
edited
Loading

The two issues I found so far:

  • Including relations in select/include can get funny and can cause a mismatch between .findMany / count - .count doesnt support including relations, so the current implementation doesn't support injecting guards based on relations. The solution I have here is to pass .count through the same funnel .findMany goes through, but override select to true before the final prisma call is made - this lets zenstack inject relevant relational queries to the where clause
  • .count currently injects using .injectAuthGuardAsWhere, which always wraps the where clause in 'AND' - this isn't the same process as .findMany goes through (haven't done too much investigation to see what .findMany does, but it seems to more smartly combine the original & new args)

@ymc9ymc9 marked this pull request as draftJuly 7, 2025 03:15
@JoeRoddy
Copy link

JoeRoddy commentedJul 8, 2025
edited
Loading

Relevant discord discussion from a similar issue.

https://discord.com/channels/1035538056146595961/1338578707086049372

I was never able to create a simple proof of concept replication. It was only happening in our large real world project with highly complex rules across tables, including usingcheck() across tables.

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

Reviewers

@coderabbitaicoderabbitai[bot]coderabbitai[bot] left review comments

At least 1 approving review is required to merge this pull request.

Assignees

No one assigned

Labels

None yet

Projects

None yet

Milestone

No milestone

Development

Successfully merging this pull request may close these issues.

2 participants

@PodkopovP@JoeRoddy

[8]ページ先頭

©2009-2025 Movatter.jp