Skip to content
This repository was archived by the owner on Mar 1, 2026. It is now read-only.

fix(orm): incorrect result type when "_count" is nested inside "include"#589

Merged
ymc9 merged 1 commit into
devfrom
fix/issue-570
Jan 11, 2026
Merged

fix(orm): incorrect result type when "_count" is nested inside "include"#589
ymc9 merged 1 commit into
devfrom
fix/issue-570

Conversation

@ymc9
Copy link
Copy Markdown
Member

@ymc9 ymc9 commented Jan 11, 2026

Summary by CodeRabbit

New Features

  • Added support for selecting count information on related records using _count within include queries. Retrieve aggregate counts alongside related data in a single operation.

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

Copilot AI review requested due to automatic review settings January 11, 2026 09:23
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Jan 11, 2026

📝 Walkthrough

Walkthrough

The PR extends the ModelResult type definition to conditionally augment results with a _count field when using include with an _count selector. Three files are modified: the core type definition in crud-types.ts, an end-to-end test validating _count functionality with various include configurations, and typing test cases confirming proper type inference.

Changes

Cohort / File(s) Summary
Type Definition Augmentation
packages/orm/src/client/crud-types.ts
Adds conditional intersection to ModelResult include branch: if _count is present and truthy, includes { _count: SelectCountResult<Schema, Model, I['_count']> }; otherwise includes {}. Core logic change enables count selection on related fields with proper typing.
End-to-End Test Coverage
tests/e2e/orm/client-api/find.test.ts
New test "supports _count inside include" validates _count functionality across three scenarios: nested select with _count, boolean include with _count, and include with filter and _count. Asserts correct result structure and count values.
Typing Validation
tests/e2e/orm/schemas/typing/typecheck.ts
New typing test cases verify correct type inference for _count within include: validates field access on result._count.posts and proper typing in both nested select and boolean include patterns.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~14 minutes

Possibly related PRs

  • PR #22: Modifies client CRUD type definitions to add/adjust _count support in include/select paths with typed results.
  • PR #21: Updates client CRUD type definitions to adjust _count handling in ModelSelectResult and SelectCount types.

Poem

🐰 Hop, hop, counting we go!
Include brings _count in tow,
Types now know the tale,
Relations never fail!

🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and specifically describes the main change: fixing the result type for _count nested inside include in the ORM.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings

📜 Recent review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f54093d and 732072e.

📒 Files selected for processing (3)
  • packages/orm/src/client/crud-types.ts
  • tests/e2e/orm/client-api/find.test.ts
  • tests/e2e/orm/schemas/typing/typecheck.ts
🧰 Additional context used
📓 Path-based instructions (2)
tests/e2e/**/*.{ts,tsx}

📄 CodeRabbit inference engine (CLAUDE.md)

E2E tests should validate real-world schema compatibility with established projects

Files:

  • tests/e2e/orm/schemas/typing/typecheck.ts
  • tests/e2e/orm/client-api/find.test.ts
tests/**/type*.{ts,tsx}

📄 CodeRabbit inference engine (CLAUDE.md)

Ensure TypeScript inference and type coverage are validated through type coverage tests

Files:

  • tests/e2e/orm/schemas/typing/typecheck.ts
🧠 Learnings (6)
📓 Common learnings
Learnt from: CR
Repo: zenstackhq/zenstack-v3 PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-11-26T01:55:04.540Z
Learning: Applies to tests/**/type*.{ts,tsx} : Ensure TypeScript inference and type coverage are validated through type coverage tests
📚 Learning: 2025-11-26T01:55:04.540Z
Learnt from: CR
Repo: zenstackhq/zenstack-v3 PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-11-26T01:55:04.540Z
Learning: Applies to tests/**/type*.{ts,tsx} : Ensure TypeScript inference and type coverage are validated through type coverage tests

Applied to files:

  • tests/e2e/orm/schemas/typing/typecheck.ts
  • tests/e2e/orm/client-api/find.test.ts
