Skip to content

Commit 65b67be

Browse files
feat(mcp): aggregate_records orders, cuts and counts groups in the database (#35193)
Fixes #35144 Clause-②: yes (widening: `orderBy` and `limit` arguments on `aggregate_records`) Metadata-protocol: none The card's `query_dataset` half is split to #35194 (seat ruling 6978086158, Q1), which carries the group total on `QueryDatasetOutputSchema`; this PR closes the card on the `aggregate_records` half. Per the same ruling (Q2 = C) the answer keeps the published `totalGroups` (the groups before the cut) and adds no second key. ## 维护者速读 - 改了什么:MCP 的 `aggregate_records` 新增 `orderBy` 与 `limit`。排名类问题(如“收入前五的客户”)由数据库一条语句完成排序、截断和分组计数;结果沿用已发布的 `totalGroups`(截断前的分组总数),并在有截断时给出 `truncated: true`。只给 `limit` 不给 `orderBy` 时,按单选/radio 字段声明的选项顺序在数据库里排序后再截断(与 #35186 的无序默认路径同一条规则);固定币种金额在截断结果上同样给出 `currencies`;按 lookup/主从字段分组时,截断结果与默认路径一样在键旁给出 `KEY__label`(以调用者权限读取的记录名称,#35202 的同一个 `withLookupGroupLabels`)。 - 为什么改:分组数超过行上限(50)时,原来只能拿到无序的前 50 组,客户端在不完整的数据上自行排名,答案会错。 - 风险与回滚:只有 SQL 驱动(含 WASM SQLite、Turso 本地/副本)执行;其余驱动、内存计算路径和带 `having` 的聚合一律以 INVALID_QUERY/400 拒绝,不会退化成内存排序。不带新参数的调用行为与 main 完全一致。回滚即 revert 本 PR。窗口函数 `count(*) over ()` 要求 MySQL 8 及以上。 - 先看:`packages/drivers/driver-sql/src/sql-driver-aggregation.ts`(派生表加 ORDER BY/LIMIT/窗口计数、rank 编译成 CASE 的那段)、`packages/mcp/src/mcp-http-tools.ts`(截断路径:未给 `orderBy` 时由 `declaredOptionOrderBy` 推导声明顺序、探测组与 `truncated`、`currencies`)、`packages/objectql/src/aggregate-order-cut.ts`(判定谁能执行、哪些情况拒绝)。 - 两分钟验证:`pnpm --filter @objectstack/runtime exec vitest run src/mcp-aggregate-order-cut.test.ts`,预期 6 个用例全绿;其中一条断言真实 SQLite 语句里带 `order by case ... end asc` 与 `limit`,声明顺序在前、NULL 在最后、`totalGroups` 为 4。 - 需要你做的:无,席位落地。 ## What changes - **Engine (`@objectstack/objectql`).** `engine.aggregate` takes an engine-internal read option, `AGGREGATE_ORDER_CUT`. It is a `Symbol.for` key, so no wire request or JSON query can set it. - The request has `orderBy` (aggregation aliases and group keys), an optional `limit`, and an outcome slot that the engine writes once the driver has served the request: `{ kind: 'served', totalGroups }`. - The engine checks the request before it asks the driver. An order key that names no column of the aggregated row is `INVALID_SORT`/400, and the message names the columns. - Each of these is `INVALID_QUERY`/400: any driver not on the compiling list, an aggregate the engine computes in memory, a `having`, and a relation group. - Rows that come back without the count column are `INTERNAL_ERROR`/500 and are never served. - An order key may also carry a `rank`: a list of the column's values in declared order. This is how a declared option order reaches the statement. - **SQL driver (`@objectstack/driver-sql`).** The grouped statement becomes a derived table, with `count(*) over ()` and `ORDER BY`/`LIMIT` over its columns. It is one statement and one round trip. - On a key without a `rank`, a NULL ranks last in either direction. - A `sum` or count with no value ranks as the `0` it is served as. - A `rank` key compiles to a `case ... when ? then i ... else n end` expression: every unlisted value (a NULL among them) shares rank `n`, so the unlisted values come after the listed ones ascending and before them descending. - Tie-breakers are the group keys the request does not name, plus any group key it names only by a `rank`, ascending, NULL last (engine, `aggregateOrderCutDirective`). So the unlisted values of a ranked column keep their own order, and a cut among them answers the same groups on every run (contract review S1). - **Turso driver.** Its remote face refuses the directive (`INVALID_QUERY`/400). The local and replica faces inherit the SQL driver. - **Runtime HTTP bridge and stdio bridge.** Both have a new optional member, `McpDataBridge.aggregateGroups`, answering `{ rows, totalGroups }`. It runs through the same gates as `aggregate`, carries the request, and reads the engine's outcome back. - **`aggregate_records`.** - New arguments: `orderBy` and `limit` (at most the row cap). - Aliases: `sort`, `sortBy`, `order` and `order_by` map to `orderBy`; `top`, `take` and `pageSize` map to `limit`. - The tool asks for one probe group beyond the cap, so `truncated` is a fact rather than a guess. - On the order-and-cut path `totalGroups` is the statement's own count of the groups before the cut. - A `limit` with no `orderBy`: the leading select/radio group keys' declared option order is handed to the database as `rank` keys, so it is taken before the cut. The leading-key reading is one helper (`declaredOptionOrderKeys`) that both paths call: the uncut path sorts by it, the cut path sends it. A declared list longer than the engine's rank maximum (500) ends the reading at its key rather than send a rank the engine refuses. An `orderBy` the caller sends is passed unchanged and overrides the option order. - `currencies` (a fixed-currency amount's ISO code, by alias) is on the cut result as on the uncut one. - A lookup or master-detail group key carries `KEY__label` on the cut result as on the uncut one: both paths call one local closure over #35202's `withLookupGroupLabels`, applied to the served rows after the cut, so the name read never covers the probe group past the cap. - The description says that ranking an amount whose records each carry their own currency compares bare numbers across currencies, and to rank it inside one currency by filtering `where` on its currency code field (contract review S2, option 1; no refusal added). - A bridge without `aggregateGroups` answers `NOT_IMPLEMENTED`/501. - Calls without the new arguments answer exactly as on `main`. ## Tests - New `packages/objectql/src/aggregate-order-cut.test.ts` (14): the directive the driver receives, the count taken off the rows, `INVALID_SORT` naming the columns, malformed requests and ranks, `having`, a timezone bucket computed in memory, a missing count, refusal on every driver that does not compile the cut, and the Turso local face and WASM driver served. - New `packages/drivers/driver-sql/src/sql-driver-aggregate-order-cut.test.ts`: live dialect cells, where SQLite always runs and Postgres/MySQL run where they are provisioned. It covers the top five of 62 groups; NULL and the 0 identity ranking; rank order; tenant wall plus `where`; a query spy showing ORDER BY, LIMIT and the window in the statement; CONTROL with no directive; a malformed or unprojected directive refused. - New `packages/runtime/src/mcp-aggregate-order-cut.test.ts` (6): HTTP bridge `buildMcpBridge`, over a real `ObjectQL`, a real `SqlDriver` and SQLite in memory. It covers the top five of 70 customers in order with `totalGroups` 70 and the statement regex; a group key ascending; a declared rank; the declared option order a limit-only call sends (declared groups first, NULL last, the cut after the CASE, `totalGroups` 4); `INVALID_SORT`; CONTROL. - New `packages/mcp/src/stdio-data-bridge.aggregate-order-cut.test.ts` (6): stdio, through a real MCP client against a real `ObjectQL`. It covers the top five of 80 groups (exactly 5, in order, `totalGroups` 80, `truncated`); `INVALID_SORT`; a memory driver refused; a missing count never answered; a limit-only call over a select key reaching the driver directive as a `rank` before the cut; CONTROL with no order and no limit (`totalGroups`, no `groupCount`). - Updated `packages/mcp/src/mcp-http-tools.aggregation-entry.test.ts`: the tool half (probe group, `truncated`, aliases, 501 without the member, CONTROL), #35186's option-order and currency block unchanged, and a new block for the carried items: the limit-only push-down (the bridge receives `{ field, order: 'asc', rank }` and the cut keeps the first declared groups, `totalGroups` 5), the rank read by alias for each leading select key and ending at the first that is not one, the over-long declared list, the explicit-order CONTROL (an `orderBy` reaches the bridge unchanged, with no rank), `currencies` on the cut result, and a bridge without the served definition cutting as before. Every served result in that block is pinned to carry no `groupCount`. - The #35138 lookup-label block in the same file gains one pin: an `orderBy` + `limit` call grouped by a lookup answers the served groups with `account__label`, `totalGroups` 3 and `truncated`, from one read of the referenced object for the served ids only (never the probe group). - Round 5 (contract review 6985265817): - S1, `runtime` real SQLite: one declared value and three unlisted (`lost`, `open`, NULL), cut at 3: the answer is `won`, `lost`, `open` twice over, the statement carries the column's null-last ascending tie-break after the CASE, and the uncut order ends with NULL. The engine directive pin and the stdio directive pin show the ranked column among the trailing keys. - S2, the `tools/list` pin asserts the record-mode ranking sentence. - S3, `runtime` real SQLite: a registered read middleware that narrows `ast.where` to one stage leaves the cut and `totalGroups` with only the 18 admitted groups (top five c69, c65, c61, c57, c53), and the uncut aggregate through the same middleware agrees. - N3, stdio over the real engine: a 500-value declared list is sent as the rank and served; a 501-value list is not sent, and the engine refuses a 501-value rank. Either maximum moving alone goes red. - The bridge-member tripwires (`mcp-write-response-internal-fields.tripwire.test.ts`, `stdio-data-bridge.stored-metadata-body.test.ts`) classify `aggregateGroups`. ## Acceptance notes - **Carried from #35186 as the second PR to merge `main`** (rule 6977042103): the limit-only push-down of the declared option order through `rank`, derived from #35186's `declaredOptionRank` (the leading-key loop moved into `declaredOptionOrderKeys`, which `inDeclaredOptionOrder` now calls; the rule is not restated); `groups` kept on the default path; `totalGroups` kept; the explicit-order CONTROL pin, which #35186 recorded as NOT MEASURED until both were in; `currencies` on the cut result. - **Carried from #35202 as the second PR to merge `main`** (carry note 6980343159): the order-and-cut path labels its served rows through the same `withLookupGroupLabels`, after the cut; the default path keeps `groups`, `totalGroups` and the labels; #35202's pins stay green. - **One spelling.** `groupCount` is gone from the result, the tool text, the pins and the changeset; the engine outcome, the bridge member's answer and the driver directive's column field spell it `totalGroups` too (`totalGroupsColumn`, column `__os_total_groups`). None of these was released. - **The rank maximum is mirrored, not imported.** `@objectstack/mcp` does not depend on `@objectstack/objectql` at runtime, so the tool carries `ORDER_RANK_MAX = 500` beside a comment naming `AGGREGATE_ORDER_RANK_MAX`. - **Out of scope, noted and not filed (reach not measured at a public door).** The REST grouped-query branch (`metadata-protocol/src/protocol-data-crud.ts`, the grouped arm) does not apply `orderBy` on a grouped query and slices `limit` in memory. - `count(*) over ()` needs MySQL 8 or later. MySQL 5.7 would fail the statement rather than return a wrong answer. - **Contract review 6985265817 should-fixes (round 5).** S1: the ranked column stays among the trailing ascending keys (the first of the review's two routes); unlisted values still come first under a descending rank, and the changeset says so (N1). S2: option 1, text only. S3: pinned, green with no behaviour change. N3: the boundary pin above. N4: the two `Symbol.for` read-option constants in `stdio-data-bridge.ts` now sit above `unwrapRows`' docblock. #35199's `STDIO_LATEST_PER` moved with ours, because it held the same position. N2 skipped by order. - Overlap at `5839005b034` (`overlap-check --branch=HEAD`, VERDICT clean exit 0): `origin/main` (`b02484e13a2`, #35240 landed after the merge and touches none of this PR's packages) and #34817 merge cleanly. #35225 landed first and is merged in (`dbb2f6805b0`). Its one conflict, in `packages/mcp/src/stdio-data-bridge.ts`, was resolved keeping both sides: the two `Symbol.for` read-option constants each under their own docblock, then #35225's `stdioExpandMap`, byte-identical to main, then `unwrapRows` under its docblock. ## Verification Readings at head `5839005b034` (`origin/main` `dbb2f6805b0` merged, with #35225). The round-5 ablation and the `objectql` and `driver-sql` full suites were read at `87429381cbc`; that merge changes no code they exercise. The gate union and the reconciliation are quoted in the dev report on #35144. <details><summary>Round 5 ablation: the ranked column in the trailing keys (S1)</summary> The engine line `const named = new Set(request.orderBy.filter((k) => k.rank === undefined).map((k) => k.field));` was replaced with `const named = new Set(request.orderBy.map((k) => k.field));` (`node scripts/ablation-replace.mjs`, blob 0760cdd to the mutation). Then `@objectstack/objectql` was rebuilt, and `ablation-dist-preflight` found the marker in 4 built files. - Red: runtime 1 of 9. The cut answered `won`, NULL, `lost` instead of `won`, `lost`, `open`, so SQLite really did keep NULL at the boundary. Also red: objectql 1 of 14 (the directive pin) and stdio 1 of 7 (the directive pin). - Restore: blob equals HEAD (0760cdd) and `git diff HEAD` is empty. After the rebuild, preflight `--absent` exited 0. - The first attempt was a no-op. Its replacement text already occurred elsewhere in the file, so the tool refused it and restored, and the run read green on the pristine build. It was redone with a unique anchor. </details> <details><summary>Round 3 ablation: the label call on the order-and-cut path</summary> `node scripts/ablation-replace.mjs` replaced `rows: await labelServed(cut ? groups.slice(0, cap) : groups, fields),` with `rows: cut ? groups.slice(0, cap) : groups,` in `packages/mcp/src/mcp-http-tools.ts` (anchor 1 to 0, blob 84c75cd to 529eafa55eaf; the test imports the source, not `dist/`). - Red, 1 failed / 42 passed: the new cut-path label pin, and nothing else. - Restore: blob after restore equals HEAD (84c75cd), `git diff HEAD` empty. </details> <details><summary>Round 2 ablation (unchanged code): the declared-order derivation on the limit-only path</summary> Replacing the `declaredOptionOrderBy` fallback with `orderBy ?? []` reddened 4 of 40: the three limit-only pins and the stdio rank pin; restored, blob equals HEAD. </details> <details><summary>Round 1 ablations (unchanged code): the order push-down and the rank arm</summary> - The order push-down (`for (const key of orderCut.orderBy) {` replaced with an empty list, rebuilt, preflighted against `dist/`): three driver pins red; restored, blob equals HEAD. - The `rank` arm made unreachable (rebuilt, marker in `dist/`): the driver rank pin and the runtime rank pin red; restored, marker absent, tree clean. </details> <details><summary>Suites and typecheck</summary> - After a full `pnpm build` (120/120): `objectql` `src/aggregate-order-cut.test.ts` 14/14; `driver-sql` `src/sql-driver-aggregate-order-cut.test.ts` 7 passed, 2 skipped (live Postgres/MySQL cells, unprovisioned); `runtime` `src/mcp-aggregate-order-cut.test.ts` 9/9; `mcp` stdio order-cut + aggregation-entry + both tripwires: 4 files, 92 passed. Lock VERDICT 0. - `mcp` full suite at `5839005b034`: Test Files 77 passed (77), Tests 1400 passed (1400). At `87429381cbc`: `objectql` full suite: Test Files 615 passed (615), Tests 13881 passed (13881). `driver-sql` full suite: Test Files 263 passed, 13 skipped (276), Tests 4387 passed, 257 skipped (4644). Each VERDICT command-exit 0. - Typecheck `objectql`, `driver-sql`, `driver-turso`, `mcp`, `runtime` (incl. `check:test-typecheck` ledgers): VERDICT command-exit 0. - `dispatch-gates --commands` at `5839005b034`: 75 families, all exit 0. `--ran` with exit codes: 75 derived, 75 run, 0 NOT-MEASURED (a derived zero). `check:query-options-erasure` test surface is 236, at its ceiling. - `check-governed-merges --branch HEAD`: NOT governed, 0 of 17 paths, +2005/-43. `check-platform-checklist --changed-from origin/main`: OK, 29 anchors judged, 0 lost. </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01JQwxbWDsbbJizuYnDwBxT8)_ <!-- signed: repo:objectstack#1 · os-warren · session_01JQwxbWDsbbJizuYnDwBxT8 --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 00110fd commit 65b67be

17 files changed

Lines changed: 2005 additions & 43 deletions
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
---
2+
'@objectstack/mcp': patch
3+
'@objectstack/objectql': patch
4+
'@objectstack/driver-sql': patch
5+
'@objectstack/driver-turso': patch
6+
'@objectstack/runtime': patch
7+
---
8+
9+
feat(mcp): `aggregate_records` orders, cuts and counts its groups in the database
10+
11+
Clause-②: yes (widening: `orderBy` and `limit` arguments on `aggregate_records`)
12+
Metadata-protocol: none
13+
14+
A ranking question ("the top five customers by revenue") over more groups than the tool's row cap used to come back as every group, or the first page of them, in no stated order, and the client ranked what it happened to get. `aggregate_records` now takes `orderBy` — a list of `{ field, order }` naming an aggregation alias or a group key (its alias when it has one) — and `limit` (at most the row cap). The database orders the groups, cuts them, and counts how many groups it formed before the cut, in one statement; the result carries the groups, `totalGroups` (the key the tool already answers, now the database's count of the groups before the cut), and `truncated: true` when more groups existed than came back.
15+
16+
- An order key that names no column of the aggregated row is refused `INVALID_SORT` / 400, naming the columns the query projects.
17+
- Only a driver that runs the cut in its own SQL statement serves it: `driver-sql` (every dialect it speaks; the window `count(*) over ()` needs MySQL 8 or later), the WASM SQLite driver, and the Turso driver's local and replica faces. Every other driver (the in-memory driver, MongoDB, OData, Turso's remote face), an aggregate the engine computes in memory (a date bucket, a reference timezone or a measure filter the driver does not run), and an aggregate with `having` are refused `INVALID_QUERY` / 400 before anything is read. Groups are never ordered or cut in the application.
18+
- On an order key without a `rank`, a NULL ranks last in either direction, except a `sum` or a count with no value, which ranks as the `0` it is served as. Group keys the order does not name, and a group key it names only by a `rank`, break ties, ascending, NULL last, so two runs of one call answer the same groups in the same order.
19+
- An order key may carry a `rank`, a list of the column's values: the statement ranks each listed value by its position and every other value (a NULL among them) on one rank past them, before the cut, so the unlisted values come after the listed ones ascending and before them descending; among themselves they follow the column's own ascending order, NULL last. It is the tool's own, never an `aggregate_records` argument.
20+
- A `limit` with no `orderBy` keeps the declared option order the uncut answer already follows: groups keyed by a leading select or radio field come back in the order the field declares its options, a value no option declares last, and the database takes that order before the cut, so the cut keeps the first declared groups. An `orderBy` the caller sends overrides it.
21+
- The cut answer carries what the uncut one does: a fixed-currency amount's currency in `currencies`, and `KEY__label` beside each lookup or master-detail group key, the record's name read with the caller's own permissions.
22+
- An amount whose records each carry their own currency is ranked by its bare numbers across currencies: the tool description says to rank it inside one currency by filtering `where` on its currency code field.
23+
- Without `orderBy` and `limit` the tool answers as before.
24+
25+
`@objectstack/objectql` exports `AGGREGATE_ORDER_CUT`, the engine-internal read option of `aggregate` that carries the request (a symbol, so no wire request can set it), with the `AggregateOrderCutRequest`, `AggregateOrderKey` and `AggregateOrderCutOutcome` types. `McpDataBridge` gains the optional member `aggregateGroups`; a bridge without it refuses `orderBy` / `limit` with `NOT_IMPLEMENTED` / 501 and keeps serving the rest of the tool. Nothing that was accepted before is refused.
Lines changed: 173 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,173 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [aggregate order and cut] `aggregate()` compiles the order-and-cut directive
5+
* the engine hands it (objectql `aggregate-order-cut.ts`) into its own
6+
* statement: the grouped statement as a derived table, `count(*) over ()` for
7+
* the groups it formed, and ORDER BY / LIMIT over the derived table's columns.
8+
*
9+
* Pinned here: the top N by a measure, in order, with the count of every group
10+
* before the cut (more groups than the cut, as a top-N over a large set asks);
11+
* an order by a group key; a `sum` whose group has no value ranks as the `0` it
12+
* is served as, in either direction; a NULL group key ranks last in either
13+
* direction; the cut inside the tenant wall and the `where`; the statement
14+
* itself carries the ORDER BY, the LIMIT and the window (a query spy, so an
15+
* in-application sort cannot pass); and a malformed directive, or one ordering
16+
* by a column the statement does not project, refused before anything runs.
17+
*
18+
* Every live cell runs where the suite provisions it (`OS_TEST_POSTGRES_URL`,
19+
* `OS_TEST_MYSQL_URL`); SQLite always runs.
20+
*/
21+
22+
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
23+
import type { DriverQuery } from '@objectstack/spec/contracts';
24+
import { SqlDriver } from './sql-driver.js';
25+
import { DIALECT_CELLS, declareDialectCell, type DialectCell } from './live-dialect-matrix.testkit.js';
26+
import { AGGREGATE_ORDER_CUT_DIRECTIVE, type AggregateOrderCutDirective } from './sql-driver-aggregation.js';
27+
28+
const TABLE = 'os_agg_order_cut_order';
29+
const COUNT_COLUMN = '__os_total_groups';
30+
31+
/**
32+
* 60 customers `c00`..`c59` in org_a, each with two orders (`i * 10` and `5`),
33+
* so customer `cNN` totals `NN * 10 + 5`; `cnull` has one order with no amount
34+
* (its `sum` is NULL in SQL, served as `0`); one order has no customer (a NULL
35+
* group key); org_b holds a customer `cz` richer than all of them.
36+
*/
37+
function orders(): Array<Record<string, unknown>> {
38+
const rows: Array<Record<string, unknown>> = [];
39+
for (let i = 0; i < 60; i++) {
40+
const c = `c${String(i).padStart(2, '0')}`;
41+
rows.push({ id: `${c}-a`, customer: c, amount: i * 10, status: 'won', organization_id: 'org_a' });
42+
rows.push({ id: `${c}-b`, customer: c, amount: 5, status: i % 2 === 0 ? 'won' : 'lost', organization_id: 'org_a' });
43+
}
44+
rows.push({ id: 'n-1', customer: 'cnull', amount: null, status: 'won', organization_id: 'org_a' });
45+
rows.push({ id: 'k-1', customer: null, amount: 1, status: 'won', organization_id: 'org_a' });
46+
rows.push({ id: 'z-1', customer: 'cz', amount: 99999, status: 'won', organization_id: 'org_b' });
47+
return rows;
48+
}
49+
50+
const REVENUE = [{ function: 'sum' as const, field: 'amount', alias: 'revenue' }];
51+
52+
const query = (directive: unknown, over: Partial<DriverQuery> = {}): DriverQuery => ({
53+
groupBy: ['customer'],
54+
aggregations: REVENUE,
55+
...over,
56+
[AGGREGATE_ORDER_CUT_DIRECTIVE]: directive,
57+
} as unknown as DriverQuery);
58+
59+
const cut = (
60+
orderBy: AggregateOrderCutDirective['orderBy'],
61+
limit?: number,
62+
): AggregateOrderCutDirective => ({ orderBy, ...(limit !== undefined ? { limit } : {}), totalGroupsColumn: COUNT_COLUMN });
63+
64+
const customers = (rows: Array<Record<string, unknown>>) => rows.map((r) => r.customer);
65+
66+
function declareCell(cell: DialectCell): void {
67+
describe(`[aggregate order and cut] driver-sql — aggregate orders, cuts and counts groups (${cell.label})`, () => {
68+
let driver: SqlDriver;
69+
const OLD_POSTURE = process.env.OS_TENANCY_POSTURE;
70+
71+
beforeAll(async () => {
72+
process.env.OS_TENANCY_POSTURE = 'isolated';
73+
driver = new SqlDriver(cell.config());
74+
await driver.execute(`drop table if exists ${TABLE}`).catch(() => {});
75+
await driver.initObjects([
76+
{
77+
name: TABLE,
78+
fields: {
79+
customer: { type: 'text' }, amount: { type: 'number' }, status: { type: 'text' },
80+
organization_id: { type: 'text' },
81+
},
82+
},
83+
] as never);
84+
for (const row of orders()) await driver.create(TABLE, { ...row }, { bypassTenantAudit: true });
85+
});
86+
87+
afterAll(async () => {
88+
await driver?.execute(`drop table if exists ${TABLE}`).catch(() => {});
89+
await driver?.disconnect?.();
90+
if (OLD_POSTURE === undefined) delete process.env.OS_TENANCY_POSTURE;
91+
else process.env.OS_TENANCY_POSTURE = OLD_POSTURE;
92+
});
93+
94+
it('the top five by a measure, in order, and every group counted before the cut', async () => {
95+
const rows = await driver.aggregate(TABLE, query(cut([{ column: 'revenue', order: 'desc' }, { column: 'customer', order: 'asc' }], 5)), { tenantId: 'org_a' });
96+
expect(customers(rows)).toEqual(['c59', 'c58', 'c57', 'c56', 'c55']);
97+
expect(rows.map((r) => r.revenue)).toEqual([595, 585, 575, 565, 555]);
98+
// 60 customers, `cnull` and the NULL customer: 62 groups in org_a.
99+
expect(rows.map((r) => r[COUNT_COLUMN])).toEqual([62, 62, 62, 62, 62]);
100+
});
101+
102+
it('a sum with no value ranks as the 0 it is served as; a NULL group key ranks last either way', async () => {
103+
const asc = await driver.aggregate(TABLE, query(cut([{ column: 'revenue', order: 'asc' }, { column: 'customer', order: 'asc' }], 3)), { tenantId: 'org_a' });
104+
expect(customers(asc)).toEqual(['cnull', null, 'c00']);
105+
expect(asc.map((r) => r.revenue)).toEqual([0, 1, 5]);
106+
const byKeyAsc = await driver.aggregate(TABLE, query(cut([{ column: 'customer', order: 'asc' }])), { tenantId: 'org_a' });
107+
expect(customers(byKeyAsc).slice(0, 3)).toEqual(['c00', 'c01', 'c02']);
108+
expect(customers(byKeyAsc)[customers(byKeyAsc).length - 1]).toBeNull();
109+
const byKeyDesc = await driver.aggregate(TABLE, query(cut([{ column: 'customer', order: 'desc' }], 62)), { tenantId: 'org_a' });
110+
expect(customers(byKeyDesc).slice(0, 2)).toEqual(['cnull', 'c59']);
111+
expect(customers(byKeyDesc)[customers(byKeyDesc).length - 1]).toBeNull();
112+
});
113+
114+
it('a rank orders a group key by its listed values\' positions before the cut, any other value after them', async () => {
115+
const declared = await driver.aggregate(TABLE, query(cut([{ column: 'customer', order: 'asc', rank: ['c05', 'c40', 'c02'] }], 3)), { tenantId: 'org_a' });
116+
expect(customers(declared)).toEqual(['c05', 'c40', 'c02']);
117+
expect(declared[0][COUNT_COLUMN]).toBe(62);
118+
const reversed = await driver.aggregate(TABLE, query(cut([{ column: 'customer', order: 'desc', rank: ['c05', 'c40', 'c02'] }])), { tenantId: 'org_a' });
119+
// Descending over the ranks: the 59 unlisted groups (rank 3, the NULL key among them) first, then c02, c40, c05.
120+
expect(customers(reversed).slice(-3)).toEqual(['c02', 'c40', 'c05']);
121+
expect(customers(reversed.slice(0, 59))).toContain(null);
122+
});
123+
124+
it('the cut runs inside the tenant wall and the where', async () => {
125+
const lost = await driver.aggregate(
126+
TABLE,
127+
query(cut([{ column: 'revenue', order: 'desc' }, { column: 'customer', order: 'asc' }], 2), { where: { status: 'lost' } }),
128+
{ tenantId: 'org_a' },
129+
);
130+
// `lost` orders: the 30 odd customers' 5s — every one ties at 5, the group key breaks it.
131+
expect(customers(lost)).toEqual(['c01', 'c03']);
132+
expect(lost[0][COUNT_COLUMN]).toBe(30);
133+
const other = await driver.aggregate(TABLE, query(cut([{ column: 'revenue', order: 'desc' }], 5)), { tenantId: 'org_b' });
134+
expect(customers(other)).toEqual(['cz']);
135+
expect(other[0][COUNT_COLUMN]).toBe(1);
136+
});
137+
138+
it('the ORDER BY, the LIMIT and the group count are in the statement, not applied after it', async () => {
139+
const seen: string[] = [];
140+
const knex = (driver as unknown as { knex: { on: Function; off: Function } }).knex;
141+
const listen = (q: { sql: string }) => { seen.push(q.sql); };
142+
knex.on('query', listen);
143+
try {
144+
await driver.aggregate(TABLE, query(cut([{ column: 'revenue', order: 'desc' }], 5)), { tenantId: 'org_a' });
145+
} finally {
146+
knex.off('query', listen);
147+
}
148+
const statement = seen.find((s) => /count\(\*\) over \(\)/i.test(s));
149+
expect(statement, seen.join('\n')).toBeDefined();
150+
expect(statement).toMatch(/order by .*revenue/i);
151+
expect(statement).toMatch(/\blimit\b|\bfetch\b|\btop\b/i);
152+
expect(statement).toMatch(/group by/i);
153+
});
154+
155+
it('CONTROL — no directive: the grouped answer as before, no count column', async () => {
156+
const rows = await driver.aggregate(TABLE, { groupBy: ['customer'], aggregations: REVENUE } as DriverQuery, { tenantId: 'org_a' });
157+
expect(rows).toHaveLength(62);
158+
expect(rows[0]).not.toHaveProperty(COUNT_COLUMN);
159+
});
160+
161+
it('a malformed directive, or an order by a column the statement does not project, is refused before it runs', async () => {
162+
const malformed = await driver.aggregate(TABLE, query({ orderBy: 'revenue' }), { tenantId: 'org_a' })
163+
.then(() => null, (e: Error & { code?: string }) => e);
164+
expect(malformed?.code).toBe('INTERNAL_ERROR');
165+
const unprojected = await driver.aggregate(TABLE, query(cut([{ column: 'amount', order: 'desc' }])), { tenantId: 'org_a' })
166+
.then(() => null, (e: Error & { code?: string }) => e);
167+
expect(unprojected?.code).toBe('INTERNAL_ERROR');
168+
expect(unprojected?.message).toMatch(/'amount'/);
169+
});
170+
});
171+
}
172+
173+
for (const cell of DIALECT_CELLS) declareDialectCell(cell, 'aggregate order and cut', declareCell);

0 commit comments

Comments
 (0)