Skip to content
Merged
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
24 changes: 24 additions & 0 deletions .changeset/34990-nested-relation-filter-node.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
---
'@object-ui/core': patch
---

fix(core): a relationship-path dashboard drill is sent as one nested-relation condition, so the server joins it in the database instead of the app reading related ids first

Clause-②: yes (narrowing)
Metadata-protocol: none

<!-- adr-0087: not-required (no-migration-prescription) No schema key, accepted value or metadata type is added, removed or renamed, and nothing stored is rewritten: the narrowed input is the in-memory filter a host hands ValueDataSource at runtime, and the comparand it now refuses, a plain object with no $ key under a scalar operator, is one the spec's own comparand door already refuses and ViewFilterRuleSchema.value cannot hold. No metadata an author can save changes meaning, so there is nothing for objectstack migrate meta to do. -->

**BREAKING** for a host that filters a `ValueDataSource` (the in-memory `provider: 'value'` source) with a comparison whose comparand is a plain object (prototype `Object.prototype` or `null`) with no `$` key, such as `['account', '!=', { owner: 'u1' }]`, under `!=`, `not_contains` or an ordering operator (`>`, `>=`, `<`, `<=`).

- FROM: `!=` and `not_contains` served every row, and an ordering operator compared each value with the text `[object Object]` and served the string values that happened to sort past it.
- TO: the condition is refused by name. It excludes every row and logs the sentence the object form `{ account: { owner: 'u1' } }` already logs. `=` matched no row before and matches none now; it only gains the log line.
- The spec's comparand door already refuses an object comparand under these operators, so the rows served before were a wrong answer. Spell a relation condition only against a server-backed source, whose server joins it; a value source holds flat rows, so filter there on the row's own fields.

`convertFiltersToAST` now lowers the nested-relation form the spec declares on `FilterCondition` (`{ account: { owner: 'u1' } }`, a plain object with no `$` key beneath a field) to one equality node, `['account', '=', { owner: 'u1' }]`, which the spec's `parseFilterAST` reads back as the same nested condition. It used to refuse that shape as an unknown operator. The condition travels as written, deeper relations included; whether the field is a relationship is judged by the server, which answers `INVALID_FILTER` / 400 for such a condition under a field that stores a scalar or a structured-JSON value, and, under a relationship, for a condition key the related object does not declare, a dotted key, or a relation nested past the hop limit. A map that mixes `$` operators with plain keys is still refused.

`ValueDataSource` (the in-memory `provider: 'value'` source) does not descend into relations, and it now says so for the lowered node too: a comparison whose comparand is a plain object with no `$` key, such as `['account', '=', { owner: 'u1' }]`, excludes every row and logs the same sentence the object form `{ account: { owner: 'u1' } }` already logged, for `=`, `!=` and every other operator that reads the comparand. Before this, `=` compared the object by reference and matched no row without a word, and `!=` matched every row. A class instance is not refused, even one with keys of its own such as a moment, luxon or decimal object: it is a value, and an ordering operator still compares it through its `valueOf`.

`resolveDatasetDrillFilter` uses it: a dataset dimension whose field is a relationship path (`account.owner`, up to three hops) drills as `{ account: { owner: VALUE } }`, nested one level per hop, instead of reading up to 200 related ids per hop and filtering on `$in` them. No related record is read, nothing is capped, and the `too-many` answer is no longer produced; `DATASET_DRILL_RELATED_ID_CAP` and the `too-many` member of `DatasetDrillResolution` stay exported, marked deprecated. The schema reads that check each hop is a single-valued relationship, the hop limit and the empty-bucket refusal are unchanged.

One visible consequence: the drawer's "Open in list" escape hatch is not offered for a relationship-path drill, because the list page's `filter[...]` URL dialect has no spelling for a nested condition; the drill drawer itself lists the records.
51 changes: 45 additions & 6 deletions ui/packages/core/src/adapters/ValueDataSource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -472,6 +472,39 @@ function comparandEquals(value: unknown, target: unknown): boolean {
return value === target;
}

/**
* The refusal for a nested relation constraint, one sentence for both
* dialects: the object arm meets `{ rel: { field: value } }` as a non-operator
* key in {@link matchesDollarOperator}, and the AST arm meets its lowered
* `['rel', '=', { field: value }]` in {@link matchesComparisonNode}.
*/
function nestedRelationRefusalReason(field: string, key: string): string {
return `filter condition on field '${field}' carries the non-operator key `
+ `'${key}'; the in-memory matcher does not descend into a nested `
+ `relation constraint`;
}

/**
* The first key of an AST comparand that is a nested relation condition, or
* `undefined` when it is not one. The shape is the one `convertFiltersToAST`
* lowers to `[rel, '=', condition]`: a non-empty PLAIN object with no `$` key.
*
* Plain means prototype `Object.prototype` or `null`, the test the spec's
* filter walk uses to tell filter structure from data. A class instance is
* data even when it carries its own non-`$` keys: a moment or luxon date, or a
* decimal object, under `>` / `<` compares through its `valueOf` in the switch
* below and is not refused as a relation.
* A `Date` has no own keys, so it is never one either.
*/
function nestedRelationComparandKey(target: unknown): string | undefined {
if (!target || typeof target !== 'object' || Array.isArray(target)) return undefined;
const proto = Object.getPrototypeOf(target) as object | null;
if (proto !== Object.prototype && proto !== null) return undefined;
const keys = Object.keys(target);
if (keys.length === 0 || keys.some((key) => key.startsWith('$'))) return undefined;
return keys[0];
}

