Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/value-class-equality.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@tanstack/db': minor
---

Compare instances of value classes, classes whose instances define `toJSON()` such as the `surrealdb` SDK's `RecordId`, by their serialized value instead of by reference. `eq`, `inArray`, join conditions, `groupBy`, indexes and ordering now match a distinct instance with an equal `toJSON()` result, so filtering or joining on record IDs works in any table. Query identity follows the same relation: equal captures are one query, so `useLiveQuery` needs no `queryKey` for them, and `getStableValueHash` (and therefore a `queryKey`) accepts such instances instead of throwing `UnhashableQueryIRError`. A value class instance never equals a plain value equal to its serialization. Dates, Temporal values, binary data, Maps and Sets (including subclasses that define `toJSON()`) keep their own rules, and plain objects, arrays and classes without `toJSON()` still compare by reference. Range predicates (`gt`, `gte`, `lt`, `lte`) order a value class by the same serialized value as `orderBy`, rather than by `valueOf()`.
19 changes: 19 additions & 0 deletions docs/contributing/oracle-coverage.md
Original file line number Diff line number Diff line change
Expand Up @@ -2283,6 +2283,25 @@ The deep-equality and Collection change-event history owners check a Duration
field replacement and its subscriber mirror. These fixed histories do not
establish arbitrary multirow Duration updates or live-query publication.

