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/trusted-provider-collation.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@tanstack/db': patch
---

Add `trustProviderOrder` to custom string collations, so an on-demand query can page through a backend that orders strings with the same comparator. `gt`, `gte`, `lt` and `lte` accept an optional collation for string cursors.
2 changes: 1 addition & 1 deletion docs/contributing/oracle-coverage.md

Large diffs are not rendered by default.

8 changes: 8 additions & 0 deletions docs/guides/live-queries.md
Original file line number Diff line number Diff line change
Expand Up @@ -2098,6 +2098,14 @@ const timeline = createLiveQueryCollection((q) =>
)
```

A custom string collation (`stringSort: 'custom'` with a `compare` function)
makes an on-demand query load its whole filtered source and sort locally,
because the backend's order is unknown. If your backend orders and compares
strings with exactly that comparator, set `trustProviderOrder: true` on the
collation. Ordered queries then pass `orderBy`, `limit` and string cursors to
`loadSubset` and page through the backend. TanStack DB does not verify this, and
a backend with a different order returns the wrong pages.

### Ordering by SELECT Fields

When you use `select()` with aggregates or computed values, you can order by those fields using the `$selected` namespace:
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/query/trusted-provider-collation-oracle.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",
"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
6 changes: 5 additions & 1 deletion packages/db/src/collection/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1383,7 +1383,11 @@ function buildCompareOptionsFromConfig(
}

if (options.stringSort === `custom`) {
return { stringSort: `custom`, compare: options.compare }
return {
stringSort: `custom`,
compare: options.compare,
...(options.trustProviderOrder && { trustProviderOrder: true }),
}
}

return {
Expand Down
65 changes: 53 additions & 12 deletions packages/db/src/query/builder/functions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { registerWrapper } from './wrapper-identity.js'
import type { BasicExpression } from '../ir'
import type { IncludesRuntime } from '../live/includes-runtime.js'
import type { RefProxy } from './ref-proxy.js'
import type { CustomStringCollation } from '../../types.js'
import type {
ContainsAggregate,
Context,
Expand Down Expand Up @@ -207,14 +208,24 @@ export function gt<L extends ExpressionLike, R extends ExpressionLike>(
export function gt<T>(
left: ComparisonOperand<T>,
right: ComparisonOperand<T>,
collation?: CustomStringCollation,
): BasicExpression<boolean>
export function gt<T extends string | number>(
left: ComparisonOperandPrimitive<T>,
right: ComparisonOperandPrimitive<T>,
collation?: CustomStringCollation,
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
): BasicExpression<boolean>
export function gt<T>(left: Aggregate<T>, right: any): BasicExpression<boolean>
export function gt(left: any, right: any): BasicExpression<boolean> {
return new Func(`gt`, [toExpression(left), toExpression(right)])
export function gt<T>(
left: Aggregate<T>,
right: any,
collation?: CustomStringCollation,
): BasicExpression<boolean>
export function gt(
left: any,
right: any,
collation?: CustomStringCollation,
): BasicExpression<boolean> {
return new Func(`gt`, [toExpression(left), toExpression(right)], collation)
}

export function gte<L extends ExpressionLike, R extends ExpressionLike>(
Expand All @@ -224,14 +235,24 @@ export function gte<L extends ExpressionLike, R extends ExpressionLike>(
export function gte<T>(
left: ComparisonOperand<T>,
right: ComparisonOperand<T>,
collation?: CustomStringCollation,
): BasicExpression<boolean>
export function gte<T extends string | number>(
left: ComparisonOperandPrimitive<T>,
right: ComparisonOperandPrimitive<T>,
collation?: CustomStringCollation,
): BasicExpression<boolean>
export function gte<T>(left: Aggregate<T>, right: any): BasicExpression<boolean>
export function gte(left: any, right: any): BasicExpression<boolean> {
return new Func(`gte`, [toExpression(left), toExpression(right)])
export function gte<T>(
left: Aggregate<T>,
right: any,
collation?: CustomStringCollation,
): BasicExpression<boolean>
export function gte(
left: any,
right: any,
collation?: CustomStringCollation,
): BasicExpression<boolean> {
return new Func(`gte`, [toExpression(left), toExpression(right)], collation)
}

export function lt<L extends ExpressionLike, R extends ExpressionLike>(
Expand All @@ -241,14 +262,24 @@ export function lt<L extends ExpressionLike, R extends ExpressionLike>(
export function lt<T>(
left: ComparisonOperand<T>,
right: ComparisonOperand<T>,
collation?: CustomStringCollation,
): BasicExpression<boolean>
export function lt<T extends string | number>(
left: ComparisonOperandPrimitive<T>,
right: ComparisonOperandPrimitive<T>,
collation?: CustomStringCollation,
): BasicExpression<boolean>
export function lt<T>(left: Aggregate<T>, right: any): BasicExpression<boolean>
export function lt(left: any, right: any): BasicExpression<boolean> {
return new Func(`lt`, [toExpression(left), toExpression(right)])
export function lt<T>(
left: Aggregate<T>,
right: any,
collation?: CustomStringCollation,
): BasicExpression<boolean>
export function lt(
left: any,
right: any,
collation?: CustomStringCollation,
): BasicExpression<boolean> {
return new Func(`lt`, [toExpression(left), toExpression(right)], collation)
}

export function lte<L extends ExpressionLike, R extends ExpressionLike>(
Expand All @@ -258,14 +289,24 @@ export function lte<L extends ExpressionLike, R extends ExpressionLike>(
export function lte<T>(
left: ComparisonOperand<T>,
right: ComparisonOperand<T>,
collation?: CustomStringCollation,
): BasicExpression<boolean>
export function lte<T extends string | number>(
left: ComparisonOperandPrimitive<T>,
right: ComparisonOperandPrimitive<T>,
collation?: CustomStringCollation,
): BasicExpression<boolean>
export function lte<T>(left: Aggregate<T>, right: any): BasicExpression<boolean>
export function lte(left: any, right: any): BasicExpression<boolean> {
return new Func(`lte`, [toExpression(left), toExpression(right)])
export function lte<T>(
left: Aggregate<T>,
right: any,
collation?: CustomStringCollation,
): BasicExpression<boolean>
export function lte(
left: any,
right: any,
collation?: CustomStringCollation,
): BasicExpression<boolean> {
return new Func(`lte`, [toExpression(left), toExpression(right)], collation)
}

// Overloads for and() - support 2 or more arguments
Expand Down
3 changes: 3 additions & 0 deletions packages/db/src/query/builder/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -678,6 +678,9 @@ export class BaseQueryBuilder<TContext extends Context = Context> {
? {
stringSort: `custom`,
compare: options.compare,
...(options.trustProviderOrder && {
trustProviderOrder: true,
}),
}
: {
stringSort: options.stringSort,
Expand Down
15 changes: 11 additions & 4 deletions packages/db/src/query/compiler/evaluators.ts
Original file line number Diff line number Diff line change
Expand Up @@ -278,6 +278,13 @@ function compileFunction(func: Func, isSingleRow: boolean): (data: any) => any {
const compiledArgs = func.args.map((arg) =>
compileExpressionInternal(arg, isSingleRow),
)
const collation = func.collation
const order = collation
? (a: any, b: any) =>
typeof a === `string` && typeof b === `string`
? collation.compare(a, b)
: compareValues(a, b)
: compareValues

switch (func.name) {
case `array`:
Expand Down Expand Up @@ -322,7 +329,7 @@ function compileFunction(func: Func, isSingleRow: boolean): (data: any) => any {
if (isUnorderable(a) || isUnorderable(b)) {
return isUnorderable(a) && !isUnorderable(b)
}
return compareValues(a, b) > 0
return order(a, b) > 0
}
}
case `gte`: {
Expand All @@ -338,7 +345,7 @@ function compileFunction(func: Func, isSingleRow: boolean): (data: any) => any {
if (isUnorderable(a) || isUnorderable(b)) {
return isUnorderable(a)
}
return compareValues(a, b) >= 0
return order(a, b) >= 0
}
}
case `lt`: {
Expand All @@ -354,7 +361,7 @@ function compileFunction(func: Func, isSingleRow: boolean): (data: any) => any {
if (isUnorderable(a) || isUnorderable(b)) {
return isUnorderable(b) && !isUnorderable(a)
}
return compareValues(a, b) < 0
return order(a, b) < 0
}
}
case `lte`: {
Expand All @@ -370,7 +377,7 @@ function compileFunction(func: Func, isSingleRow: boolean): (data: any) => any {
if (isUnorderable(a) || isUnorderable(b)) {
return isUnorderable(b)
}
return compareValues(a, b) <= 0
return order(a, b) <= 0
}
}

Expand Down
2 changes: 1 addition & 1 deletion packages/db/src/query/compiler/expressions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ export function normalizeExpressionPaths(
)
args.push(convertedArg)
}
return new Func(whereClause.name, args)
return new Func(whereClause.name, args, whereClause.collation)
}
}

Expand Down
8 changes: 6 additions & 2 deletions packages/db/src/query/compiler/group-by.ts
Original file line number Diff line number Diff line change
Expand Up @@ -608,6 +608,9 @@ function expressionsEqual(expr1: any, expr2: any): boolean {
case `func`:
return (
expr1.name === expr2.name &&
expr1.collation?.compare === expr2.collation?.compare &&
expr1.collation?.trustProviderOrder ===
expr2.collation?.trustProviderOrder &&
expr1.args?.length === expr2.args?.length &&
(expr1.args || []).every((arg: any, i: number) =>
expressionsEqual(arg, expr2.args[i]),
Expand Down Expand Up @@ -730,7 +733,7 @@ export function replaceAggregatesByRefs(
(arg: BasicExpression | Aggregate) =>
replaceAggregatesByRefs(arg, selectClause),
)
return new Func(funcExpr.name, transformedArgs)
return new Func(funcExpr.name, transformedArgs, funcExpr.collation)
}

case `ref`:
Expand Down Expand Up @@ -819,7 +822,7 @@ function extractAndReplaceAggregates(
return result.transformed as BasicExpression
})
return {
transformed: new Func(expr.name, newArgs),
transformed: new Func(expr.name, newArgs, expr.collation),
extracted: allExtracted,
}
}
Expand Down Expand Up @@ -953,6 +956,7 @@ function replaceGroupByRefsInExpression(
expr.args.map((arg) =>
replaceGroupByRefsInExpression(arg, groupByClause, groupKeyRefs),
),
expr.collation,
)
}

Expand Down
Loading