Skip to content

fix(orm): support _count nested inside an include#2712

Merged
ymc9 merged 1 commit into
devfrom
fix/issue-2669-nested-count-include
Jun 17, 2026
Merged

fix(orm): support _count nested inside an include#2712
ymc9 merged 1 commit into
devfrom
fix/issue-2669-nested-count-include

Conversation

@ymc9

@ymc9 ymc9 commented Jun 16, 2026

Copy link
Copy Markdown
Member

Problem

Fixes #2669.

Using _count inside a nested relation's include throws at runtime:

await db.user.findMany({
  include: {
    posts: {
      include: {
        _count: { select: { comments: true } },
      },
    },
  },
});
  • SQLite: QueryError: Field "_count" not found in model "Post"
  • Postgres/MySQL: missing FROM-clause entry for table "$$t3"

This is valid Prisma syntax (verified against Prisma 6 — it returns posts[].​_count.comments), so it's a Prisma-compatibility gap.

Root cause

The relation-JSON builder resolves a nested payload through two separate branches — one for select and one for include. The select branch already special-cased _count (calling buildCountJson), but the include branch did not:

  • SQLite called requireField(schema, 'Post', '_count') → throws.
  • Postgres/MySQL emitted a reference to a lateral join ($$..._count.$data) that buildRelationJoins never creates (it only joins real relation fields).

Fix

Apply the same _count handling to the include branch in both dialects, calling buildCountJson with the relation's alias so the count subquery correlates correctly:

  • packages/orm/src/client/crud/dialects/sqlite.ts
  • packages/orm/src/client/crud/dialects/lateral-join-dialect-base.ts

Why it wasn't caught

The e2e suite covered _count at the top level of select/include and _count nested inside a relation's select — all of which hit the (working) select path. No test nested _count inside an include, the one broken path.

Tests

  • Added 'supports _count nested inside an include' to tests/e2e/orm/client-api/find.test.ts, covering _count: { select: ... }, _count: true, and _count with a where filter on the counted relation. Verified it fails against the un-fixed build with the exact issue error and passes with the fix.
  • Added tests/regression/test/issue-2669.test.ts (SQLite + Postgres).

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes

    • Fixed aggregation count functionality when nested within relation queries.
  • Tests

    • Added regression test for nested aggregation counts in relation queries across multiple database providers.

When `_count` appears inside a nested relation's `include` (e.g.
`include: { posts: { include: { _count: ... } } }`), the relation-JSON
builder treated it as a regular relation field. SQLite threw
`Field "_count" not found in model "Post"`, and Postgres/MySQL generated
a reference to a never-created lateral join (`missing FROM-clause entry`).

The `select` branch already special-cased `_count`; this applies the same
handling to the `include` branch in both dialects, calling `buildCountJson`.

Fixes #2669

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@claude

claude Bot commented Jun 16, 2026

Copy link
Copy Markdown
Contributor

Claude encountered an error —— View job


I'll analyze this and get back to you.

@coderabbitai

coderabbitai Bot commented Jun 16, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: e5c544f9-d016-4a5c-8daf-06debad35611

📥 Commits

Reviewing files that changed from the base of the PR and between 4f462a7 and e6c36ab.

📒 Files selected for processing (4)
  • packages/orm/src/client/crud/dialects/lateral-join-dialect-base.ts
  • packages/orm/src/client/crud/dialects/sqlite.ts
  • tests/e2e/orm/client-api/find.test.ts
  • tests/regression/test/issue-2669.test.ts

📝 Walkthrough

Walkthrough

Two ORM dialect implementations (SqliteCrudDialect and the lateral-join base) are patched to detect _count as an include field and route it through buildCountJson rather than the generic relation path. A new regression test file for issue-2669 and an extended e2e test validate the fix across SQLite and PostgreSQL.

Changes

_count inside include fix

Layer / File(s) Summary
Dialect-level _count detection in include processing
packages/orm/src/client/crud/dialects/sqlite.ts, packages/orm/src/client/crud/dialects/lateral-join-dialect-base.ts
Both buildRelationJSON (SQLite) and buildRelationObjectArgs (lateral-join base) now check field === '_count' inside payload.include and call buildCountJson to generate the count fragment, instead of falling through to the general nested-relation logic that previously threw a QueryError.
Regression and e2e tests
tests/regression/test/issue-2669.test.ts, tests/e2e/orm/client-api/find.test.ts
A new parameterized regression test (SQLite + PostgreSQL) seeds User/Post/Comment records and asserts _count is correctly returned when nested inside include. The e2e test adds three scenarios: _count with select, _count: true, and _count with a filter on the counted relation.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Poem

🐇 Hop, hop, a count went astray,
Nested in include — it just wouldn't play.
With a branch and a check, _count finds its lane,
buildCountJson called, no more runtime pain!
The rabbit rejoices: the tests all turn green. 🌿

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main fix: supporting _count nested inside an include clause, which is the core issue addressed across all modified files.
Linked Issues check ✅ Passed The PR comprehensively addresses issue #2669 by implementing _count support in include payloads for SQLite and lateral-join dialects, adding regression test coverage, and fixing the runtime error described in the issue.
Out of Scope Changes check ✅ Passed All code changes are directly scoped to fixing _count handling in include payloads: two dialect implementations, one e2e test, and one regression test—all focused on the reported issue.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

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

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/issue-2669-nested-count-include

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.

@ymc9 ymc9 merged commit d229533 into dev Jun 17, 2026
7 of 8 checks passed
@ymc9 ymc9 deleted the fix/issue-2669-nested-count-include branch June 17, 2026 05:53
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.

[Bug] Runtime error when using _count inside the include

1 participant