The [value class equality oracle](https://github.com/TanStack/db/blob/main/packages/db/tests/query/serialized-value-equality-oracle.property.test.ts)
(`serialized-value.query-equality`, issue #2459) owns query equality for class
instances with `toJSON()`. An independent model compares record references by
their table and ID fields. Generated histories of up to four source rows, three
join rows and three synced updates, with no index, a BasicIndex or a
BTreeIndex, compare scans before and after indexing, an ordered read (equal
values in one run), a live-query `eq` filter, range filters against a record
probe, an inner join, query identity, demand keys and `getStableValueHash`,
including an unequal record and a nested query key. Every row and probe is a
fresh instance with its own `valueOf()`,
and a constructed history replaces an indexed group's first instance with an
equal one. Rows and join rows also hold Map, Set and ArrayBuffer subclasses
whose `toJSON()` spells a record reference; they keep their built-in rule and
never match a record probe or join row, and a constructed history places one
among equal records. Plain records and arrays hold a throwing `toJSON`
accessor that must not be read. It does not cover `inArray` (fixed tests in
`ir-stable-identity.test.ts`), on-demand or persisted sources, exact-output
identity, which keeps reference semantics, or throwing `toJSON()` methods.

The
[Temporal index order tests](https://github.com/TanStack/db/blob/main/packages/db/tests/temporal-index-order.test.ts)
(fixed tests; no oracle owner (tracked in #2264)) covers ZonedDateTime instant
Expand Down
23 changes: 23 additions & 0 deletions docs/guides/live-queries.md
Original file line number Diff line number Diff line change
Expand Up @@ -884,6 +884,29 @@ Comparisons follow SQL/PostgreSQL conventions rather than raw JavaScript:
- **`null` / `undefined` use three-valued logic.** Any comparison involving `null` or `undefined` evaluates to `UNKNOWN`, so the row is not matched. For example `eq(user.score, null)` matches nothing — use a dedicated null check (e.g. `isUndefined`) to match missing values.
- **`NaN` follows PostgreSQL float semantics.** `NaN` is treated as equal to itself and greater than every other (non-null) value. So `eq(row.value, NaN)` matches `NaN` rows, `gt(row.value, x)` includes `NaN`, and ordering by such a field places `NaN` last. (Invalid `Date` values, whose timestamp is `NaN`, behave the same way.) This differs from JavaScript, where `NaN === NaN` is `false`, and matches how PostgreSQL orders and indexes floating-point values.

#### Value classes

A value class is a class whose instances define a `toJSON()` method, such as the `RecordId` of the `surrealdb` SDK or a decimal type. Queries compare its instances by their serialized value rather than by reference, so a distinct instance with the same `toJSON()` result matches:

```tsx
// userId and user.id are both RecordId instances, not the same object
const { data: user } = useLiveQuery({
query: (q) =>
q
.from({ user: usersCollection })
.where(({ user }) => eq(user.id, userId))
.findOne(),
})
```

This applies to `eq`, `inArray`, join conditions, `groupBy`, indexes and ordering, and to query identity: two captures with equal `toJSON()` results are the same query, so the hook needs no `queryKey`, and a `queryKey` may contain value class instances.

- A value class instance never equals a plain value, even one equal to its serialization: `eq(user.id, 'user:abc')` does not match a `RecordId` that serializes to `'user:abc'`.
- Instances of two classes that serialize to the same value are equal.
- Ordering and range predicates (`gt`, `gte`, `lt`, `lte`) use a value class's serialized value, never `valueOf()`. A primitive sorts before a value class and any other object after it.
- Built-in values keep their own rules: a `Date` compares by its timestamp, binary data by its bytes, and Temporal values by their own rules. Plain objects, arrays, and class instances without `toJSON()` compare by reference. A `Map`, `Set` or `ArrayBuffer` keeps its built-in rule even in a subclass that defines `toJSON()`, so it is not a value class.
- Treat value class instances as immutable while they are in a query or a row.

## Select

Use `select` to specify which fields to include in your results and transform your data. Without `select`, you get the full schema.
Expand Down
2 changes: 1 addition & 1 deletion packages/db/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
"test": "vitest --run",
"test:dist": "vitest run --config vitest.dist.config.ts",
"test:facade-retention": "node --expose-gc --import tsx tests/facade-retention.probe.ts",
"test:oracles": "vitest --run --coverage.enabled=false tests/oracle-campaign-units.test.ts tests/reverse-index-oracle.property.test.ts tests/query/compiler/in-evaluator-oracle.property.test.ts tests/query/compiler/group-by-pipeline-oracle.test.ts tests/cleanup-queue-oracle.property.test.ts tests/comparison-oracle.property.test.ts tests/duration-query-equality-oracle.test.ts tests/cursor-oracle.property.test.ts tests/index-update-oracle.property.test.ts tests/utils-oracle.property.test.ts tests/change-event-history-oracle.test.ts tests/index-suggestion-oracle.test.ts tests/btree-map-oracle.test.ts tests/paced-mutations-oracle.test.ts tests/db-client-hydration-authority-oracle.test.ts tests/local-storage-order-oracle.test.ts tests/local-storage-write-order-oracle.test.ts tests/local-storage-peers-oracle.test.ts tests/local-storage-value-fidelity-oracle.property.test.ts tests/collection-cleanup-restart-oracle.test.ts tests/collection-gc-transaction-oracle.property.test.ts tests/collection-gc-retention-oracle.property.test.ts tests/collection-gc-mutation-oracle.property.test.ts tests/effect-disposal-oracle.test.ts tests/optimistic-transaction-oracle.property.test.ts tests/transaction-ownership-oracle.property.test.ts tests/optimistic-history-oracle.property.test.ts tests/optimistic-history-publication-oracle.test.ts tests/optimistic-history-outcomes-oracle.test.ts tests/collection-metadata-publication-oracle.property.test.ts tests/collection-index-value-oracle.test.ts tests/collection-state-retention-oracle.property.test.ts tests/collection-subscription-lifecycle-history-oracle.property.test.ts tests/collection-subscription-lifecycle-oracle.test.ts tests/collection-subscription-reentrancy-oracle.test.ts tests/collection-subscription-lifecycle-publication-oracle.property.test.ts tests/collection-subscription-replay-oracle.property.test.ts tests/d2-source-reconciliation-oracle.property.test.ts tests/live-query-cache-options-oracle.test.ts tests/mutation-confirmation-calibration.test.ts tests/mutation-handler-types-oracle.test.ts tests/live-query-observer-history-oracle.property.test.ts tests/live-query-observer-hydration-oracle.property.test.ts tests/live-query-observer-snapshot-oracle.property.test.ts tests/query/cold-join-reconciliation-oracle.test.ts tests/query/identity-output-shape-oracle.test.ts tests/query/optimizer-semantics-oracle.test.ts tests/query/index-path-collision-oracle.test.ts tests/query/custom-index-order-selection-oracle.test.ts tests/query/mixed-index-order-oracle.test.ts tests/query/includes-collection-oracle.property.test.ts tests/query/includes-functional-projection-oracle.test.ts tests/query/includes-functional-input-boundary.test.ts tests/query/public-container-copy-oracle.test.ts tests/query/includes-context-transport-oracle.test.ts tests/query/includes-cross-formulation-oracle.property.test.ts tests/query/includes-optimistic-oracle.property.test.ts tests/query/includes-oracle.property.test.ts tests/query/includes-alias-shadowing-oracle.test.ts tests/query/includes-outer-join-route-work-oracle.test.ts tests/query/includes-publication-oracle.test.ts tests/query/includes-query-shape-oracle.test.ts tests/query/subquery-user-value-oracle.test.ts tests/query/includes-temporal-oracle.test.ts tests/query/includes-work-counter-oracle.test.ts tests/query/load-subset-oracle.property.test.ts tests/query/load-subset-replay-refinement-oracle.test.ts tests/query/load-subset-source-readiness-refinement-oracle.test.ts tests/query/load-subset-transaction-refinement-oracle.test.ts tests/query/ordered-source-loader-state-oracle.test.ts tests/query/ordered-demand-retirement.test.ts tests/query/ordered-default-work.test.ts tests/query/ordered-lifecycle-oracle.property.test.ts tests/query/ordered-work-oracle.property.test.ts tests/query/pagination-oracle.property.test.ts tests/query/includes-space-oracle.test.ts tests/query/virtual-row-fields-oracle.test.ts tests/query/virtual-row-fields-input-oracle.test.ts tests/query/virtual-row-fields-effect-oracle.test.ts tests/query/virtual-row-fields-types-oracle.test.ts tests/query/where-predicate-publication-oracle.property.test.ts tests/query/join-result-key-oracle.property.test.ts tests/query/pooled-live-query-oracle.property.test.ts tests/live-query-deferred-acquisition-oracle.test.ts tests/flat-change-tracking-oracle.property.test.ts tests/truncate-readiness-oracle.test.ts tests/proxy-detachment-contract-oracle.test.ts tests/production-error-messages-oracle.test.ts tests/query/bucket-facade-rollback-oracle.property.test.ts tests/query/aggregate-select-oracle.property.test.ts tests/query/load-subset-joint-replay-oracle.property.test.ts",
"test:oracles": "vitest --run --coverage.enabled=false tests/oracle-campaign-units.test.ts tests/reverse-index-oracle.property.test.ts tests/query/compiler/in-evaluator-oracle.property.test.ts tests/query/compiler/group-by-pipeline-oracle.test.ts tests/cleanup-queue-oracle.property.test.ts tests/comparison-oracle.property.test.ts tests/duration-query-equality-oracle.test.ts tests/cursor-oracle.property.test.ts tests/index-update-oracle.property.test.ts tests/utils-oracle.property.test.ts tests/change-event-history-oracle.test.ts tests/index-suggestion-oracle.test.ts tests/btree-map-oracle.test.ts tests/paced-mutations-oracle.test.ts tests/db-client-hydration-authority-oracle.test.ts tests/local-storage-order-oracle.test.ts tests/local-storage-write-order-oracle.test.ts tests/local-storage-peers-oracle.test.ts tests/local-storage-value-fidelity-oracle.property.test.ts tests/collection-cleanup-restart-oracle.test.ts tests/collection-gc-transaction-oracle.property.test.ts tests/collection-gc-retention-oracle.property.test.ts tests/collection-gc-mutation-oracle.property.test.ts tests/effect-disposal-oracle.test.ts tests/optimistic-transaction-oracle.property.test.ts tests/transaction-ownership-oracle.property.test.ts tests/optimistic-history-oracle.property.test.ts tests/optimistic-history-publication-oracle.test.ts tests/optimistic-history-outcomes-oracle.test.ts tests/collection-metadata-publication-oracle.property.test.ts tests/collection-index-value-oracle.test.ts tests/collection-state-retention-oracle.property.test.ts tests/collection-subscription-lifecycle-history-oracle.property.test.ts tests/collection-subscription-lifecycle-oracle.test.ts tests/collection-subscription-reentrancy-oracle.test.ts tests/collection-subscription-lifecycle-publication-oracle.property.test.ts tests/collection-subscription-replay-oracle.property.test.ts tests/d2-source-reconciliation-oracle.property.test.ts tests/live-query-cache-options-oracle.test.ts tests/mutation-confirmation-calibration.test.ts tests/mutation-handler-types-oracle.test.ts tests/live-query-observer-history-oracle.property.test.ts tests/live-query-observer-hydration-oracle.property.test.ts tests/live-query-observer-snapshot-oracle.property.test.ts tests/query/cold-join-reconciliation-oracle.test.ts tests/query/identity-output-shape-oracle.test.ts tests/query/optimizer-semantics-oracle.test.ts tests/query/index-path-collision-oracle.test.ts tests/query/custom-index-order-selection-oracle.test.ts tests/query/mixed-index-order-oracle.test.ts tests/query/includes-collection-oracle.property.test.ts tests/query/includes-functional-projection-oracle.test.ts tests/query/includes-functional-input-boundary.test.ts tests/query/public-container-copy-oracle.test.ts tests/query/includes-context-transport-oracle.test.ts tests/query/includes-cross-formulation-oracle.property.test.ts tests/query/includes-optimistic-oracle.property.test.ts tests/query/includes-oracle.property.test.ts tests/query/includes-alias-shadowing-oracle.test.ts tests/query/includes-outer-join-route-work-oracle.test.ts tests/query/includes-publication-oracle.test.ts tests/query/includes-query-shape-oracle.test.ts tests/query/subquery-user-value-oracle.test.ts tests/query/includes-temporal-oracle.test.ts tests/query/includes-work-counter-oracle.test.ts tests/query/load-subset-oracle.property.test.ts tests/query/load-subset-replay-refinement-oracle.test.ts tests/query/load-subset-source-readiness-refinement-oracle.test.ts tests/query/load-subset-transaction-refinement-oracle.test.ts tests/query/ordered-source-loader-state-oracle.test.ts tests/query/ordered-demand-retirement.test.ts tests/query/ordered-default-work.test.ts tests/query/ordered-lifecycle-oracle.property.test.ts tests/query/ordered-work-oracle.property.test.ts tests/query/pagination-oracle.property.test.ts tests/query/includes-space-oracle.test.ts tests/query/virtual-row-fields-oracle.test.ts tests/query/virtual-row-fields-input-oracle.test.ts tests/query/virtual-row-fields-effect-oracle.test.ts tests/query/virtual-row-fields-types-oracle.test.ts tests/query/where-predicate-publication-oracle.property.test.ts tests/query/join-result-key-oracle.property.test.ts tests/query/pooled-live-query-oracle.property.test.ts tests/live-query-deferred-acquisition-oracle.test.ts tests/flat-change-tracking-oracle.property.test.ts tests/truncate-readiness-oracle.test.ts tests/proxy-detachment-contract-oracle.test.ts tests/production-error-messages-oracle.test.ts tests/query/bucket-facade-rollback-oracle.property.test.ts tests/query/aggregate-select-oracle.property.test.ts tests/query/load-subset-joint-replay-oracle.property.test.ts tests/query/serialized-value-equality-oracle.property.test.ts",
"bench:nested-includes": "vitest bench tests/query/includes-performance.bench.ts --run --coverage.enabled=false --reporter=verbose",
"test:indexed-db:package": "pnpm --filter @tanstack/db... build && vitest run --config vitest.indexed-db.package.config.ts",
"test:collection-gc:browser": "playwright test --config playwright.collection-gc.config.ts",
Expand Down
9 changes: 8 additions & 1 deletion packages/db/src/query/ir-stable-identity.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { isPlainObject } from '../utils/type-guards.js'
import { UnhashableQueryIRError } from '../errors.js'
import { normalizeValue } from '../utils/comparison.js'
import { normalizeValue, serializedClassValue } from '../utils/comparison.js'
import { isRefProxy, toExpression } from './builder/ref-proxy.js'
import { getQueryIR } from './builder/query-ir.js'
import {
Expand Down Expand Up @@ -1036,6 +1036,13 @@ function canonicalizeRuntimeValue(
return canonicalizeObject(value, path, seen)
}

// A value class hashes by its serialized value. The tag keeps it apart from
// a plain string or record equal to that serialization.
const serialized = serializedClassValue(value)
if (serialized !== undefined) {
return [`toJSON`, serialized]
}

throw new UnhashableQueryIRError(path, `non-plain object value`)
}

Expand Down
Loading