MCPcopy Create free account
hub / github.com/TanStack/db / drainNestedBuffers

Function drainNestedBuffers

packages/db/src/query/live/collection-config-builder.ts:1473–1548  ·  view source on GitHub ↗

* Drains shared buffers into per-entry states using the routing index. * Returns the set of parent correlation keys that had changes routed to them.

(state: IncludesOutputState)

Source from the content-addressed store, hash-verified

1471 * Returns the set of parent correlation keys that had changes routed to them.
1472 */
1473function drainNestedBuffers(state: IncludesOutputState): Set<unknown> {
1474 const dirtyCorrelationKeys = new Set<unknown>()
1475
1476 if (!state.nestedSetups) return dirtyCorrelationKeys
1477
1478 for (const setup of state.nestedSetups) {
1479 const toDelete: Array<unknown> = []
1480
1481 for (const [nestedCorrelationKey, childChanges] of setup.buffer) {
1482 const stateRoutes = setup.routingIndex.get(nestedCorrelationKey)
1483 if (stateRoutes === undefined || stateRoutes.size === 0) {
1484 // Unroutable — parent not yet seen; keep in buffer
1485 continue
1486 }
1487
1488 // A single nested correlation key can map to multiple parent groups when
1489 // sibling parents share the same correlation value, and at depth 4+ those
1490 // parents may live in different per-entry states. Fan the buffered changes
1491 // out to every ready target before clearing the shared buffer entry.
1492 let routedToAny = false
1493 for (const [targetState, parentRoutes] of stateRoutes) {
1494 const targetSetupIndex = targetState.nestedSetups?.indexOf(setup) ?? -1
1495 if (targetSetupIndex < 0) continue
1496
1497 for (const parentCorrelationKey of parentRoutes.keys()) {
1498 const entry = targetState.childRegistry.get(parentCorrelationKey)
1499 if (!entry || !entry.includesStates) {
1500 continue
1501 }
1502
1503 // Route changes into this entry's per-entry state at the same setup.
1504 const entryState = entry.includesStates[targetSetupIndex]!
1505 for (const [childKey, changes] of childChanges) {
1506 let byChild =
1507 entryState.pendingChildChanges.get(nestedCorrelationKey)
1508 if (!byChild) {
1509 byChild = new Map()
1510 entryState.pendingChildChanges.set(nestedCorrelationKey, byChild)
1511 }
1512 const existing = byChild.get(childKey)
1513 if (existing) {
1514 existing.inserts += changes.inserts
1515 existing.deletes += changes.deletes
1516 if (changes.inserts > 0) {
1517 existing.value = changes.value
1518 if (changes.orderByIndex !== undefined) {
1519 existing.orderByIndex = changes.orderByIndex
1520 }
1521 }
1522 } else {
1523 byChild.set(childKey, { ...changes })
1524 }
1525 }
1526
1527 if (targetState === state) {
1528 dirtyCorrelationKeys.add(parentCorrelationKey)
1529 }
1530 routedToAny = true

Callers 1

flushIncludesStateFunction · 0.85

Calls 7

accumulateSnapshotFunction · 0.85
getMethod · 0.45
indexOfMethod · 0.45
keysMethod · 0.45
setMethod · 0.45
addMethod · 0.45
deleteMethod · 0.45

Tested by

no test coverage detected