📚 Learning: 2025-11-26T01:55:04.540Z
Learnt from: CR
Repo: zenstackhq/zenstack-v3 PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-11-26T01:55:04.540Z
Learning: Applies to tests/e2e/**/*.{ts,tsx} : E2E tests should validate real-world schema compatibility with established projects

Applied to files:

  • tests/e2e/orm/schemas/typing/typecheck.ts
  • tests/e2e/orm/client-api/find.test.ts
📚 Learning: 2025-11-26T01:55:04.540Z
Learnt from: CR
Repo: zenstackhq/zenstack-v3 PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-11-26T01:55:04.540Z
Learning: Applies to packages/zenstackhq/orm/**/*.test.{ts,tsx} : ORM package tests should include comprehensive client API tests and policy tests

Applied to files:

  • tests/e2e/orm/schemas/typing/typecheck.ts
  • tests/e2e/orm/client-api/find.test.ts
📚 Learning: 2025-11-26T01:55:04.540Z
Learnt from: CR
Repo: zenstackhq/zenstack-v3 PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-11-26T01:55:04.540Z
Learning: Applies to packages/zenstackhq/orm/**/*.{ts,tsx} : Implement plugin hooks at ORM, Kysely, and entity mutation levels for query interception and customization

Applied to files:

  • packages/orm/src/client/crud-types.ts
