Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions .changeset/31340-driver-sql-columnmap-aggregate-distinct.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
---
'@objectstack/driver-sql': patch
---

fix(driver-sql): `aggregate()` and `distinct()` honour `external.columnMap` on every dialect

Clause-②: no
Metadata-protocol: none

A federated object whose `external.columnMap` names a remote column different from the field could not be aggregated or listed for distinct values. `find()`, `count()` and every WHERE already read through the map, but `aggregate()` named the field verbatim in its GROUP BY, its date-bucket expression and its aggregand, and `distinct()` named it in `SELECT DISTINCT`. The remote table was asked for a column it does not have. On SQLite, PostgreSQL and MySQL that surfaced as the driver's unresolvable-column refusal.

Both doors now spell every identifier as the remote column and keep the field everywhere the caller reads: as the output key, in the presentation (`min`/`max` over a mapped date, a mapped boolean's distinct values) and in the per-field registries. An object without a `columnMap` compiles exactly the statement it compiled before.
12 changes: 12 additions & 0 deletions .changeset/31340-driver-sql-columnmap-by-id-writes.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
---
'@objectstack/driver-sql': patch
---

fix(driver-sql): `update()`, `delete()` and `bulkDelete()` find their row through `external.columnMap` on every dialect

Clause-②: no
Metadata-protocol: none

A federated object whose `external.columnMap` maps its key to a remote column (`CUST_NO: 'id'`) could be created and read, but not updated or deleted by id. The payload was already mapped, but the by-id doors wrote `WHERE "id" = ?` whatever the map said. The same held on SQLite, PostgreSQL and MySQL. On a remote table without an `id` column the statement failed. On a remote table that also has its own `id` column, which is not the mapped key, it matched rows by that other column: an update answered `null` or a delete removed a row nobody named.

The three doors now match the key's mapped column, the column the insert read-back already used. An object without a `columnMap`, and every rotation shard, compiles the statement it compiled before.
33 changes: 23 additions & 10 deletions packages/drivers/driver-sql/src/sql-driver-aggregation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,13 +66,24 @@ export interface AggregationHost {
readonly numericFields: SqlDriver['numericFields'];
presentReadColumns: SqlDriver['presentReadColumns'];
readPresentationKind: SqlDriver['readPresentationKind'];
remoteColumn: SqlDriver['remoteColumn'];
}

/** The bodies of the "Aggregation" section of `SqlDriver`: a stateless facet, called by the class's stubs. */
export class AggregationFacet {
/** The body of `SqlDriver#aggregate`; the method's docblock there is its contract. */
static async aggregate(this: Pick<AggregationHost, 'aggregandColumnClassOf' | 'aggregateBackendFault' | 'aliasIdentifierSql' | 'applyFilters' | 'applyTenantScope' | 'buildDateBucketExpr' | 'coercionKey' | 'config' | 'dateGranularityCapabilities' | 'dialectName' | 'foldEmptyAggregateAnswers' | 'getBuilder' | 'knex' | 'mapAggregateFunc' | 'presentReadColumns' | 'readPresentationKind'>, object: string, query: DriverQuery, options?: DriverOptions): Promise<Record<string, unknown>[]> {
static async aggregate(this: Pick<AggregationHost, 'aggregandColumnClassOf' | 'aggregateBackendFault' | 'aliasIdentifierSql' | 'applyFilters' | 'applyTenantScope' | 'buildDateBucketExpr' | 'coercionKey' | 'config' | 'dateGranularityCapabilities' | 'dialectName' | 'foldEmptyAggregateAnswers' | 'getBuilder' | 'knex' | 'mapAggregateFunc' | 'presentReadColumns' | 'readPresentationKind' | 'remoteColumn'>, object: string, query: DriverQuery, options?: DriverOptions): Promise<Record<string, unknown>[]> {
const builder = this.getBuilder(object, options);
// The column a FIELD names in this statement: its `external.columnMap`
// remote column on a federated object, the field itself otherwise. Every
// identifier below is spelled through it, while every registry lookup
// (`readPresentationKind`, `aggregandColumnClassOf`, the bucket's
// `temporalFieldKind`) and every output key stays the FIELD — the name the
// caller asked for and reads back. `find()` / `count()` / the WHERE have
// always mapped (`remoteColumn` in `findRows`, `applyFilters`); this door
// named the field verbatim, so a mapped object's GROUP BY / aggregand /
// `distinct` asked the remote table for a column it does not have.
const columnOf = (field: string): string => this.remoteColumn(object, field, field);
this.applyTenantScope(builder, object, options);

if (query.where) {
Expand Down Expand Up @@ -115,8 +126,9 @@ export class AggregationFacet {
// what forced the `as any` on the `buildDateBucketExpr` call below.
for (const g of query.groupBy) {
if (typeof g === 'string') {
builder.groupBy(g);
builder.select(g);
const column = columnOf(g);
builder.groupBy(column);
builder.select(column === g ? g : this.knex.raw(`?? as ${this.aliasIdentifierSql(g)}`, [column]));
const kind = this.readPresentationKind(table, g);
if (kind) presentedOutput.set(g, kind);
} else if (g && typeof g === 'object' && g.field) {
Expand All @@ -133,7 +145,7 @@ export class AggregationFacet {
// moves.
const outKey = g.alias ?? g.field;
if (g.dateGranularity) {
const bucket = this.buildDateBucketExpr(g.field, g.dateGranularity, table);
const bucket = this.buildDateBucketExpr(g.field, g.dateGranularity, table, columnOf(g.field));
if (!bucket) {
// [#6212] Was a bare `throw new Error(...)`; see
// {@link refuseDateBucketedGroupBy} for why it now carries the
Expand All @@ -147,14 +159,15 @@ export class AggregationFacet {
builder.groupByRaw(bucket.sql, bucket.bindings);
builder.select(this.knex.raw(`${bucket.sql} as ${this.aliasIdentifierSql(outKey)}`, [...bucket.bindings]));
} else {
builder.groupBy(g.field);
const column = columnOf(g.field);
builder.groupBy(column);
// Aliased only when the name actually moves: an alias equal to
// the field would otherwise rewrite `select "region"` into
// the column would otherwise rewrite `select "region"` into
// `select "region" as "region"` on every dialect for no gain.
// [#13714] The alias half is {@link aliasIdentifierSql}, never a
// `??` binding — the FIELD stays a `??` reference (it may be
// `??` binding — the COLUMN stays a `??` reference (it may be
// qualified), the alias is one identifier by definition.
builder.select(outKey === g.field ? g.field : this.knex.raw(`?? as ${this.aliasIdentifierSql(outKey)}`, [g.field]));
builder.select(outKey === column ? column : this.knex.raw(`?? as ${this.aliasIdentifierSql(outKey)}`, [column]));
// Keyed by the OUTPUT column, like the aggregation branch below —
// `presentReadColumns` matches on the name the row actually
// carries, so an aliased group value went unpresented before.
Expand Down Expand Up @@ -230,7 +243,7 @@ export class AggregationFacet {
if (fieldExpr === '*') {
builder.select(this.knex.raw(`${lowering.sql}(*) as ${this.aliasIdentifierSql(agg.alias)}`));
} else {
builder.select(this.knex.raw(`${rawFunc} as ${this.aliasIdentifierSql(agg.alias)}`, [fieldExpr]));
builder.select(this.knex.raw(`${rawFunc} as ${this.aliasIdentifierSql(agg.alias)}`, [columnOf(fieldExpr)]));
}
// [#15546] What this aggregate answers over NOTHING, read from the
// policy rather than restated: `sum` (and the two counts, which never
Expand Down Expand Up @@ -279,7 +292,7 @@ export class AggregationFacet {
if (fieldExpr === '*') {
builder.select(this.knex.raw(`${lowering.sql}(*)`));
} else {
builder.select(this.knex.raw(rawFunc, [fieldExpr]));
builder.select(this.knex.raw(rawFunc, [columnOf(fieldExpr)]));
}
}
}
Expand Down
7 changes: 5 additions & 2 deletions packages/drivers/driver-sql/src/sql-driver-bulk-operations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ export interface BulkOperationsHost {
readonly knex: SqlDriver['knex'];
readBackInsertedRows: SqlDriver['readBackInsertedRows'];
resyncSequenceToDataMax: SqlDriver['resyncSequenceToDataMax'];
remoteColumn: SqlDriver['remoteColumn'];
rotationShardsOf: SqlDriver['rotationShardsOf'];
rotationWriteTarget: SqlDriver['rotationWriteTarget'];
stampInsertTimestamps: SqlDriver['stampInsertTimestamps'];
Expand Down Expand Up @@ -256,10 +257,12 @@ export class BulkOperationsFacet {
}

/** The body of `SqlDriver#bulkDelete`; the method's docblock there is its contract. */
static async bulkDelete(this: Pick<BulkOperationsHost, 'applyTenantScope' | 'auditMissingTenant' | 'getBuilder' | 'rotationShardsOf'>, object: string, ids: Array<string | number>, options?: DriverOptions): Promise<void> {
static async bulkDelete(this: Pick<BulkOperationsHost, 'applyTenantScope' | 'auditMissingTenant' | 'getBuilder' | 'remoteColumn' | 'rotationShardsOf'>, object: string, ids: Array<string | number>, options?: DriverOptions): Promise<void> {
this.auditMissingTenant(object, 'bulkDelete', options);
for (const target of this.rotationShardsOf(object) ?? [object]) {
const builder = this.getBuilder(target, options).whereIn('id', ids);
// The primary key's column: the `external.columnMap` remote column on a
// federated object, `id` otherwise (a rotation shard is never federated).
const builder = this.getBuilder(target, options).whereIn(this.remoteColumn(object, 'id', 'id'), ids);
this.applyTenantScope(builder, object, options);
await builder.delete();
}
Expand Down
10 changes: 9 additions & 1 deletion packages/drivers/driver-sql/src/sql-driver-date-bucket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,9 +59,17 @@ export interface DateBucketHost {
}

/** The body of `SqlDriver#buildDateBucketExpr`; the method's docblock there is its contract. */
export function buildDateBucketExpr(this: Pick<DateBucketHost, 'dateGranularityCapabilities' | 'isMysql' | 'isPostgres' | 'isSqlite' | 'sqliteTemporalArg' | 'temporalFieldKind'>, field: string, granularity: 'day' | 'week' | 'month' | 'quarter' | 'year', table?: string | null): { sql: string; bindings: any[] } | null {
export function buildDateBucketExpr(this: Pick<DateBucketHost, 'dateGranularityCapabilities' | 'isMysql' | 'isPostgres' | 'isSqlite' | 'sqliteTemporalArg' | 'temporalFieldKind'>, field: string, granularity: 'day' | 'week' | 'month' | 'quarter' | 'year', table?: string | null, column: string = field): { sql: string; bindings: any[] } | null {
if (!this.dateGranularityCapabilities[granularity]) return null;

// `field` is the FIELD — the registries (`temporalFieldKind`, the SQLite
// repair) are keyed by it; `column` is the identifier the statement names,
// the remote column an `external.columnMap` maps the field to.
if (column !== field) {
const bucket = buildDateBucketExpr.call(this, field, granularity, table);
return bucket && { sql: bucket.sql, bindings: bucket.bindings.map((b) => (b === field ? column : b)) };
}

const calendarDay = this.temporalFieldKind(table, field) === 'date';

if (this.isPostgres) {
Expand Down
12 changes: 9 additions & 3 deletions packages/drivers/driver-sql/src/sql-driver-distinct.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,12 +46,13 @@ export interface DistinctHost {
getBuilder: SqlDriver['getBuilder'];
presentReadValue: SqlDriver['presentReadValue'];
readPresentationKind: SqlDriver['readPresentationKind'];
remoteColumn: SqlDriver['remoteColumn'];
}

/** The bodies of the "Distinct" section of `SqlDriver`: a stateless facet, called by the class's stubs. */
export class DistinctFacet {
/** The body of `SqlDriver#distinct`; the method's docblock there is its contract. */
static async distinct(this: Pick<DistinctHost, 'applyFilters' | 'applyTenantScope' | 'coercionKey' | 'distinctBackendFault' | 'getBuilder' | 'presentReadValue' | 'readPresentationKind'>, object: string, field: string, filters?: FilterCondition, options?: DriverOptions): Promise<any[]> {
static async distinct(this: Pick<DistinctHost, 'applyFilters' | 'applyTenantScope' | 'coercionKey' | 'distinctBackendFault' | 'getBuilder' | 'presentReadValue' | 'readPresentationKind' | 'remoteColumn'>, object: string, field: string, filters?: FilterCondition, options?: DriverOptions): Promise<any[]> {
const builder = this.getBuilder(object, options);
// The third read door that skipped the chokepoint, and the one #6792 does
// NOT name — the card asserts the opposite ("called at 13 sites — …,
Expand All @@ -70,7 +71,12 @@ export class DistinctFacet {
this.applyFilters(builder, filters, options);
}

builder.distinct(field);
// The column the field names on this table — its `external.columnMap`
// remote column on a federated object (the mapping `find()` and the WHERE
// above already apply), the field itself otherwise. The values are read
// back under that column, and presented by the FIELD's registry entry.
const column = this.remoteColumn(object, field, field);
builder.distinct(column);
// [commit 7c2c5aedd] The THIRD read door joins the other two. `find()` and `count()`
// have carried the terminal envelope since #8931 and `aggregate()` since
// #11455; this one still executed BARE, so any dialect refusal the
Expand Down Expand Up @@ -123,7 +129,7 @@ export class DistinctFacet {
} catch (error) {
throw this.distinctBackendFault(object, field, error, filters);
}
const values = results.map((row: any) => row[field]);
const values = results.map((row: any) => row[column]);

// Same presentation `find()` gives the column (#3797, #3849) — a caller
// listing a datetime's values should not get epoch integers here and ISO
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

/**
* `aggregate()` and `distinct()` honour `external.columnMap` (ADR-0015 §18).
*
* `find()`, `count()` and every WHERE have mapped a federated object's local
* field to its remote column since columnMap landed (`remoteColumn` in
* `findRows`, `applyFilters`). The two analytic doors did not: they named the
* FIELD verbatim in GROUP BY, in the aggregand and in `SELECT DISTINCT`, so
* the remote table was asked for a column it does not have. Measured before
* the fix on SQLite (this file's fixture) as the driver's unattributed-column
* refusal.
*
* The rule pinned here: identifiers are the REMOTE column; output keys,
* presentation and the per-field registries stay the FIELD.
*/

import { describe, it, expect, afterAll, beforeAll } from 'vitest';
import { rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { SqlDriver } from './index.js';

const REMOTE = {
name: 'legacy_deal',
fields: {
deal_no: { type: 'text' },
region_code: { type: 'text' },
amt: { type: 'number' },
closed_dt: { type: 'date' },
won_flag: { type: 'boolean' },
},
};

const COLUMN_MAP = { deal_no: 'id', region_code: 'region', amt: 'amount', closed_dt: 'closed_on', won_flag: 'won' };
const LOCAL_FIELDS = {
region: { type: 'text' },
amount: { type: 'number' },
closed_on: { type: 'date' },
won: { type: 'boolean' },
};

let file: string;
let driver: any;

beforeAll(async () => {
file = join(tmpdir(), `os-cm-agg-${process.pid}-${Date.now()}.db`);
const fx = new SqlDriver({ client: 'better-sqlite3', connection: { filename: file }, useNullAsDefault: true }) as any;
fx.name = 'fx';
await fx.connect();
await fx.initObjects([REMOTE]);
await fx.create('legacy_deal', { deal_no: 'd1', region_code: 'NA', amt: 100, closed_dt: '2026-01-10', won_flag: true });
await fx.create('legacy_deal', { deal_no: 'd2', region_code: 'EU', amt: 40, closed_dt: '2026-01-20', won_flag: false });
await fx.create('legacy_deal', { deal_no: 'd3', region_code: 'EU', amt: 60, closed_dt: '2026-04-02', won_flag: true });
await fx.disconnect();

driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: file }, useNullAsDefault: true, schemaMode: 'external' } as any) as any;
driver.name = 'extds';
await driver.connect();
driver.registerExternalObject({ name: 'deal', external: { remoteName: 'legacy_deal', columnMap: COLUMN_MAP }, fields: LOCAL_FIELDS });
});

afterAll(async () => {
await driver?.disconnect();
if (file) rmSync(file, { force: true });
});

const byRegion = (rows: any[]) => [...rows].sort((a, b) => String(a.region).localeCompare(String(b.region)));

describe('aggregate() over a columnMap-ed object', () => {
it('groups by the remote column and keys the group under the field', async () => {
const rows = await driver.aggregate('deal', {
groupBy: ['region'],
aggregations: [{ function: 'sum', field: 'amount', alias: 'total' }, { function: 'count', alias: 'n' }],
});
expect(byRegion(rows)).toEqual([
{ region: 'EU', total: 100, n: 2 },
{ region: 'NA', total: 100, n: 1 },
]);
});

it('an aliased structured group key lands under its alias', async () => {
const rows = await driver.aggregate('deal', {
groupBy: [{ field: 'region', alias: 'r' }],
aggregations: [{ function: 'max', field: 'amount', alias: 'top' }],
});
expect([...rows].sort((a: any, b: any) => a.r.localeCompare(b.r))).toEqual([
{ r: 'EU', top: 60 },
{ r: 'NA', top: 100 },
]);
});

it('a date-bucketed group reads the remote column and keeps the field registry (calendar day)', async () => {
const rows = await driver.aggregate('deal', {
groupBy: [{ field: 'closed_on', dateGranularity: 'month' }],
aggregations: [{ function: 'count', alias: 'n' }],
});
expect([...rows].sort((a: any, b: any) => a.closed_on.localeCompare(b.closed_on))).toEqual([
{ closed_on: '2026-01', n: 2 },
{ closed_on: '2026-04', n: 1 },
]);
});

it('min/max over a mapped column take the field presentation; count_distinct maps too', async () => {
const [row] = await driver.aggregate('deal', {
aggregations: [
{ function: 'min', field: 'closed_on', alias: 'first' },
{ function: 'count_distinct', field: 'region', alias: 'regions' },
],
});
expect(row).toEqual({ first: '2026-01-10', regions: 2 });
});

it('the WHERE and the GROUP BY agree on the mapping', async () => {
const rows = await driver.aggregate('deal', {
where: { won: true },
groupBy: ['region'],
aggregations: [{ function: 'sum', field: 'amount', alias: 'total' }],
});
expect(byRegion(rows)).toEqual([
{ region: 'EU', total: 60 },
{ region: 'NA', total: 100 },
]);
});
});

describe('distinct() over a columnMap-ed object', () => {
it('reads the remote column and answers its values', async () => {
expect([...(await driver.distinct('deal', 'region'))].sort()).toEqual(['EU', 'NA']);
});

it('presents by the field registry (a mapped boolean reads as a boolean)', async () => {
expect([...(await driver.distinct('deal', 'won'))].sort()).toEqual([false, true]);
});

it('with a filter on another mapped field', async () => {
expect(await driver.distinct('deal', 'region', { amount: { $gt: 50 } })).toEqual(expect.arrayContaining(['EU', 'NA']));
expect(await driver.distinct('deal', 'region', { amount: { $lt: 50 } })).toEqual(['EU']);
});
});
Loading
Loading