Skip to content

Commit 990d063

Browse files
docs(data): a structured groupBy alias is the row key on the SQL face too (#35051)
<!-- claude-projects-attribution: {"github_login":"os-support-ai"} --> _Requested by **Yibo Wang** · [project thread](https://claude.ai/code/project/chan_01BVUyyPie8gHwoPM18iABwB?thread=cmsg_01BVUyyPie8gHwoPM18iABwBLW6dHPW6sSheA32XPKZzPV)_ Fixes #35015 Clause-②: no Metadata-protocol: none ## 维护者速读 - 改了什么:两页文档各改一句。`queries.mdx` 原来说「SQL 驱动忽略结构化 groupBy 的 `alias`,结果列永远叫字段名」;`query-syntax.mdx` 原来说「`alias` 只在内存路径生效」。现在两处都改为:下推到数据库和内存兜底两条路径上,结果列都叫 `alias`。另加一个 driver-sql 测试文件,在每种方言上钉住结果行的键。 - 为什么改:在 SQLite 和 PostgreSQL 16 上实测 `engine.aggregate`,下推和内存兜底两条路径都返回 `alias` 作为列名。驱动自 #6401 起就这样做,旧文档是过期的。查询技能 `aggregation.md` 写的是对的,没有改动。 - 风险与回滚:只改文档,加了一个测试文件,没有产品代码,也没有发布面;回滚就是还原这个 PR。 - 先看:`content/docs/data-modeling/queries.mdx` 第 714–718 行,`packages/drivers/driver-sql/src/sql-driver-35015-groupby-alias-row-key.test.ts`,`content/docs/protocol/objectql/query-syntax.mdx` 第 1151 行。 - 两分钟验证:`pnpm --filter @objectstack/driver-sql exec vitest run src/sql-driver-35015-groupby-alias-row-key.test.ts`,预期 sqlite 4 条用例通过;设置 `OS_TEST_POSTGRES_URL` 时 PG 也是 4 条通过。 - 需要你做的:无,席位落地。 ## What changes - `content/docs/data-modeling/queries.mdx`, in the date-bucketing warn callout. The old paragraph said the SQL driver ignores a structured `groupBy` node's `alias` and "always projects the bucket under the **field name**". It now says the alias renames the projected column on both paths, that grouping still keys on the field, that the result is read under `alias ?? field`, and that `having` references that name. Once an alias is set, a `having` on the field name is refused. - `content/docs/protocol/objectql/query-syntax.mdx:1151`: "(or `alias`, on the in-memory path)" now reads "or under `alias` when the node sets one (pushed down or in memory alike)". This file joined the claim through amendment 6964093495. - `packages/drivers/driver-sql/src/sql-driver-35015-groupby-alias-row-key.test.ts` (new, test only). It runs on every `DIALECT_CELLS` cell and pins the exact key set of each row on the pushed-down face: - a quarter bucket with `alias: 'quarter'` yields keys `quarter,revenue`; - the unaliased control yields `closed_at,revenue`; - a plain alias `r` beside the bucket alias yields `quarter,r,revenue`. - The skill (`skills/objectstack-query/rules/aggregation.md`) is **unchanged**. Its text ("results are correct either way, including the column keys"; "Read the result under `alias ?? field`, and reference that same name from `having`") matches every measured arm. No eval case was added: the order asks for one only if the skill text changes. Because no `skills/**` file changed, this branch is cut from `origin/main` (6d2db1d), not from the head of #35012. It shares no file with #35012: `overlap-check` answered `VERDICT clean exit 0` against origin/main 367e324, with 0 PR heads sharing a file. ## Tests <details><summary>Phase 1 reading: engine.aggregate on a real SqlDriver, SQLite and live PostgreSQL 16.15</summary> The probe was a scratch script (not committed). It used `ObjectQL` plus `SqlDriver` against a `datetime` field. The driver's `aggregate` and `find` were wrapped to record which path the engine took. Every run exited 0. Four runs: `sqlite`, `sqlite` with `quarter` capability off, `pg`, and `pg` with `quarter` off. | case | sqlite | pg | keys (every arm) | |---|---|---|---| | bucket `alias: 'quarter'`, UTC | NATIVE | NATIVE | `quarter, revenue` | | same, `timezone: '+00:00'` | IN-MEMORY | IN-MEMORY | `quarter, revenue` | | same, `timezone: 'Asia/Taipei'` | IN-MEMORY | NATIVE (zoned) | `quarter, revenue` | | same, driver declares no `quarter` | IN-MEMORY | IN-MEMORY | `quarter, revenue` | | `having: { quarter: … }` | served, filtered | served, filtered | `quarter, revenue` | | `having: { closed_at: … }` with alias set | INVALID_FILTER / 400 | INVALID_FILTER / 400 | refused | | plain `{ field: 'region', alias: 'r' }` | NATIVE | NATIVE | `r, revenue` | | plain `r` + bucket `quarter`, `+00:00` | IN-MEMORY | IN-MEMORY | `r, quarter, revenue` | | no alias (control) | NATIVE | NATIVE | `closed_at, revenue` | Bucket values and sums were identical on every arm (`2025-Q1 = 30`, `2025-Q2 = 12`). The code lines that decide the key: - `packages/drivers/driver-sql/src/sql-driver-aggregation.ts:239`: `const outKey = g.alias ?? g.field`. It is used by the bucket projection (line 252) and the plain-field projection (line 276). - `packages/objectql/src/in-memory-aggregation.ts:194`: `g.alias ?? g.field`. - `packages/objectql/src/having-filter.ts:1126-1131`: `aggregatedRowColumns`, which builds the `having` namespace from `alias ?? field`. - The engine's fork is `packages/objectql/src/engine-delete-and-aggregate.ts:1431-1488` (`allStructuredSupported`, `tzRequiresInMemory`, `nativeAggregate`). </details> <details><summary>Pin and ablation</summary> The pin at head 0682686 ran with `OS_TEST_POSTGRES_URL` set to a local PostgreSQL 16 cluster. Result: `Test Files 1 passed (1)`, `Tests 8 passed | 1 skipped (9)`, `live postgres RAN`. The skipped one is the named live-mysql cell. Lock line: `VERDICT command-exit 0`. Ablation, after the fix was committed: - `scripts/ablation-replace.mjs` replaced `const outKey = g.alias ?? g.field;` with `const outKey = g.field /* ablated-35015 */;` in `sql-driver-aggregation.ts`. Anchor count went 1 → 0, blob 1e81807 → 524fc156d99c. - Result: `Tests 4 failed | 4 passed | 1 skipped`. The two alias cases failed on both sqlite and live postgres; the control and the capability case stayed green. - Restore: blob after restore 1e81807, equal to the HEAD blob; `git diff HEAD` is empty. The suite imports `../src/index.js`, so no `dist/` is involved. </details> <details><summary>Package suite and typecheck</summary> - `pnpm --filter @objectstack/driver-sql exec vitest run --maxWorkers=2` at 0682686: `Test Files 261 passed | 13 skipped (274)`, `Tests 4358 passed | 253 skipped (4611)`, `VERDICT command-exit 0`. - `pnpm --filter @objectstack/driver-sql typecheck`: exit 0. `tsc --listFiles` includes the new test file. </details> ## Acceptance notes - Claim 6963952530; amendment 6964093495 added `content/docs/protocol/objectql/query-syntax.mdx`. - Driver defect: none. The SQL face has honoured the alias since #6401. Existing pins on other faces and dialects: `sql-driver-13714-aggregate-alias-single-identifier.test.ts:228-239` (bucket alias, every cell); `sql-driver-aggregation-conformance.test.ts` (`groupByAlias` case, every cell); `sql-driver-33697-zoned-date-bucket.test.ts:181` (zoned PG bucket alias); `packages/objectql/src/in-memory-aggregation.test.ts:44-53` (in-memory `qtr`); `engine-aggregate-having-comparand-shape.test.ts:728` (`having` on the field name is refused once aliased). - `skip-changeset`: content/docs is not published, and `driver-sql` publishes only `dist`, which carries no test file. ## Verification - Local gates: `dispatch-gates --commands` derived 82 families, run at f7e7a14. 81 exited 0. `pnpm check:dual-build-cjs-loads` exited 3 (PREREQUISITE NOT MET, needs a full build), so it is NOT MEASURED locally and left to CI. `--ran` reconciliation: 82 accounted, 81 run, 1 NOT-MEASURED. - The head commit 0682686 changed only the type-import path in the new test file. These families were re-run at that head, all exit 0: `cross-package-test-inputs`, `test-source-alias`, `nul-bytes`, `undeclared-dep-imports`, `issue-citations`, `engine-double-contract`, `driver-conformance`, `tier-file-adoption`, `where-matcher`, `org-identifier`, `role-word`, `keyed-text-bounds`, `refd-timer-probe`, `objectql-double-limit`, `driver-memory-census`, `comment-mask-adoption`, `comment-mask-corpus`, `doc-authoring`, plus `check-skills-token-ratchet`. - The CI check-runs are cited in the report once they finish; this body does not wait for them. --- _Generated by [Claude Code](https://claude.ai/code/session_01WGufzfrh8TiPJf1i2kMSoa)_ 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01WGufzfrh8TiPJf1i2kMSoa <!-- signed: repo:objectstack#3 · os-support-ai · session_01WGufzfrh8TiPJf1i2kMSoa --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent eb7b09d commit 990d063

3 files changed

Lines changed: 109 additions & 4 deletions

File tree

‎content/docs/data-modeling/queries.mdx‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -711,9 +711,11 @@ Buckets are computed in **UTC**. A non-UTC reference timezone is only reachable
711711
route does not forward `timezone` to the engine, so a query sent over REST always
712712
buckets on UTC calendar boundaries.
713713

714-
The optional `alias` on a structured `groupBy` node is honoured only on the in-memory
715-
path. The SQL driver ignores it and always projects the bucket under the **field name**,
716-
so don't depend on the aliased key being present.
714+
The optional `alias` on a structured `groupBy` node renames the projected column on
715+
both paths: the SQL driver's pushed-down bucket and the in-memory fallback put the
716+
bucket under the **alias** (`alias ?? field`), and grouping still keys on the field.
717+
Read the result under that name, and reference it from `having`. Once an alias is set,
718+
a `having` on the field name is refused, because the row has no such column.
717719
</Callout>
718720

719721
---

‎content/docs/protocol/objectql/query-syntax.mdx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1148,7 +1148,7 @@ const rows = await engine.aggregate('opportunity', {
11481148

11491149
A `groupBy` entry may be an object carrying `dateGranularity`, which buckets a
11501150
`date`/`datetime` column into uniform periods. The bucketed value is projected under
1151-
the field name (or `alias`, on the in-memory path):
1151+
the field name, or under `alias` when the node sets one (pushed down or in memory alike):
11521152

11531153
```typescript
11541154
const revenueByMonth = await engine.aggregate('order', {
Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [#35015] The row key a structured `groupBy` node's `alias` produces on the
5+
* pushed-down SQL face: the alias, on every dialect cell, for a date bucket and
6+
* for a plain field alike.
7+
*
8+
* The data-modeling docs said the SQL driver ignored the alias and always
9+
* projected the bucket under the field name. That has been false since #6401
10+
* (`sql-driver-aggregation.ts`, `const outKey = g.alias ?? g.field`), and the
11+
* query skill (`skills/objectstack-query/rules/aggregation.md`) already teaches
12+
* that the column keys match on both paths. This file holds that answer at the
13+
* key level: the EXACT key set of every row, so a face that projected the field
14+
* name (or both names) turns it red. The in-memory half of the same answer is
15+
* `packages/objectql/src/in-memory-aggregation.test.ts` ('groups by a structured
16+
* groupBy with dateGranularity (quarter)', alias `qtr`).
17+
*
18+
* Measured through `engine.aggregate` on SQLite and live PostgreSQL 16 before
19+
* this file was written: every arm (pushed down; in memory, forced by an offset
20+
* zone or by a driver that declares no `quarter` bucket) answered the same keys.
21+
*/
22+
23+
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
24+
import type { DriverQuery } from '@objectstack/spec/contracts';
25+
import { SqlDriver } from '../src/index.js';
26+
import { DIALECT_CELLS, declareDialectCell, type DialectCell } from './live-dialect-matrix.testkit.js';
27+
28+
const TABLE = 'os35015_groupby_alias';
29+
30+
const ROWS = [
31+
{ id: 'd1', region: 'us', amount: 10, closed_at: '2025-01-15T12:00:00.000Z' },
32+
{ id: 'd2', region: 'us', amount: 20, closed_at: '2025-02-15T12:00:00.000Z' },
33+
{ id: 'd3', region: 'eu', amount: 5, closed_at: '2025-04-15T12:00:00.000Z' },
34+
{ id: 'd4', region: 'us', amount: 7, closed_at: '2025-05-15T12:00:00.000Z' },
35+
];
36+
37+
const revenue = [{ function: 'sum', field: 'amount', alias: 'revenue' }];
38+
39+
/** Every row's key set, sorted, and the rows as `key|revenue` pairs (pg hands some numbers back as strings). */
40+
function read(rows: Array<Record<string, unknown>>, groupKeys: string[]) {
41+
return {
42+
keys: [...new Set(rows.map((r) => Object.keys(r).sort().join(',')))],
43+
pairs: rows.map((r) => `${groupKeys.map((k) => String(r[k])).join('/')}|${Number(r.revenue)}`).sort(),
44+
};
45+
}
46+
47+
function declareCell(cell: DialectCell): void {
48+
describe(`[#35015] a structured groupBy alias is the row key (${cell.label})`, () => {
49+
let driver: SqlDriver;
50+
let quarterNative = false;
51+
52+
beforeAll(async () => {
53+
driver = new SqlDriver(cell.config());
54+
await driver.execute(`drop table if exists ${TABLE}`).catch(() => {});
55+
await driver.initObjects([
56+
{ name: TABLE, fields: { region: { type: 'string' }, amount: { type: 'number' }, closed_at: { type: 'datetime' } } },
57+
] as never);
58+
for (const row of ROWS) await driver.create(TABLE, { ...row }, { bypassTenantAudit: true } as never);
59+
const caps = (driver as unknown as { supports: { queryDateGranularity?: Record<string, boolean> } }).supports;
60+
quarterNative = caps.queryDateGranularity?.quarter === true;
61+
});
62+
63+
afterAll(async () => {
64+
await driver.execute(`drop table if exists ${TABLE}`).catch(() => {});
65+
await driver.disconnect();
66+
});
67+
68+
it('declares a native quarter bucket, so the cases below are the pushed-down face', () => {
69+
expect(quarterNative).toBe(true);
70+
});
71+
72+
it('a date bucket with alias projects under the alias, not the field name', async () => {
73+
const rows = (await driver.aggregate(TABLE, {
74+
groupBy: [{ field: 'closed_at', dateGranularity: 'quarter', alias: 'quarter' }],
75+
aggregations: revenue,
76+
} as unknown as DriverQuery)) as Array<Record<string, unknown>>;
77+
expect(read(rows, ['quarter'])).toEqual({ keys: ['quarter,revenue'], pairs: ['2025-Q1|30', '2025-Q2|12'] });
78+
});
79+
80+
it('control: the same bucket without alias projects under the field name', async () => {
81+
const rows = (await driver.aggregate(TABLE, {
82+
groupBy: [{ field: 'closed_at', dateGranularity: 'quarter' }],
83+
aggregations: revenue,
84+
} as unknown as DriverQuery)) as Array<Record<string, unknown>>;
85+
expect(read(rows, ['closed_at'])).toEqual({ keys: ['closed_at,revenue'], pairs: ['2025-Q1|30', '2025-Q2|12'] });
86+
});
87+
88+
it('a plain field alias beside a bucket alias: both columns carry their alias', async () => {
89+
const rows = (await driver.aggregate(TABLE, {
90+
groupBy: [{ field: 'region', alias: 'r' }, { field: 'closed_at', dateGranularity: 'quarter', alias: 'quarter' }],
91+
aggregations: revenue,
92+
} as unknown as DriverQuery)) as Array<Record<string, unknown>>;
93+
expect(read(rows, ['r', 'quarter'])).toEqual({
94+
keys: ['quarter,r,revenue'],
95+
pairs: ['eu/2025-Q2|5', 'us/2025-Q1|30', 'us/2025-Q2|7'],
96+
});
97+
});
98+
});
99+
}
100+
101+
for (const cell of DIALECT_CELLS) {
102+
declareDialectCell(cell, '#35015 structured groupBy alias row key', declareCell);
103+
}

0 commit comments

Comments
 (0)