diff --git a/.changeset/lazy-join-keeps-key-filter.md b/.changeset/lazy-join-keeps-key-filter.md new file mode 100644 index 0000000000..2d42534fea --- /dev/null +++ b/.changeset/lazy-join-keeps-key-filter.md @@ -0,0 +1,5 @@ +--- +'@tanstack/db': patch +--- + +Keep loading the lazy side of a join inside an include by its join keys when the query also filters one side with `where`. The filter now narrows each keyed `loadSubset` request (for example `active = true AND id IN (7, 8, 9)`) instead of replacing it, so an on-demand Collection no longer receives a request for every row that matches the filter, or for every row when the filter is on the other side. diff --git a/docs/contributing/oracle-coverage.md b/docs/contributing/oracle-coverage.md index 22042483b8..4420c339ed 100644 --- a/docs/contributing/oracle-coverage.md +++ b/docs/contributing/oracle-coverage.md @@ -1285,6 +1285,30 @@ fixed collapse and the detail page; a child that takes over `setWindow` fails the rows law. Focused tests require a window inside a `from` or joined subquery not to answer `setWindow`. +Its two joined work laws (unmatched links, and indexed join targets) also +generate a join filter: none, a `where` on the links alone, or a `where` on the +joined targets alone. The optimizer pushes each filter into a subquery over its +own source, and the include must still filter the links by parent and load the +targets by the kept links' join values, so the filter narrows each keyed read +(live/ARCHITECTURE.md, Initial demand and Work). Both campaigns declare the +three filter states with `createOracleReach` and run one fixed example per +state; each state is reached by at least one fixed history in every run. On +main the include parent-routed both filtered sources and scanned the target +Collection: the target filter delivered 3 and examined 4 target rows at +baseline where the keyed bound is 2 and 3, and one unmatched link with a link +filter delivered 4 target rows where the bound is 2. Mutants that route the +filtered target, or the filtered links, by parent fail the target and link +states respectively. A focused test in +`packages/db/tests/query/lazy-join-source-where.test.ts` replays the on-demand +report: each `loadSubset` the lazy side receives names the join keys. The +owner does not generate subqueries that read a parent value, filters on both +sides at once, or `fn.where()` filters, which remain parent-routed. Only a +focused test in the same file shows that a joined subquery whose `where` reads +the parent stays parent-routed: a mutant that drops that check returns empty +child arrays there, and the existing include suites (637 tests) pass it. A +generated parent-reading subquery dimension in the cross-formulation owner +would close that gap. + Recorded limit (#2151): while an index-backed parent top-K refills within one graph run (a held row moved out, a tie group loaded at the window edge, a forward window move), it can briefly hold a row outside the window it shows once diff --git a/packages/db/src/query/compiler/index.ts b/packages/db/src/query/compiler/index.ts index 5fb83aecc8..7771b247e9 100644 --- a/packages/db/src/query/compiler/index.ts +++ b/packages/db/src/query/compiler/index.ts @@ -66,7 +66,12 @@ import { isCaseWhenConditionTrue, toBooleanPredicate, } from './evaluators.js' -import { processJoins, processSource, registerLazyDemandPlan } from './joins.js' +import { + isSourceFilter, + processJoins, + processSource, + registerLazyDemandPlan, +} from './joins.js' import { findAggregate } from './find-aggregate.js' import { getLazyLoadTargets } from './lazy-targets.js' import { processOrderBy } from './order-by.js' @@ -1652,6 +1657,12 @@ function processFromClause( } const compileSource = (source: CollectionSourceRef | QueryRef) => { + // A pushed-down source filter reads no parent value: it is filtered by the + // parent like its Collection, so keyed lazy demand still applies. + const isParentRouted = + parentKeyStream !== undefined && + source.type === `queryRef` && + !isSourceFilter(source) const result = processSource( source, allInputs, @@ -1678,7 +1689,7 @@ function processFromClause( sourceWhereClauses, valueIdentity, `from`, - parentKeyStream, + isParentRouted ? parentKeyStream : undefined, ) return { ...result, @@ -1687,8 +1698,7 @@ function processFromClause( sourceAlias: source.alias, include, })) ?? [], - isParentRouted: - source.type === `queryRef` && parentKeyStream !== undefined, + isParentRouted, } } diff --git a/packages/db/src/query/compiler/joins.ts b/packages/db/src/query/compiler/joins.ts index 9b82b68035..b13e589b07 100644 --- a/packages/db/src/query/compiler/joins.ts +++ b/packages/db/src/query/compiler/joins.ts @@ -24,6 +24,7 @@ import { collectPropRefs, getFromSources, getPropRefSourceAlias, + getWhereExpression, requireCollectionSource, } from '../ir.js' import { compileExpression } from './evaluators.js' @@ -250,7 +251,8 @@ export function processJoins( ) const routeJoinedSource = parentKeyStream !== undefined && - (joinClause.from.type === `queryRef` || + ((joinClause.from.type === `queryRef` && + !isSourceFilter(joinClause.from)) || ((joinClause.type === `right` || joinClause.type === `full`) && !mainSourceIsParentFiltered) || joinedExpressionUsesParent) @@ -475,6 +477,23 @@ export function processJoins( type JoinRefRole = `joined` | `main` | `ancestor` | `unknown` +// The optimizer pushes a source's own `where` into a subquery over that +// source. The subquery reads no parent value, so an include need not route it +// by parent: it joins like the source and keeps keyed lazy demand, and the +// filter narrows each keyed load. +export function isSourceFilter({ query }: QueryRef): boolean { + const { from, where = [], ...rest } = query + return ( + (from.type === `collectionRef` || from.type === `descriptorRef`) && + Object.values(rest).every((value) => value === undefined) && + where.every((clause) => + collectPropRefs(getWhereExpression(clause)).every( + (ref) => ref.bindingId === from.bindingId, + ), + ) + ) +} + function getJoinRefAlias(ref: PropRef): string | undefined { return getPropRefSourceAlias(ref) ?? ref.path[0] } diff --git a/packages/db/src/query/optimizer.ts b/packages/db/src/query/optimizer.ts index d214a737e8..950a694459 100644 --- a/packages/db/src/query/optimizer.ts +++ b/packages/db/src/query/optimizer.ts @@ -1049,8 +1049,8 @@ function remapWhereForSubquery( whereClause: BasicExpression, outerAlias: string, ): BasicExpression | undefined { - const firstFromAlias = getFirstFromAlias(subquery) - if (firstFromAlias === undefined) return undefined + const firstFrom = getFromSources(subquery.from)[0] + if (firstFrom === undefined) return undefined const remapExpression = (expression: BasicExpression): BasicExpression => { if (expression instanceof PropRef) { @@ -1060,14 +1060,22 @@ function remapWhereForSubquery( const projected = field ? subquery.select?.[field] : undefined const hasNamespacedResult = subquery.join !== undefined || subquery.from.type === `unionFrom` - const innerPath = - projected instanceof PropRef - ? [...projected.path, ...expression.path.slice(2)] - : hasNamespacedResult - ? expression.path.slice(1) - : [firstFromAlias, ...expression.path.slice(1)] - - return new PropRef(innerPath) + + if (projected instanceof PropRef) { + return new PropRef( + [...projected.path, ...expression.path.slice(2)], + undefined, + projected.bindingId, + ) + } + if (hasNamespacedResult) { + return new PropRef(expression.path.slice(1)) + } + return new PropRef( + [firstFrom.alias, ...expression.path.slice(1)], + undefined, + firstFrom.bindingId, + ) } if (expression instanceof Func) { diff --git a/packages/db/tests/query/includes-work-counter-oracle.test.ts b/packages/db/tests/query/includes-work-counter-oracle.test.ts index 9dd822a918..ab265a47df 100644 --- a/packages/db/tests/query/includes-work-counter-oracle.test.ts +++ b/packages/db/tests/query/includes-work-counter-oracle.test.ts @@ -54,6 +54,7 @@ import type { Collection } from '../../src/collection/index.js' import type { LoadSubsetOptions } from '../../src/types.js' import type { Context, QueryBuilder } from '../../src/query/index.js' import type { + JoinFilter, SourceWork, WorkObservation, } from './includes-work-counter-support.js' @@ -79,9 +80,15 @@ import type { * The input grammar varies an integer filler count from 1 through 24. Zero is * the ablated baseline; negative and fractional counts are invalid fixture * sizes. Joined queries vary unrelated links and join targets separately. - * The join-free query grows every source together. Counts 1, 2, and 3 cover the - * smallest valid boundary, 24 covers the upper bound, and fixed and random - * campaigns sample the range. + * Both joined laws also vary a join filter: none, a `where` on the links + * alone, or a `where` on the joined targets alone. The optimizer pushes each + * filter into its own source, and laws 2 and 3 must still hold: the targets + * stay keyed by the kept links' join values, so a filter narrows the keyed + * load and must not replace it or make the include scan a side + * (live/ARCHITECTURE.md, Initial demand and Work). The reference drops the + * filtered row's link. The join-free query grows every source together. + * Counts 1, 2, and 3 cover the smallest valid boundary, 24 covers the upper + * bound, and fixed and random campaigns sample the range. * * The boundary conditions matter. Collections preload before they receive * B-tree indexes. Filler rows never match a selected route. This suite checks @@ -98,6 +105,21 @@ const joinedBaselineWork: SourceWork = { links: { delivered: 2, examined: 2 }, } +// Each join filter drops one row after a keyed read. A target filter drops +// one of the two named targets: the root and both named targets are +// examined, the root and one target delivered. A link filter drops one of +// the group's two links, so only the kept link's target is named. +const joinedBaselineWorkByFilter: Record = { + none: joinedBaselineWork, + target: { ...joinedBaselineWork, terms: { delivered: 2, examined: 3 } }, + link: { + ...joinedBaselineWork, + terms: { delivered: 2, examined: 2 }, + links: { delivered: 1, examined: 2 }, + }, +} +const joinFilters = Object.keys(joinedBaselineWorkByFilter) as Array + const joinFreeBaselineWork: SourceWork = { terms: { delivered: 1, examined: 1 }, meanings: { delivered: 1, examined: 1 }, @@ -105,61 +127,49 @@ const joinFreeBaselineWork: SourceWork = { links: { delivered: 2, examined: 2 }, } -let joinedBaselineObservation: WorkObservation +const joinedBaselineObservations = new Map() let joinFreeBaselineObservation: WorkObservation -async function expectCorrelatedJoinWorkBound( - fillerCount: number, +// Both joined laws compare a scaled run with the minimal run of the same +// query, under each join filter. +async function expectJoinedWorkBound( + filler: { terms: number; links: number }, + joinFilter: JoinFilter, ): Promise { - const baseline = joinedBaselineObservation + const baseline = joinedBaselineObservations.get(joinFilter)! const scaled = await observeWork({ - filler: { - terms: 0, - meanings: 0, - groups: 0, - links: fillerCount, - }, + filler: { ...filler, meanings: 0, groups: 0 }, joinTargets: true, + joinFilter, }) oracleAssertion('includes work-counter-oracle comparison 112', () => - expect(baseline.result).toEqual(expectedResult({ joinTargets: true })), + expect(baseline.result).toEqual( + expectedResult({ joinTargets: true, joinFilter }), + ), ) oracleAssertion('includes work-counter-oracle comparison 113', () => expect(scaled.result).toEqual(baseline.result), ) oracleAssertion('includes work-counter-oracle comparison 114', () => - expect(baseline.sourceWork).toEqual(joinedBaselineWork), + expect(baseline.sourceWork).toEqual(joinedBaselineWorkByFilter[joinFilter]), ) - oracleAssertion('includes work-counter-oracle comparison 116', () => expectSourceWorkBound(scaled.sourceWork, baseline.sourceWork), ) } -async function expectJoinTargetWorkBound(fillerCount: number): Promise { - const baseline = joinedBaselineObservation - const scaled = await observeWork({ - filler: { - terms: fillerCount, - meanings: 0, - groups: 0, - links: 0, - }, - joinTargets: true, - }) +async function expectCorrelatedJoinWorkBound( + fillerCount: number, + joinFilter: JoinFilter = `none`, +): Promise { + await expectJoinedWorkBound({ terms: 0, links: fillerCount }, joinFilter) +} - oracleAssertion('includes work-counter-oracle comparison 131', () => - expect(baseline.result).toEqual(expectedResult({ joinTargets: true })), - ) - oracleAssertion('includes work-counter-oracle comparison 132', () => - expect(scaled.result).toEqual(baseline.result), - ) - oracleAssertion('includes work-counter-oracle comparison 133', () => - expect(baseline.sourceWork).toEqual(joinedBaselineWork), - ) - oracleAssertion('includes work-counter-oracle comparison 134', () => - expectSourceWorkBound(scaled.sourceWork, baseline.sourceWork), - ) +async function expectJoinTargetWorkBound( + fillerCount: number, + joinFilter: JoinFilter = `none`, +): Promise { + await expectJoinedWorkBound({ terms: fillerCount, links: 0 }, joinFilter) } async function expectJoinFreeWorkBound(fillerCount: number): Promise { @@ -198,12 +208,16 @@ const joinFreeLaw = `Join-free correlated includes keep source work flat as unre describe(`includes deterministic work-counter oracle`, () => { beforeAll(async () => { - const [joinedBaseline, joinFreeBaseline] = await Promise.all([ - observeWork({ filler: noFillers, joinTargets: true }), + const [joinFreeBaseline, ...joinedBaselines] = await Promise.all([ observeWork({ filler: noFillers, joinTargets: false }), + ...joinFilters.map((joinFilter) => + observeWork({ filler: noFillers, joinTargets: true, joinFilter }), + ), ]) - joinedBaselineObservation = joinedBaseline joinFreeBaselineObservation = joinFreeBaseline + joinFilters.forEach((joinFilter, index) => + joinedBaselineObservations.set(joinFilter, joinedBaselines[index]!), + ) }) oracleProperty({ @@ -241,7 +255,7 @@ describe(`includes deterministic work-counter oracle`, () => { law: { statement: joinTargetsLaw, authority: `Law 12 (work) and the physical planning and work contract in packages/db/src/query/live/ARCHITECTURE.md, stated at the start of this owner.`, - limits: `The join-target filler range endpoints 1 and 24.`, + limits: `The join-target filler range endpoints 1 and 24, under each join filter.`, }, owns: [ `src/collection/index.ts#createCollection`, @@ -249,13 +263,16 @@ describe(`includes deterministic work-counter oracle`, () => { `src/local-only.ts#localOnlyCollectionOptions`, `src/query/live-query-collection.ts#createLiveQueryCollection`, ], - histories: [1, 24], - label: (fillers) => `checks join-target growth at filler count ${fillers}`, - resolve: (fillers) => ({ fillers }), + histories: joinFilters.flatMap((joinFilter) => + [1, 24].map((fillers) => ({ fillers, joinFilter })), + ), + label: ({ fillers, joinFilter }) => + `checks join-target growth at filler count ${fillers} (join filter ${joinFilter})`, + resolve: (history) => ({ ...history }), model: recordedAssertionJudgment, driver: (plan, observe) => recordAssertionJudgment(joinTargetsLaw, plan, observe, () => - expectJoinTargetWorkBound(plan.fillers), + expectJoinTargetWorkBound(plan.fillers, plan.joinFilter), ), check: forwardAssertionJudgment, }) @@ -284,42 +301,41 @@ describe(`includes deterministic work-counter oracle`, () => { check: forwardAssertionJudgment, }) - for (const campaign of campaigns(1709, `includes-work.correlated-links`)) { - registerIncludesProperty( - [fc.integer({ min: 1, max: 24 })], - { - ...campaign.options, - owns: [ - `src/collection/index.ts#createCollection`, - `src/indexes/btree-index.ts`, - `src/local-only.ts#localOnlyCollectionOptions`, - `src/query/live-query-collection.ts#createLiveQueryCollection`, - ], - }, - `a join preserves correlated source pushdown (${campaign.name})`, - (...args: Parameters) => { - return expectCorrelatedJoinWorkBound(...args) - }, - ) - } - - for (const campaign of campaigns(170_900, `includes-work.join-targets`)) { - registerIncludesProperty( - [fc.integer({ min: 1, max: 24 })], - { - ...campaign.options, - owns: [ - `src/collection/index.ts#createCollection`, - `src/indexes/btree-index.ts`, - `src/local-only.ts#localOnlyCollectionOptions`, - `src/query/live-query-collection.ts#createLiveQueryCollection`, - ], - }, - `indexed join-target growth keeps source work flat (${campaign.name})`, - (...args: Parameters) => { - return expectJoinTargetWorkBound(...args) - }, - ) + for (const [property, seed, statement, check] of [ + [ + `includes-work.correlated-links`, + 1709, + `a join preserves correlated source pushdown`, + expectCorrelatedJoinWorkBound, + ], + [ + `includes-work.join-targets`, + 170_900, + `indexed join-target growth keeps source work flat`, + expectJoinTargetWorkBound, + ], + ] as const) { + for (const campaign of campaigns(seed, property)) { + // Every generated filler count runs under each join filter, so each + // campaign reaches every filter state whatever its seed. + registerIncludesProperty( + [fc.integer({ min: 1, max: 24 })], + { + ...campaign.options, + owns: [ + `src/collection/index.ts#createCollection`, + `src/indexes/btree-index.ts`, + `src/local-only.ts#localOnlyCollectionOptions`, + `src/query/live-query-collection.ts#createLiveQueryCollection`, + ], + }, + `${statement} under each join filter (${campaign.name})`, + async (fillerCount: number) => { + for (const joinFilter of joinFilters) + await check(fillerCount, joinFilter) + }, + ) + } } for (const campaign of campaigns(17_090, `includes-work.join-free`)) { diff --git a/packages/db/tests/query/includes-work-counter-support.ts b/packages/db/tests/query/includes-work-counter-support.ts index 7cb30a5172..521f64830f 100644 --- a/packages/db/tests/query/includes-work-counter-support.ts +++ b/packages/db/tests/query/includes-work-counter-support.ts @@ -6,6 +6,7 @@ import { createLiveQueryCollection, eq, materialize, + not, } from '../../src/query/index.js' import type { Collection } from '../../src/collection/index.js' @@ -41,8 +42,18 @@ type FillerCounts = { type WorkScenario = { filler: FillerCounts joinTargets: boolean + joinFilter?: JoinFilter } +// A source-local filter on one side of the target join. The optimizer pushes +// it into that side's source. `link` filters the parent-correlated side and +// `target` the joined side, which stays the join's lazy side either way. +export type JoinFilter = `none` | `link` | `target` + +// Each filter keeps every row except one. +const excludedLinkId = `link-1` +const excludedTargetText = `second target` + type WorkCount = { delivered: number examined: number @@ -227,6 +238,7 @@ export function observeResult( export async function observeWork({ filler, joinTargets, + joinFilter = `none`, }: WorkScenario): Promise { const rows = createFixtureRows(filler) const sources = { @@ -282,21 +294,31 @@ export async function observeWork({ const selectedLinks = q .from({ link: sources.links }) .where(({ link }) => eq(link.groupId, group.id)) + const keptLinks = + joinFilter === `link` + ? selectedLinks.where(({ link }) => + not(eq(link.id, excludedLinkId)), + ) + : selectedLinks + const joinedTargets = keptLinks.innerJoin( + { target: sources.terms }, + ({ link, target }) => eq(link.targetId, target.id), + ) + const keptTargets = + joinFilter === `target` + ? joinedTargets.where(({ target }) => + not(eq(target.text, excludedTargetText)), + ) + : joinedTargets return { id: group.id, links: joinTargets ? materialize( - selectedLinks - .innerJoin( - { target: sources.terms }, - ({ link, target }) => - eq(link.targetId, target.id), - ) - .select(({ link, target }) => ({ - id: link.id, - text: target.text, - })), + keptTargets.select(({ link, target }) => ({ + id: link.id, + text: target.text, + })), ) : materialize( selectedLinks.select(({ link }) => ({ @@ -337,9 +359,28 @@ export async function observeWork({ } } +// The relational reference: an inner join keeps a link only when the link +// passes the link filter and its target exists and passes the target filter. export function expectedResult({ joinTargets, -}: Pick): WorkObservation[`result`] { + joinFilter = `none`, +}: Pick< + WorkScenario, + 'joinTargets' | 'joinFilter' +>): WorkObservation[`result`] { + const links: Array = joinTargets + ? [ + { id: `link-0`, text: `first target` }, + { id: `link-1`, text: `second target` }, + ].filter( + (link) => + !(joinFilter === `link` && link.id === excludedLinkId) && + !(joinFilter === `target` && link.text === excludedTargetText), + ) + : [ + { id: `link-0`, targetId: `term-1` }, + { id: `link-1`, targetId: `term-2` }, + ] return [ { id: `term-0`, @@ -349,20 +390,7 @@ export function expectedResult({ groups: [ { id: `group-0`, - links: [ - joinTargets - ? { id: `link-0`, text: `first target` } - : { id: `link-0`, targetId: `term-1` }, - joinTargets - ? { - id: `link-1`, - text: `second target`, - } - : { - id: `link-1`, - targetId: `term-2`, - }, - ], + links, }, ], }, diff --git a/packages/db/tests/query/lazy-join-source-where.test.ts b/packages/db/tests/query/lazy-join-source-where.test.ts new file mode 100644 index 0000000000..1f0ecc595f --- /dev/null +++ b/packages/db/tests/query/lazy-join-source-where.test.ts @@ -0,0 +1,339 @@ +import { afterEach, describe, expect, it } from 'vitest' +import { + createLiveQueryCollection, + eq, + not, + toArray, +} from '../../src/query/index.js' +import { createCollection } from '../../src/collection/index.js' +import { BasicIndex } from '../../src/indexes/basic-index.js' +import { flushPromises } from '../utils.js' +import type { LoadSubsetOptions } from '../../src/types.js' + +type TodoList = { id: number } +type Todo = { id: number; listId: number; assigneeId: number } +type User = { id: number; active: boolean } + +const todoListRows: Array = [{ id: 1 }, { id: 2 }] +const todoRows: Array = [ + { id: 1, listId: 1, assigneeId: 7 }, + { id: 2, listId: 1, assigneeId: 8 }, + { id: 3, listId: 2, assigneeId: 9 }, +] +// Users 10 and 11 are assigned no todo: a keyed load must not ask for them. +const userRows: Array = [ + { id: 7, active: true }, + { id: 8, active: false }, + { id: 9, active: true }, + { id: 10, active: true }, + { id: 11, active: true }, +] + +let sequence = 0 +const cleanups: Array<() => void | Promise> = [] + +function createEagerCollection( + name: string, + rows: Array, +) { + const collection = createCollection({ + id: `lazy-join-where-${name}-${sequence++}`, + getKey: (row) => row.id, + sync: { + sync: ({ begin, write, commit, markReady }) => { + begin() + for (const row of rows) write({ type: `insert`, value: row }) + commit() + markReady() + }, + }, + }) + cleanups.push(() => collection.cleanup()) + return collection +} + +// An on-demand source that serves every loadSubset from its full table, as +// a server would, and records the options each load receives. +function createOnDemandCollection( + name: string, + rows: Array, +) { + const loads: Array = [] + const collection = createCollection({ + id: `lazy-join-where-${name}-${sequence++}`, + getKey: (row) => row.id, + syncMode: `on-demand`, + autoIndex: `eager`, + defaultIndexType: BasicIndex, + sync: { + sync: ({ begin, write, commit, markReady }) => { + markReady() + return { + loadSubset: (options: LoadSubsetOptions) => { + loads.push(options) + begin() + for (const row of rows) { + if (collection.has(row.id)) continue + write({ type: `insert`, value: row }) + } + commit() + return Promise.resolve() + }, + } + }, + }, + }) + cleanups.push(() => collection.cleanup()) + return { collection, loads } +} + +// Lazy demand is the only part of a load that names join keys, so a keyed +// load is one whose predicate holds `id IN (...)`. +function describeLoad(options: LoadSubsetOptions): string { + return JSON.stringify(options.where) +} + +type LoadPredicate = NonNullable + +function sortedKeys(keys: Array): string { + return JSON.stringify([...keys].sort()) +} + +function hasKeyFilter(options: LoadSubsetOptions, keys: Array) { + const isKeyFilter = (expression: LoadPredicate): boolean => { + if (expression.type !== `func`) return false + if (expression.name === `and`) { + return expression.args.some((arg) => isKeyFilter(arg as LoadPredicate)) + } + const [ref, values] = expression.args + return ( + expression.name === `in` && + ref?.type === `ref` && + JSON.stringify(ref.path) === JSON.stringify([`id`]) && + values?.type === `val` && + Array.isArray(values.value) && + sortedKeys(values.value) === sortedKeys(keys) + ) + } + return options.where !== undefined && isKeyFilter(options.where) +} + +describe(`lazy join source where`, () => { + afterEach(async () => { + for (const cleanup of cleanups.splice(0).reverse()) await cleanup() + }) + + it(`include: a where on the lazy joined side keeps the join-key filter`, async () => { + const todoLists = createEagerCollection(`todo-lists`, todoListRows) + const todos = createEagerCollection(`todos`, todoRows) + const { collection: users, loads } = createOnDemandCollection( + `users`, + userRows, + ) + + const live = createLiveQueryCollection((q) => + q.from({ list: todoLists }).select(({ list }) => ({ + id: list.id, + todos: toArray( + q + .from({ todo: todos }) + .where(({ todo }) => eq(todo.listId, list.id)) + .innerJoin({ assignee: users }, ({ todo, assignee }) => + eq(todo.assigneeId, assignee.id), + ) + .where(({ assignee }) => eq(assignee.active, true)) + .select(({ todo, assignee }) => ({ + id: todo.id, + assignee: assignee.id, + })), + ), + })), + ) + cleanups.push(() => live.cleanup()) + await live.preload() + await flushPromises() + + expect(loads.length).toBeGreaterThan(0) + for (const load of loads) { + expect(hasKeyFilter(load, [7, 8, 9]), describeLoad(load)).toBe(true) + } + expect( + live.toArray + .map((list) => ({ + id: list.id, + assignees: [...list.todos].map((todo) => todo.assignee).sort(), + })) + .sort((a, b) => a.id - b.id), + ).toEqual([ + { id: 1, assignees: [7] }, + { id: 2, assignees: [9] }, + ]) + }) + + it(`include: a where pushed into a joined subquery keeps the join-key filter`, async () => { + const todoLists = createEagerCollection(`todo-lists`, todoListRows) + const todos = createEagerCollection(`todos`, todoRows) + const { collection: users, loads } = createOnDemandCollection( + `users`, + userRows, + ) + + const live = createLiveQueryCollection((q) => + q.from({ list: todoLists }).select(({ list }) => ({ + id: list.id, + todos: toArray( + q + .from({ todo: todos }) + .where(({ todo }) => eq(todo.listId, list.id)) + .innerJoin( + { assignee: q.from({ user: users }) }, + ({ todo, assignee }) => eq(todo.assigneeId, assignee.id), + ) + .where(({ assignee }) => eq(assignee.active, true)) + .select(({ todo, assignee }) => ({ + id: todo.id, + assignee: assignee.id, + })), + ), + })), + ) + cleanups.push(() => live.cleanup()) + await live.preload() + await flushPromises() + + expect(loads.length).toBeGreaterThan(0) + for (const load of loads) { + expect(hasKeyFilter(load, [7, 8, 9]), describeLoad(load)).toBe(true) + } + expect( + live.toArray + .map((list) => ({ + id: list.id, + assignees: [...list.todos].map((todo) => todo.assignee).sort(), + })) + .sort((a, b) => a.id - b.id), + ).toEqual([ + { id: 1, assignees: [7] }, + { id: 2, assignees: [9] }, + ]) + }) + + it(`include: a where on the parent-filtered side keeps the join-key filter`, async () => { + const todoLists = createEagerCollection(`todo-lists`, todoListRows) + const todos = createEagerCollection(`todos`, todoRows) + const { collection: users, loads } = createOnDemandCollection( + `users`, + userRows, + ) + + const live = createLiveQueryCollection((q) => + q.from({ list: todoLists }).select(({ list }) => ({ + id: list.id, + todos: toArray( + q + .from({ todo: todos }) + .where(({ todo }) => eq(todo.listId, list.id)) + .where(({ todo }) => not(eq(todo.assigneeId, 8))) + .innerJoin({ assignee: users }, ({ todo, assignee }) => + eq(todo.assigneeId, assignee.id), + ) + .select(({ todo, assignee }) => ({ + id: todo.id, + assignee: assignee.id, + })), + ), + })), + ) + cleanups.push(() => live.cleanup()) + await live.preload() + await flushPromises() + + expect(loads.length).toBeGreaterThan(0) + for (const load of loads) { + expect(hasKeyFilter(load, [7, 9]), describeLoad(load)).toBe(true) + } + }) + + it(`leftJoin: a where on the lazy joined side keeps the join-key filter`, async () => { + const todos = createEagerCollection(`todos`, todoRows) + const { collection: users, loads } = createOnDemandCollection( + `users`, + userRows, + ) + + const live = createLiveQueryCollection((q) => + q + .from({ todo: todos }) + .leftJoin({ assignee: users }, ({ todo, assignee }) => + eq(todo.assigneeId, assignee.id), + ) + .where(({ assignee }) => eq(assignee.active, true)) + .select(({ todo, assignee }) => ({ + id: todo.id, + assignee: assignee.id, + })), + ) + cleanups.push(() => live.cleanup()) + await live.preload() + await flushPromises() + + expect(loads.length).toBeGreaterThan(0) + for (const load of loads) { + expect(hasKeyFilter(load, [7, 8, 9]), describeLoad(load)).toBe(true) + } + }) + + // A joined subquery whose filter reads the parent is not a source filter: + // it must stay routed by parent, so each list sees only its own team's + // assignees. + it(`include: a joined subquery that reads the parent row keeps its parent filter`, async () => { + const todoLists = createEagerCollection(`team-todo-lists`, [ + { id: 1, team: `a` }, + { id: 2, team: `b` }, + ]) + const todos = createEagerCollection(`team-todos`, [ + { id: 1, listId: 1, assigneeId: 7 }, + { id: 2, listId: 1, assigneeId: 8 }, + { id: 3, listId: 2, assigneeId: 7 }, + { id: 4, listId: 2, assigneeId: 8 }, + ]) + const users = createEagerCollection(`team-users`, [ + { id: 7, team: `a` }, + { id: 8, team: `b` }, + ]) + + const live = createLiveQueryCollection((q) => + q.from({ list: todoLists }).select(({ list }) => ({ + id: list.id, + todos: toArray( + q + .from({ todo: todos }) + .where(({ todo }) => eq(todo.listId, list.id)) + .innerJoin( + { + assignee: q + .from({ assignee: users }) + .where(({ assignee }) => eq(assignee.team, list.team)), + }, + ({ todo, assignee }) => eq(todo.assigneeId, assignee.id), + ) + .select(({ assignee }) => ({ id: assignee.id })), + ), + })), + ) + cleanups.push(() => live.cleanup()) + await live.preload() + + expect( + live.toArray + .map((list) => ({ + id: list.id, + assignees: [...list.todos].map((assignee) => assignee.id), + })) + .sort((a, b) => a.id - b.id), + ).toEqual([ + { id: 1, assignees: [7] }, + { id: 2, assignees: [8] }, + ]) + }) +})