Skip to content

fix(db): avoid undefined enumerable keys in compare options#1552

Open
v-anton wants to merge 2 commits into
TanStack:mainfrom
v-anton:fix/compare-options-undefined-keys
Open

fix(db): avoid undefined enumerable keys in compare options#1552
v-anton wants to merge 2 commits into
TanStack:mainfrom
v-anton:fix/compare-options-undefined-keys

Conversation

@v-anton
Copy link
Copy Markdown

@v-anton v-anton commented May 25, 2026

🎯 Changes

buildCompareOptionsFromConfig assigned locale: undefined and localeOptions: undefined as enumerable properties when stringSort !== 'locale'. These extra keys cause deepEquals in BaseIndex.matchesCompareOptions to fail on Object.keys length mismatch, preventing index matching and silently falling back to full scan.

The fix conditionally spreads these properties so they only exist when they have actual values.

✅ Checklist

  • I have tested this code locally with pnpm test:pr.
  • I have followed the steps in the Contributing guide.

🚀 Release Impact

  • This change affects published code, and I have generated a changeset.
  • This change is docs/CI/dev-only (no release).

Summary by CodeRabbit

  • Bug Fixes

    • Fixed string-collation handling so locale and locale options are only included when applicable, preventing unnecessary undefined values and clarifying text comparison/sorting configs.
  • Tests

    • Added tests verifying conditional inclusion of locale fields and auto-index de-duplication/usage behavior under various collation and indexing scenarios.

Review Change Stack

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 25, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: a0464233-e973-45d0-87ad-69fcdce47c76

📥 Commits

Reviewing files that changed from the base of the PR and between c94e780 and ef25208.

📒 Files selected for processing (2)
  • packages/db/src/collection/index.ts
  • packages/db/tests/collection-auto-index.test.ts

📝 Walkthrough

Walkthrough

Fixed buildCompareOptionsFromConfig to avoid spreading undefined locale and localeOptions. Uses conditional object spreads when stringSort === 'locale'. Added tests covering four compareOptions scenarios and an auto-index reuse test; added changeset for a patch release.

Changes

String Collation Undefined Properties Fix

Layer / File(s) Summary
Fix compareOptions to omit undefined locale properties
packages/db/src/collection/index.ts, .changeset/fix-compare-options-undefined-keys.md
buildCompareOptionsFromConfig computes stringSortEffective/localeMode and conditionally spreads locale and localeOptions only when stringSort === 'locale' and values are defined; changeset documents the patch fix.
Test compareOptions handling for defaultStringCollation configurations
packages/db/tests/collection-auto-index.test.ts
Four tests validate compareOptions omits locale/localeOptions when appropriate, includes them when explicitly provided with stringSort: 'locale', and sets stringSort: 'locale' if locale fields are provided without stringSort.
Verify auto-index reuse with fixed compareOptions
packages/db/tests/collection-auto-index.test.ts
Test confirms auto-index de-duplication and that subsequent queries use the auto-created index rather than a full scan when autoIndex: 'eager' and default collation uses locale sorting.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

A rabbit hops with glee today,
No undefined spreads clutter the way!
Collation fields now tidy and neat,
Indexes reused — queries complete. 🐰✨

🚥 Pre-merge checks | ✅ 4 | ❌ 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 (4 passed)
Check name Status Explanation
Title check ✅ Passed The title 'fix(db): avoid undefined enumerable keys in compare options' clearly and specifically summarizes the main change—preventing undefined enumerable properties in compare options.
Description check ✅ Passed The PR description includes the required Changes section explaining the fix, a completed Checklist with local testing confirmation, and Release Impact section indicating a changeset was generated.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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

✨ 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 and usage tips.

Copy link
Copy Markdown
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

🧹 Nitpick comments (1)
packages/db/tests/collection-auto-index.test.ts (1)

967-1011: ⚡ Quick win

Add a test for locale/localeOptions when stringSort is omitted.

Current cases miss the defaulted path where defaultStringCollation includes locale but not stringSort. That case should still include locale fields because stringSort defaults to locale.

✅ Suggested test addition
+  it(`should include locale fields when stringSort is omitted but locale values are provided`, () => {
+    const collection = createCollection<TestItem, string>({
+      getKey: (item) => item.id,
+      defaultStringCollation: {
+        locale: `en-US`,
+        localeOptions: { sensitivity: `base` },
+      },
+      startSync: true,
+      sync: {
+        sync: ({ begin, commit, markReady }) => {
+          begin()
+          commit()
+          markReady()
+        },
+      },
+    })
+
+    const opts = collection.compareOptions
+    expect(opts.stringSort).toBe(`locale`)
+    expect(opts.locale).toBe(`en-US`)
+    expect(opts.localeOptions).toEqual({ sensitivity: `base` })
+  })

As per coding guidelines, "Always add unit tests that reproduce a bug before fixing it to ensure the bug is fixed and prevent regression."

🤖 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/collection-auto-index.test.ts` around lines 967 - 1011, Add
a new unit test in collection-auto-index.test.ts that constructs a collection
via createCollection<TestItem, string> where defaultStringCollation provides
locale and localeOptions but omits stringSort; assert that
collection.compareOptions.stringSort equals "locale" (defaulted), and that
compareOptions includes the locale and localeOptions keys with the expected
values—use the same sync stub pattern as the other tests and reference
createCollection, defaultStringCollation, and compareOptions to locate where to
add the test.
🤖 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 `@packages/db/src/collection/index.ts`:
- Around line 999-1003: Compute the effective stringSort first and derive
localeMode from it instead of from options.stringSort; e.g., set a local
variable like stringSortEffective = options.stringSort ?? 'locale', then set
localeMode = stringSortEffective === 'locale' and return stringSort:
stringSortEffective while conditionally including locale and localeOptions based
on that localeMode (use the existing identifiers localeMode, options.locale,
options.localeOptions, and the returned stringSort).

---

Nitpick comments:
In `@packages/db/tests/collection-auto-index.test.ts`:
- Around line 967-1011: Add a new unit test in collection-auto-index.test.ts
that constructs a collection via createCollection<TestItem, string> where
defaultStringCollation provides locale and localeOptions but omits stringSort;
assert that collection.compareOptions.stringSort equals "locale" (defaulted),
and that compareOptions includes the locale and localeOptions keys with the
expected values—use the same sync stub pattern as the other tests and reference
createCollection, defaultStringCollation, and compareOptions to locate where to
add the test.
🪄 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

Run ID: dc1c5b52-815d-43f3-bc99-eee4bc6c2fed

📥 Commits

Reviewing files that changed from the base of the PR and between be656be and c94e780.

📒 Files selected for processing (3)
  • .changeset/fix-compare-options-undefined-keys.md
  • packages/db/src/collection/index.ts
  • packages/db/tests/collection-auto-index.test.ts

Comment thread packages/db/src/collection/index.ts Outdated
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