@tanstack/db 0.5.32 → 0.5.33

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/dist/cjs/index.cjs +2 -0
  2. package/dist/cjs/index.cjs.map +1 -1
  3. package/dist/cjs/index.d.cts +1 -0
  4. package/dist/cjs/query/effect.cjs +602 -0
  5. package/dist/cjs/query/effect.cjs.map +1 -0
  6. package/dist/cjs/query/effect.d.cts +94 -0
  7. package/dist/cjs/query/live/collection-config-builder.cjs +5 -74
  8. package/dist/cjs/query/live/collection-config-builder.cjs.map +1 -1
  9. package/dist/cjs/query/live/collection-subscriber.cjs +33 -100
  10. package/dist/cjs/query/live/collection-subscriber.cjs.map +1 -1
  11. package/dist/cjs/query/live/collection-subscriber.d.cts +0 -1
  12. package/dist/cjs/query/live/utils.cjs +179 -0
  13. package/dist/cjs/query/live/utils.cjs.map +1 -0
  14. package/dist/cjs/query/live/utils.d.cts +109 -0
  15. package/dist/esm/index.d.ts +1 -0
  16. package/dist/esm/index.js +2 -0
  17. package/dist/esm/index.js.map +1 -1
  18. package/dist/esm/query/effect.d.ts +94 -0
  19. package/dist/esm/query/effect.js +602 -0
  20. package/dist/esm/query/effect.js.map +1 -0
  21. package/dist/esm/query/live/collection-config-builder.js +1 -70
  22. package/dist/esm/query/live/collection-config-builder.js.map +1 -1
  23. package/dist/esm/query/live/collection-subscriber.d.ts +0 -1
  24. package/dist/esm/query/live/collection-subscriber.js +31 -98
  25. package/dist/esm/query/live/collection-subscriber.js.map +1 -1
  26. package/dist/esm/query/live/utils.d.ts +109 -0
  27. package/dist/esm/query/live/utils.js +179 -0
  28. package/dist/esm/query/live/utils.js.map +1 -0
  29. package/package.json +1 -1
  30. package/src/index.ts +11 -0
  31. package/src/query/effect.ts +1119 -0
  32. package/src/query/live/collection-config-builder.ts +6 -132
  33. package/src/query/live/collection-subscriber.ts +40 -156
  34. package/src/query/live/utils.ts +356 -0
@@ -1,6 +1,5 @@
1
1
  import { D2, output } from '@tanstack/db-ivm'
2
2
  import { compileQuery } from '../compiler/index.js'
3
- import { buildQuery, getQueryIR } from '../builder/index.js'
4
3
  import {
5
4
  MissingAliasInputsError,
6
5
  SetWindowRequiresOrderByError,
@@ -10,6 +9,12 @@ import { getActiveTransaction } from '../../transactions.js'
10
9
  import { CollectionSubscriber } from './collection-subscriber.js'
11
10
  import { getCollectionBuilder } from './collection-registry.js'
12
11
  import { LIVE_QUERY_INTERNAL } from './internal.js'
12
+ import {
13
+ buildQueryFromConfig,
14
+ extractCollectionAliases,
15
+ extractCollectionFromSource,
16
+ extractCollectionsFromQuery,
17
+ } from './utils.js'
13
18
  import type { LiveQueryInternalUtils } from './internal.js'
14
19
  import type { WindowOptions } from '../compiler/index.js'
15
20
  import type { SchedulerContextId } from '../../scheduler.js'
@@ -984,16 +989,6 @@ export class CollectionConfigBuilder<
984
989
  }
985
990
  }
986
991
 
987
- function buildQueryFromConfig<TContext extends Context>(
988
- config: LiveQueryCollectionConfig<any, any>,
989
- ) {
990
- // Build the query using the provided query builder function or instance
991
- if (typeof config.query === `function`) {
992
- return buildQuery<TContext>(config.query)
993
- }
994
- return getQueryIR(config.query)
995
- }
996
-
997
992
  function createOrderByComparator<T extends object>(
998
993
  orderByIndices: WeakMap<object, string>,
999
994
  ) {
@@ -1018,127 +1013,6 @@ function createOrderByComparator<T extends object>(
1018
1013
  }
1019
1014
  }
1020
1015
 
