Skip to content

.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 our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open

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.

Copy link
Contributor

coderabbitai bot commented Jun 24, 2025

📝 Walkthrough

Walkthrough

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

Changes

File Change Summary
packages/runtime/src/enhancements/node/policy/handler.ts Extended FindOperations type to include 'count'; updated doFind to handle 'count'; refactored count method to delegate to doFind.

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 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 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 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: 1

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9596d33 and 0de0b7d.

📒 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 of FindOperations 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 examples
rg -A 10 -B 5 "\.count\(" --type ts

}
return this.modelClient.count(args);
});
return createDeferredPromise<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, not Promise<unknown[]>
  2. Incorrect fallback: The fallback () => [] returns an empty array, but count operations should return 0 when no results match
  3. API incompatibility: Using doFind 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
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);
});
}
🤖 Prompt for AI Agents
In packages/runtime/src/enhancements/node/policy/handler.ts at line 1657, the
count method incorrectly returns a Promise of an unknown array and uses an empty
array as fallback, which is incompatible with expected count results. To fix
this, change the return type to a number or appropriate count object, replace
the fallback with a function returning 0, and avoid using doFind for count
operations by directly invoking Prisma's count API or a method designed for
counting.

@PodkopovP
Copy link
Author

PodkopovP commented Jun 24, 2025

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)

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