Skip to content
Source
Sign inSign up
TanStack/db

fix: resolve materialize(findOne()) to undefined when the correlation key is null #1707

ClosedMohith26(GitHub profile, opens in a new tab)wants to merge 2 commits intomain fromrefs/pull/1707/headopened

Fixes #1706, reported by @Jaime02.

materialize(q...findOne()) returned null instead of the typed undefined whenever the correlated FK column was itself null: the compiler replaces the include in select with a literal null placeholder, and Phase 1 of the includes flush only handled correlationKey != null, so null-FK parents never reached materializeIncludedValue and the raw placeholder leaked out, violating the T | undefined contract in the types.

The fix resolves null-correlation-key fields eagerly to their empty materialized value at parent-insert time (undefined for findOne, [] for arrays, "" for concat), with a skipped routing flag so conditional-select branches that do not own the field are untouched. Bare non-materialized includes with null FK intentionally keep the placeholder pending RFC #1658.

Independent of #1705 (different region of the compiler plus the live-collection routing; reproduced on plain main; no overlapping hunks). Patch changeset included. Three regression tests (the issue's three-post repro with an FK-set-but-unmatched control, array shape, live FK-update-to-null transition) fail without the fix; full suite 2486 passed, zero new failures; eslint/prettier/typecheck clean.