1021
- /**
1022
- * Helper function to extract collections from a compiled query
1023
- * Traverses the query IR to find all collection references
1024
- * Maps collections by their ID (not alias) as expected by the compiler
1025
- */
1026
- function extractCollectionsFromQuery(
1027
- query: any,
1028
- ): Record<string, Collection<any, any, any>> {
1029
- const collections: Record<string, any> = {}
1030
-
1031
- // Helper function to recursively extract collections from a query or source
1032
- function extractFromSource(source: any) {
1033
- if (source.type === `collectionRef`) {
1034
- collections[source.collection.id] = source.collection
1035
- } else if (source.type === `queryRef`) {
1036
- // Recursively extract from subquery
1037
- extractFromQuery(source.query)
1038
- }
1039
- }
1040
-
1041
- // Helper function to recursively extract collections from a query
1042
- function extractFromQuery(q: any) {
1043
- // Extract from FROM clause
1044
- if (q.from) {
1045
- extractFromSource(q.from)
1046
- }
1047
-
1048
- // Extract from JOIN clauses
1049
- if (q.join && Array.isArray(q.join)) {
1050
- for (const joinClause of q.join) {
1051
- if (joinClause.from) {
1052
- extractFromSource(joinClause.from)
1053
- }
1054
- }
1055
- }
1056
- }
1057
-
1058
- // Start extraction from the root query
1059
- extractFromQuery(query)
1060
-
1061
- return collections
1062
- }
1063
-
1064
- /**
1065
- * Helper function to extract the collection that is referenced in the query's FROM clause.
1066
- * The FROM clause may refer directly to a collection or indirectly to a subquery.
1067
- */
1068
- function extractCollectionFromSource(query: any): Collection<any, any, any> {
1069
- const from = query.from
1070
-
1071
- if (from.type === `collectionRef`) {
1072
- return from.collection
1073
- } else if (from.type === `queryRef`) {
1074
- // Recursively extract from subquery
1075
- return extractCollectionFromSource(from.query)
1076
- }
1077
-
1078
- throw new Error(
1079
- `Failed to extract collection. Invalid FROM clause: ${JSON.stringify(query)}`,
1080
- )
1081
- }
1082
-
1083
- /**
1084
- * Extracts all aliases used for each collection across the entire query tree.
1085
- *
1086
- * Traverses the QueryIR recursively to build a map from collection ID to all aliases
1087
- * that reference that collection. This is essential for self-join support, where the
1088
- * same collection may be referenced multiple times with different aliases.
1089
- *
1090
- * For example, given a query like:
1091
- * ```ts
1092
- * q.from({ employee: employeesCollection })
1093
- * .join({ manager: employeesCollection }, ({ employee, manager }) =>
1094
- * eq(employee.managerId, manager.id)
1095
- * )
1096
- * ```
1097
- *
1098
- * This function would return:
1099
- * ```
1100
- * Map { "employees" => Set { "employee", "manager" } }
1101
- * ```
1102
- *
1103
- * @param query - The query IR to extract aliases from
1104
- * @returns A map from collection ID to the set of all aliases referencing that collection
1105
- */
1106
- function extractCollectionAliases(query: QueryIR): Map<string, Set<string>> {
1107
- const aliasesById = new Map<string, Set<string>>()
1108
-
1109
- function recordAlias(source: any) {
1110
- if (!source) return
1111
-
1112
- if (source.type === `collectionRef`) {
1113
- const { id } = source.collection
1114
- const existing = aliasesById.get(id)
1115
- if (existing) {
1116
- existing.add(source.alias)
1117
- } else {
1118
- aliasesById.set(id, new Set([source.alias]))
1119
- }
1120
- } else if (source.type === `queryRef`) {
1121
- traverse(source.query)
1122
- }
1123
- }
1124
-
1125
- function traverse(q?: QueryIR) {
1126
- if (!q) return
1127
-
1128
- recordAlias(q.from)
1129
-
1130
- if (q.join) {
1131
- for (const joinClause of q.join) {
1132
- recordAlias(joinClause.from)
1133
- }
1134
- }
1135
- }
1136
-
1137
- traverse(query)
1138
-
1139
- return aliasesById
1140
- }
1141
-
1142
1016
  function accumulateChanges<T>(
1143
1017
  acc: Map<unknown, Changes<T>>,
1144
1018
  [[key, tupleData], multiplicity]: [
@@ -1,9 +1,15 @@
1
- import { MultiSet, serializeValue } from '@tanstack/db-ivm'
2
1
  import {
3
2
  normalizeExpressionPaths,
4
3
  normalizeOrderByPaths,
5
4
  } from '../compiler/expressions.js'
6
- import type { MultiSetArray, RootStreamBuilder } from '@tanstack/db-ivm'
5
+ import {
6
+ computeOrderedLoadCursor,
7
+ computeSubscriptionOrderByHints,
8
+ filterDuplicateInserts,
9
+ sendChangesToInput,
10
+ splitUpdates,
11
+ trackBiggestSentValue,
12
+ } from './utils.js'
7
13
  import type { Collection } from '../../collection/index.js'
8
14
  import type {
9
15
  ChangeMessage,
@@ -147,25 +153,11 @@ export class CollectionSubscriber<
147
153
  changes: Iterable<ChangeMessage<any, string | number>>,
148
154
  callback?: () => boolean,
149
155
  ) {
150
- // Filter changes to prevent duplicate inserts to D2 pipeline.
151
- // This ensures D2 multiplicity stays at 1 for visible items, so deletes
152
- // properly reduce multiplicity to 0 (triggering DELETE output).
153
156
  const changesArray = Array.isArray(changes) ? changes : [...changes]
154
- const filteredChanges: Array<ChangeMessage<any, string | number>> = []
155
- for (const change of changesArray) {
156
- if (change.type === `insert`) {
157
- if (this.sentToD2Keys.has(change.key)) {
158
- // Skip duplicate insert - already sent to D2
159
- continue
160
- }
161
- this.sentToD2Keys.add(change.key)
162
- } else if (change.type === `delete`) {
163
- // Remove from tracking so future re-inserts are allowed
164
- this.sentToD2Keys.delete(change.key)
165
- }
166
- // Updates are handled as delete+insert by splitUpdates, so no special handling needed
167
- filteredChanges.push(change)
168
- }
157
+ const filteredChanges = filterDuplicateInserts(
158
+ changesArray,
159
+ this.sentToD2Keys,
160
+ )
169
161
 
170
162
  // currentSyncState and input are always defined when this method is called
171
163
  // (only called from active subscriptions during a sync session)
@@ -202,27 +194,10 @@ export class CollectionSubscriber<
202
194
  }
203
195
 
204
196
  // Get the query's orderBy and limit to pass to loadSubset.
205
- // Only include orderBy when it is scoped to this alias and uses simple refs,
206
- // to avoid leaking cross-collection paths into backend-specific compilers.
207
- const { orderBy, limit, offset } = this.collectionConfigBuilder.query
208
- const effectiveLimit =
209
- limit !== undefined && offset !== undefined ? limit + offset : limit
210
- const normalizedOrderBy = orderBy
211
- ? normalizeOrderByPaths(orderBy, this.alias)
212
- : undefined
213
- const canPassOrderBy =
214
- normalizedOrderBy?.every((clause) => {
215
- const exp = clause.expression
216
- if (exp.type !== `ref`) {
217
- return false
218
- }
219
- const path = exp.path
220
- return Array.isArray(path) && path.length === 1
221
- }) ?? false
222
- const orderByForSubscription = canPassOrderBy
223
- ? normalizedOrderBy
224
- : undefined
225
- const limitForSubscription = canPassOrderBy ? effectiveLimit : undefined
197
+ const hints = computeSubscriptionOrderByHints(
198
+ this.collectionConfigBuilder.query,
199
+ this.alias,
200
+ )
226
201
 
227
202
  // Track loading via the loadSubset promise directly.
228
203
  // requestSnapshot uses trackLoadSubsetPromise: false (needed for truncate handling),
@@ -241,8 +216,8 @@ export class CollectionSubscriber<
241
216
  ...(includeInitialState && { includeInitialState }),
242
217
  whereExpression,
243
218
  onStatusChange,
244
- orderBy: orderByForSubscription,
245
- limit: limitForSubscription,
219
+ orderBy: hints.orderBy,
220
+ limit: hints.limit,
246
221
  onLoadSubsetResult,
247
222
  })
248
223
 
@@ -415,52 +390,28 @@ export class CollectionSubscriber<
415
390
  if (!orderByInfo) {
416
391
  return
417
392
  }
418
- const { orderBy, valueExtractorForRawRow, offset } = orderByInfo
419
- const biggestSentRow = this.biggest
420
-
421
- // Extract all orderBy column values from the biggest sent row
422
- // For single-column: returns single value, for multi-column: returns array
423
- const extractedValues = biggestSentRow
424
- ? valueExtractorForRawRow(biggestSentRow)
425
- : undefined
426
-
427
- // Normalize to array format for minValues
428
- let minValues: Array<unknown> | undefined
429
- if (extractedValues !== undefined) {
430
- minValues = Array.isArray(extractedValues)
431
- ? extractedValues
432
- : [extractedValues]
433
- }
434
-
435
- const loadRequestKey = this.getLoadRequestKey({
436
- minValues,
437
- offset,
438
- limit: n,
439
- })
440
393
 
441
- // Skip if we already requested a load for this cursor+window.
442
- // This prevents infinite loops from cached data re-writes while still allowing
443
- // window moves (offset/limit changes) to trigger new requests.
444
- if (this.lastLoadRequestKey === loadRequestKey) {
445
- return
446
- }
394
+ const cursor = computeOrderedLoadCursor(
395
+ orderByInfo,
396
+ this.biggest,
397
+ this.lastLoadRequestKey,
398
+ this.alias,
399
+ n,
400
+ )
401
+ if (!cursor) return // Duplicate request — skip
447
402
 
