Skip to content

Commit 3a02407

Browse files
committed
test(service-analytics): pin the plain-group refusal over a formula on every analytics face
Claude-Session: https://claude.ai/code/session_016WV4cyTehJsfYGVMzcXLJD Co-authored-by: Claude <noreply@anthropic.com>
1 parent 6e07b40 commit 3a02407

3 files changed

Lines changed: 111 additions & 2 deletions

File tree

‎packages/services/service-analytics/src/__tests__/fallback-delegate-date-bucket-type.test.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,9 @@
2727
* capturing a pre-registered analytics service under a `queryCapabilities`
2828
* override with `objectqlAggregate: false`.
2929
*
30+
* [#29304] …and a plain group over the `formula`, which the engine face now
31+
* refuses at `groupBy.0`: the delegate reads no field type either.
32+
*
3033
* The delegate here is a recording double: the pin is the service's face (the
3134
* refusal, and that the delegate was never called), not the delegate's fold.
3235
*/
@@ -182,6 +185,8 @@ describe('[#29364] the fallback face refuses a date bucket over a field that is
182185
['a formula by month', bucket(['calc', 'month']), 'calc', 'groupBy.0.dateGranularity'],
183186
['a text column by month', bucket(['region', 'month']), 'region', 'groupBy.0.dateGranularity'],
184187
['a formula after a datetime bucket', bucket(['closed_at', 'year'], ['calc', 'month']), 'calc', 'groupBy.1.dateGranularity'],
188+
// [#29304] A plain group over the formula, no bucket.
189+
['a formula, grouped plainly', { cube: CUBE, measures: [`${CUBE}.amount_sum`], dimensions: [`${CUBE}.calc`] }, 'calc', 'groupBy.0'],
185190
];
186191