📚 Learning: 2025-12-30T15:07:06.254Z
Learnt from: mwillbanks
Repo: zenstackhq/zenstack-v3 PR: 550
File: packages/orm/src/client/crud/operations/base.ts:158-159
Timestamp: 2025-12-30T15:07:06.254Z
Learning: Do not use ts-expect-error in production code within the zenstackhq/zenstack-v3 repo (e.g., packages/*). Use explicit type annotations, targeted type assertions, or refactor to resolve the type error. ts-expect-error may be acceptable only in test files for stubbing or temporary silencing. Ensure production code is type-safe and maintainable.

Applied to files:

  • packages/orm/src/client/crud-types.ts
🧬 Code graph analysis (1)
tests/e2e/orm/client-api/find.test.ts (1)
tests/e2e/orm/client-api/utils.ts (2)
  • createUser (6-21)
  • createPosts (23-32)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (4)
  • GitHub Check: Agent
  • GitHub Check: build-test (22.x, sqlite)
  • GitHub Check: build-test (22.x, postgresql)
  • GitHub Check: claude-review
🔇 Additional comments (3)
packages/orm/src/client/crud-types.ts (1)

217-221: Type definition correctly implements _count support in include clause.

The conditional type properly handles the three cases:

  • _count not present → empty object
  • _count: false | undefined → empty object
  • _count: true | { select: ... } → adds typed _count property

This aligns with the existing _count support in the select branch (lines 159-161) and correctly reuses SelectCountResult which handles both boolean and object forms.

tests/e2e/orm/client-api/find.test.ts (1)

1125-1169: Comprehensive test coverage for _count inside include.

The test validates three important scenarios:

  1. _count with nested select on the relation
  2. _count with boolean true
  3. _count with filtered relations

All scenarios properly verify both the presence of _count and the correctness of the count values. The test aligns well with E2E testing guidelines.

Based on coding guidelines: E2E tests should validate real-world schema compatibility with established projects.

tests/e2e/orm/schemas/typing/typecheck.ts (1)

165-183: Type coverage tests properly validate _count inference in include clause.

The tests verify TypeScript correctly infers:

  • _count.posts as a number
  • posts[0]?.title from the included relation

This validates the type definition changes in crud-types.ts and ensures proper type safety for the new feature.

Based on learnings and coding guidelines: Ensure TypeScript inference and type coverage are validated through type coverage tests.


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

Comment @coderabbitai help to get the list of available commands and usage tips.

@claude
Copy link
Copy Markdown
Contributor

claude Bot commented Jan 11, 2026

Claude finished @ymc9's task —— View job


Code Review Complete ✅

Reviewing PR #589: fix(orm): incorrect result type when "_count" is nested inside "include"

Todo List:

  • Analyze the type system changes in crud-types.ts
  • Review test additions in find.test.ts
  • Check type checking additions in typecheck.ts
  • Evaluate code quality and best practices
  • Check for potential bugs or edge cases
  • Assess test coverage completeness
  • Provide comprehensive review feedback

Summary

This PR addresses a type inference issue when using _count inside the include clause. The fix adds proper TypeScript typing support for this pattern, which was previously not correctly typed.

Code Review Feedback

Code Quality & Best Practices

Strengths:

  • Minimal, targeted fix: The change is surgical and only affects the problematic type scenario
  • Preserves existing behavior: The fix maintains backward compatibility for all existing patterns
  • Follows existing patterns: Uses the same conditional type pattern as the select branch above it

Type System Changes in crud-types.ts:217-221:

} & ('_count' extends keyof I
    ? I['_count'] extends false | undefined
        ? {}
        : { _count: SelectCountResult<Schema, Model, I['_count']> }
    : {})

This properly handles the _count field when present in the include clause, mirroring the logic already present in the select branch.

Test Coverage

Excellent test additions:

  • Runtime behavior testing: Validates that _count works correctly with various include patterns
  • Type validation: TypeScript compilation tests ensure proper type inference
  • Edge case coverage: Tests both _count: true and _count: { select: {...} } patterns
  • Filtered counts: Tests counting with where clauses in the _count specification

Test scenarios covered:

  1. _count with select inside include
  2. _count with boolean true inside include
  3. _count with filtered posts inside include

Security & Performance

  • No security concerns: This is a pure TypeScript type change with no runtime implications
  • No performance impact: Changes only affect compile-time type checking
  • No runtime behavior changes: The underlying ORM logic remains unchanged

Potential Issues Analysis

No significant issues found:

  • The fix is type-system only and doesn't introduce runtime risks
  • The conditional type logic correctly handles all edge cases (false, undefined, object configurations)
  • The implementation follows the exact same pattern used elsewhere in the codebase

Architecture Consistency

  • Follows established patterns: The fix mirrors the existing select branch logic
  • Maintains symmetry: Both select and include now handle _count consistently
  • Type-safe: Leverages existing SelectCountResult type for consistency

Recommendations

Ready to Merge

This is a well-implemented fix that:

  • Solves the specific typing issue described in the title
  • Includes comprehensive test coverage
  • Maintains code quality and follows existing patterns
  • Introduces no breaking changes or security concerns

Minor Suggestions

  1. Consider adding JSDoc comment: The complex conditional type could benefit from a brief comment explaining the _count handling in include clauses
  2. Future enhancement: Consider whether similar patterns exist elsewhere in the type system that might need the same treatment

Conclusion

This is a solid, minimal fix that addresses the type inference issue for _count in include clauses. The implementation is clean, well-tested, and follows established patterns. Approved for merge.


Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

This PR fixes a TypeScript typing issue where the _count property was not properly typed when nested inside an include clause. The runtime already supported this functionality, but the type definitions were incomplete, leading to type errors when accessing the _count property.

Changes:

  • Added conditional type support for _count in include clauses to the ModelResult type
  • Added runtime tests to verify _count works correctly with include in multiple scenarios
  • Added type-checking tests to ensure TypeScript correctly infers types for _count in include

Reviewed changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated no comments.

File Description
packages/orm/src/client/crud-types.ts Extended the ModelResult type to properly type the _count property when it appears in include clauses
tests/e2e/orm/client-api/find.test.ts Added comprehensive runtime tests for _count inside include with select syntax, boolean true, and filtered counts
tests/e2e/orm/schemas/typing/typecheck.ts Added type-checking tests to verify TypeScript correctly infers types for _count usage in include

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@ymc9 ymc9 merged commit 154ba29 into dev Jan 11, 2026
11 checks passed
@ymc9 ymc9 deleted the fix/issue-570 branch January 11, 2026 09:45
@claude claude Bot mentioned this pull request Jan 11, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants