Skip to content

Commit 59a53a6

Browse files
fix(service-analytics): the draft preview resolves a { $field } comparand as the live faces do (#37299)
Fixes #36677 Clause-②: no Metadata-protocol: none ## 维护者速读 - 用户能看到什么变化:在 Studio 预览模式里给数据集或仪表盘写"字段与字段比较"的筛选时,预览的数字现在和发布后一致;发布后会被拒绝的写法,预览也同样报错。 - 为什么做:分析预览此前不认识字段引用,作者对着错误的数字调筛选,发布后数字才变(拆自"预览成员筛选"那张卡)。 - 出错会怎样:只影响草稿预览,不改任何已存数据或已发布查询;有问题可直接撤回本改动。 - 要你做什么:无 ## What changes The analytics draft preview (`queryDataset` with `previewDrafts`) compared the row value against the `{ $field }` reference OBJECT, as text, so every field-to-field filter answered a wrong count with a 200. It now gives the live faces' answer: - **Scalar-to-scalar references are resolved.** Under the six scalar operators (`$eq` `$ne` `$gt` `$gte` `$lt` `$lte`) the preview compares the row's two columns, with the shared cross-field corpus's truth table (both empty is equal, `$ne` is the exact complement, an ordering needs both sides). New module `preview-field-reference.ts`; the arm sits in `matchesWhere`. - **What the live faces refuse is refused**, `INVALID_FILTER` / 400, judged once before any row is read: a multi-value / JSON / file / formula column on either side and a cross-class pair (through `@objectstack/spec`'s `crossFieldComparisonVerdict`, the one classification driver-sql and the write check read), an undeclared column, a dotted path, and a reference in an `$in` / `$nin` list or under a text-pattern operator (through this package's own `where`-door sentences in `comparand-shape.ts`). - **The ruling's second choice was not taken**: the live faces' resolution rules are reusable (the spec verdict, the corpus truth table, this package's refusal sentences), so references are resolved, not refused wholesale. - **One shape is refused where a live face serves it**: a `{ $field, addDays }` offset reference. The live faces shift a date/datetime referent in SQL; the only in-memory copy of that arithmetic is private to `@objectstack/formula`, which this package does not depend on, and a second copy here would be a second rule set. The preview refuses it by name, in its not-evaluated words. On the numeric pair the live faces refuse it too. ## Tests `src/__tests__/preview-field-reference-36677.test.ts`, on the production composition (ObjectQL + SqlDriver on SQLite, six rows, one per truth-table cell): - the scalar rows `$eq` / `$ne` / `$gt` (and `$gte` / `$lt` / `$lte`, a numeric pair, `$not`, `$or`, a self-reference): native, ObjectQL and preview counts all equal the native count (2 / 4 / 1 for the card's three); - the multi-value rows `$eq` / `$ne` on `tags` and on a `select` declared `multiple`, and the other refused shapes: `code` `INVALID_FILTER` and `status` 400 on all three faces; - the shared corpus from `@objectstack/driver-sql`: every `CROSS_FIELD_CASES` row through the preview's filters with the corpus's expected ids, every `CROSS_FIELD_REFUSALS` row refused except the two tenant-column rows (see Acceptance notes), every offset case refused by name, and the offset fixture's bare-reference controls served with their rows. <details><summary>Measured on origin/main e845656 before the change (native / objectql / preview)</summary> ``` label $eq {$field:alias} 2 / 2 / 0 label $ne {$field:alias} 4 / 4 / 6 label $gt {$field:alias} 1 / 1 / 4 label $eq {$field:tags} 400 / 400 / 200 count 0 label $ne {$field:tags} 400 / 400 / 200 count 6 label $eq {$field:picks} 400 / 400 / 200 count 0 label $eq {$field:amount} 400 / 400 / 200 count 0 label $in [{$field:alias}] 400 / 400 / 200 count 0 ``` </details> <details><summary>Ablation (one-shot, not kept)</summary> The new arm in `matchesWhere` replaced by `undefined` with `scripts/ablation-replace.mjs` (anchor hit 1, injected text present 1): the 12 scalar pins went red (`Tests 12 failed | 104 skipped`), the card's scalar `$eq` pin among them. Restore proven by the script: blob after restore `821f350cb98d` equals the HEAD blob, `git diff HEAD` empty. The subject is imported from `src/`, so no rebuild leg applies. </details> <details><summary>Package suite and typecheck</summary> - `pnpm --filter @objectstack/service-analytics exec vitest run --maxWorkers=2` on 9370100: `Test Files 227 passed (227)`, `Tests 5897 passed | 345 skipped (6242)`, exit 0. - `tsc --noEmit` (the package's `typecheck`): red on 9370100 with one TS2352 in the new test file; fixed in 8a7f8ff, re-run exit 0. The new pin file re-run on 8a7f8ff: `Tests 116 passed (116)`. </details> ## Acceptance notes - **The tenant-isolation column is not judged on the preview.** driver-sql refuses a reference to it on either side, reading which column it is off the object schema (`resolveTenantFieldName`). The preview is handed a field's declared shape only (`sourceFieldMeta`), so `{ label: { $eq: { $field: 'organization_id' } } }` is still compared on the preview (measured: native 400, preview count 2). Closing it needs the tenant column handed to the service, a change to the exported `AnalyticsServiceConfig` shape, which is outside this card's surface; raised in the report as an open question rather than guessed by name. - The refusal wording on the preview is the preview's own sentence (`code` and `status` match the live faces; the pins assert those, not the prose). ## Verification Read first: `packages/services/service-analytics/src/preview-field-reference.ts` (the refusal walk and the truth table), the `matchesWhere` hunk in `preview-evaluator.ts`, then the integration block of the test file. Two-minute check: `pnpm --filter @objectstack/service-analytics exec vitest run --maxWorkers=2 src/__tests__/preview-field-reference-36677.test.ts` prints `Tests 116 passed (116)`. --- _Generated by [Claude Code](https://claude.ai/code/session_011y7As92T28dA9wc7wtu3iE)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 9e6533b commit 59a53a6

4 files changed

Lines changed: 546 additions & 2 deletions

File tree

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
---
2+
'@objectstack/service-analytics': patch
3+
---
4+
5+
Clause-②: no
6+
Metadata-protocol: none
7+
8+
The analytics draft preview (`queryDataset` with `previewDrafts`, the face Studio's preview mode reads) now resolves a `{ $field }` comparand the way the published dataset does. A comparison between two scalar columns of the row (`{ label: { $eq: { $field: 'alias' } } }`, and `$ne` / `$gt` / `$gte` / `$lt` / `$lte`) compares the two columns, with the same answer for empty values as the live faces (both empty is equal). A reference the live faces refuse is refused with their `INVALID_FILTER` / 400: a multi-value, JSON, file or formula column on either side, two columns of different comparison classes, an undeclared column, a dotted path, and a reference in an `$in` / `$nin` list or under a text-pattern operator. Before, the preview compared the row value with the reference object as text, so every field-to-field filter showed a wrong count with no error, and the count changed at publish.
9+
10+
One shape is refused on the preview although the published dataset serves it: a reference with an `addDays` offset (`{ $field: 'due_on', addDays: 3 }`). The preview refuses it by name rather than evaluate the day shift differently; publish the draft to chart it.
Lines changed: 281 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,281 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [#36677] The draft preview answers a `{ $field }` comparand as the live
5+
* faces of the dataset door answer it: a scalar-to-scalar reference compares
6+
* the row's two columns, and a reference the live faces refuse is refused with
7+
* their `INVALID_FILTER` / 400.
8+
*
9+
* Measured on `origin/main` (`e845656d`) before the change, through
10+
* `queryDataset` on the production composition below (counts over the six
11+
* rows of {@link ROWS}):
12+
*
13+
* | filter | native | ObjectQL | preview |
14+
* |---|---|---|---|
15+
* | `label $eq {$field:'alias'}` | 2 | 2 | 0 |
16+
* | `label $ne {$field:'alias'}` | 4 | 4 | 6 |
17+
* | `label $gt {$field:'alias'}` | 1 | 1 | 4 |
18+
* | `label $eq {$field:'tags'}` (and `picks`, a `select` declared `multiple`) | 400 | 400 | 0 |
19+
* | `label $ne {$field:'tags'}` (and `picks`) | 400 | 400 | 6 |
20+
* | `label $eq {$field:'amount'}` (cross-class) | 400 | 400 | 0 |
21+
* | `label $in [{$field:'alias'}]` | 400 | 400 | 0 |
22+
*
23+
* The preview compared the row value with the reference OBJECT, as text.
24+
*
25+
* What these pins hold:
26+
* - the scalar rows, under all six operators, `$not` and `$or`: the preview's
27+
* count EQUALS the native strategy's, and both equal the declared count;
28+
* - the multi-value rows, and every other reference the live faces refuse:
29+
* the preview refuses with the same `code` and `status`;
30+
* - the shared cross-field corpus (`@objectstack/driver-sql`'s
31+
* `CROSS_FIELD_CASES`, which holds `@objectstack/formula`'s evaluator and the
32+
* SQL compile to the same rows) row for row at the preview's filters, and
33+
* its refusal table refused, but for the two tenant-column rows the preview
34+
* does not judge (`preview-field-reference.ts`);
35+
* - the one shape the preview refuses where a live face serves it: an
36+
* `addDays` offset reference, refused by name over the corpus's offset
37+
* cases, while the same corpus's bare-reference controls are served with its
38+
* rows.
39+
*/
40+
41+
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
42+
import { ObjectQL } from '@objectstack/objectql';
43+
import {
44+
CROSS_FIELD_CASES,
45+
CROSS_FIELD_OBJECT_FIELDS,
46+
CROSS_FIELD_OFFSET_CASES,
47+
CROSS_FIELD_OFFSET_OBJECT_FIELDS,
48+
CROSS_FIELD_OFFSET_ROWS,
49+
CROSS_FIELD_REFUSALS,
50+
CROSS_FIELD_ROWS,
51+
SqlDriver,
52+
} from '@objectstack/driver-sql';
53+
import type { ValueShapeFieldDef } from '@objectstack/spec/data';
54+
import { DatasetSchema, type Dataset } from '@objectstack/spec/ui';
55+
import type { AnalyticsQuery } from '@objectstack/spec/contracts';
56+
import type { AnalyticsService } from '../analytics-service.js';
57+
import { AnalyticsServicePlugin } from '../plugin.js';
58+
import { lowerPreviewRowFilters } from '../preview-evaluator.js';
59+
import { PREVIEW_FIELD_REFERENCE_OPERATORS } from '../preview-field-reference.js';
60+
import { CROSS_FIELD_COMPARISON_OPERATORS } from '../comparand-shape.js';
61+
import { installDefaultOrganization } from './default-organization.testkit.js';
62+
63+
const OBJECT = 'os36677_item';
64+
65+
/** One row per cell of the comparison's truth table, on a text pair and a numeric pair. */
66+
const ROWS = [
67+
{ id: 'r1', label: 'b', alias: 'a', amount: 10, budget: 5, tags: ['b'], picks: ['b'] }, // target > referent
68+
{ id: 'r2', label: 'a', alias: 'b', amount: 3, budget: 5, tags: ['a'], picks: ['a'] }, // target < referent
69+
{ id: 'r3', label: 'm', alias: 'm', amount: 7, budget: 7, tags: ['m'], picks: ['m'] }, // equal
70+
{ id: 'r4', label: null, alias: 'm', amount: null, budget: 5, tags: null, picks: null }, // target empty
71+
{ id: 'r5', label: 'w', alias: null, amount: 10, budget: null, tags: ['w'], picks: ['w'] }, // referent empty
72+
{ id: 'r6', label: null, alias: null, amount: null, budget: null, tags: null, picks: null }, // both empty
73+
];
74+
75+
const DATASET = DatasetSchema.parse({
76+
name: 'os36677_items',
77+
label: 'Items',
78+
object: OBJECT,
79+
dimensions: [{ name: 'label', field: 'label', type: 'string' }],
80+
measures: [{ name: 'cnt', aggregate: 'count' }],
81+
}) as Dataset;
82+
83+
/** A `'protocol'` service answering one pending seed draft of the same rows, which routes `previewDrafts` onto the draft preview. */
84+
const pendingSeedProtocol = {
85+
getMetaItems: async () => [{ name: 'os36677_seed', object: OBJECT }],
86+
getMetaItem: async () => ({ item: { records: ROWS } }),
87+
};
88+
89+
const quiet = { debug() {}, info() {}, warn() {}, error() {}, trace() {}, fatal() {}, child() { return quiet; } };
90+
91+
type Face = 'native' | 'objectql' | 'preview';
92+
const FACES: readonly Face[] = ['native', 'objectql', 'preview'];
93+
94+
/** The scalar rows: the filter and the count the native strategy answers (measured, see the header). */
95+
const SCALAR: Array<[Record<string, unknown>, number]> = [
96+
[{ label: { $eq: { $field: 'alias' } } }, 2],
97+
[{ label: { $ne: { $field: 'alias' } } }, 4],
98+
[{ label: { $gt: { $field: 'alias' } } }, 1],
99+
[{ label: { $gte: { $field: 'alias' } } }, 2],
100+
[{ label: { $lt: { $field: 'alias' } } }, 1],
101+
[{ label: { $lte: { $field: 'alias' } } }, 2],
102+
[{ amount: { $eq: { $field: 'budget' } } }, 2],
103+
[{ amount: { $ne: { $field: 'budget' } } }, 4],
104+
[{ amount: { $gt: { $field: 'budget' } } }, 1],
105+
[{ $not: { label: { $eq: { $field: 'alias' } } } }, 4],
106+
[{ $or: [{ label: { $gt: { $field: 'alias' } } }, { label: 'w' }] }, 2],
107+
[{ label: { $eq: { $field: 'label' } } }, 6],
108+
];
109+
110+
/** References every live face refuses `INVALID_FILTER` / 400. */
111+
const REFUSED: Record<string, unknown>[] = [
112+
{ label: { $eq: { $field: 'tags' } } },
113+
{ label: { $ne: { $field: 'tags' } } },
114+
{ label: { $eq: { $field: 'picks' } } },
115+
{ label: { $ne: { $field: 'picks' } } },
116+
{ label: { $gt: { $field: 'tags' } } },
117+
{ tags: { $eq: { $field: 'label' } } },
118+
{ label: { $eq: { $field: 'amount' } } },
119+
{ label: { $eq: { $field: 'nope' } } },
120+
{ label: { $eq: { $field: 'account.name' } } },
121+
{ label: { $in: [{ $field: 'alias' }] } },
122+
{ label: { $contains: { $field: 'alias' } } },
123+
{ amount: { $eq: { $field: 'budget', addDays: 1 } } },
124+
];
125+
126+
describe('[#36677] the draft preview resolves a { $field } comparand as the live faces do', () => {
127+
let engine: ObjectQL;
128+
const services: Partial<Record<'native' | 'objectql', AnalyticsService>> = {};
129+
130+
const query = (face: Face, runtimeFilter: Record<string, unknown>) =>
131+
services[face === 'preview' ? 'objectql' : face]!.queryDataset(
132+
DATASET,
133+
{ measures: ['cnt'], runtimeFilter } as never,
134+
undefined,
135+
face === 'preview' ? { previewDrafts: true } : undefined,
136+
) as Promise<{ rows: Array<Record<string, unknown>> }>;
137+
138+
const countOf = async (face: Face, filter: Record<string, unknown>) => Number((await query(face, filter)).rows[0]?.cnt ?? 0);
139+
140+
const refusalOf = async (face: Face, filter: Record<string, unknown>) => {
141+
try {
142+
await query(face, filter);
143+
} catch (e) {
144+
const { code, status } = e as { code?: unknown; status?: unknown };
145+
return { code, status };
146+
}
147+
return 'served';
148+
};
149+
150+
beforeAll(async () => {
151+
const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true } as never);
152+
engine = new ObjectQL({ logger: quiet } as never);
153+
engine.registerDriver(driver as never, true);
154+
await engine.init();
155+
engine.registry.registerObject({
156+
name: OBJECT,
157+
label: 'Item',
158+
fields: {
159+
label: { name: 'label', type: 'text' },
160+
alias: { name: 'alias', type: 'text' },
161+
amount: { name: 'amount', type: 'number' },
162+
budget: { name: 'budget', type: 'number' },
163+
tags: { name: 'tags', type: 'tags' },
164+
picks: { name: 'picks', type: 'select', multiple: true, options: ['a', 'b', 'm', 'w'].map((value) => ({ label: value, value })) },
165+
},
166+
} as never);
167+
await engine.syncSchemas();
168+
await installDefaultOrganization(engine as never);
169+
for (const row of ROWS) await engine.insert(OBJECT, { ...row } as never);
170+
171+
for (const [face, caps] of [
172+
['native', undefined],
173+
['objectql', () => ({ nativeSql: false, objectqlAggregate: true, inMemory: false })],
174+
] as const) {
175+
const registered: Record<string, unknown> = {};
176+
const provided: Record<string, unknown> = { data: engine, protocol: pendingSeedProtocol };
177+
await new AnalyticsServicePlugin({ ...(caps ? { queryCapabilities: caps } : {}) } as never).init({
178+
getService: (name: string) => provided[name] ?? registered[name],
179+
registerService: (name: string, svc: unknown) => { registered[name] = svc; },
180+
replaceService: (name: string, svc: unknown) => { registered[name] = svc; },
181+
hook: () => {},
182+
logger: quiet,
183+
} as never);
184+
services[face] = registered.analytics as AnalyticsService;
185+
}
186+
});
187+
188+
afterAll(async () => {
189+
try { await engine?.destroy(); } catch { /* noop */ }
190+
});
191+
192+
it('CONTROL: the fixture is served unfiltered on every face', async () => {
193+
for (const face of FACES) expect(await countOf(face, {}), face).toBe(ROWS.length);
194+
});
195+
196+
for (const [filter, count] of SCALAR) {
197+
it(`${JSON.stringify(filter)} → ${count}, the preview equal to the native strategy`, async () => {
198+
const [native, objectql, preview] = await Promise.all(FACES.map((face) => countOf(face, filter)));
199+
expect({ native, objectql, preview }).toEqual({ native: count, objectql: count, preview: count });
200+
});
201+
}
202+
203+
for (const filter of REFUSED) {
204+
it(`${JSON.stringify(filter)} is refused INVALID_FILTER / 400 on every face`, async () => {
205+
const answers = await Promise.all(FACES.map((face) => refusalOf(face, filter)));
206+
const refused = { code: 'INVALID_FILTER', status: 400 };
207+
expect(answers).toEqual([refused, refused, refused]);
208+
});
209+
}
210+
});
211+
212+
// ─────────────────────────────────────────────────────────────────────────────
213+
214+
/** The preview's row filters for `where`, with the corpus fixture's declarations. */
215+
function previewFiltersOver(fields: Record<string, Record<string, unknown>>) {
216+
const declaredType = (field: string) => (typeof fields[field]?.type === 'string' ? (fields[field]!.type as string) : undefined);
217+
const declaredShape = (field: string): ValueShapeFieldDef | undefined => {
218+
const type = declaredType(field);
219+
return type === undefined ? undefined : { type, multiple: fields[field]!.multiple === true };
220+
};
221+
const CUBE = { name: 'c', sql: 'x', measures: {}, dimensions: {} } as never;
222+
return (where: unknown) =>
223+
lowerPreviewRowFilters({ cube: 'c', measures: [], where } as unknown as AnalyticsQuery, CUBE, declaredType, undefined, declaredShape);
224+
}
225+
226+
/** Does any `{ $field }` in `node` carry an `addDays` offset? */
227+
function carriesOffset(node: unknown): boolean {
228+
if (Array.isArray(node)) return node.some(carriesOffset);
229+
if (node === null || typeof node !== 'object') return false;
230+
const record = node as Record<string, unknown>;
231+
if (typeof record.$field === 'string' && record.addDays !== undefined) return true;
232+
return Object.values(record).some(carriesOffset);
233+
}
234+
235+
describe('[#36677] the preview filters, measured against the shared cross-field corpus', () => {
236+
const filtersOf = previewFiltersOver(CROSS_FIELD_OBJECT_FIELDS);
237+
238+
it('evaluates exactly the six operators the live faces compile a reference under', () => {
239+
expect([...PREVIEW_FIELD_REFERENCE_OPERATORS.keys()].sort()).toEqual([...CROSS_FIELD_COMPARISON_OPERATORS].sort());
240+
});
241+
242+
it.each(CROSS_FIELD_CASES.map((c) => [c.name, c] as const))('%s', (_name, c) => {
243+
const { matches } = filtersOf(c.filter);
244+
const ids = CROSS_FIELD_ROWS.filter((row) => matches({ ...row })).map((row) => row.id);
245+
expect(ids).toEqual(c.expected);
246+
});
247+
248+
/** The two rows the preview cannot judge: it is handed no tenant-column fact (see `preview-field-reference.ts`). */
249+
const TENANT_ROWS = new Set([
250+
'the tenant-isolation column is refused as the REFERENT',
251+
'the tenant-isolation column is refused as the TARGET',
252+
]);
253+
254+
it('the tenant rows are present in the corpus, so the exclusion below names real rows', () => {
255+
expect(CROSS_FIELD_REFUSALS.filter((c) => TENANT_ROWS.has(c.name))).toHaveLength(TENANT_ROWS.size);
256+
});
257+
258+
it.each(CROSS_FIELD_REFUSALS.filter((c) => !TENANT_ROWS.has(c.name)).map((c) => [c.name, c] as const))('%s', (_name, c) => {
259+
expect(() => filtersOf(c.filter)).toThrow(expect.objectContaining({ code: 'INVALID_FILTER', status: 400 }));
260+
});
261+
262+
const offsetFiltersOf = previewFiltersOver(CROSS_FIELD_OFFSET_OBJECT_FIELDS);
263+
const OFFSET = CROSS_FIELD_OFFSET_CASES.filter((c) => carriesOffset(c.filter));
264+
const BARE = CROSS_FIELD_OFFSET_CASES.filter((c) => !carriesOffset(c.filter));
265+
266+
it('the offset corpus carries both kinds of row, so neither table below is empty', () => {
267+
expect({ offset: OFFSET.length > 0, bare: BARE.length > 0 }).toEqual({ offset: true, bare: true });
268+
});
269+
270+
it.each(OFFSET.map((c) => [c.name, c] as const))('an offset reference is refused by name: %s', (_name, c) => {
271+
expect(() => offsetFiltersOf(c.filter)).toThrow(
272+
expect.objectContaining({ code: 'INVALID_FILTER', status: 400, message: expect.stringContaining('addDays offset') }),
273+
);
274+
});
275+
276+
it.each(BARE.map((c) => [c.name, c] as const))('a bare reference on the offset fixture is served: %s', (_name, c) => {
277+
const { matches } = offsetFiltersOf(c.filter);
278+
const ids = CROSS_FIELD_OFFSET_ROWS.filter((row) => matches({ ...row })).map((row) => row.id);
279+
expect(ids).toEqual(c.expected);
280+
});
281+
});

‎packages/services/service-analytics/src/preview-evaluator.ts‎

Lines changed: 32 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,8 @@
99
//
1010
// Scope (deliberately the dataset-query subset, not a general engine):
1111
// • Mongo-style `where` filters ($eq implicit, $ne/$gt/$gte/$lt/$lte/
12-
// $between/$in/$nin/$contains/$notContains/$null, $and/$or/$not)
12+
// $between/$in/$nin/$contains/$notContains/$null, $and/$or/$not), and
13+
// a `{ $field }` comparand under the six scalar operators (#36677)
1314
// • timeDimensions date-range filtering + granularity bucketing
1415
// (day/week/month/quarter/year)
1516
// • group-by dimensions; count / count_distinct / sum / avg / min / max
@@ -62,6 +63,14 @@ import type { DurationMeasureSpec } from './strategies/types.js';
6263
import { invalidFilterError, normalizeWhereComparands } from './strategies/filter-normalizer.js';
6364
import { comparisonColumnClass, refusePreviewJsonColumnComparisons } from './json-column-comparison-refusal.js';
6465
import { isJsonStoredShape } from './contains-membership-sql.js';
66+
// [#36677] A `{ $field }` comparand: resolved against the row's own column
67+
// under the six scalar operators, and refused where the live faces refuse it.
68+
import { isFieldReference } from './comparand-shape.js';
69+
import {
70+
assertPreviewFieldReferencesEvaluable,
71+
fieldReferencePredicate,
72+
refusePreviewFieldReferenceClasses,
73+
} from './preview-field-reference.js';
6574
import type { AnalyticsQuery, AnalyticsResult } from '@objectstack/spec/contracts';
6675
import { emptyGroupValueFor, lowerFilterCondition, type Cube, type FilterLoweringOptions, type ValueShapeFieldDef } from '@objectstack/spec/data';
6776

@@ -404,6 +413,14 @@ export function matchesWhere(
404413
} else if (cond !== null && typeof cond === 'object' && !Array.isArray(cond)) {
405414
const shape = shapeOf?.(key);
406415
for (const [op, expected] of Object.entries(cond as Row)) {
416+
// [#36677] A `{ $field }` comparand compares the row's two columns.
417+
// It used to reach {@link matchOp} as a literal and be compared as the
418+
// text `[object Object]`. See `preview-field-reference.ts`.
419+
const byReference = fieldReferencePredicate(key, op, expected);
420+
if (byReference) {
421+
if (!byReference(row[key], row[(expected as { $field: string }).$field], compare)) return false;
422+
continue;
423+
}
407424
if (!matchOp(row[key], op, expected, key, shape)) return false;
408425
}
409426
} else if (!(row[key] === cond || String(row[key]) === String(cond))) {
@@ -781,7 +798,9 @@ function previewStorageComparands(node: Row | undefined, kindOf: PreviewTemporal
781798
} else {
782799
out[key] = Object.fromEntries(Object.entries(cond as Row).map(([op, expected]) => [
783800
op,
784-
STORAGE_FORM_OPERATORS.has(op) && expected != null ? storageForm(expected, kind) : expected,
801+
// [#36677] A `{ $field }` comparand names a column, not a value: the
802+
// referent is read from the row, which is in its storage form already.
803+
STORAGE_FORM_OPERATORS.has(op) && expected != null && !isFieldReference(expected) ? storageForm(expected, kind) : expected,
785804
]));
786805
}
787806
}
@@ -903,6 +922,10 @@ export function lowerPreviewRowFilters(
903922
// text `'null'` or `'undefined'` — onto every driver's answer.
904923
const lowered = lowerFilterCondition(normalizeWhereComparands(query.where), lowering);
905924
assertPreviewCanEvaluate(lowered);
925+
// [#36677] …and every `{ $field }` comparand where this face evaluates one
926+
// (the six scalar operators, a same-object column, no offset), refused in
927+
// the live faces' positions otherwise. Row-independent, so before any row.
928+
assertPreviewFieldReferencesEvaluable(lowered);
906929
// [#36168] …then a scalar comparison on a field declared multi-valued or
907930
// JSON-stored, refused as the live faces refuse it: a drafted row holds the
908931
// list, which never equals a scalar, so `$in` matched no row and `$nin`
@@ -915,6 +938,13 @@ export function lowerPreviewRowFilters(
915938
const classOf = (column: string) => comparisonColumnClass(declaredShape?.(column), storedJsonClass?.(column));
916939
refusePreviewJsonColumnComparisons(lowered, classOf, (member) => whereColumns?.[member] ?? member);
917940
}
941+
// [#36677] …then each `{ $field }` comparison's two columns, as the live
942+
// faces judge them: both declared, one comparison class
943+
// (`crossFieldComparisonVerdict`). A host that names no declaration is not
944+
// judged, and its references are compared type-blind.
945+
if (declaredShape) {
946+
refusePreviewFieldReferenceClasses(lowered, (member) => declaredShape(whereColumns?.[member] ?? member), declaredShape);
947+
}
918948
// [#21505] …then each value comparison in the temporal STORAGE form, the
919949
// comparand here and the row value at the match (see {@link previewTemporalKind}).
920950
const whereKindOf = previewTemporalKind(whereType);

0 commit comments

Comments
 (0)