From f9a071404e4550c94868425d8db23efdcfd2d5c2 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 8 Nov 2026 02:47:02 +0000 Subject: [PATCH 1/3] fix(driver-sql): aggregate() and distinct() honour external.columnMap on every dialect GROUP BY, the date-bucket expression, the aggregand and SELECT DISTINCT named the field verbatim, so a columnMap-ed federated object was asked for a column its remote table does not have. Identifiers are now the remote column; output keys, presentation and the per-field registries stay the field. buildDateBucketExpr gains a column parameter: the registries are read by the field, the statement names the column. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_017ihL2euiyuLXizr6FW32R3 --- ...driver-sql-columnmap-aggregate-distinct.md | 12 ++ .../driver-sql/src/sql-driver-aggregation.ts | 33 +++-- .../driver-sql/src/sql-driver-date-bucket.ts | 10 +- .../driver-sql/src/sql-driver-distinct.ts | 12 +- ...river-external-columnmap-aggregate.test.ts | 140 ++++++++++++++++++ packages/drivers/driver-sql/src/sql-driver.ts | 5 +- 6 files changed, 197 insertions(+), 15 deletions(-) create mode 100644 .changeset/31340-driver-sql-columnmap-aggregate-distinct.md create mode 100644 packages/drivers/driver-sql/src/sql-driver-external-columnmap-aggregate.test.ts diff --git a/.changeset/31340-driver-sql-columnmap-aggregate-distinct.md b/.changeset/31340-driver-sql-columnmap-aggregate-distinct.md new file mode 100644 index 00000000000..8e1fa871f50 --- /dev/null +++ b/.changeset/31340-driver-sql-columnmap-aggregate-distinct.md @@ -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. diff --git a/packages/drivers/driver-sql/src/sql-driver-aggregation.ts b/packages/drivers/driver-sql/src/sql-driver-aggregation.ts index 75187c12b85..e7cafe4c8a0 100644 --- a/packages/drivers/driver-sql/src/sql-driver-aggregation.ts +++ b/packages/drivers/driver-sql/src/sql-driver-aggregation.ts @@ -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, object: string, query: DriverQuery, options?: DriverOptions): Promise[]> { + static async aggregate(this: Pick, object: string, query: DriverQuery, options?: DriverOptions): Promise[]> { 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) { @@ -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) { @@ -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 @@ -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. @@ -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 @@ -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)])); } } } diff --git a/packages/drivers/driver-sql/src/sql-driver-date-bucket.ts b/packages/drivers/driver-sql/src/sql-driver-date-bucket.ts index 0bb2ccab65a..455e524e30c 100644 --- a/packages/drivers/driver-sql/src/sql-driver-date-bucket.ts +++ b/packages/drivers/driver-sql/src/sql-driver-date-bucket.ts @@ -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, field: string, granularity: 'day' | 'week' | 'month' | 'quarter' | 'year', table?: string | null): { sql: string; bindings: any[] } | null { +export function buildDateBucketExpr(this: Pick, 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) { diff --git a/packages/drivers/driver-sql/src/sql-driver-distinct.ts b/packages/drivers/driver-sql/src/sql-driver-distinct.ts index ac5318634c5..68c98f20de0 100644 --- a/packages/drivers/driver-sql/src/sql-driver-distinct.ts +++ b/packages/drivers/driver-sql/src/sql-driver-distinct.ts @@ -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, object: string, field: string, filters?: FilterCondition, options?: DriverOptions): Promise { + static async distinct(this: Pick, object: string, field: string, filters?: FilterCondition, options?: DriverOptions): Promise { 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 — …, @@ -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 @@ -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 diff --git a/packages/drivers/driver-sql/src/sql-driver-external-columnmap-aggregate.test.ts b/packages/drivers/driver-sql/src/sql-driver-external-columnmap-aggregate.test.ts new file mode 100644 index 00000000000..b7a8718c495 --- /dev/null +++ b/packages/drivers/driver-sql/src/sql-driver-external-columnmap-aggregate.test.ts @@ -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']); + }); +}); diff --git a/packages/drivers/driver-sql/src/sql-driver.ts b/packages/drivers/driver-sql/src/sql-driver.ts index cb0d17aab70..35a646ca469 100644 --- a/packages/drivers/driver-sql/src/sql-driver.ts +++ b/packages/drivers/driver-sql/src/sql-driver.ts @@ -1144,6 +1144,7 @@ export class SqlDriver implements IDataDriver { field: string, granularity: 'day' | 'week' | 'month' | 'quarter' | 'year', table?: string | null, + column?: string, ): { sql: string; bindings: any[] } | null { // [#25521 cut 20] The body moved to `sql-driver-date-bucket.ts` (see `DateBucketHost`). const readDateGranularityCapabilities = () => this.dateGranularityCapabilities; @@ -1158,7 +1159,7 @@ export class SqlDriver implements IDataDriver { sqliteTemporalArg: (...a) => this.sqliteTemporalArg(...a), temporalFieldKind: (...a) => this.temporalFieldKind(...a), }; - return buildDateBucketExpr.call(host, field, granularity, table); + return buildDateBucketExpr.call(host, field, granularity, table, column); } /** @@ -8871,6 +8872,7 @@ export class SqlDriver implements IDataDriver { get numericFields() { return driver.numericFields; }, presentReadColumns: (...a) => driver.presentReadColumns(...a), readPresentationKind: (...a) => driver.readPresentationKind(...a), + remoteColumn: (...a) => driver.remoteColumn(...a), })); bulkOperationsHost.install((driver) => ({ applyFilters: (...a) => driver.applyFilters(...a), @@ -9014,6 +9016,7 @@ export class SqlDriver implements IDataDriver { get getBuilder() { return driver.getBuilder.bind(driver); }, presentReadValue: (...a) => driver.presentReadValue(...a), readPresentationKind: (...a) => driver.readPresentationKind(...a), + remoteColumn: (...a) => driver.remoteColumn(...a), })); fieldMappingHost.install((driver) => ({ get fieldColumnByObject() { return driver.fieldColumnByObject; }, From 8c6430175afb69a2413c98d6bb7e9163bc9ce8f2 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 8 Nov 2026 02:52:50 +0000 Subject: [PATCH 2/3] fix(driver-sql): update(), delete() and bulkDelete() find their row through external.columnMap The by-id doors wrote WHERE "id" = ? whatever the map said: a failure on a remote table without an id column, and a match on the wrong column on one that has its own. They now match the key's mapped column, as the insert read-back already did. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_017ihL2euiyuLXizr6FW32R3 --- ...31340-driver-sql-columnmap-by-id-writes.md | 12 +++ .../src/sql-driver-bulk-operations.ts | 7 +- ...l-driver-external-columnmap-writes.test.ts | 101 ++++++++++++++++++ .../src/sql-driver-sequence-semantics.ts | 16 ++- packages/drivers/driver-sql/src/sql-driver.ts | 1 + 5 files changed, 130 insertions(+), 7 deletions(-) create mode 100644 .changeset/31340-driver-sql-columnmap-by-id-writes.md create mode 100644 packages/drivers/driver-sql/src/sql-driver-external-columnmap-writes.test.ts diff --git a/.changeset/31340-driver-sql-columnmap-by-id-writes.md b/.changeset/31340-driver-sql-columnmap-by-id-writes.md new file mode 100644 index 00000000000..1517e4b4b89 --- /dev/null +++ b/.changeset/31340-driver-sql-columnmap-by-id-writes.md @@ -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. 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. diff --git a/packages/drivers/driver-sql/src/sql-driver-bulk-operations.ts b/packages/drivers/driver-sql/src/sql-driver-bulk-operations.ts index 5c6d868be5d..962113d4bf1 100644 --- a/packages/drivers/driver-sql/src/sql-driver-bulk-operations.ts +++ b/packages/drivers/driver-sql/src/sql-driver-bulk-operations.ts @@ -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']; @@ -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, object: string, ids: Array, options?: DriverOptions): Promise { + static async bulkDelete(this: Pick, object: string, ids: Array, options?: DriverOptions): Promise { 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(); } diff --git a/packages/drivers/driver-sql/src/sql-driver-external-columnmap-writes.test.ts b/packages/drivers/driver-sql/src/sql-driver-external-columnmap-writes.test.ts new file mode 100644 index 00000000000..3f662c9a6e2 --- /dev/null +++ b/packages/drivers/driver-sql/src/sql-driver-external-columnmap-writes.test.ts @@ -0,0 +1,101 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * `update()`, `delete()` and `bulkDelete()` find their row through + * `external.columnMap` (ADR-0015 §18). + * + * The write payload has been mapped since columnMap landed + * (`applyWriteColumnMap`), and so has the insert read-back + * (`readBackInsertedRows`). The by-id doors were not: they wrote + * `WHERE "id" = ?` whatever the map said, so on a federated object whose key + * column is `CUST_NO` they asked for a column the remote table does not have. + * Measured before the fix on SQLite (this file). + * + * The second fixture is the silent half: a remote table that ALSO has a + * column literally named `id`, which is not the mapped key. The unmapped + * statement then updated and deleted rows by THAT column. + */ + +import { describe, it, expect, afterEach } from 'vitest'; +import { SqlDriver } from './index.js'; + +async function driverOver(ddl: string, rows: string[]): Promise { + const d = new SqlDriver({ + client: 'better-sqlite3', + connection: { filename: ':memory:' }, + useNullAsDefault: true, + pool: { min: 1, max: 1 }, + schemaMode: 'external', + } as any) as any; + d.name = 'extds'; + await d.connect(); + await d.knex.raw(ddl); + for (const row of rows) await d.knex.raw(row); + return d; +} + +let driver: any; +afterEach(async () => { await driver?.disconnect(); driver = undefined; }); + +describe('by-id writes over a columnMap-ed key', () => { + const ddl = 'create table legacy_cust (CUST_NO text primary key, FULL_NAME text)'; + const rows = ["insert into legacy_cust values ('c1', 'Aurora'), ('c2', 'Borealis'), ('c3', 'Cyan')"]; + const register = (d: any) => d.registerExternalObject({ + name: 'cust', + external: { remoteName: 'legacy_cust', columnMap: { CUST_NO: 'id', FULL_NAME: 'name' } }, + fields: { name: { type: 'text' } }, + }); + + it('update() writes the row the mapped key names and reads it back', async () => { + driver = await driverOver(ddl, rows); + register(driver); + expect(await driver.update('cust', 'c2', { name: 'Bore' })).toEqual({ id: 'c2', name: 'Bore' }); + expect(await driver.findOne('cust', { where: { id: 'c2' } })).toEqual({ id: 'c2', name: 'Bore' }); + }); + + it('delete() removes the row the mapped key names', async () => { + driver = await driverOver(ddl, rows); + register(driver); + expect(await driver.delete('cust', 'c1')).toBe(true); + expect((await driver.find('cust', {})).map((r: any) => r.id).sort()).toEqual(['c2', 'c3']); + }); + + it('bulkDelete() removes the rows the mapped keys name', async () => { + driver = await driverOver(ddl, rows); + register(driver); + await driver.bulkDelete('cust', ['c1', 'c3']); + expect((await driver.find('cust', {})).map((r: any) => r.id)).toEqual(['c2']); + }); +}); + +describe('a remote table with its own unmapped `id` column (the silent case)', () => { + // `id` here is a surrogate the remote system owns; the object's key is CODE. + const ddl = 'create table legacy_part (id integer, CODE text primary key, LABEL text)'; + const rows = ["insert into legacy_part values (1, 'B', 'bolt'), (2, 'A', 'anchor')"]; + const register = (d: any) => d.registerExternalObject({ + name: 'part', + external: { remoteName: 'legacy_part', columnMap: { CODE: 'id', LABEL: 'label' } }, + fields: { label: { type: 'text' } }, + }); + + it('update() by key does not touch the row whose surrogate equals the key', async () => { + driver = await driverOver(ddl, rows); + register(driver); + // Key 'A' is the row with surrogate id 2. The unmapped statement matched + // `id = 'A'` (no row) and answered null; the mapped one updates CODE 'A'. + expect(await driver.update('part', 'A', { label: 'anchor!' })).toEqual({ id: 'A', label: 'anchor!' }); + const raw = await driver.knex('legacy_part').select('id', 'CODE', 'LABEL').orderBy('id'); + expect(raw).toEqual([ + { id: 1, CODE: 'B', LABEL: 'bolt' }, + { id: 2, CODE: 'A', LABEL: 'anchor!' }, + ]); + }); + + it('delete() by key removes that row, not the one whose surrogate matches', async () => { + driver = await driverOver(ddl, rows); + register(driver); + // Key '1' names no row by CODE; the unmapped statement deleted surrogate 1. + expect(await driver.delete('part', '1')).toBe(false); + expect(await driver.knex('legacy_part').count({ n: '*' })).toEqual([{ n: 2 }]); + }); +}); diff --git a/packages/drivers/driver-sql/src/sql-driver-sequence-semantics.ts b/packages/drivers/driver-sql/src/sql-driver-sequence-semantics.ts index 9832f9d3c18..366985819cb 100644 --- a/packages/drivers/driver-sql/src/sql-driver-sequence-semantics.ts +++ b/packages/drivers/driver-sql/src/sql-driver-sequence-semantics.ts @@ -275,16 +275,20 @@ export class SequenceSemanticsFacet { } /** The body of `SqlDriver#update`; the method's docblock there is its contract. */ - static async update(this: Pick, object: string, id: string | number, data: Record, options?: DriverOptions): Promise | null> { + static async update(this: Pick, object: string, id: string | number, data: Record, options?: DriverOptions): Promise | null> { this.auditMissingTenant(object, 'update', options); const rotationShards = this.rotationShardsOf(object); if (rotationShards) return this.rotatedUpdateById(object, rotationShards, id, data, options); const formatted = this.applyWriteColumnMap(object, this.formatInput(object, data)); + // The primary key's column: its `external.columnMap` remote column on a + // federated object (the mapping the payload above just went through), `id` + // otherwise. + const idColumn = this.remoteColumn(object, 'id', 'id'); // One definition of the statement, so the speculative attempt, the fenced // retry and the plain path cannot drift in WHERE or tenant scope. const issue = (payload: Record, issueOptions?: DriverOptions): Promise => { - const builder = this.getBuilder(object, issueOptions).where('id', id); + const builder = this.getBuilder(object, issueOptions).where(idColumn, id); this.applyTenantScope(builder, object, issueOptions); return builder.update(payload) as unknown as Promise; }; @@ -308,7 +312,7 @@ export class SequenceSemanticsFacet { await issue(formatted, options); } - const readback = this.getBuilder(object, options).where('id', id); + const readback = this.getBuilder(object, options).where(idColumn, id); this.applyTenantScope(readback, object, options); const updated = await readback.first(); return this.formatOutput(object, updated) || null; @@ -913,7 +917,7 @@ export class SequenceSemanticsFacet { } /** The body of `SqlDriver#delete`; the method's docblock there is its contract. */ - static async delete(this: Pick, object: string, id: string | number, options?: DriverOptions): Promise { + static async delete(this: Pick, object: string, id: string | number, options?: DriverOptions): Promise { this.auditMissingTenant(object, 'delete', options); const rotationShards = this.rotationShardsOf(object); if (rotationShards) { @@ -926,7 +930,9 @@ export class SequenceSemanticsFacet { } return false; } - const builder = this.getBuilder(object, options).where('id', id); + // The primary key's column — the `external.columnMap` remote column on a + // federated object (as `update` above), `id` otherwise. + const builder = this.getBuilder(object, options).where(this.remoteColumn(object, 'id', 'id'), id); this.applyTenantScope(builder, object, options); const count = await builder.delete(); return count > 0; diff --git a/packages/drivers/driver-sql/src/sql-driver.ts b/packages/drivers/driver-sql/src/sql-driver.ts index 35a646ca469..efea97f8a41 100644 --- a/packages/drivers/driver-sql/src/sql-driver.ts +++ b/packages/drivers/driver-sql/src/sql-driver.ts @@ -8892,6 +8892,7 @@ export class SqlDriver implements IDataDriver { get knex() { return driver.knex; }, readBackInsertedRows: (...a) => driver.readBackInsertedRows(...a), resyncSequenceToDataMax: (...a) => driver.resyncSequenceToDataMax(...a), + remoteColumn: (...a) => driver.remoteColumn(...a), rotationShardsOf: (...a) => driver.rotationShardsOf(...a), rotationWriteTarget: (...a) => driver.rotationWriteTarget(...a), stampInsertTimestamps: (...a) => driver.stampInsertTimestamps(...a), From 0ceca395b86619e516ec23818c428dfc69355cec Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 8 Nov 2026 02:57:13 +0000 Subject: [PATCH 3/3] docs(changeset): the by-id write changeset names every SQL dialect Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_017ihL2euiyuLXizr6FW32R3 --- .changeset/31340-driver-sql-columnmap-by-id-writes.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.changeset/31340-driver-sql-columnmap-by-id-writes.md b/.changeset/31340-driver-sql-columnmap-by-id-writes.md index 1517e4b4b89..74fcc15de69 100644 --- a/.changeset/31340-driver-sql-columnmap-by-id-writes.md +++ b/.changeset/31340-driver-sql-columnmap-by-id-writes.md @@ -7,6 +7,6 @@ fix(driver-sql): `update()`, `delete()` and `bulkDelete()` find their row throug 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. 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. +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.