187192
for (const [faceLabel, makeFace] of FACES) {

‎packages/services/service-analytics/src/__tests__/objectql-echo-non-date-bucket.test.ts‎

Lines changed: 65 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,14 +27,21 @@
2727
* from the SQL driver's missing-column backstop: both now answer the engine's
2828
* virtual-field refusal, field for field.
2929
*
30+
* [#29304] …and a PLAIN group over a `formula`, which the native strategy
31+
* compiled into `GROUP BY calc` and ran (`DATABASE_ERROR` / 500), the ObjectQL
32+
* strategy handed the SQL driver's missing-column backstop, and the dry run
33+
* rendered on both compositions (measured on `origin/main` `447226b2`). The
34+
* native strategy now declines a grouped dimension over a virtual field, so
35+
* the query and the dry run both answer the engine's plain-group refusal.
36+
*
3037
* It now judges the keys `execute()` hands the engine with the service's one
3138
* reading of it (`dataset-date-bucket-door.ts`, #28852), after the `dateRange`
3239
* read and the column-asked-twice door as `query()` refuses, so it answers the
3340
* query's refusal field for field. A date and a datetime bucket still render
3441
* byte for byte (pinned below).
3542
*/
3643

37-
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
44+
import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest';
3845
import { ObjectQL } from '@objectstack/objectql';
3946
import { SqlDriver } from '@objectstack/driver-sql';
4047
import type { Cube } from '@objectstack/spec/data';
@@ -58,6 +65,8 @@ const CUBES = [
5865
// A time dimension over a text column, declaring one granularity: asked
5966
// raw, it is bucketed by that granularity (`withDeclaredGranularityDefaults`).
6067
region_month: { type: 'time', sql: 'region', label: 'Region month', granularities: ['month'] },
68+
// [#29304] A string dimension over the formula, asked raw: a plain group.
69+
calc_label: { type: 'string', sql: 'calc', label: 'Calc label' },
6170
},
6271
},
6372
] as unknown as Cube[];
@@ -91,7 +100,15 @@ describe('[#28977] the /analytics/sql dry run refuses a date bucket over a colum
91100
engine = new ObjectQL({ logger: quiet } as never);
92101
engine.registerDriver(driver as never, true);
93102
await engine.init();
94-
engine.registry.registerObject({ name: ACCOUNT, label: 'Account', fields: { name: { name: 'name', type: 'text' } } } as never);
103+
engine.registry.registerObject({
104+
name: ACCOUNT,
105+
label: 'Account',
106+
fields: {
107+
name: { name: 'name', type: 'text' },
108+
// [#29304] A formula on the related object, read through `account.`.
109+
name_calc: { name: 'name_calc', type: 'formula', expression: 'name', returnType: 'text' },
110+
},
111+
} as never);
95112
engine.registry.registerObject({
96113
name: DEAL,
97114
label: 'Deal',
@@ -181,6 +198,52 @@ describe('[#28977] the /analytics/sql dry run refuses a date bucket over a colum
181198
expect(asSql, 'the dry run vs the query').toEqual(asQuery);
182199
});
183200

201+
/** The engine's plain-group refusal of the formula `field` on `object`, at `path`. */
202+
const plainGroupRefusal = (object: string, field: string, path: string) => ({
203+
message:
204+
`aggregate('${object}'): ${path} groups by '${field}', but '${field}' is a formula field — its value is computed `
205+
+ 'on read and never stored, so no driver materialises a column to group by. The query was NOT run. Denormalise '
206+
+ `the value onto '${object}' (a stored field, written when the source changes) and group by that. A formula `
207+
+ 'field is virtual: with no column behind it the group key reached the driver as a column that does not exist, '
208+
+ 'and an engine that aggregates in memory put every row into one null group while the answer looked served.',
209+
code: 'INVALID_FIELD', status: 400, httpStatus: 400,
210+
object, param: 'groupBy', path, field, fields: [field],
211+
});
212+
213+
it.each<[string, Query, [object: string, field: string, path: string]]>([
214+
['an inferred dimension', onObject({ dimensions: ['calc'] }), [DEAL, 'calc', 'groupBy.0']],
215+
['after a stored dimension', onObject({ dimensions: ['region', 'calc'] }), [DEAL, 'calc', 'groupBy.1']],
216+
["a cube dimension's sql", onCube({ dimensions: ['calc_label'] }), [DEAL, 'calc', 'groupBy.0']],
217+
// The cross-object path's FK-resolve aggregate on the related object
218+
// (`groupBy: ['id', attr]`): the engine's position there, judged by the
219+
// service before the related object is read.
220+
["a related object's formula through 'account.'", onObject({ dimensions: ['account.name_calc'] }), [ACCOUNT, 'name_calc', 'groupBy.1']],
221+
])('[#29304] refuses a plain group over a formula (%s) on the query and the dry run alike, where native answered 500 and the dry run rendered GROUP BY calc', async (_label, query, expected) => {
222+
const { asQuery, asSql } = await bothRefusals(query);
223+
expect(asQuery).toEqual(plainGroupRefusal(...expected));
224+
expect(asSql, 'the dry run vs the query').toEqual(asQuery);
225+
});
226+
227+
it('[#29304] routes only a grouped formula off the native strategy: a stored dimension and a measure-only query stay native', async () => {
228+
const aggregate = vi.spyOn(engine, 'aggregate');
229+
try {
230+
// The default composition answers both on the native strategy, which runs
231+
// raw SQL and never calls `engine.aggregate`.
232+
for (const query of [onObject({ dimensions: ['region'] }), onObject({}), onCube({ dimensions: ['region'] })]) {
233+
const label = JSON.stringify(query);
234+
const result = await analytics.query({ ...query } as never);
235+
expect(result.rows, label).toHaveLength(1);
236+
expect(result.sql, label).toContain('COALESCE(SUM(amount), 0)');
237+
}
238+
expect(aggregate, 'native: no engine aggregate').not.toHaveBeenCalled();
239+
// A grouped formula declines to the ObjectQL strategy, whose engine refuses it.
240+
await expect(analytics.query({ ...onObject({ dimensions: ['calc'] }) } as never)).rejects.toMatchObject({ code: 'INVALID_FIELD', path: 'groupBy.0' });
241+
expect(aggregate, 'declined: the engine judged it').toHaveBeenCalledTimes(1);
242+
} finally {
243+
aggregate.mockRestore();
244+
}
245+
});
246+
184247
it.each<[string, Query, string]>([
185248
["beside a cross-object 'account.name' (its FK column first)", onObject({ dimensions: ['account.name'], timeDimensions: [td('region', 'month')] }), 'groupBy.1.dateGranularity'],
186249
['after a raw date column and a datetime bucket', onObject({ dimensions: ['closed_on'], timeDimensions: [td('closed_at', 'month'), td('region', 'month')] }), 'groupBy.2.dateGranularity'],

‎packages/services/service-analytics/src/__tests__/preview-date-bucket-type.test.ts‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,12 @@
3232
* where the live strategy lowers them, so an unrecognised `dateRange` beside
3333
* either fault is refused about the `dateRange` on every face; the preview
3434
* answered the door's refusal.
35+
*
36+
* [#29304] …and a PLAIN dimension over a `formula` (`returnType` `date` or
37+
* `text`), measured on `origin/main` `447226b2`: native `DATABASE_ERROR` /
38+
* 500, ObjectQL the SQL driver's missing-column backstop (400, no `path`), the
39+
* preview one `null` group holding the total. Every face now answers the
40+
* engine's plain-group refusal at `groupBy.N`, field for field.
3541
*/
3642

3743
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
@@ -64,6 +70,7 @@ const DATASET = DatasetSchema.parse({
6470
{ name: 'calc', field: 'calc', type: 'date' },
6571
{ name: 'region_month', field: 'region', type: 'date', dateGranularity: 'month' },
6672
{ name: 'calc_month', field: 'calc', type: 'date', dateGranularity: 'month' },
73+
{ name: 'calc_s', field: 'calc_s', type: 'string' },
6774
],
6875
measures: [{ name: 'total', aggregate: 'sum', field: 'amount' }],
6976
});
@@ -111,6 +118,8 @@ describe('[#28852] a date bucket over a column that is not a date, on every face
111118
opened_time: { name: 'opened_time', type: 'time' },
112119
// A formula the table stores no column for.
113120
calc: { name: 'calc', type: 'formula', expression: 'closed_on', returnType: 'date' },
121+
// [#29304] …and one whose result is text.
122+
calc_s: { name: 'calc_s', type: 'formula', expression: 'region', returnType: 'text' },
114123
},
115124
} as never);
116125
await engine.syncSchemas();
@@ -216,6 +225,38 @@ describe('[#28852] a date bucket over a column that is not a date, on every face
216225
expect(refusal).toMatchObject({ path: 'groupBy.0.dateGranularity', field: 'calc', fields: ['calc'] });
217226
});
218227

228+
it.each([
229+
['date', 'calc'],
230+
['text', 'calc_s'],
231+
])('[#29304] refuses a plain dimension over a formula (returnType %s) with the engine\'s refusal on every face, where native answered 500, ObjectQL the driver backstop, and the preview one null group', async (_label, field) => {
232+
const refusal = await refusedAlike({ dimensions: [field], measures: ['total'] });
233+
expect(refusal).toEqual({
234+
message:
235+
`aggregate('${OBJECT}'): groupBy.0 groups by '${field}', but '${field}' is a formula field — its value is `
236+
+ 'computed on read and never stored, so no driver materialises a column to group by. The query was NOT run. '
237+
+ `Denormalise the value onto '${OBJECT}' (a stored field, written when the source changes) and group by that. `
238+
+ 'A formula field is virtual: with no column behind it the group key reached the driver as a column that does '
239+
+ 'not exist, and an engine that aggregates in memory put every row into one null group while the answer looked '
240+
+ 'served.',
241+
code: 'INVALID_FIELD', status: 400, httpStatus: 400,
242+
object: OBJECT, param: 'groupBy', path: 'groupBy.0', field, fields: [field],
243+
});
244+
});
245+
246+
it('[#29304] names the position of a plain formula dimension after a stored one', async () => {
247+
const refusal = await refusedAlike({ dimensions: ['region', 'calc_s'], measures: ['total'] });
248+
expect(refusal).toMatchObject({ path: 'groupBy.1', field: 'calc_s', fields: ['calc_s'] });
249+
});
250+
251+
it('[#29304] still serves a plain dimension over a stored column alike on every face', async () => {
252+
for (const face of FACES) {
253+
const result = await ask(face, { dimensions: ['region'], measures: ['total'] });
254+
const rows = (result.rows as Array<Record<string, unknown>>).map((r) => ({ ...r, total: Number(r.total) }));
255+
expect(rows.sort((a, b) => String(a.region).localeCompare(String(b.region))), face)
256+
.toEqual([{ region: 'amer', total: 100 }, { region: 'emea', total: 50 }]);
257+
}
258+
});
259+
219260
/** Every face refuses `selection` with one refusal of `code`, message included. */
220261
const refusedAlikeWith = async (selection: Selection, code: string) => {
221262
const refusals: Array<Record<string, unknown>> = [];

0 commit comments

Comments
 (0)