/**
* Evaluate ONE comparison node — `[field, operator]` or `[field, operator, value]`.
*
Expand Down Expand Up @@ -522,6 +555,17 @@ function matchesComparisonNode(
return refuseListMemberFieldReference(refusals, field, String(rawOperator));
}

// The nested-relation node `['rel', '=', { field: value }]`, which
// `convertFiltersToAST` lowers `{ rel: { field: value } }` to. This matcher
// does not descend into relations, and without this arm `=` compared the
// condition object by reference: no row matched and nothing was logged, while
// the object form of the same filter is refused by name. Checked for every
// operator that reads the slot, so `!=` cannot answer it as every row.
const nestedKey = nestedRelationComparandKey(rawTarget);
if (nestedKey !== undefined && !AST_NO_COMPARAND_OPERATORS.has(operator)) {
return refuseFilterNode(refusals, nestedRelationRefusalReason(field, nestedKey));
}

// objectui#8515 — a `{ $field }` reference as the WHOLE comparand. Resolved
// against this record so the switch below compares two of its own values,
// exactly as `matchesFilter` (`@objectstack/formula`) and `driver-sql` do.
Expand Down Expand Up @@ -924,12 +968,7 @@ function matchesDollarOperator(
);
}
if (!operator.startsWith('$')) {
return refuseFilterNode(
refusals,
`filter condition on field '${field}' carries the non-operator key `
+ `'${operator}'; the in-memory matcher does not descend into a nested `
+ `relation constraint`,
);
return refuseFilterNode(refusals, nestedRelationRefusalReason(field, operator));
}
return refuseFilterNode(
refusals,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -458,3 +458,120 @@ describe('objectui#7349 — the production chain, end to end', () => {
expect(await selectedIds(filter)).toEqual(['a', 'c']);
});
});

// ---------------------------------------------------------------------------
// The nested-relation node is refused by name in both dialects
// ---------------------------------------------------------------------------

/**
* `convertFiltersToAST` lowers the nested relation condition
* `{ profile: { verified: true } }` to `['profile', '=', { verified: true }]`,
* the node a server data source serves as a subquery. This matcher does not
* descend into relations. The object form was already refused by name; the
* AST form reached the `=` arm, which compared the condition object by
* reference, so no row matched and nothing was logged. Both forms now give
* the same refusal sentence. The `=` answer was the empty set on both trees,
* so the discriminant there is the logged refusal; `!=` answered EVERY row
* before the arm existed, so its row set discriminates on its own.
*/
describe('the nested-relation node is refused by name in both dialects', () => {
const NESTED = { profile: { verified: true } };
const REFUSAL =
"filter condition on field 'profile' carries the non-operator key 'verified'; "
+ 'the in-memory matcher does not descend into a nested relation constraint';

it('the AST form and the object form are refused alike, with one sentence', async () => {
const node = toFilterNode(NESTED);
expect(node).toEqual(['profile', '=', { verified: true }]);

const astWarn = vi.spyOn(console, 'warn').mockImplementation(() => {});
expect(await selectedIds(node)).toEqual([]);
expect(astWarn).toHaveBeenCalledTimes(1);
const astLine = String(astWarn.mock.calls[0]?.[0]);
astWarn.mockRestore();

const objectWarn = vi.spyOn(console, 'warn').mockImplementation(() => {});
expect(await selectedIds(NESTED)).toEqual([]);
expect(objectWarn).toHaveBeenCalledTimes(1);
const objectLine = String(objectWarn.mock.calls[0]?.[0]);

expect(astLine).toContain(REFUSAL);
expect(astLine).toBe(objectLine);
});

it('`!=` on the node is refused too, rather than answering every row', async () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
expect(await selectedIds(['profile', '!=', { verified: true }])).toEqual([]);
expect(warn).toHaveBeenCalledTimes(1);
expect(String(warn.mock.calls[0]?.[0])).toContain(REFUSAL);
});

/**
* `profile` holds text here, so the operators below answered rows of their
* own without the arm: `not_contains` every row, and `>` the values that sort
* past the text `[object Object]` (`'zeta'`, not `'Alpha'`). The empty set
* plus the logged sentence is the refusal.
*/
const PROFILE_ROWS = [
{ id: 'a', profile: 'zeta' },
{ id: 'b', profile: 'Alpha' },
];

it.each(['not_contains', '>'])(
'`%s` on the node is refused too, rather than reading the object as text',
async (operator) => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
expect(await selectedIds(['profile', operator, { verified: true }], PROFILE_ROWS))
.toEqual([]);
expect(warn).toHaveBeenCalledTimes(1);
expect(String(warn.mock.calls[0]?.[0])).toContain(REFUSAL);
},
);

it('CONTROL: a scalar `=` still matches, with nothing logged', async () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
expect(await selectedIds(['role', '=', 'admin'])).toEqual(['a', 'c']);
expect(warn).not.toHaveBeenCalled();
});

/**
* Only a PLAIN object is a nested condition. A class instance with its own
* non-`$` keys is data, the way a moment or luxon date or a decimal object
* is: an ordering operator compares it through its `valueOf`. `Amount`
* stands in for that population; `age` is 30 / 25 / 20.
*/
class Amount {
readonly units: number;
constructor(units: number) {
this.units = units;
}
valueOf(): number {
return this.units;
}
}

it.each([
['>', 22, ['a', 'b']],
['<', 26, ['b', 'c']],
] as const)(
'CONTROL: a class instance with own keys under `%s` compares through valueOf, with nothing logged',
async (operator, units, expected) => {
const comparand = new Amount(units);
expect(Object.keys(comparand)).toEqual(['units']);
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
expect(await selectedIds(['age', operator, comparand])).toEqual(expected);
expect(warn).not.toHaveBeenCalled();
},
);

it('CONTROL: a `Date` comparand under `>` is still accepted, with nothing logged', async () => {
const rows = [
{ id: 'a', created: new Date('2026-03-01T00:00:00Z') },
{ id: 'b', created: new Date('2026-01-01T00:00:00Z') },
];
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
expect(await selectedIds(['created', '>', new Date('2026-02-01T00:00:00Z')], rows))
.toEqual(['a']);
expect(warn).not.toHaveBeenCalled();
});
});
Loading
Loading