448
- // Normalize the orderBy clauses such that the references are relative to the collection
449
- const normalizedOrderBy = normalizeOrderByPaths(orderBy, this.alias)
403
+ this.lastLoadRequestKey = cursor.loadRequestKey
450
404
 
451
405
  // Take the `n` items after the biggest sent value
452
- // Pass the current window offset to ensure proper deduplication
406
+ // Omit offset so requestLimitedSnapshot can advance based on
407
+ // the number of rows already loaded (supports offset-based backends).
453
408
  subscription.requestLimitedSnapshot({
454
- orderBy: normalizedOrderBy,
409
+ orderBy: cursor.normalizedOrderBy,
455
410
  limit: n,
456
- minValues,
457
- // Omit offset so requestLimitedSnapshot can advance the offset based on
458
- // the number of rows already loaded (supports offset-based backends).
411
+ minValues: cursor.minValues,
459
412
  trackLoadSubsetPromise: false,
460
413
  onLoadSubsetResult: this.orderedLoadSubsetResult,
461
414
  })
462
-
463
- this.lastLoadRequestKey = loadRequestKey
464
415
  }
465
416
 
466
417
  private getWhereClauseForAlias(): BasicExpression<boolean> | undefined {
@@ -487,24 +438,15 @@ export class CollectionSubscriber<
487
438
  changes: Array<ChangeMessage<any, string | number>>,
488
439
  comparator: (a: any, b: any) => number,
489
440
  ): void {
490
- for (const change of changes) {
491
- if (change.type === `delete`) {
492
- continue
493
- }
494
-
495
- const isNewKey = !this.sentToD2Keys.has(change.key)
496
-
497
- // Only track inserts/updates for cursor positioning, not deletes
498
- if (!this.biggest) {
499
- this.biggest = change.value
500
- this.lastLoadRequestKey = undefined
501
- } else if (comparator(this.biggest, change.value) < 0) {
502
- this.biggest = change.value
503
- this.lastLoadRequestKey = undefined
504
- } else if (isNewKey) {
505
- // New key with same orderBy value - allow another load if needed
506
- this.lastLoadRequestKey = undefined
507
- }
441
+ const result = trackBiggestSentValue(
442
+ changes,
443
+ this.biggest,
444
+ this.sentToD2Keys,
445
+ comparator,
446
+ )
447
+ this.biggest = result.biggest
448
+ if (result.shouldResetLoadKey) {
449
+ this.lastLoadRequestKey = undefined
508
450
  }
509
451
  }
510
452
 
@@ -525,62 +467,4 @@ export class CollectionSubscriber<
525
467
  promise,
526
468
  )
527
469
  }
528
-
529
- private getLoadRequestKey(options: {
530
- minValues: Array<unknown> | undefined
531
- offset: number
532
- limit: number
533
- }): string {
534
- return serializeValue({
535
- minValues: options.minValues ?? null,
536
- offset: options.offset,
537
- limit: options.limit,
538
- })
539
- }
540
- }
541
-
542
- /**
543
- * Helper function to send changes to a D2 input stream
544
- */
545
- function sendChangesToInput(
546
- input: RootStreamBuilder<unknown>,
547
- changes: Iterable<ChangeMessage>,
548
- getKey: (item: ChangeMessage[`value`]) => any,
549
- ): number {
550
- const multiSetArray: MultiSetArray<unknown> = []
551
- for (const change of changes) {
552
- const key = getKey(change.value)
553
- if (change.type === `insert`) {
554
- multiSetArray.push([[key, change.value], 1])
555
- } else if (change.type === `update`) {
556
- multiSetArray.push([[key, change.previousValue], -1])
557
- multiSetArray.push([[key, change.value], 1])
558
- } else {
559
- // change.type === `delete`
560
- multiSetArray.push([[key, change.value], -1])
561
- }
562
- }
563
-
564
- if (multiSetArray.length !== 0) {
565
- input.sendData(new MultiSet(multiSetArray))
566
- }
567
-
568
- return multiSetArray.length
569
- }
570
-
571
- /** Splits updates into a delete of the old value and an insert of the new value */
572
- function* splitUpdates<
573
- T extends object = Record<string, unknown>,
574
- TKey extends string | number = string | number,
575
- >(
576
- changes: Iterable<ChangeMessage<T, TKey>>,
577
- ): Generator<ChangeMessage<T, TKey>> {
578
- for (const change of changes) {
579
- if (change.type === `update`) {
580
- yield { type: `delete`, key: change.key, value: change.previousValue! }
581
- yield { type: `insert`, key: change.key, value: change.value }
582
- } else {
583
- yield change
584
- }
585
- }
586
470
  }