Skip to content

Commit 54f8e16

Browse files
fix(analytics): a dimension through a lookup is one LEFT JOIN … GROUP BY on SQL drivers, no 500 past the bind limit (#34430)
Fixes #33664 Clause-②: no Metadata-protocol: none ## 维护者速读 - 改了什么:分析查询里"经 lookup 的维度"(如明细立方体上的 `opportunity.stage`)在 SQL 驱动上改为数据库内一条 `LEFT JOIN … GROUP BY`,不再先按外键分组、再用 `id IN (所有外键)` 读关联对象。 - 为什么改:关联记录数超过数据库绑定参数上限时(SQLite 约 3.2 万、PostgreSQL 65535),原路径直接报 500 `DATABASE_ERROR`,大数据量的看板无法出数。 - 风险与回滚:关联读取仍按调用者身份规划(CRUD、读中间件、行级范围、字段级权限、租户墙全部生效),分桶与度量与原路径逐格对等;内存/MongoDB/OData/Turso 驱动不变;任何 4xx 拒绝都回落原路径重判,报错信封不变;基础对象上的外键字段本身仍作为分组键交给中间件,字段级权限看不到它的调用者在两条路径上得到同一个 403。回滚即撤销本 PR,无数据或元数据迁移。 - 先看:`packages/drivers/driver-sql/src/sql-driver-aggregation.ts`(JOIN 子查询的租户墙与范围拼接)、`packages/objectql/src/relation-group-join.ts`(规划与拒绝条件)、`packages/services/service-analytics/src/strategies/objectql-strategy.ts`(`executeCrossObjectJoined` 的回落与重分桶)。 - 两分钟验证:`pnpm --filter @objectstack/service-analytics exec vitest run src/__tests__/cross-object-relation-group-join.test.ts`,预期 23 个用例全绿,其中 33000 个外键的用例原路径 500、新路径每个 stage 11000 行。 - 需要你做的:无,席位落地。 ## What changes A dimension through a lookup on the ObjectQL analytics path (`POST /analytics/query`, cube `bench_line_item`, `dimensions: ['opportunity.stage']`) is now one SQL statement on the SQL drivers instead of an FK-expand whose `id IN (every distinct FK)` overflowed the dialect's bind limit. - **objectql, an engine-internal single-hop relation group key (option A1).** `relation-group-join.ts` adds a `Symbol.for` read option (`RELATION_GROUP_BY`) that no wire request can carry, so the public `groupBy` still refuses a dotted path. `aggregate()` reads it, plans the related object's read **as the caller** through the existing `RELATION_SCOPE_PLAN` / `planRelationSemiJoinLeaf` / `plannedRelationLeafVerdict` (no second copy of the read-scope leaf, ADR-0139 D6), and hands the driver a `ReadableIds.compose(leaf, plannedWhere)` parent per relation under a second symbol (`RELATION_GROUP_JOINS`). The planned read is an `aggregate` grouped by `['id', ...attrs]`, the same read `resolveFkAttr` ran minus its id list, so the CRUD gate, read middlewares, row scope and the FLS group-by gate all apply. A deny-sentinel scope hands a `null` parent (nothing readable). - **The base relation field is still a group key to every door.** The FK-expand's base read groups by the relation field (`opportunity`), so plugin-security's aggregate input gate (step 2.5b) and every other group-key guard judge it. On the joined path the strategy drops that key, so the engine now hands the middleware chain the base read grouped by each relation field `groupBy` does not already name (`relationFieldsJudgedAsGroupKeys`), and takes those keys back out only in the statement it hands the driver (`withoutJudgedRelationFields`), where the join replaces them. No field gate is copied: the field goes through the chain's existing guards, so a caller who may not read `line.opportunity` is refused on the joined path by the same gate, with the same 403, as on the FK-expand. The docblock now says this rather than only "Holding the key grants nothing" (L1 S1). - **The related object's API exposure (#22661 pin).** `relation-group-join.ts` calls `referenceTargetOf`, so `second-object-read-exposure.pin.test.ts` must classify it. It is classified `decided`: the analytics door asks the related object's `enable` block through the spec's decision (`assertObjectsExposed`, `api-exposure-door.ts`, for `aggregate`) over `queryObjects`, which holds every hop's object, before any strategy runs. So the joined path and the FK-expand get one verdict, and the engine is never handed the request for an unexposed related object. The row adds `aggregate` to the row type's operation union and `assertObjectsExposed` to the roster of decision functions, which the `decided` form requires. - **Decline, never guess.** The engine writes `request.outcome` = joined or declined. It declines, with nothing read, for a driver outside `RELATION_GROUP_JOIN_COMPILING_DRIVERS` (`driver.sql`, `driver.sqlite-wasm`), a federated object, a multi-valued relation, a relation whose target is not the requested object, a related object `relationSemiJoinServes` keeps the id read for, a read middleware that answers without the driver, and an aggregate the driver does not answer natively (a non-UTC date bucket). - **driver-sql.** `aggregate()` compiles each join as `LEFT JOIN (SELECT id, attr… FROM parent WHERE planned scope AND parent tenant wall) __rgN ON child.fk = __rgN.id`, groups by the attributes and a two-state `CASE WHEN __rgN.id IS NULL THEN 0 ELSE 1 END` resolved column. The parent's tenant wall comes from the read's own options, as for a composed `ReadableIds` subquery. A parent the engine did not compose is refused with INTERNAL_ERROR / 500 before anything compiles. - **service-analytics.** The plugin's auto-bridge wires `executeRelationGroupAggregate`. `ObjectQLStrategy#executeCrossObject` tries the joined path first and maps each row through the same `rebucketCrossObject` (an unresolved row is `(restricted)`, exactly as an id the FK-expand's read did not return). On no hook, a decline, or any 4xx it falls back to the unchanged FK-expand, which re-derives a refusal in its own order and envelope. - MongoDB, OData, memory and Turso keep today's FK-expand unchanged. **Divergence from the card's Expected.** The card says "MongoDB/OData refuse with a stable 400". Per seat route B (record 6917462284) they keep today's FK-expand unchanged and nothing here refuses. That refusal, if it lands, is owned by #33876. ## Why The FK-expand bound one parameter per distinct related record. Past the dialect's ceiling, SQLite answered `too many SQL variables` and PostgreSQL a bind count overflow, both surfaced as `500 DATABASE_ERROR`. The join binds only the scope's comparands and the two tenant walls, whatever the row count. ## Tests - `packages/objectql/src/relation-group-join.test.ts` (15, recording driver). The middleware chain sees the base read grouped by the relation field (for a `groupBy` with other keys, with none, and with the FK column already named), and the driver's statement does not. Joined: one driver call, no read of the related object reaches the driver, and the parent scope is the request's condition as the related read's own doors lowered it AND the middleware's condition. A deny sentinel gives a `null` parent. A virtual attribute gives INVALID_FIELD / 400 with no driver call. A driver row missing the resolved column gives INTERNAL_ERROR / 500, as does an alias collision. Declines: memory, MongoDB, OData, Turso, multi-valued, object mismatch, short-circuit middleware, non-UTC bucket. - `packages/drivers/driver-sql/src/sql-driver-relation-group-join.test.ts`, dialect matrix. Buckets with an empty FK, an orphan FK, a scope-hidden parent and another tenant's parent all unresolved, every child counted once. A base group key beside the join. A `null` parent. At most 3 bindings (child wall, parent wall, one comparand). A forged parent gives 500. - `packages/services/service-analytics/src/__tests__/cross-object-relation-group-join.test.ts` (23, real ObjectQL + SqliteWasmDriver, isolated tenancy). New in this round: a caller whose field permissions hide `line.opportunity` gets the same `PERMISSION_DENIED` / 403 with the join wired as without it, and the engine is handed no request. The engine, handed the relation group request directly (no analytics door), refuses that caller with the same envelope as the FK-expand's base read grouped by the field; an admin control joins, and its rows carry no `opportunity` key. A related object declaring `apiEnabled: false` answers `OBJECT_API_DISABLED` / 404, and one whose `apiMethods` does not grant the aggregate read answers `OBJECT_API_METHOD_NOT_ALLOWED` / 405, on both paths, with no request handed to the engine. The field gate in this suite is a test middleware that judges the AST's `groupBy` and `aggregations` the way step 2.5b does, because this package does not depend on plugin-security. Parity of the joined path against the FK-expand for 3 callers (admin org A; member org A with a policy scope and a read middleware hiding parents; admin org B) × 4 dimension shapes. Explicit buckets for `(restricted)`, null FK, orphan FK and a cross-tenant FK. The read scope and the tenant wall on the joined parent. 33,000 distinct FKs: the FK-expand answers DATABASE_ERROR / 500, the joined path answers 11,000 per stage. - `packages/objectql/src/federated-injected-column-readers.test.ts`: two disposition rows for the new module's federated seams (`exempt`). - `packages/core/src/security/second-object-read-exposure.pin.test.ts`: the `decided` row above (4/4). <details><summary>Ablations (each disable → red → restore; restore proven by blob == HEAD and an empty git diff HEAD)</summary> All run through `scripts/ablation-replace.mjs` in WRAP mode against `src` (every subject is resolved from source in its suite). The first six rows were measured at `c87aab92d`, the last two at `2f6eef1ff`. | pin | mutation | suite | result | |:--|:--|:--|:--| | parity / `(restricted)` | resolved column read as always 1 | analytics join test | 15 failed / 18 | | bind limit + routing | plugin wires no `executeRelationGroupAggregate` | analytics join test | 13 failed / 18 (incl. the 33,000-FK joined case) | | read scope on the parent | compose with `undefined` instead of the planned scope | objectql join test | 1 failed / 14 | | tenant wall on the parent | `applyTenantScope(sub, …)` deleted | driver-sql join test (sqlite) | 3 failed | | non-SQL unchanged | memory driver added to the compiling set | objectql join test | 1 failed / 14 | | refusal envelope unchanged | the 4xx fallback disabled | `objectql-echo-non-date-bucket.test.ts` | 1 failed / 22 (`groupBy.0` vs `groupBy.1`) | | base relation field judged as a group key | `relationFieldsJudgedAsGroupKeys(…)` replaced by `[]` | analytics join test; objectql join test | 1 failed / 23 (the engine-level FLS pin); 1 failed / 15 | | related object's exposure | `assertObjectsExposed` answers every object as served | analytics join test | 2 failed / 23 (the two exposure cases) | The first parity attempt replaced the anchor with the single character `i`. The tool refused it because the replacement count could not rise, so that attempt measured nothing; it was rerun with a distinct replacement (row above). </details> ## Acceptance notes - **Bench (M0, `packages/qa/dogfood/bench/sql-perf`, `--only analytics_cross_object_dim`, admin, SQLite, 20 iterations).** "Before" is this head with the hook unwired in the built `service-analytics` dist (the ablation above, proven present in `dist/` and absent after the restore and rebuild). That path is today's FK-expand. | scale (line items / opportunities) | path | status | p50 ms | p95 ms | db ms p50 | SQL statements | |:--|:--|:--|--:|--:|--:|--:| | 400,000 / 40,000 | before | 500 DATABASE_ERROR | 284.1 | 350.0 | 205.8 | 10 | | 400,000 / 40,000 | after | 200 | 528.6 | 591.6 | 498 | 9 | | 200,000 / 20,000 | before | 200 | 220.0 | 261.3 | 146.7 | 10 | | 200,000 / 20,000 | after | 200 | 241.0 | 256.7 | 220.5 | 9 | These are shared-box seconds: the bench ran outside the verify lock after about 40 minutes queued behind another battery. Under the bind limit, SQLite pays more database time for the joined statement than for the two FK-expand reads (about 1.5x db time, about 1.1x request p50 at 20k parents). Past the limit, the request answers instead of failing. PostgreSQL bench: NOT MEASURED (the local PG server died mid-session; see Verification). - Turso is not served (its remote transport compiles its own aggregates). It keeps the FK-expand. - Optional L1 N2 was not taken: building the derived table from `readableIdsSubquery(…)` needs that method on the driver's aggregation host, which is bound in `sql-driver.ts`, not in the same file. - `main`'s `check:platform-checklist` red (approver-resolution-matrix VARIANTS STALE, since #34300) is not this PR's and is not fixed here. `Lint & Repo Gates` reads success on `2f6eef1ff`. - The analytics-suite field gate stands in for plugin-security's step 2.5b, whose own input contract (`ast.groupBy` / `ast.aggregations`) is pinned in `security-plugin.test.ts`. - Files beyond the claim's literal names: `objectql/src/engine.ts` (one host-wiring line), `service-analytics/src/analytics-service.ts` (config pass-through of the hook), and `objectql/src/federated-injected-column-readers.test.ts` (two ledger rows its census demanded) are wiring for the claimed doors and the plugin bridge. `core/src/security/second-object-read-exposure.pin.test.ts` (one CALLERS row, its operation literal and its roster entry) is the census the new module's `referenceTargetOf` call joins. - Out of scope, noted and not fixed: the ObjectQL path buckets a line whose FK is not set under `(restricted)`, a label that reads as a permission outcome. This is pre-existing, and parity is kept here on purpose. - Serial constraint with #34198: it merged into `main` before this branch's last merge of `origin/main`. `git merge-tree` against its head and against `origin/main` is clean. ## Verification Head of record: `2f6eef1ff`. <details><summary>Suites and typechecks (at 2f6eef1, under the verify lock)</summary> - `pnpm --filter @objectstack/objectql test`: 604/604 files, 13485/13485 tests. - `pnpm --filter @objectstack/driver-sql test`: 256 files passed, 13 skipped; 4331 tests passed, 247 skipped. The PostgreSQL cell of the join test ran in round 1 against a local PostgreSQL 16. MySQL, MSSQL and Oracle cells: NOT MEASURED locally. - `pnpm --filter @objectstack/service-analytics test`: 218/218 files; 5318 tests passed, 335 skipped. - `@objectstack/core` repo project, `second-object-read-exposure.pin.test.ts`: 4/4. It was red on `c87aab92d` in CI (Test Core 7/8). - `typecheck` for objectql (with `check:test-typecheck`), driver-sql, service-analytics and core: exit 0 each. </details> <details><summary>Derived gates (at 2f6eef1)</summary> `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack` derived 82 commands. 81 exited 0 on the first run. `check:dual-build-cjs-loads` exited 3 (PREREQUISITE NOT MET, no workspace `dist/`), and after `pnpm build` (exit 0) it exited 0. `--ran` reconciliation with an exit code on every line: 82 derived, 82 run, 0 NOT-MEASURED, 0 UNRUN, a derived zero. The working tree was clean after the build. </details> <details><summary>CI on 2f6eef1</summary> Check-runs: 55 success, 11 skipped, 0 failed. `Test Core` (all 8 shards), `Lint & Repo Gates`, `TypeScript Type Check`, `Build Core`, `Governed Surface Queue Guard`, `Type Check UI`, `Test UI`, `Build & E2E UI`, `Live E2E UI` and `Dogfood Regression Gate` all report success. </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01FEkQ5nNrLRm8ssuwWcBVcw)_ <!-- signed: repo:objectstack#1 · os-project-manager · session_01FEkQ5nNrLRm8ssuwWcBVcw --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent d4e4dfb commit 54f8e16

14 files changed

Lines changed: 1844 additions & 58 deletions
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
---
2+
'@objectstack/objectql': patch
3+
'@objectstack/driver-sql': patch
4+
'@objectstack/service-analytics': patch
5+
---
6+
7+
fix(analytics): a dimension through a lookup is one `LEFT JOIN … GROUP BY` on SQL drivers, so it no longer answers 500 past the bind limit
8+
9+
Clause-②: no
10+
Metadata-protocol: none
11+
12+
`POST /analytics/query` with a dimension through a lookup (`opportunity.stage` on a line-item cube) answered `500 DATABASE_ERROR` once the rows pointed at more distinct related records than the database binds parameters for: SQLite refused with `too many SQL variables`, PostgreSQL with a bind count overflow. The ObjectQL analytics path grouped the base rows by the foreign key, then read the related object with `id IN (every distinct key)` and re-bucketed the answer in the service.
13+
14+
On the SQL driver (every dialect, and the WASM SQLite driver) the same query is now one statement. The base aggregate `LEFT JOIN`s the related rows the caller may read and groups by the attribute in the database, with no id list and no bound-parameter ceiling. The related rows are the related object's own aggregate, planned as the caller, the read the old path ran without its id list. Its CRUD gate, read middlewares, row scope and field-level gate all apply, and the tenant wall bounds the joined table. The base read is still judged as grouped by the lookup field itself, so a caller who may not read that field is refused exactly as before. A line whose related record is missing, unreadable, in another tenant or not set still counts under `(restricted)`, as before. Every bucket and measure is the one the old path answered.
15+
16+
The request is an engine-internal read option, so nothing a client sends changes and the public `groupBy` still refuses a dotted path. The in-memory driver, MongoDB, OData and Turso keep the old path for this dimension, unchanged.

‎packages/core/src/security/second-object-read-exposure.pin.test.ts‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,7 @@ type Classification =
9797
/** The read, in words. */
9898
read: string;
9999
/** The operation the target is judged as. */
100-
operation: 'get' | 'list';
100+
operation: 'get' | 'list' | 'aggregate';
101101
/** The function that asks the decision, and the file it lives in. */
102102
decision: { file: string; fn: string };
103103
/** Where the read takes its answer from that function: a call site that must exist. */
@@ -195,6 +195,17 @@ const CALLERS: Record<string, Classification> = {
195195
wiring: { file: 'packages/plugins/plugin-audit/src/audit-writers.ts', call: 'servesSummaryTitleTarget(objectName' },
196196
pin: 'packages/plugins/plugin-audit/src/audit-lookup-summary.test.ts',
197197
},
198+
// The engine's relation group join: an analytics cross-object dimension as one `LEFT JOIN … GROUP BY`.
199+
'packages/objectql/src/relation-group-join.ts': {
200+
kind: 'decided',
201+
read:
202+
"the engine's relation group join (an analytics dimension through a lookup grouped by the related record's " +
203+
'attribute in one statement; `referenceTargetOf` checks that the relation points at the object the request names)',
204+
operation: 'aggregate',
205+
decision: { file: 'packages/services/service-analytics/src/api-exposure-door.ts', fn: 'assertObjectsExposed' },
206+
wiring: { file: 'packages/services/service-analytics/src/analytics-service.ts', call: 'assertObjectsExposed(objects, provider' },
207+
pin: 'packages/services/service-analytics/src/__tests__/cross-object-relation-group-join.test.ts',
208+
},
198209
'packages/core/src/utils/relation-condition-sites.ts': {
199210
kind: 'not-a-served-read',
200211
reason:
@@ -489,6 +500,7 @@ describe('[#22661] every read that reaches a second object asks that object its
489500
(c): c is Extract<Classification, { kind: 'decided' }> => c.kind === 'decided',
490501
);
491502
expect(decided.map((d) => d.decision.fn).sort()).toEqual([
503+
'assertObjectsExposed',
492504
'refuseUnservedRelationTarget',
493505
'servesExpansionTarget',
494506
'servesLabelTarget',

‎packages/drivers/driver-sql/src/sql-driver-aggregation.ts‎

Lines changed: 114 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,9 +29,9 @@
2929
*/
3030

3131
import { coreSqlDialectOf } from './sql-driver-oracle-dialect.js';
32-
import { emptyGroupValueFor } from '@objectstack/spec/data';
32+
import { emptyGroupValueFor, isComposedReadableIds } from '@objectstack/spec/data';
3333
import type { Knex } from 'knex';
34-
import type { DriverOptions } from '@objectstack/spec/data';
34+
import type { ComposedReadableIds, DriverOptions } from '@objectstack/spec/data';
3535
import type { DriverQuery } from '@objectstack/spec/contracts';
3636
import { AGGREGATE_ACCUMULATION, AGGREGATE_ANSWER_KIND, aggregandOperandSql } from '@objectstack/core';
3737
import type { AggregandColumnClass } from '@objectstack/core';
@@ -79,6 +79,10 @@ export interface AggregationHost {
7979
export class AggregationFacet {
8080
/** The body of `SqlDriver#aggregate`; the method's docblock there is its contract. */
8181
static async aggregate(this: Pick<AggregationHost, 'aggregandColumnClassOf' | 'aggregateBackendFault' | 'aliasIdentifierSql' | 'applyFilters' | 'applyTenantScope' | 'buildDateBucketExpr' | 'coercionKey' | 'config' | 'dateGranularityCapabilities' | 'dialectName' | 'foldEmptyAggregateAnswers' | 'getBuilder' | 'isMssql' | 'isOracle' | 'knex' | 'mapAggregateFunc' | 'presentReadColumns' | 'primeMssqlGuidColumns' | 'primeOracleRawUuidColumns' | 'readPresentationKind' | 'remoteColumn'>, object: string, query: DriverQuery, options?: DriverOptions): Promise<Record<string, unknown>[]> {
82+
// [relation group join] The related rows each relation joins, handed by
83+
// the engine (`objectql` `relation-group-join.ts`); read once, judged
84+
// before anything compiles.
85+
const relationJoins = relationGroupJoinsOf(query);
8286
// [#33698] The per-measure `filter`s that carry a condition (`{}` is the
8387
// vacuous filter, same convention as `where` / `having`): each compiles
8488
// with the where compiler below, so each is primed and read like a `where`.
@@ -95,6 +99,13 @@ export class AggregationFacet {
9599
// [#31390] On Oracle a federated object's RAW(16) uuid columns are read from
96100
// the remote catalog before a comparand or a written value is bound.
97101
if (this.isOracle) await this.primeOracleRawUuidColumns(object);
102+
// …and the same two primes for each joined related object, whose scope
103+
// compiles against its own table.
104+
for (const join of relationJoins ?? []) {
105+
if (join.parent === null) continue;
106+
if (this.isMssql) await this.primeMssqlGuidColumns(join.parent.object, join.parent.scope);
107+
if (this.isOracle) await this.primeOracleRawUuidColumns(join.parent.object);
108+
}
98109
const builder = this.getBuilder(object, options);
99110
// The column a FIELD names in this statement: its `external.columnMap`
100111
// remote column on a federated object, the field itself otherwise. Every
@@ -240,6 +251,61 @@ export class AggregationFacet {
240251
}
241252
}
242253

254+
// [relation group join] Each relation the engine hands joins the related
255+
// rows the caller may read, and groups by their attributes:
256+
//
257+
// LEFT JOIN (SELECT id AS __rgN_id, attr AS __rgN_aJ … FROM related
258+
// WHERE <tenant wall> AND <composed read scope>) AS __rgN
259+
// ON fk = __rgN.__rgN_id
260+
// … GROUP BY __rgN.__rgN_aJ, CASE WHEN __rgN.__rgN_id IS NULL THEN 0 ELSE 1 END
261+
//
262+
// The derived table is compiled as a composed `ReadableIds` subquery is
263+
// (`readableIdsSubquery`): the related object's tenant wall from THIS
264+
// read's options (ADR-0139 D3 — the engine proved them the related read's
265+
// own) and its composed scope through this same where compiler, so it
266+
// binds only the scope's and the wall's own parameters, never one per
267+
// related record. Its columns are renamed so no column of the
268+
// aggregated table is ambiguous beside them; the join's left column is
269+
// the FK, unqualified, for the same reason. `__rgN_id` is unique in the
270+
// derived table (it is the key), so the join multiplies no row and every
271+
// measure aggregates the rows it would have without it. The resolved
272+
// column is `1` where a readable related record joined, `0` where none
273+
// did (an empty relation, or a record the caller cannot read) — the
274+
// attribute is NULL there, and the resolved column tells it from a real
275+
// NULL. A `null` parent is a related object nothing is readable of.
276+
(relationJoins ?? []).forEach((join, i) => {
277+
const at = `__rg${i}`;
278+
const idColumn = `${at}_id`;
279+
if (join.parent === null) {
280+
for (const a of join.attrs) builder.select(this.knex.raw(`NULL as ${this.aliasIdentifierSql(a.alias)}`));
281+
builder.select(this.knex.raw(`0 as ${this.aliasIdentifierSql(join.resolvedAlias)}`));
282+
presentedOutput.set(join.resolvedAlias, 'number');
283+
return;
284+
}
285+
const related = join.parent.object;
286+
const sub = this.getBuilder(related).select(
287+
this.knex.raw(`?? as ${this.aliasIdentifierSql(idColumn)}`, [this.remoteColumn(related, 'id', 'id')]),
288+
);
289+
join.attrs.forEach((a, j) => {
290+
sub.select(this.knex.raw(`?? as ${this.aliasIdentifierSql(`${at}_a${j}`)}`, [this.remoteColumn(related, a.attr, a.attr)]));
291+
});
292+
this.applyTenantScope(sub, related, options);
293+
if (join.parent.scope !== undefined) this.applyFilters(sub, join.parent.scope, options);
294+
const relatedTable = this.coercionKey(sub);
295+
builder.leftJoin(sub.as(at), columnOf(join.field), `${at}.${idColumn}`);
296+
join.attrs.forEach((a, j) => {
297+
const ref = `${at}.${at}_a${j}`;
298+
builder.groupBy(ref);
299+
builder.select(this.knex.raw(`?? as ${this.aliasIdentifierSql(a.alias)}`, [ref]));
300+
const kind = this.readPresentationKind(relatedTable, a.attr);
301+
if (kind) presentedOutput.set(a.alias, kind);
302+
});
303+
const resolved = 'CASE WHEN ?? IS NULL THEN 0 ELSE 1 END';
304+
builder.groupByRaw(resolved, [`${at}.${idColumn}`]);
305+
builder.select(this.knex.raw(`${resolved} as ${this.aliasIdentifierSql(join.resolvedAlias)}`, [`${at}.${idColumn}`]));
306+
presentedOutput.set(join.resolvedAlias, 'number');
307+
});
308+
243309
// [#6321] Was `query.aggregations || query.aggregate` / `agg.function ||
244310
// agg.func`. Neither `aggregate` nor `func` is declared anywhere in the
245311
// Query Protocol — `QueryASTSchema` declares `aggregations` and
@@ -457,6 +523,52 @@ export class AggregationFacet {
457523
}
458524
}
459525

526+
/**
527+
* [relation group join] The AST key the engine hands its relation joins on
528+
* (`objectql` `relation-group-join.ts`, the same `Symbol.for` key — this
529+
* package does not import the engine). A symbol, so no wire request and no
530+
* JSON query can carry one; set by the engine after every middleware ran.
531+
*/
532+
export const RELATION_GROUP_JOINS: unique symbol = Symbol.for('objectstack.driver.aggregate.relationGroupJoins');
533+
534+
/** One relation join, as the engine hands it. */
535+
export interface RelationGroupJoin {
536+
/** The single-valued relation (FK) column of the aggregated object. */
537+
readonly field: string;
538+
/** The related rows the caller may read, composed by the engine; `null` = none. */
539+
readonly parent: ComposedReadableIds | null;
540+
readonly attrs: ReadonlyArray<{ readonly attr: string; readonly alias: string }>;
541+
/** The output column: `1` where a readable related record joined, `0` where none did. */
542+
readonly resolvedAlias: string;
543+
}
544+
545+
/**
546+
* The joins on `query`, or `undefined` when it carries none. A parent that is
547+
* not a leaf the engine composed is refused before anything compiles, as an
548+
* uncomposed `ReadableIds` leaf is: its scope is the only thing that bounds
549+
* the joined rows, and ⛔ a scope the engine did not compose is never read as
550+
* one.
551+
*/
552+
function relationGroupJoinsOf(query: DriverQuery): readonly RelationGroupJoin[] | undefined {
553+
const joins = (query as unknown as Record<symbol, unknown>)[RELATION_GROUP_JOINS];
554+
if (joins === undefined) return undefined;
555+
const ok = Array.isArray(joins) && joins.every((j: RelationGroupJoin) =>
556+
j !== null && typeof j === 'object'
557+
&& typeof j.field === 'string'
558+
&& (j.parent === null || isComposedReadableIds(j.parent))
559+
&& Array.isArray(j.attrs) && j.attrs.every((a) => typeof a?.attr === 'string' && typeof a?.alias === 'string')
560+
&& typeof j.resolvedAlias === 'string');
561+
if (!ok) {
562+
const err = new Error(
563+
'aggregate: a relation group join the engine did not compose was refused; the query was NOT run.',
564+
) as Error & { code?: string; status?: number };
565+
err.code = 'INTERNAL_ERROR';
566+
err.status = 500;
567+
throw err;
568+
}
569+
return joins as readonly RelationGroupJoin[];
570+
}
571+
460572
/**
461573
* The aggregate operand on SQL Server — the two `@objectstack/core` operand
462574
* policies (`aggregandOperandSql`), restated for the one dialect that policy

0 commit comments

Comments
 (0)