Summary by CodeRabbit

  • Bug Fixes
    • Fixed materialized query results when correlation keys are null.
    • findOne() now consistently returns undefined, array queries return [], and concatenated results return an empty value.
    • Corrected updates when a correlation key changes from a valid value to null.
    • Prevented placeholder values from appearing in included results.
    1. Review Change Stack

      📝 Walkthrough

      Walkthrough

      This change distinguishes skipped include routing from null correlation keys, emits empty materialized values for inline includes with null correlations, synchronizes stored parent rows, and adds regression coverage for findOne(), array materialization, and correlation updates.

      Changes

      Null correlation materialization

      Layer / File(s)Summary
      Routing metadata and guard handling
      packages/db/src/query/compiler/index.ts
      Include routing metadata now carries skipped?: boolean across source, direct, and compiled subquery routing paths.
      Inline empty materialization
      packages/db/src/query/live/collection-config-builder.ts
      Inline includes with non-skipped null or undefined correlation keys receive the appropriate empty materialized value, while stored parent rows are synchronized.
      Regression coverage and release note
      packages/db/tests/query/includes.test.ts, .changeset/shiny-donkeys-repeat.md
      Tests verify undefined, empty-array, and reactive null-correlation results; a patch changeset documents the fix.

      Estimated code review effort: 3 (Moderate) | ~20 minutes

      Possibly related issues

      • Issue 1495 — Both changes involve flushIncludesState and nested include materialization, though they address different behaviors.

      Possibly related PRs

      • TanStack/db#1705 — Both changes update compiler routing and include tests for correlated-subquery materialization behavior.

      Suggested reviewers: kevin-dp, kyleamathews

      🚥 Pre-merge checks | ✅ 5
      ✅ Passed checks (5 passed)
      Check nameStatusExplanation
      Title check✅ PassedThe title clearly states the main bug fix and the affected materialize(findOne()) behavior.
      Description check✅ PassedThe description covers the bug, fix, tests, changeset, and release impact, though it doesn't use the exact template headings.
      Linked Issues check✅ PassedThe changes address #1706 by resolving null correlation keys to undefined for findOne, with array/concat handling and regression tests.
      Out of Scope Changes check✅ PassedThe added compiler, live-query, changeset, and test updates all support the #1706 fix and don't appear unrelated.
      Docstring Coverage✅ PassedNo functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
      ✨ Finishing Touches
      🧪 Generate unit tests (beta)
      • Create PR with unit 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.
    2. Actionable comments posted: 1

      🧹 Nitpick comments (1)
      packages/db/tests/query/includes.test.ts (1)

      6583-6597: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

      Keep the regression fixtures type-safe.

      The helper has no return annotation and the assertions use as any, so result-shape regressions are not type-checked. Use a precise helper return type and inferred/narrowed query results instead.

      As per coding guidelines, avoid any and provide the most precise TypeScript return type annotations.

      Also applies to: 6620-6682

      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In `@packages/db/tests/query/includes.test.ts` around lines 6583 - 6597, The
      createAuthorAndPostCollections helper should declare a precise return type for
      both collection instances, and the related query assertions should remove as any
      casts. Use inferred or properly narrowed result types so regressions in the
      query result shape are caught by TypeScript.

      Source: Coding guidelines

      🤖 Prompt for all review comments with AI agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      Inline comments:
      In @.changeset/shiny-donkeys-repeat.md:
      - Line 5: Update the changeset description to replace the invalid-looking
      `materialize(q…findOne())` expression with valid API syntax such as
      `materialize(q.from(...).findOne())`, or describe the behavior in prose while
      preserving the existing null-correlation-key details.
      
      ---
      
      Nitpick comments:
      In `@packages/db/tests/query/includes.test.ts`:
      - Around line 6583-6597: The createAuthorAndPostCollections helper should
      declare a precise return type for both collection instances, and the related
      query assertions should remove as any casts. Use inferred or properly narrowed
      result types so regressions in the query result shape are caught by TypeScript.
      🪄 Autofix (Beta)

      Fix all unresolved CodeRabbit comments on this PR:

      • Push a commit to this branch (recommended)
      • Create a new PR with the fixes

      ℹ️ Review info
      ⚙️ Run configuration

      Configuration used: defaults

      Review profile: CHILL

      Plan: Pro Plus

      Run ID: a3f855fd-290c-4076-8ce6-410bcea0f9aa

      📥 Commits

      Reviewing files that changed from the base of the PR and between 67c840fe7a45d818de768fa790ebec2f27654d04 and 0997bedbd9297243ea2f15e113fdf469dbf3ba6d.

      📒 Files selected for processing (4)
      • .changeset/shiny-donkeys-repeat.md
      • packages/db/src/query/compiler/index.ts
      • packages/db/src/query/live/collection-config-builder.ts
      • packages/db/tests/query/includes.test.ts
      .changeset/shiny-donkeys-repeat.md line 5
      @@ -0,0 +1,5 @@
      1+---
      2+'@tanstack/db': patch
      3+---
      4+
      5+Fix: `materialize(q…findOne())` resolved to `null` instead of `undefined` when the correlation key itself was null. A null correlation key never reached the includes materialization step, so the compiler's `null` select placeholder leaked into the result, violating the typed `T | undefined` contract. Null correlation keys now resolve to the empty materialized value (`undefined` for `findOne()`, `[]` for arrays, `` for `concat`).

      📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

      Use a valid-looking query expression.

      materialize(q…findOne()) is unclear and reads like invalid API syntax. Use materialize(q.from(...).findOne()) or prose instead.

      Proposed fix
      -Fix: `materialize(q…findOne())` resolved to `null` instead of `undefined`
      +Fix: `materialize(q.from(...).findOne())` resolved to `null` instead of `undefined`
      📝 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.

      Fix: `materialize(q.from(...).findOne())` resolved to `null` instead of `undefined` when the correlation key itself was null. A null correlation key never reached the includes materialization step, so the compiler's `null` select placeholder leaked into the result, violating the typed `T | undefined` contract. Null correlation keys now resolve to the empty materialized value (`undefined` for `findOne()`, `[]` for arrays, `` for `concat`).
      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In @.changeset/shiny-donkeys-repeat.md at line 5, Update the changeset
      description to replace the invalid-looking `materialize(q…findOne())` expression
      with valid API syntax such as `materialize(q.from(...).findOne())`, or describe
      the behavior in prose while preserving the existing null-correlation-key
      details.
    3. Thank you so much for the contribution, but I guess that this PR is outdated and should be closed, see https://github.com/TanStack/db/pull/1740

Sign in to join this conversation.