From 1a28babd2660a122dd40f83ee5a289b417265d52 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 8 Nov 2026 16:25:12 +0000 Subject: [PATCH 1/6] fix(driver-sql): bind Oracle RAW(16) uuid comparands and writes through HEXTORAW The catalog says which federated columns are RAW(16); those fields bind uuid text as HEXTORAW(?) over its hex digits, as comparands, written values and by-id keys. Text that is not a uuid is refused before the statement is built. Every other column and dialect binds as before. Claude-Session: https://claude.ai/code/session_01ADHkmQ9H84XNocJ8waPS1P Co-authored-by: Claude --- .../src/sql-driver-bulk-operations.ts | 7 +- .../drivers/driver-sql/src/sql-driver-crud.ts | 17 ++- .../src/sql-driver-filter-helpers.ts | 11 +- .../src/sql-driver-oracle-dialect.ts | 95 ++++++++++++ .../src/sql-driver-sequence-semantics.ts | 17 ++- .../src/sql-driver-sqlite-serialisation.ts | 21 ++- packages/drivers/driver-sql/src/sql-driver.ts | 137 ++++++++++++++++-- 7 files changed, 273 insertions(+), 32 deletions(-) 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 6ea2c423915..11b22e30441 100644 --- a/packages/drivers/driver-sql/src/sql-driver-bulk-operations.ts +++ b/packages/drivers/driver-sql/src/sql-driver-bulk-operations.ts @@ -61,6 +61,7 @@ export interface BulkOperationsHost { readonly isMssql: SqlDriver['isMssql']; keepSuppliedUpdatedAt: SqlDriver['keepSuppliedUpdatedAt']; readonly knex: SqlDriver['knex']; + oracleUuidBinding: SqlDriver['oracleUuidBinding']; readBackInsertedRows: SqlDriver['readBackInsertedRows']; resyncSequenceToDataMax: SqlDriver['resyncSequenceToDataMax']; remoteColumn: SqlDriver['remoteColumn']; @@ -261,12 +262,14 @@ 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]) { // 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); + // [#31390] On Oracle a RAW(16) uuid key binds each id as `HEXTORAW(?)`. + const keys = ids.map((id) => this.oracleUuidBinding(object, 'id', id, 'comparand')); + const builder = this.getBuilder(target, options).whereIn(this.remoteColumn(object, 'id', 'id'), keys as any[]); this.applyTenantScope(builder, object, options); await builder.delete(); } diff --git a/packages/drivers/driver-sql/src/sql-driver-crud.ts b/packages/drivers/driver-sql/src/sql-driver-crud.ts index 8e179c279fc..91464858337 100644 --- a/packages/drivers/driver-sql/src/sql-driver-crud.ts +++ b/packages/drivers/driver-sql/src/sql-driver-crud.ts @@ -68,6 +68,7 @@ export interface CrudHost { readonly isSqlite: SqlDriver['isSqlite']; readonly knex: SqlDriver['knex']; mapSortField: SqlDriver['mapSortField']; + oracleUuidBinding: SqlDriver['oracleUuidBinding']; orderKeysFor: SqlDriver['orderKeysFor']; primeMssqlPagingKey: SqlDriver['primeMssqlPagingKey']; readBackInsertedRows: SqlDriver['readBackInsertedRows']; @@ -415,7 +416,7 @@ export class CrudFacet { * Refused with {@link insertedRowsNotReadBackError}, never answered with the * payload: see that function for why. */ - static async readBackInsertedRows(this: Pick, object: string, writeTable: string, written: Record[], options?: DriverOptions): Promise[]> { + static async readBackInsertedRows(this: Pick, object: string, writeTable: string, written: Record[], options?: DriverOptions): Promise[]> { if (written.length === 0) return []; const idColumn = this.remoteColumn(object, 'id', 'id'); const tenantField = this.resolveTenantField(object); @@ -437,15 +438,17 @@ export class CrudFacet { : { ...options }; const builder = this.getBuilder(writeTable, options); this.applyTenantScope(builder, object, scopeOptions); - const stored: Record[] = await builder.whereIn( - idColumn, - written.map((row) => row.id), - ); + // [#31390] On Oracle a RAW(16) uuid key binds each id as `HEXTORAW(?)`, and + // reads back as lowercase uuid text whatever case it was written in. + const keys = written.map((row) => this.oracleUuidBinding(object, 'id', row.id, 'comparand')); + const writtenKey = (row: Record, i: number): string => + keys[i] === row.id ? String(row.id) : String(row.id).toLowerCase(); + const stored: Record[] = await builder.whereIn(idColumn, keys as any[]); const byId = new Map>(); for (const row of stored) byId.set(String(row[idColumn]), row); - const missing = written.filter((row) => !byId.has(String(row.id))).map((row) => row.id); + const missing = written.filter((row, i) => !byId.has(writtenKey(row, i))).map((row) => row.id); if (missing.length > 0) throw insertedRowsNotReadBackError(object, missing, written.length); - return written.map((row) => this.formatOutput(object, byId.get(String(row.id)))); + return written.map((row, i) => this.formatOutput(object, byId.get(writtenKey(row, i)))); } /** The body of `SqlDriver#ensureSequencesTable`; the method's docblock there is its contract. */ diff --git a/packages/drivers/driver-sql/src/sql-driver-filter-helpers.ts b/packages/drivers/driver-sql/src/sql-driver-filter-helpers.ts index e6b3e8ca846..33f6e042b1c 100644 --- a/packages/drivers/driver-sql/src/sql-driver-filter-helpers.ts +++ b/packages/drivers/driver-sql/src/sql-driver-filter-helpers.ts @@ -107,6 +107,8 @@ export interface FilterHelpersHost { needsLegacyTimeRepair: SqlDriver['needsLegacyTimeRepair']; readonly numericFields: SqlDriver['numericFields']; readonly objectByPhysicalTable: SqlDriver['objectByPhysicalTable']; + readonly oracleRawUuidFieldsByObject: SqlDriver['oracleRawUuidFieldsByObject']; + oracleUuidBinding: SqlDriver['oracleUuidBinding']; presentReadValue: SqlDriver['presentReadValue']; readonly readableIdsDriverName: SqlDriver['readableIdsDriverName']; readonly readableIdsRefusalLog: SqlDriver['readableIdsRefusalLog']; @@ -155,10 +157,17 @@ export class FilterHelpersFacet { } /** The body of `SqlDriver#coerceFilterValue`; the method's docblock there is its contract. */ - static coerceFilterValue(this: Pick, table: string | null, field: string, value: any): any { + static coerceFilterValue(this: Pick, table: string | null, field: string, value: any): any { if (value == null || !table) return value; if (Array.isArray(value)) return value.map((v) => this.coerceFilterValue(table, field, v)); + // [#31390] Oracle: a comparand against a `RAW(16)` uuid column (as the + // catalog reports it — `SqlDriver#primeOracleRawUuidColumns`) binds as + // `HEXTORAW(?)`; a value that is not uuid text is INVALID_FILTER, unsent. + if (this.isOracle && this.oracleRawUuidFieldsByObject.get(table)?.has(field) === true) { + return this.oracleUuidBinding(table, field, value, 'comparand'); + } + const kind = this.temporalFieldKind(table, field); if (!kind) { // [#31328] A `Date` against a NON-temporal column on Oracle: the client diff --git a/packages/drivers/driver-sql/src/sql-driver-oracle-dialect.ts b/packages/drivers/driver-sql/src/sql-driver-oracle-dialect.ts index 11a41882b7e..b8c951f8912 100644 --- a/packages/drivers/driver-sql/src/sql-driver-oracle-dialect.ts +++ b/packages/drivers/driver-sql/src/sql-driver-oracle-dialect.ts @@ -138,6 +138,101 @@ export function oracleRaw16AsUuid(value: unknown): unknown { return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`; } +/** + * Uuid text as the column reads it back ({@link oracleRaw16AsUuid}): 8-4-4-4-12 + * hexadecimal digits, either case. + */ +const UUID_TEXT = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; + +/** Where an {@link oracleUuidRawBinding} value goes: a WHERE comparand or a written column. */ +export type OracleUuidBindingRole = 'comparand' | 'write'; + +/** + * The write half of {@link oracleRaw16AsUuid}: uuid text bound into a + * `RAW(16)` column, as a comparand or as a written value. + * + * Oracle refuses a text bind against a `RAW` column, so a `SYS_GUID()` key the + * driver had just READ as a uuid was refused the moment that same uuid came + * back as a filter or a write. It is bound as `HEXTORAW(?)` over its 32 hex + * digits, the inverse of what the read presents. + * + * Which columns take this is decided by the catalog, never by the value (see + * {@link oracleRawUuidColumns}): a text column that happens to hold uuids is + * bound as text, as before. + * + * A value that is not uuid text is refused before any statement is sent — + * Oracle would otherwise raise ORA-01465 on bad hex, or compare valid hex of + * another length and silently match nothing: + * + * - a comparand answers `INVALID_FILTER` / 400 ({@link withheldFilterError}, + * the filter refusal family); + * - a written value answers `VALIDATION_ERROR` / 400, the family the write + * path refuses an unwritable value with. + * + * `null` never reaches here: the callers keep `IS NULL` and a null write as + * they were. + */ +export function oracleUuidRawBinding( + knexInstance: Knex, + field: string, + value: unknown, + role: OracleUuidBindingRole, +): Knex.Raw { + if (typeof value === 'string' && UUID_TEXT.test(value)) { + return knexInstance.raw('HEXTORAW(?)', [value.replace(/-/g, '').toUpperCase()]); + } + const why = + 'is not a uuid. The column is a RAW(16) uuid on an Oracle table, and only uuid text ' + + '(8-4-4-4-12 hexadecimal digits, the form the column reads back as) can be bound to it.'; + if (role === 'comparand') { + throw withheldFilterError( + `This filter compares a uuid column with a value that ${why} The field is withheld from the message; ` + + 'the full diagnostic is in the server log.', + `Field "${field}" is compared with a value that ${why}`, + ); + } + const err = new Error(`The value written to field "${field}" ${why}`) as Error & { + code?: string; + status?: number; + }; + err.code = StandardErrorCode.enum.VALIDATION_ERROR; + err.status = 400; + throw err; +} + +/** + * The `RAW(16)` columns of one remote table, read from the catalog + * (`ALL_TAB_COLUMNS`): the columns {@link oracleUuidRawBinding} binds. + * + * Read rather than declared because nothing an author writes says it: a + * `lookup` or `text` field is the exact pairing for a `VARCHAR2` uuid column + * and for a `RAW(16)` one alike, and only the second needs `HEXTORAW`. + * + * The owner is `remoteSchema` when the binding names one, else the owner + * spelled into `remoteName` (`OWNER.TABLE`), else the session's current + * schema — the resolution the statements themselves get. + */ +export async function oracleRawUuidColumns( + knexInstance: Knex, + remoteTable: string, + remoteSchema?: string, +): Promise { + let owner = remoteSchema; + let table = remoteTable; + if (!owner && remoteTable.includes('.')) { + const dot = remoteTable.indexOf('.'); + owner = remoteTable.slice(0, dot); + table = remoteTable.slice(dot + 1); + } + const ownerSql = owner ? '?' : `SYS_CONTEXT('USERENV', 'CURRENT_SCHEMA')`; + const result = (await knexInstance.raw( + `SELECT COLUMN_NAME FROM ALL_TAB_COLUMNS WHERE OWNER = ${ownerSql} AND TABLE_NAME = ? ` + + `AND DATA_TYPE = 'RAW' AND DATA_LENGTH = 16`, + owner ? [owner, table] : [table], + )) as unknown; + return Array.isArray(result) ? (result as Array<{ COLUMN_NAME: string }>).map((row) => row.COLUMN_NAME) : []; +} + /** * The `fetchTypeHandler` every statement this client runs is executed with * (unless a caller passed its own): zone-less `DATE` / `TIMESTAMP` columns 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 c54976e1d60..a66dcd4c010 100644 --- a/packages/drivers/driver-sql/src/sql-driver-sequence-semantics.ts +++ b/packages/drivers/driver-sql/src/sql-driver-sequence-semantics.ts @@ -91,6 +91,7 @@ export interface SequenceSemanticsHost { maxAutonumberCounter: SqlDriver['maxAutonumberCounter']; mergeLandsInWrittenOrganization: SqlDriver['mergeLandsInWrittenOrganization']; observedUpdatedAtColumn: SqlDriver['observedUpdatedAtColumn']; + oracleUuidBinding: SqlDriver['oracleUuidBinding']; readonly organizationObjectRegistered: SqlDriver['organizationObjectRegistered']; readonly physicalTableByObject: SqlDriver['physicalTableByObject']; remoteColumn: SqlDriver['remoteColumn']; @@ -277,7 +278,7 @@ 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); @@ -286,11 +287,13 @@ export class SequenceSemanticsFacet { // federated object (the mapping the payload above just went through), `id` // otherwise. const idColumn = this.remoteColumn(object, 'id', 'id'); + // [#31390] On Oracle a RAW(16) uuid key binds as `HEXTORAW(?)`; the id itself otherwise. + const idComparand = this.oracleUuidBinding(object, 'id', id, 'comparand'); // 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(idColumn, id); + const builder = this.getBuilder(object, issueOptions).where(idColumn, idComparand as any); this.applyTenantScope(builder, object, issueOptions); return builder.update(payload) as unknown as Promise; }; @@ -314,7 +317,7 @@ export class SequenceSemanticsFacet { await issue(formatted, options); } - const readback = this.getBuilder(object, options).where(idColumn, id); + const readback = this.getBuilder(object, options).where(idColumn, idComparand as any); this.applyTenantScope(readback, object, options); const updated = await readback.first(); return this.formatOutput(object, updated) || null; @@ -935,7 +938,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) { @@ -950,7 +953,11 @@ export class SequenceSemanticsFacet { } // 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); + // [#31390] On Oracle a RAW(16) uuid key binds as `HEXTORAW(?)`. + const builder = this.getBuilder(object, options).where( + this.remoteColumn(object, 'id', 'id'), + this.oracleUuidBinding(object, 'id', id, 'comparand') as any, + ); this.applyTenantScope(builder, object, options); const count = await builder.delete(); return count > 0; diff --git a/packages/drivers/driver-sql/src/sql-driver-sqlite-serialisation.ts b/packages/drivers/driver-sql/src/sql-driver-sqlite-serialisation.ts index 2e2e6bac533..8d3f8174088 100644 --- a/packages/drivers/driver-sql/src/sql-driver-sqlite-serialisation.ts +++ b/packages/drivers/driver-sql/src/sql-driver-sqlite-serialisation.ts @@ -55,6 +55,8 @@ export interface SqliteSerialisationHost { readonly mediaFields: SqlDriver['mediaFields']; readonly numericFields: SqlDriver['numericFields']; readonly numericValueFields: SqlDriver['numericValueFields']; + readonly oracleRawUuidFieldsByObject: SqlDriver['oracleRawUuidFieldsByObject']; + oracleUuidBinding: SqlDriver['oracleUuidBinding']; storageDatetimeValue: SqlDriver['storageDatetimeValue']; readonly timeFields: SqlDriver['timeFields']; toDateOnly: SqlDriver['toDateOnly']; @@ -65,7 +67,7 @@ export interface SqliteSerialisationHost { /** The bodies of the "SQLite serialisation" section of `SqlDriver`: a stateless facet, called by the class's stubs. */ export class SqliteSerialisationFacet { /** The body of `SqlDriver#formatInput`; the method's docblock there is its contract. */ - static formatInput(this: Pick, object: string, data: any): any { + static formatInput(this: Pick, object: string, data: any): any { let copy: any = data; let copied = false; @@ -258,6 +260,23 @@ export class SqliteSerialisationFacet { } } + // [#31390] Oracle: a field over a `RAW(16)` uuid column (as the catalog + // reports it — `SqlDriver#primeOracleRawUuidColumns`) is written as + // `HEXTORAW(?)` over the uuid's hex digits, and a value that is not uuid + // text is refused before the statement is built. No other dialect, and no + // other Oracle column, reaches this arm. + if (this.isOracle && copy && typeof copy === 'object') { + const rawUuidFields = this.oracleRawUuidFieldsByObject.get(object); + if (rawUuidFields && rawUuidFields.size > 0) { + for (const field of rawUuidFields) { + const v = copy[field]; + if (v === undefined || v === null) continue; + if (!copied) { copy = { ...copy }; copied = true; } + copy[field] = this.oracleUuidBinding(object, field, v, 'write'); + } + } + } + if (!this.isSqlite) return copy; // Safety net: better-sqlite3 can only bind numbers/strings/bigints/buffers/ diff --git a/packages/drivers/driver-sql/src/sql-driver.ts b/packages/drivers/driver-sql/src/sql-driver.ts index 11f596afe99..f9f669d525d 100644 --- a/packages/drivers/driver-sql/src/sql-driver.ts +++ b/packages/drivers/driver-sql/src/sql-driver.ts @@ -294,7 +294,12 @@ import { SqliteSerialisationFacet } from './sql-driver-sqlite-serialisation.js'; // [cloud#3652 D3] Declared renames: the methods of the same names below hand the bodies what they read (`DeclaredRenameHost`). import { DeclaredRenameFacet } from './sql-driver-declared-rename.js'; import type { DeclaredRenameCarry, DeclaredRenamePlan } from './declared-rename.js'; -import { withOracleFederationClient } from './sql-driver-oracle-dialect.js'; +import { + oracleRawUuidColumns, + oracleUuidRawBinding, + withOracleFederationClient, + type OracleUuidBindingRole, +} from './sql-driver-oracle-dialect.js'; // [#29520 codemod] The facets' hosts, one per driver, which the static block at the end of the class builds. import { aggregationHost, bulkOperationsHost, classHeadHost, columnCreationHost, crudHost, databaseHelpersHost, @@ -1325,6 +1330,16 @@ export class SqlDriver implements IDataDriver { */ protected mssqlPagingKeyByObject = new Map(); + /** + * Oracle (#31390): per external object, the LOGICAL fields whose remote + * column is a `RAW(16)` uuid, read from the catalog by + * {@link primeOracleRawUuidColumns} the first time the object is read or + * written. A field here binds as `HEXTORAW(?)` ({@link oracleUuidBinding}); + * an object with no entry binds every value as before. Empty on every other + * dialect. + */ + protected oracleRawUuidFieldsByObject = new Map>(); + /** Deferred-DDL mode (#3917) — see {@link setDeferredDdl}. */ protected deferredDdl = false; @@ -1786,7 +1801,8 @@ export class SqlDriver implements IDataDriver { // `sql-driver-doors-declared-types.test.ts`. find(object: string, query: DriverQuery, options?: DriverOptions): Promise[]> { // [#29520 codemod] The body moved to `sql-driver-crud.ts` (see `CrudHost`). - return CrudFacet.find.call(crudHost.of(this), object, query, options); + // [#31390] Oracle learns the object's RAW(16) uuid columns first; any other dialect runs as before. + return this.withOracleRawUuidColumns(object, () => CrudFacet.find.call(crudHost.of(this), object, query, options)); } private async findRows( @@ -1821,6 +1837,72 @@ export class SqlDriver implements IDataDriver { return FieldMappingFacet.primeMssqlPagingKey.call(fieldMappingHost.of(this), object); } + /** + * Oracle (#31390): learn, once per object, which of a FEDERATED table's + * columns are `RAW(16)` uuids — read from the remote catalog + * (`oracleRawUuidColumns`) and mapped back through the object's + * `external.columnMap` to the fields that read them. + * + * Why the driver reads it rather than being told: nothing an author writes + * names the physical type. A `lookup` (or `text`) field is the exact pairing + * for a `VARCHAR2` uuid column and a `RAW(16)` one alike, and only the second + * needs its comparands and written values bound through `HEXTORAW`. The value + * is never the evidence: a uuid-shaped string in a text column stays text. + * + * Recorded once per object, so a read costs the catalog one statement for + * the object's lifetime in this driver (re-registering the object forgets + * it). A failed catalog read records nothing: the statement is then bound as + * before, and the next read asks again. A no-op on every other dialect, and + * for an object that was never registered as external. + */ + protected async primeOracleRawUuidColumns(object: string): Promise { + if (!this.isOracle || this.oracleRawUuidFieldsByObject.has(object)) return; + const remoteTable = this.physicalTableByObject[object]; + if (remoteTable === undefined) return; + let columns: string[]; + try { + columns = await this.readOracleRawUuidColumns(remoteTable, this.physicalSchemaByObject[object]); + } catch { + return; + } + const colToField = this.columnFieldByObject[object]; + this.oracleRawUuidFieldsByObject.set(object, new Set(columns.map((column) => colToField?.[column] ?? column))); + } + + /** The catalog read behind {@link primeOracleRawUuidColumns}: the remote table's `RAW(16)` column names. */ + protected readOracleRawUuidColumns(remoteTable: string, remoteSchema: string | undefined): Promise { + return oracleRawUuidColumns(this.knex, remoteTable, remoteSchema); + } + + /** + * Oracle (#31390): `value` as bound against `field` of `object` — through + * `HEXTORAW(?)` when the catalog reported the field's column as a `RAW(16)` + * uuid ({@link primeOracleRawUuidColumns}), refused when it is not uuid text + * (`INVALID_FILTER` for a comparand, `VALIDATION_ERROR` for a written value). + * Returned untouched for any other column, a null, and on every other + * dialect. + */ + protected oracleUuidBinding( + object: string | null | undefined, + field: string, + value: unknown, + role: OracleUuidBindingRole, + ): unknown { + if (!this.isOracle || !object || value === null || value === undefined) return value; + if (this.oracleRawUuidFieldsByObject.get(object)?.has(field) !== true) return value; + return oracleUuidRawBinding(this.knex, field, value, role); + } + + /** + * Run a door that compiles comparands or written values for `object` after + * {@link primeOracleRawUuidColumns}. On every other dialect `run` is called + * at once, synchronously, exactly as the door did before. + */ + private withOracleRawUuidColumns(object: string, run: () => Promise): Promise { + if (!this.isOracle) return run(); + return this.primeOracleRawUuidColumns(object).then(run); + } + /** * `IDataDriver.findOne` — find a single record BY QUERY. * @@ -1846,7 +1928,8 @@ export class SqlDriver implements IDataDriver { */ findOne(object: string, query: DriverQuery, options?: DriverOptions): Promise | null> { // [#29520 codemod] The body moved to `sql-driver-crud.ts` (see `CrudHost`). - return CrudFacet.findOne.call(crudHost.of(this), object, query, options); + // [#31390] Oracle learns the object's RAW(16) uuid columns first; any other dialect runs as before. + return this.withOracleRawUuidColumns(object, () => CrudFacet.findOne.call(crudHost.of(this), object, query, options)); } // `findStream` was removed with the contract method in 17.0.0 (#4484). This driver's @@ -1869,7 +1952,8 @@ export class SqlDriver implements IDataDriver { */ create(object: string, data: Record, options?: DriverOptions): Promise> { // [#29520 codemod] The body moved to `sql-driver-crud.ts` (see `CrudHost`). - return CrudFacet.create.call(crudHost.of(this), object, data, options); + // [#31390] Oracle learns the object's RAW(16) uuid columns first; any other dialect runs as before. + return this.withOracleRawUuidColumns(object, () => CrudFacet.create.call(crudHost.of(this), object, data, options)); } private readBackInsertedRows( @@ -2741,7 +2825,8 @@ export class SqlDriver implements IDataDriver { */ update(object: string, id: string | number, data: Record, options?: DriverOptions): Promise | null> { // [#29520 codemod] The body moved to `sql-driver-sequence-semantics.ts` (see `SequenceSemanticsHost`). - return SequenceSemanticsFacet.update.call(sequenceSemanticsHost.of(this), object, id, data, options); + // [#31390] Oracle learns the object's RAW(16) uuid columns first; any other dialect runs as before. + return this.withOracleRawUuidColumns(object, () => SequenceSemanticsFacet.update.call(sequenceSemanticsHost.of(this), object, id, data, options)); } /** @@ -3111,7 +3196,8 @@ export class SqlDriver implements IDataDriver { delete(object: string, id: string | number, options?: DriverOptions): Promise { // [#29520 codemod] The body moved to `sql-driver-sequence-semantics.ts` (see `SequenceSemanticsHost`). - return SequenceSemanticsFacet.delete.call(sequenceSemanticsHost.of(this), object, id, options); + // [#31390] Oracle learns the object's RAW(16) uuid columns first; any other dialect runs as before. + return this.withOracleRawUuidColumns(object, () => SequenceSemanticsFacet.delete.call(sequenceSemanticsHost.of(this), object, id, options)); } // =================================== @@ -3127,7 +3213,8 @@ export class SqlDriver implements IDataDriver { */ bulkCreate(object: string, data: any[], options?: DriverOptions): Promise[]> { // [#29520 codemod] The body moved to `sql-driver-bulk-operations.ts` (see `BulkOperationsHost`). - return BulkOperationsFacet.bulkCreate.call(bulkOperationsHost.of(this), object, data, options); + // [#31390] Oracle learns the object's RAW(16) uuid columns first; any other dialect runs as before. + return this.withOracleRawUuidColumns(object, () => BulkOperationsFacet.bulkCreate.call(bulkOperationsHost.of(this), object, data, options)); } /** @@ -3198,7 +3285,8 @@ export class SqlDriver implements IDataDriver { bulkDelete(object: string, ids: Array, options?: DriverOptions): Promise { // [#29520 codemod] The body moved to `sql-driver-bulk-operations.ts` (see `BulkOperationsHost`). - return BulkOperationsFacet.bulkDelete.call(bulkOperationsHost.of(this), object, ids, options); + // [#31390] Oracle learns the object's RAW(16) uuid columns first; any other dialect runs as before. + return this.withOracleRawUuidColumns(object, () => BulkOperationsFacet.bulkDelete.call(bulkOperationsHost.of(this), object, ids, options)); } /** @@ -3253,12 +3341,14 @@ export class SqlDriver implements IDataDriver { */ updateMany(object: string, query: DriverQuery, data: any, options?: DriverOptions): Promise { // [#29520 codemod] The body moved to `sql-driver-bulk-operations.ts` (see `BulkOperationsHost`). - return BulkOperationsFacet.updateMany.call(bulkOperationsHost.of(this), object, query, data, options); + // [#31390] Oracle learns the object's RAW(16) uuid columns first; any other dialect runs as before. + return this.withOracleRawUuidColumns(object, () => BulkOperationsFacet.updateMany.call(bulkOperationsHost.of(this), object, query, data, options)); } deleteMany(object: string, query: DriverQuery, options?: DriverOptions): Promise { // [#29520 codemod] The body moved to `sql-driver-bulk-operations.ts` (see `BulkOperationsHost`). - return BulkOperationsFacet.deleteMany.call(bulkOperationsHost.of(this), object, query, options); + // [#31390] Oracle learns the object's RAW(16) uuid columns first; any other dialect runs as before. + return this.withOracleRawUuidColumns(object, () => BulkOperationsFacet.deleteMany.call(bulkOperationsHost.of(this), object, query, options)); } /** By-id update for a rotation-managed object: the row lives in exactly one @@ -3374,7 +3464,8 @@ export class SqlDriver implements IDataDriver { count(object: string, query?: DriverQuery, options?: DriverOptions): Promise { // [#29520 codemod] The body moved to `sql-driver-bulk-operations.ts` (see `BulkOperationsHost`). - return BulkOperationsFacet.count.call(bulkOperationsHost.of(this), object, query, options); + // [#31390] Oracle learns the object's RAW(16) uuid columns first; any other dialect runs as before. + return this.withOracleRawUuidColumns(object, () => BulkOperationsFacet.count.call(bulkOperationsHost.of(this), object, query, options)); } // =================================== @@ -3592,7 +3683,8 @@ export class SqlDriver implements IDataDriver { */ aggregate(object: string, query: DriverQuery, options?: DriverOptions): Promise[]> { // [#29520 codemod] The body moved to `sql-driver-aggregation.ts` (see `AggregationHost`). - return AggregationFacet.aggregate.call(aggregationHost.of(this), object, query, options); + // [#31390] Oracle learns the object's RAW(16) uuid columns first; any other dialect runs as before. + return this.withOracleRawUuidColumns(object, () => AggregationFacet.aggregate.call(aggregationHost.of(this), object, query, options)); } /** @@ -3821,7 +3913,8 @@ export class SqlDriver implements IDataDriver { */ distinct(object: string, field: string, filters?: FilterCondition, options?: DriverOptions): Promise { // [#29520 codemod] The body moved to `sql-driver-distinct.ts` (see `DistinctHost`). - return DistinctFacet.distinct.call(distinctHost.of(this), object, field, filters, options); + // [#31390] Oracle learns the object's RAW(16) uuid columns first; any other dialect runs as before. + return this.withOracleRawUuidColumns(object, () => DistinctFacet.distinct.call(distinctHost.of(this), object, field, filters, options)); } /** @@ -3981,7 +4074,8 @@ export class SqlDriver implements IDataDriver { */ findWithWindowFunctions(object: string, query: SqlWindowFunctionQuery, options?: DriverOptions): Promise { // [#29520 codemod] The body moved to `sql-driver-window-functions.ts` (see `WindowFunctionsHost`). - return WindowFunctionsFacet.findWithWindowFunctions.call(windowFunctionsHost.of(this), object, query, options); + // [#31390] Oracle learns the object's RAW(16) uuid columns first; any other dialect runs as before. + return this.withOracleRawUuidColumns(object, () => WindowFunctionsFacet.findWithWindowFunctions.call(windowFunctionsHost.of(this), object, query, options)); } // =================================== @@ -4001,7 +4095,8 @@ export class SqlDriver implements IDataDriver { */ explain(object: string, query: DriverQuery, options?: DriverOptions): Promise { // [#29520 codemod] The body moved to `sql-driver-query-plan.ts` (see `QueryPlanHost`). - return QueryPlanFacet.explain.call(queryPlanHost.of(this), object, query, options); + // [#31390] Oracle learns the object's RAW(16) uuid columns first; any other dialect runs as before. + return this.withOracleRawUuidColumns(object, () => QueryPlanFacet.explain.call(queryPlanHost.of(this), object, query, options)); } /** @@ -4012,7 +4107,8 @@ export class SqlDriver implements IDataDriver { */ analyzeQuery(object: string, query: DriverQuery, options?: DriverOptions): Promise { // [#29520 codemod] The body moved to `sql-driver-query-plan.ts` (see `QueryPlanHost`). - return QueryPlanFacet.analyzeQuery.call(queryPlanHost.of(this), object, query, options); + // [#31390] Oracle learns the object's RAW(16) uuid columns first; any other dialect runs as before. + return this.withOracleRawUuidColumns(object, () => QueryPlanFacet.analyzeQuery.call(queryPlanHost.of(this), object, query, options)); } // =================================== @@ -4314,6 +4410,8 @@ export class SqlDriver implements IDataDriver { external?: { remoteName?: string; remoteSchema?: string; columnMap?: Record }; }): void { // [#25521 cut 17] The body moved to `sql-driver-schema-sync.ts` (see `SchemaSyncHost`). + // [#31390] A re-registration may name another remote table: its RAW(16) columns are read again. + this.oracleRawUuidFieldsByObject.delete(schema.name); const readAutoNumberFields = () => this.autoNumberFields; const readBooleanFields = () => this.booleanFields; const readColumnFieldByObject = () => this.columnFieldByObject; @@ -9111,6 +9209,7 @@ export class SqlDriver implements IDataDriver { get isMssql() { return driver.isMssql; }, keepSuppliedUpdatedAt: (...a) => driver.keepSuppliedUpdatedAt(...a), get knex() { return driver.knex; }, + oracleUuidBinding: (...a) => driver.oracleUuidBinding(...a), readBackInsertedRows: (...a) => driver.readBackInsertedRows(...a), resyncSequenceToDataMax: (...a) => driver.resyncSequenceToDataMax(...a), remoteColumn: (...a) => driver.remoteColumn(...a), @@ -9182,6 +9281,7 @@ export class SqlDriver implements IDataDriver { get isSqlite() { return driver.isSqlite; }, get knex() { return driver.knex; }, mapSortField: (...a) => driver.mapSortField(...a), + oracleUuidBinding: (...a) => driver.oracleUuidBinding(...a), orderKeysFor: (...a) => driver.orderKeysFor(...a), primeMssqlPagingKey: (...a) => driver.primeMssqlPagingKey(...a), readBackInsertedRows: (...a) => driver.readBackInsertedRows(...a), @@ -9311,6 +9411,8 @@ export class SqlDriver implements IDataDriver { needsLegacyTimeRepair: (...a) => driver.needsLegacyTimeRepair(...a), get numericFields() { return driver.numericFields; }, get objectByPhysicalTable() { return driver.objectByPhysicalTable; }, + get oracleRawUuidFieldsByObject() { return driver.oracleRawUuidFieldsByObject; }, + oracleUuidBinding: (...a) => driver.oracleUuidBinding(...a), presentReadValue: (...a) => driver.presentReadValue(...a), get readableIdsDriverName() { return driver.readableIdsDriverName; }, get readableIdsRefusalLog() { return driver.readableIdsRefusalLog; }, @@ -9483,6 +9585,7 @@ export class SqlDriver implements IDataDriver { maxAutonumberCounter: (...a) => driver.maxAutonumberCounter(...a), mergeLandsInWrittenOrganization: (...a) => driver.mergeLandsInWrittenOrganization(...a), observedUpdatedAtColumn: (...a) => driver.observedUpdatedAtColumn(...a), + oracleUuidBinding: (...a) => driver.oracleUuidBinding(...a), get organizationObjectRegistered() { return driver.organizationObjectRegistered; }, get physicalTableByObject() { return driver.physicalTableByObject; }, remoteColumn: (...a) => driver.remoteColumn(...a), @@ -9519,6 +9622,8 @@ export class SqlDriver implements IDataDriver { get mediaFields() { return driver.mediaFields; }, get numericFields() { return driver.numericFields; }, get numericValueFields() { return driver.numericValueFields; }, + get oracleRawUuidFieldsByObject() { return driver.oracleRawUuidFieldsByObject; }, + oracleUuidBinding: (...a) => driver.oracleUuidBinding(...a), storageDatetimeValue: (...a) => driver.storageDatetimeValue(...a), get timeFields() { return driver.timeFields; }, toDateOnly: (...a) => driver.toDateOnly(...a), From cd0a502d2d5a4b40dded380180c0788777344ea6 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 8 Nov 2026 16:27:23 +0000 Subject: [PATCH 2/6] test(driver-sql): pin the Oracle RAW(16) uuid bind and the other dialects' unchanged statements Claude-Session: https://claude.ai/code/session_01ADHkmQ9H84XNocJ8waPS1P Co-authored-by: Claude --- .../src/sql-driver-oracle-dialect.test.ts | 312 ++++++++++++++++++ 1 file changed, 312 insertions(+) diff --git a/packages/drivers/driver-sql/src/sql-driver-oracle-dialect.test.ts b/packages/drivers/driver-sql/src/sql-driver-oracle-dialect.test.ts index 911f5da2025..df1c3ba6a2d 100644 --- a/packages/drivers/driver-sql/src/sql-driver-oracle-dialect.test.ts +++ b/packages/drivers/driver-sql/src/sql-driver-oracle-dialect.test.ts @@ -304,3 +304,315 @@ describe('#31328 introspection type strings', () => { expect(oracleColumnTypeString(row as any)).toBe(expected); }); }); + +// ── #31390 RAW(16) uuid columns bind through HEXTORAW ──────────────────────── + +const UUID = '0f8fad5b-d9cb-469f-a165-70867728950e'; +const UUID_HEX = '0F8FAD5BD9CB469FA16570867728950E'; +const UUID_2 = '7c9e6679-7425-40de-944b-e07fc1f90ae7'; +const UUID_2_HEX = '7C9E6679742540DE944BE07FC1F90AE7'; + +/** + * An Oracle driver whose catalog read is answered from `catalog` (remote + * table → its RAW(16) columns; a missing entry throws, as a failed read), and + * whose statements are captured instead of sent: `_query` records the SQL + * and bindings and answers `respond(obj)` as the rows. + */ +class OracleUuidProbe extends SqlDriver { + catalogReads: string[] = []; + sent: Array<{ sql: string; bindings: unknown[] }> = []; + respond: (obj: { sql: string; method?: string }) => unknown[] = () => []; + constructor(private readonly catalog: Record) { + super(ORACLE_CONFIG as any); + (this as any).name = 'ora'; + this.registerExternalObject({ + name: 'acct', + external: { remoteName: 'ACCT', columnMap: { ACCT_ID: 'id', NAME: 'name' } }, + fields: { name: { type: 'text' } }, + } as any); + this.registerExternalObject({ + name: 'ord', + external: { + remoteName: 'ORD', + columnMap: { ORD_ID: 'id', ACCT_REF: 'account', LEGACY_REF: 'legacy_account', NOTE: 'note' }, + }, + fields: { + account: { type: 'lookup', reference: 'acct' }, + // The control: a lookup over a VARCHAR2 uuid column (the catalog does not list it). + legacy_account: { type: 'lookup', reference: 'acct' }, + note: { type: 'text' }, + }, + } as any); + const client = (this as any).knex.client; + client.acquireConnection = async () => ({}); + client.releaseConnection = async () => undefined; + client._query = async (_conn: unknown, obj: any) => { + this.sent.push({ sql: obj.sql, bindings: obj.bindings }); + obj.response = this.respond(obj); + obj.rowsAffected = 1; + return obj; + }; + } + protected override readOracleRawUuidColumns(remoteTable: string): Promise { + this.catalogReads.push(remoteTable); + const columns = this.catalog[remoteTable]; + return columns ? Promise.resolve(columns) : Promise.reject(new Error('ORA-00942 (stubbed)')); + } + prime(object: string): Promise { + return (this as any).primeOracleRawUuidColumns(object); + } + compileWhere(object: string, where: FilterCondition): Knex.Sql { + const b = (this as any).getBuilder(object); + this.applyFilters(b, where); + return b.toSQL(); + } + compileInsert(object: string, row: Record): Knex.Sql { + const formatted = (this as any).applyWriteColumnMap(object, (this as any).formatInput(object, row)); + return (this as any).getBuilder(object).insert(formatted).toSQL(); + } +} + +const CATALOG = { ACCT: ['ACCT_ID'], ORD: ['ORD_ID', 'ACCT_REF'] }; +const primed = async () => { + const p = new OracleUuidProbe(CATALOG); + await p.prime('acct'); + await p.prime('ord'); + return p; +}; +const caught = (fn: () => unknown): Error & { code?: string; status?: number } => { + try { + fn(); + } catch (e) { + return e as Error & { code?: string; status?: number }; + } + throw new Error('expected a refusal'); +}; + +describe('#31390 a RAW(16) uuid comparand binds as HEXTORAW(?) over its hex digits', () => { + it('equality on a lookup over a RAW(16) column', async () => { + const { sql, bindings } = (await primed()).compileWhere('ord', { account: UUID }); + expect(sql).toBe('select * from "ORD" where "ACCT_REF" = HEXTORAW(?)'); + expect(bindings).toEqual([UUID_HEX]); + }); + + it('$eq on the SYS_GUID key itself (the mapped id)', async () => { + const { sql, bindings } = (await primed()).compileWhere('acct', { id: { $eq: UUID } }); + expect(sql).toBe('select * from "ACCT" where "ACCT_ID" = HEXTORAW(?)'); + expect(bindings).toEqual([UUID_HEX]); + }); + + it('$in binds every member, upper- or lower-case input alike', async () => { + const { sql, bindings } = (await primed()).compileWhere('ord', { account: { $in: [UUID, UUID_2.toUpperCase()] } }); + expect(sql).toBe('select * from "ORD" where "ACCT_REF" in (HEXTORAW(?), HEXTORAW(?))'); + expect(bindings).toEqual([UUID_HEX, UUID_2_HEX]); + }); + + it('$ne keeps its null-safe shape around the bound comparand', async () => { + const { sql, bindings } = (await primed()).compileWhere('ord', { account: { $ne: UUID } }); + expect(sql).toBe('select * from "ORD" where ("ACCT_REF" is null or "ACCT_REF" <> HEXTORAW(?))'); + expect(bindings).toEqual([UUID_HEX]); + }); + + it('a null comparand stays IS NULL', async () => { + const { sql, bindings } = (await primed()).compileWhere('ord', { account: null }); + expect(sql).toBe('select * from "ORD" where "ACCT_REF" is null'); + expect(bindings).toEqual([]); + }); + + it('control: a lookup over a VARCHAR2 uuid column binds the text, as before', async () => { + const { sql, bindings } = (await primed()).compileWhere('ord', { legacy_account: UUID }); + expect(sql).toBe('select * from "ORD" where "LEGACY_REF" = ?'); + expect(bindings).toEqual([UUID]); + }); + + it('control: a uuid-shaped value in a text column binds the text — the value is never the evidence', async () => { + const { sql, bindings } = (await primed()).compileWhere('ord', { note: UUID }); + expect(sql).toBe('select * from "ORD" where "NOTE" = ?'); + expect(bindings).toEqual([UUID]); + }); +}); + +describe('#31390 a comparand that is not uuid text is INVALID_FILTER, never sent', () => { + for (const [label, where] of [ + ['equality', { account: 'not-a-uuid' }], + ['$eq with valid hex of another length', { account: { $eq: '0f8fad5b' } }], + ['$in holding one bad member', { account: { $in: [UUID, 'nope'] } }], + ['$ne with a number', { account: { $ne: 42 } }], + ['the key, undashed', { id: UUID_HEX }], + ] as const) { + it(`${label}: INVALID_FILTER / 400`, async () => { + const p = await primed(); + const err = caught(() => p.compileWhere(label === 'the key, undashed' ? 'acct' : 'ord', where as FilterCondition)); + expect(err.code).toBe('INVALID_FILTER'); + expect(err.status).toBe(400); + }); + } + + it('through the find door: refused, and no statement reaches the database', async () => { + const p = await primed(); + await expect(p.find('ord', { where: { account: 'not-a-uuid' } } as any)).rejects.toMatchObject({ + code: 'INVALID_FILTER', + status: 400, + }); + expect(p.sent).toEqual([]); + }); +}); + +describe('#31390 a written RAW(16) uuid value binds as HEXTORAW(?)', () => { + it('insert: the key and the lookup bind through HEXTORAW, the text column as text', async () => { + const { sql, bindings } = (await primed()).compileInsert('ord', { id: UUID, account: UUID_2, legacy_account: UUID, note: 'x' }); + expect(sql).toBe('insert into "ORD" ("ACCT_REF", "LEGACY_REF", "NOTE", "ORD_ID") values (HEXTORAW(?), ?, ?, HEXTORAW(?))'); + expect(bindings).toEqual([UUID_2_HEX, UUID, 'x', UUID_HEX]); + }); + + it('a null write stays a null bind', async () => { + const { sql, bindings } = (await primed()).compileInsert('ord', { id: UUID, account: null }); + expect(sql).toBe('insert into "ORD" ("ACCT_REF", "ORD_ID") values (?, HEXTORAW(?))'); + expect(bindings).toEqual([null, UUID_HEX]); + }); + + it('a value that is not uuid text is VALIDATION_ERROR / 400 through create, and nothing is sent', async () => { + const p = await primed(); + await expect(p.create('ord', { id: UUID, account: 'acct-17' })).rejects.toMatchObject({ + code: 'VALIDATION_ERROR', + status: 400, + }); + expect(p.sent).toEqual([]); + }); + + it('update by key: the SET value and the key bind through HEXTORAW, and the read-back is by the same key', async () => { + const p = await primed(); + await p.update('ord', UUID, { account: UUID_2 }); + expect(p.sent.map((s) => s.sql)).toEqual([ + 'update "ORD" set "ACCT_REF" = HEXTORAW(:1) where "ORD_ID" = HEXTORAW(:2)', + 'select * from "ORD" where "ORD_ID" = HEXTORAW(:1) fetch next :2 rows only', + ]); + expect(p.sent[0]!.bindings).toEqual([UUID_2_HEX, UUID_HEX]); + expect(p.sent[1]!.bindings).toEqual([UUID_HEX, 1]); + }); + + it('delete and bulkDelete by key bind through HEXTORAW', async () => { + const p = await primed(); + await p.delete('ord', UUID); + await p.bulkDelete('ord', [UUID, UUID_2]); + expect(p.sent.map((s) => [s.sql, s.bindings])).toEqual([ + ['delete from "ORD" where "ORD_ID" = HEXTORAW(:1)', [UUID_HEX]], + ['delete from "ORD" where "ORD_ID" in (HEXTORAW(:1), HEXTORAW(:2))', [UUID_HEX, UUID_2_HEX]], + ]); + }); + + it('create reads its row back by the HEXTORAW key, matching an upper-case written id to the lower-case read', async () => { + const p = await primed(); + p.respond = (obj) => (obj.sql.startsWith('select') ? [{ ORD_ID: UUID, ACCT_REF: UUID_2, NOTE: 'x' }] : []); + const row = await p.create('ord', { id: UUID.toUpperCase(), account: UUID_2, note: 'x' }); + expect(p.sent.map((s) => s.sql)).toEqual([ + 'insert into "ORD" ("ACCT_REF", "NOTE", "ORD_ID") values (HEXTORAW(:1), :2, HEXTORAW(:3))', + 'select * from "ORD" where "ORD_ID" in (HEXTORAW(:1))', + ]); + expect(row).toMatchObject({ id: UUID, account: UUID_2, note: 'x' }); + }); +}); + +describe('#31390 which columns: read from the catalog, once per object', () => { + it('the doors read the catalog once per object, not once per statement', async () => { + const p = new OracleUuidProbe(CATALOG); + await p.find('ord', { where: { account: UUID } } as any); + await p.count('ord', { where: { account: UUID } } as any); + await p.find('acct', { where: { id: UUID } } as any); + await p.find('ord', { where: { account: UUID_2 } } as any); + expect(p.catalogReads).toEqual(['ORD', 'ACCT']); + expect(p.sent.every((s) => s.sql.includes('HEXTORAW('))).toBe(true); + }); + + it('a failed catalog read records nothing: the statement binds text as before, and the next door asks again', async () => { + const p = new OracleUuidProbe({}); + await p.find('ord', { where: { account: UUID } } as any); + expect(p.sent[0]).toMatchObject({ sql: 'select * from "ORD" where "ACCT_REF" = :1', bindings: [UUID] }); + await p.find('ord', { where: { account: UUID } } as any); + expect(p.catalogReads).toEqual(['ORD', 'ORD']); + }); + + it('an empty catalog answer (no RAW(16) column) binds text, and is not asked again', async () => { + const p = new OracleUuidProbe({ ORD: [] }); + await p.find('ord', { where: { account: UUID } } as any); + await p.find('ord', { where: { account: 'not-a-uuid' } } as any); + expect(p.sent.map((s) => s.bindings)).toEqual([[UUID], ['not-a-uuid']]); + expect(p.catalogReads).toEqual(['ORD']); + }); + + it('re-registering an object forgets its catalog reading', async () => { + const p = await primed(); + p.registerExternalObject({ + name: 'ord', + external: { remoteName: 'ORD', columnMap: { ORD_ID: 'id', ACCT_REF: 'account' } }, + fields: { account: { type: 'lookup', reference: 'acct' } }, + } as any); + expect(p.compileWhere('ord', { account: UUID }).sql).toBe('select * from "ORD" where "ACCT_REF" = ?'); + }); +}); + +describe('#31390 every other dialect binds exactly as before', () => { + const ORD = { + name: 'ord', + external: { remoteName: 'ORD', columnMap: { ORD_ID: 'id', ACCT_REF: 'account', NOTE: 'note' } }, + fields: { account: { type: 'lookup', reference: 'acct' }, note: { type: 'text' } }, + }; + /** A non-Oracle driver whose uuid-column registry is POISONED: only the dialect guard keeps it out. */ + const poisoned = (config: Record) => { + const d = new SqlDriver({ ...config, schemaMode: 'external' } as any) as any; + d.name = 'other'; + d.registerExternalObject(ORD); + d.oracleRawUuidFieldsByObject.set('ord', new Set(['id', 'account'])); + d.readOracleRawUuidColumns = () => { + throw new Error('the catalog read is Oracle-only'); + }; + return d; + }; + + for (const [client, where, insert] of [ + ['pg', 'select * from "ORD" where "ACCT_REF" = ?', 'insert into "ORD" ("ACCT_REF", "NOTE", "ORD_ID") values (?, ?, ?)'], + ['mysql2', 'select * from `ORD` where `ACCT_REF` = ?', 'insert into `ORD` (`ACCT_REF`, `NOTE`, `ORD_ID`) values (?, ?, ?)'], + ['mssql', 'select * from [ORD] where [ACCT_REF] = ?', 'insert into [ORD] ([ACCT_REF], [NOTE], [ORD_ID]) values (?, ?, ?)'], + ] as const) { + it(`${client}: comparands (coerceFilterValue) and written values (formatInput) are the text`, () => { + const d = poisoned({ client, connection: { host: '127.0.0.1', port: 1 } }); + const sel = d.getBuilder('ord'); + d.applyFilters(sel, { account: UUID }); + expect(sel.toSQL().sql).toBe(where); + expect(sel.toSQL().bindings).toEqual([UUID]); + const sel2 = d.getBuilder('ord'); + d.applyFilters(sel2, { account: 'not-a-uuid' }); + expect(sel2.toSQL().bindings).toEqual(['not-a-uuid']); + const ins = d.getBuilder('ord').insert(d.applyWriteColumnMap('ord', d.formatInput('ord', { id: UUID, account: UUID_2, note: 'x' }))).toSQL(); + expect(ins.sql).toBe(insert); + expect(ins.bindings).toEqual([UUID_2, 'x', UUID]); + }); + } + + it('sqlite: the doors (find, create, update, delete, bulkDelete) and the read-back send the same statements', async () => { + const d = poisoned({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }); + await d.connect(); + try { + await d.knex.raw('create table ORD (ORD_ID text primary key, ACCT_REF text, NOTE text)'); + const sent: Array<[string, unknown[]]> = []; + d.knex.on('query', (q: { sql: string; bindings: unknown[] }) => sent.push([q.sql, q.bindings])); + await d.create('ord', { id: UUID, account: UUID_2, note: 'x' }); + await d.find('ord', { where: { account: UUID_2 } }); + await d.update('ord', UUID, { account: UUID }); + await d.readBackInsertedRows('ord', 'ord', [{ id: UUID }]); + await d.delete('ord', UUID); + await d.bulkDelete('ord', [UUID, UUID_2]); + expect(sent).toEqual([ + ['insert into `ORD` (`ACCT_REF`, `NOTE`, `ORD_ID`) values (?, ?, ?) returning *', [UUID_2, 'x', UUID]], + ['select * from `ORD` where `ACCT_REF` = ?', [UUID_2]], + ['update `ORD` set `ACCT_REF` = ? where `ORD_ID` = ?', [UUID, UUID]], + ['select * from `ORD` where `ORD_ID` = ? limit ?', [UUID, 1]], + ['select * from `ORD` where `ORD_ID` in (?)', [UUID]], + ['delete from `ORD` where `ORD_ID` = ?', [UUID]], + ['delete from `ORD` where `ORD_ID` in (?, ?)', [UUID, UUID_2]], + ]); + } finally { + await d.disconnect(); + } + }); +}); From e369e20e510a3a32b28fbd18f5e258aa26adfa4b Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 8 Nov 2026 16:32:33 +0000 Subject: [PATCH 3/6] fix(driver-sql): accept the undashed uuid form, read back by the read form, and pin the Oracle live cell Claude-Session: https://claude.ai/code/session_01ADHkmQ9H84XNocJ8waPS1P Co-authored-by: Claude --- .../31390-oracle-raw16-uuid-hextoraw.md | 12 +++ .../drivers/driver-sql/src/sql-driver-crud.ts | 5 +- .../src/sql-driver-oracle-dialect.test.ts | 32 ++++--- .../src/sql-driver-oracle-dialect.ts | 19 +++- ...iver-oracle-federation-conformance.test.ts | 94 +++++++++++++++++++ 5 files changed, 144 insertions(+), 18 deletions(-) create mode 100644 .changeset/31390-oracle-raw16-uuid-hextoraw.md diff --git a/.changeset/31390-oracle-raw16-uuid-hextoraw.md b/.changeset/31390-oracle-raw16-uuid-hextoraw.md new file mode 100644 index 00000000000..467cb9b9dd6 --- /dev/null +++ b/.changeset/31390-oracle-raw16-uuid-hextoraw.md @@ -0,0 +1,12 @@ +--- +'@objectstack/driver-sql': patch +--- + +fix(driver-sql): an Oracle `RAW(16)` uuid column (a `SYS_GUID()` key, or a lookup over one) is now filtered and written by the uuid text it reads back as + +Clause-②: yes (widening) +Metadata-protocol: none + +The driver already read a `RAW(16)` column as a lowercase hyphenated uuid, but it bound that same text back as a string, which Oracle refuses against `RAW`. So a lookup keyed by a `SYS_GUID()` column displayed correctly and could not be filtered, written, updated or deleted by its value. + +The driver now reads, once per federated object, which of its remote columns are `RAW(16)` (`ALL_TAB_COLUMNS`), and binds a comparand, a written value or a by-id key for those columns as `HEXTORAW(?)` over the uuid's 32 hex digits. The column type decides, never the value: a `VARCHAR2` column holding uuids is bound as text, as before. Uuid text is accepted dashed (the read form) or as the 32 digits undashed, in either case. Anything else is refused before the statement is sent: a filter comparand with `INVALID_FILTER` / 400, a written value with `VALIDATION_ERROR` / 400. A failed catalog read changes nothing: values are bound as before and the next read asks again. Other dialects are unchanged. diff --git a/packages/drivers/driver-sql/src/sql-driver-crud.ts b/packages/drivers/driver-sql/src/sql-driver-crud.ts index 91464858337..85cfb314696 100644 --- a/packages/drivers/driver-sql/src/sql-driver-crud.ts +++ b/packages/drivers/driver-sql/src/sql-driver-crud.ts @@ -38,6 +38,7 @@ import { isUnresolvableColumnError, } from './sql-driver-top-level.js'; import type { SqlDriver } from './sql-driver.js'; +import { oracleUuidReadForm } from './sql-driver-oracle-dialect.js'; /** * The `SqlDriver` members the bodies of {@link CrudFacet} read — every one of @@ -439,10 +440,10 @@ export class CrudFacet { const builder = this.getBuilder(writeTable, options); this.applyTenantScope(builder, object, scopeOptions); // [#31390] On Oracle a RAW(16) uuid key binds each id as `HEXTORAW(?)`, and - // reads back as lowercase uuid text whatever case it was written in. + // reads back in the lowercase hyphenated form whatever form it was written in. const keys = written.map((row) => this.oracleUuidBinding(object, 'id', row.id, 'comparand')); const writtenKey = (row: Record, i: number): string => - keys[i] === row.id ? String(row.id) : String(row.id).toLowerCase(); + keys[i] === row.id ? String(row.id) : oracleUuidReadForm(String(row.id)); const stored: Record[] = await builder.whereIn(idColumn, keys as any[]); const byId = new Map>(); for (const row of stored) byId.set(String(row[idColumn]), row); diff --git a/packages/drivers/driver-sql/src/sql-driver-oracle-dialect.test.ts b/packages/drivers/driver-sql/src/sql-driver-oracle-dialect.test.ts index df1c3ba6a2d..95771a4f73f 100644 --- a/packages/drivers/driver-sql/src/sql-driver-oracle-dialect.test.ts +++ b/packages/drivers/driver-sql/src/sql-driver-oracle-dialect.test.ts @@ -407,6 +407,12 @@ describe('#31390 a RAW(16) uuid comparand binds as HEXTORAW(?) over its hex digi expect(bindings).toEqual([UUID_HEX, UUID_2_HEX]); }); + it('the 32 hex digits undashed (the RAWTOHEX form) bind the same bytes', async () => { + const { sql, bindings } = (await primed()).compileWhere('acct', { id: UUID_HEX.toLowerCase() }); + expect(sql).toBe('select * from "ACCT" where "ACCT_ID" = HEXTORAW(?)'); + expect(bindings).toEqual([UUID_HEX]); + }); + it('$ne keeps its null-safe shape around the bound comparand', async () => { const { sql, bindings } = (await primed()).compileWhere('ord', { account: { $ne: UUID } }); expect(sql).toBe('select * from "ORD" where ("ACCT_REF" is null or "ACCT_REF" <> HEXTORAW(?))'); @@ -438,11 +444,11 @@ describe('#31390 a comparand that is not uuid text is INVALID_FILTER, never sent ['$eq with valid hex of another length', { account: { $eq: '0f8fad5b' } }], ['$in holding one bad member', { account: { $in: [UUID, 'nope'] } }], ['$ne with a number', { account: { $ne: 42 } }], - ['the key, undashed', { id: UUID_HEX }], + ['31 hex digits', { id: UUID_HEX.slice(1) }], ] as const) { it(`${label}: INVALID_FILTER / 400`, async () => { const p = await primed(); - const err = caught(() => p.compileWhere(label === 'the key, undashed' ? 'acct' : 'ord', where as FilterCondition)); + const err = caught(() => p.compileWhere(label === '31 hex digits' ? 'acct' : 'ord', where as FilterCondition)); expect(err.code).toBe('INVALID_FILTER'); expect(err.status).toBe(400); }); @@ -501,16 +507,18 @@ describe('#31390 a written RAW(16) uuid value binds as HEXTORAW(?)', () => { ]); }); - it('create reads its row back by the HEXTORAW key, matching an upper-case written id to the lower-case read', async () => { - const p = await primed(); - p.respond = (obj) => (obj.sql.startsWith('select') ? [{ ORD_ID: UUID, ACCT_REF: UUID_2, NOTE: 'x' }] : []); - const row = await p.create('ord', { id: UUID.toUpperCase(), account: UUID_2, note: 'x' }); - expect(p.sent.map((s) => s.sql)).toEqual([ - 'insert into "ORD" ("ACCT_REF", "NOTE", "ORD_ID") values (HEXTORAW(:1), :2, HEXTORAW(:3))', - 'select * from "ORD" where "ORD_ID" in (HEXTORAW(:1))', - ]); - expect(row).toMatchObject({ id: UUID, account: UUID_2, note: 'x' }); - }); + for (const [label, written] of [['upper-case', UUID.toUpperCase()], ['undashed', UUID_HEX]] as const) { + it(`create reads its row back by the HEXTORAW key, matching a ${label} written id to the read form`, async () => { + const p = await primed(); + p.respond = (obj) => (obj.sql.startsWith('select') ? [{ ORD_ID: UUID, ACCT_REF: UUID_2, NOTE: 'x' }] : []); + const row = await p.create('ord', { id: written, account: UUID_2, note: 'x' }); + expect(p.sent.map((s) => s.sql)).toEqual([ + 'insert into "ORD" ("ACCT_REF", "NOTE", "ORD_ID") values (HEXTORAW(:1), :2, HEXTORAW(:3))', + 'select * from "ORD" where "ORD_ID" in (HEXTORAW(:1))', + ]); + expect(row).toMatchObject({ id: UUID, account: UUID_2, note: 'x' }); + }); + } }); describe('#31390 which columns: read from the catalog, once per object', () => { diff --git a/packages/drivers/driver-sql/src/sql-driver-oracle-dialect.ts b/packages/drivers/driver-sql/src/sql-driver-oracle-dialect.ts index b8c951f8912..27aadf8a60a 100644 --- a/packages/drivers/driver-sql/src/sql-driver-oracle-dialect.ts +++ b/packages/drivers/driver-sql/src/sql-driver-oracle-dialect.ts @@ -139,10 +139,20 @@ export function oracleRaw16AsUuid(value: unknown): unknown { } /** - * Uuid text as the column reads it back ({@link oracleRaw16AsUuid}): 8-4-4-4-12 - * hexadecimal digits, either case. + * Uuid text: the form the column reads back as ({@link oracleRaw16AsUuid}), + * 8-4-4-4-12 hexadecimal digits, or the same 32 digits undashed (the column's + * own hex form, which Oracle's `RAWTOHEX` prints) — either case. */ -const UUID_TEXT = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; +const UUID_TEXT = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|[0-9a-f]{32})$/i; + +/** + * Uuid text (either accepted form) as the column reads it back: lowercase and + * hyphenated, what {@link oracleRaw16AsUuid} answers for the same 16 bytes. + */ +export function oracleUuidReadForm(text: string): string { + const hex = text.replace(/-/g, '').toLowerCase(); + return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`; +} /** Where an {@link oracleUuidRawBinding} value goes: a WHERE comparand or a written column. */ export type OracleUuidBindingRole = 'comparand' | 'write'; @@ -183,7 +193,8 @@ export function oracleUuidRawBinding( } const why = 'is not a uuid. The column is a RAW(16) uuid on an Oracle table, and only uuid text ' + - '(8-4-4-4-12 hexadecimal digits, the form the column reads back as) can be bound to it.'; + '(8-4-4-4-12 hexadecimal digits, the form the column reads back as, or the same 32 digits undashed) ' + + 'can be bound to it.'; if (role === 'comparand') { throw withheldFilterError( `This filter compares a uuid column with a value that ${why} The field is withheld from the message; ` + diff --git a/packages/drivers/driver-sql/src/sql-driver-oracle-federation-conformance.test.ts b/packages/drivers/driver-sql/src/sql-driver-oracle-federation-conformance.test.ts index d32a05b42b0..f58f10bb897 100644 --- a/packages/drivers/driver-sql/src/sql-driver-oracle-federation-conformance.test.ts +++ b/packages/drivers/driver-sql/src/sql-driver-oracle-federation-conformance.test.ts @@ -423,6 +423,100 @@ function declareFederationSweep(cell: Cell, build: () => SqlDriver): void { }); } }); + + // ── #31390: a SYS_GUID() key is filtered and written by its uuid text ── + describe('RAW(16) uuid keys: filtered, written and looked up by the uuid they read as', () => { + const ACCT = { table: 'OSFC_UACCT', object: 'fc_uacct' }; + const ORD = { table: 'OSFC_UORD', object: 'fc_uord' }; + const ORDER_ID = '0f8fad5b-d9cb-469f-a165-70867728950e'; + let accounts: string[] = []; + + beforeAll(async () => { + await dropRemote(knex, cell, ORD.table); + await dropRemote(knex, cell, ACCT.table); + await knex.raw(`CREATE TABLE "${ACCT.table}" ("ACCT_ID" RAW(16) DEFAULT SYS_GUID() PRIMARY KEY, "NAME" VARCHAR2(100))`); + await knex.raw( + `CREATE TABLE "${ORD.table}" ("ORD_ID" RAW(16) PRIMARY KEY, "ACCT_REF" RAW(16), ` + + `"LEGACY_REF" VARCHAR2(36), "NOTE" VARCHAR2(100))`, + ); + await knex.raw(`INSERT INTO "${ACCT.table}" ("NAME") VALUES ('first')`); + await knex.raw(`INSERT INTO "${ACCT.table}" ("NAME") VALUES ('second')`); + (driver as any).registerExternalObject({ + name: ACCT.object, + external: { remoteName: ACCT.table, columnMap: { ACCT_ID: 'id', NAME: 'name' } }, + fields: { name: { type: 'text' } }, + }); + (driver as any).registerExternalObject({ + name: ORD.object, + external: { + remoteName: ORD.table, + columnMap: { ORD_ID: 'id', ACCT_REF: 'account', LEGACY_REF: 'legacy_account', NOTE: 'note' }, + }, + fields: { + account: { type: 'lookup', reference: ACCT.object }, + legacy_account: { type: 'lookup', reference: ACCT.object }, + note: { type: 'text' }, + }, + }); + const read = await driver.find(ACCT.object, { orderBy: [{ field: 'name', order: 'asc' }] }, BYPASS); + accounts = read.map((r) => String(r.id)); + }, 60_000); + + afterAll(async () => { + await dropRemote(knex, cell, ORD.table).catch(() => {}); + await dropRemote(knex, cell, ACCT.table).catch(() => {}); + }); + + it('the SYS_GUID keys read as lowercase hyphenated uuids', () => { + expect(accounts).toHaveLength(2); + for (const id of accounts) expect(id).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/); + }); + + it('create writes the key and the lookup by their uuid text, and answers the stored row', async () => { + const row = await driver.create( + ORD.object, + { id: ORDER_ID.toUpperCase(), account: accounts[0], legacy_account: accounts[0], note: 'n1' }, + BYPASS, + ); + expect(row).toMatchObject({ id: ORDER_ID, account: accounts[0], legacy_account: accounts[0], note: 'n1' }); + }); + + it('eq / $in on the lookup, and eq on the key, answer the row', async () => { + expect((await driver.find(ORD.object, { where: { account: accounts[0] } }, BYPASS)).map((r) => r.id)).toEqual([ORDER_ID]); + expect((await driver.find(ORD.object, { where: { account: { $in: [accounts[1]!, accounts[0]!] } } }, BYPASS)).map((r) => r.id)) + .toEqual([ORDER_ID]); + expect((await driver.find(ORD.object, { where: { account: accounts[1] } }, BYPASS))).toEqual([]); + expect((await driver.find(ORD.object, { where: { id: ORDER_ID } }, BYPASS)).map((r) => r.note)).toEqual(['n1']); + // The control: the VARCHAR2 column compares text, as it always did. + expect((await driver.find(ORD.object, { where: { legacy_account: accounts[0] } }, BYPASS)).map((r) => r.id)).toEqual([ORDER_ID]); + }); + + it('the lookup round-trips: the value read off the order finds its account by key', async () => { + const [order] = await driver.find(ORD.object, { where: { id: ORDER_ID } }, BYPASS); + const [account] = await driver.find(ACCT.object, { where: { id: String(order!.account) } }, BYPASS); + expect(account).toMatchObject({ id: accounts[0], name: 'first' }); + }); + + it('update by key rewrites the lookup, and delete by key removes the row', async () => { + const updated = await driver.update(ORD.object, ORDER_ID, { account: accounts[1] }, BYPASS); + expect(updated).toMatchObject({ id: ORDER_ID, account: accounts[1] }); + expect(await driver.delete(ORD.object, ORDER_ID, BYPASS)).toBe(true); + expect(await driver.find(ORD.object, { where: { id: ORDER_ID } }, BYPASS)).toEqual([]); + }); + + it('a comparand that is not uuid text is INVALID_FILTER; a written one is VALIDATION_ERROR', async () => { + const filterErr = await driver + .find(ORD.object, { where: { account: 'not-a-uuid' } }, BYPASS) + .then(() => null, (e: unknown) => e as WireBearingError); + expect(filterErr?.code).toBe('INVALID_FILTER'); + expect(filterErr?.status).toBe(400); + const writeErr = await driver + .create(ORD.object, { id: ORDER_ID, account: 'acct-17' }, BYPASS) + .then(() => null, (e: unknown) => e as WireBearingError); + expect(writeErr?.code).toBe('VALIDATION_ERROR'); + expect(writeErr?.status).toBe(400); + }); + }); } }); } From a22234a9a2971d1707db2a40e6bcbb83ce7ada7c Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 8 Nov 2026 16:41:03 +0000 Subject: [PATCH 4/6] fix(driver-sql): refuse a non-uuid RAW(16) comparand at the compile sites, through the seam with its subtree The refusal carries the filter subtree it was raised from, so the provenance mark decides what the wire names, as for every other compile refusal. Pattern operators on the column are not judged. Claude-Session: https://claude.ai/code/session_01ADHkmQ9H84XNocJ8waPS1P Co-authored-by: Claude --- .../sql-driver-compile-refusal-seam.test.ts | 14 +++++ .../src/sql-driver-filter-helpers.ts | 30 +++++++++-- .../src/sql-driver-oracle-dialect.test.ts | 6 +++ .../src/sql-driver-oracle-dialect.ts | 54 +++++++++++++++---- 4 files changed, 88 insertions(+), 16 deletions(-) diff --git a/packages/drivers/driver-sql/src/sql-driver-compile-refusal-seam.test.ts b/packages/drivers/driver-sql/src/sql-driver-compile-refusal-seam.test.ts index 8238d3ad1d6..35391ee464b 100644 --- a/packages/drivers/driver-sql/src/sql-driver-compile-refusal-seam.test.ts +++ b/packages/drivers/driver-sql/src/sql-driver-compile-refusal-seam.test.ts @@ -293,6 +293,20 @@ const DOORS: readonly Door[] = [ Object.defineProperty(driver, 'isOracle', { get: () => true, configurable: true }); }, }, + // ── #31390: a RAW(16) uuid column's comparand must be uuid text ────────── + { + builder: 'assertOracleUuidComparand', + where: () => ({ [POLICY_COL]: SECRET }), + secrets: [POLICY_COL], + klass: 'compares a uuid column with a value that is not a uuid', + // The fixture is SQLite; the refusal reads the dialect and the catalog's + // RAW(16) reading for the object, both set here. + setup: (driver) => { + Object.defineProperty(driver, 'isOracle', { get: () => true, configurable: true }); + (driver as unknown as { oracleRawUuidFieldsByObject: Map> }) + .oracleRawUuidFieldsByObject.set('deal', new Set([POLICY_COL])); + }, + }, // ── #31327: JSON-array membership on SQL Server, refused rather than guessed ── { builder: 'jsonMembershipUnsupportedDialectError', diff --git a/packages/drivers/driver-sql/src/sql-driver-filter-helpers.ts b/packages/drivers/driver-sql/src/sql-driver-filter-helpers.ts index 33f6e042b1c..1a706ad76e9 100644 --- a/packages/drivers/driver-sql/src/sql-driver-filter-helpers.ts +++ b/packages/drivers/driver-sql/src/sql-driver-filter-helpers.ts @@ -55,7 +55,13 @@ import { presentAuditTimestampOutput, reduceFilterKey, reduceFilterNode, refusalSubtree, retiredFilterOperatorError, unsupportedFilterError, unsupportedFilterOperatorError, withheldFilterDiagnosticOf, } from './sql-driver-top-level.js'; -import { assertOracleComparandNotEmptyString, oracleDayBinding, oracleInstantBinding } from './sql-driver-oracle-dialect.js'; +import { + assertOracleComparandNotEmptyString, + assertOracleUuidComparand, + isOracleUuidText, + oracleDayBinding, + oracleInstantBinding, +} from './sql-driver-oracle-dialect.js'; import { jsonMembershipUnsupportedOnOracleError } from './sql-driver-predicate-emitters.js'; import type { ReadPresentationKind } from './sql-driver-top-level.js'; import type { SqlDriver } from './sql-driver.js'; @@ -163,9 +169,11 @@ export class FilterHelpersFacet { // [#31390] Oracle: a comparand against a `RAW(16)` uuid column (as the // catalog reports it — `SqlDriver#primeOracleRawUuidColumns`) binds as - // `HEXTORAW(?)`; a value that is not uuid text is INVALID_FILTER, unsent. + // `HEXTORAW(?)`. A comparison comparand that is not uuid text was refused + // before this (`assertOracleUuidComparand`); a pattern operator's text is + // computed here too but never bound as the value, so it is left as it is. if (this.isOracle && this.oracleRawUuidFieldsByObject.get(table)?.has(field) === true) { - return this.oracleUuidBinding(table, field, value, 'comparand'); + return isOracleUuidText(value) ? this.oracleUuidBinding(table, field, value, 'comparand') : value; } const kind = this.temporalFieldKind(table, field); @@ -539,7 +547,7 @@ export class FilterHelpersFacet { } /** The body of `SqlDriver#compileFilters`; the method's docblock there is its contract. */ - static compileFilters(this: Pick, builder: Knex.QueryBuilder, filters: any, options?: DriverOptions) { + static compileFilters(this: Pick, builder: Knex.QueryBuilder, filters: any, options?: DriverOptions) { if (!filters) return; // [#5158] `where` is a `FilterCondition` OBJECT. It always was — the spec @@ -613,6 +621,10 @@ export class FilterHelpersFacet { // the issue measured as silently answering zero rows on an array column. this.assertOperatorAppliesToColumn(table, key, column, '=', true, refusalSubtree(value, filters)); if (this.isOracle) assertOracleComparandNotEmptyString('=', key, value, refusalSubtree(value, filters)); + // [#31390] A RAW(16) uuid column's comparand must be uuid text. + if (this.isOracle && this.oracleRawUuidFieldsByObject.get(table ?? '')?.has(key) === true) { + assertOracleUuidComparand('=', key, value, refusalSubtree(value, filters)); + } const coerced = this.coerceFilterValue(table, key, value); const expr = this.filterColumnExpr(table, key, column); if (expr && this.applyNormalizedComparison(builder, 'and', expr, '=', coerced)) continue; @@ -642,7 +654,7 @@ export class FilterHelpersFacet { } /** The body of `SqlDriver#applyFilterCondition`; the method's docblock there is its contract. */ - static applyFilterCondition(this: Pick, + static applyFilterCondition(this: Pick, builder: Knex.QueryBuilder, condition: any, logicalOp: 'and' | 'or' = 'and', @@ -868,6 +880,10 @@ export class FilterHelpersFacet { if ((op === '$contains' || op === '$notContains') && this.isJsonColumn(table, localField)) { throw jsonMembershipUnsupportedOnOracleError(localField, refusalSubtree(value, condition)); } + // [#31390] A RAW(16) uuid column's comparison comparand must be uuid text. + if (this.oracleRawUuidFieldsByObject.get(table ?? '')?.has(localField) === true) { + assertOracleUuidComparand(op, localField, opValue, refusalSubtree(value, condition)); + } } const coerced = this.coerceFilterValue(table, localField, opValue); if (columnExpr && this.applyNormalizedComparison(builder, logicalOp, columnExpr, op, coerced)) continue; @@ -1059,6 +1075,10 @@ export class FilterHelpersFacet { table, localField, field, '=', true, refusalSubtree(value, condition), ); if (this.isOracle) assertOracleComparandNotEmptyString('=', localField, value, refusalSubtree(value, condition)); + // [#31390] A RAW(16) uuid column's comparand must be uuid text. + if (this.isOracle && this.oracleRawUuidFieldsByObject.get(table ?? '')?.has(localField) === true) { + assertOracleUuidComparand('=', localField, value, refusalSubtree(value, condition)); + } const coerced = this.coerceFilterValue(table, localField, value); const columnExpr = this.filterColumnExpr(table, localField, field); if (columnExpr && this.applyNormalizedComparison(builder, logicalOp, columnExpr, '=', coerced)) continue; diff --git a/packages/drivers/driver-sql/src/sql-driver-oracle-dialect.test.ts b/packages/drivers/driver-sql/src/sql-driver-oracle-dialect.test.ts index 95771a4f73f..6bd618634a3 100644 --- a/packages/drivers/driver-sql/src/sql-driver-oracle-dialect.test.ts +++ b/packages/drivers/driver-sql/src/sql-driver-oracle-dialect.test.ts @@ -431,6 +431,12 @@ describe('#31390 a RAW(16) uuid comparand binds as HEXTORAW(?) over its hex digi expect(bindings).toEqual([UUID]); }); + it('control: a pattern operator on the RAW(16) column compiles its text pattern as before, unjudged', async () => { + const { sql, bindings } = (await primed()).compileWhere('ord', { account: { $contains: 'abc' } }); + expect(sql).toBe('select * from "ORD" where "ACCT_REF" LIKE ? ESCAPE ?'); + expect(bindings).toEqual(['%abc%', '\\']); + }); + it('control: a uuid-shaped value in a text column binds the text — the value is never the evidence', async () => { const { sql, bindings } = (await primed()).compileWhere('ord', { note: UUID }); expect(sql).toBe('select * from "ORD" where "NOTE" = ?'); diff --git a/packages/drivers/driver-sql/src/sql-driver-oracle-dialect.ts b/packages/drivers/driver-sql/src/sql-driver-oracle-dialect.ts index 27aadf8a60a..2040f511a7f 100644 --- a/packages/drivers/driver-sql/src/sql-driver-oracle-dialect.ts +++ b/packages/drivers/driver-sql/src/sql-driver-oracle-dialect.ts @@ -188,21 +188,14 @@ export function oracleUuidRawBinding( value: unknown, role: OracleUuidBindingRole, ): Knex.Raw { - if (typeof value === 'string' && UUID_TEXT.test(value)) { + if (isOracleUuidText(value)) { return knexInstance.raw('HEXTORAW(?)', [value.replace(/-/g, '').toUpperCase()]); } - const why = - 'is not a uuid. The column is a RAW(16) uuid on an Oracle table, and only uuid text ' + - '(8-4-4-4-12 hexadecimal digits, the form the column reads back as, or the same 32 digits undashed) ' + - 'can be bound to it.'; if (role === 'comparand') { - throw withheldFilterError( - `This filter compares a uuid column with a value that ${why} The field is withheld from the message; ` + - 'the full diagnostic is in the server log.', - `Field "${field}" is compared with a value that ${why}`, - ); + // A by-key door's id has no filter subtree to carry a mark: withheld. + assertOracleUuidComparand('=', field, value); } - const err = new Error(`The value written to field "${field}" ${why}`) as Error & { + const err = new Error(`The value written to field "${field}" ${NOT_A_UUID}`) as Error & { code?: string; status?: number; }; @@ -211,6 +204,45 @@ export function oracleUuidRawBinding( throw err; } +/** Whether `value` is uuid text a `RAW(16)` column can be bound to — see {@link UUID_TEXT}. */ +export function isOracleUuidText(value: unknown): value is string { + return typeof value === 'string' && UUID_TEXT.test(value); +} + +const NOT_A_UUID = + 'is not a uuid. The column is a RAW(16) uuid on an Oracle table, and only uuid text ' + + '(8-4-4-4-12 hexadecimal digits, the form the column reads back as, or the same 32 digits undashed) ' + + 'can be bound to it.'; + +/** + * Refuses a comparison comparand against a `RAW(16)` uuid column that is not + * uuid text (`INVALID_FILTER` / 400, through {@link withheldFilterError} with + * the subtree it was raised from), for the comparison operators — the ones + * whose comparand is bound to the column ({@link ORACLE_EMPTY_STRING_SENSITIVE_OPERATORS}). + * A list comparand is judged member by member; a `null` member is left to the + * operator's own null handling. + * + * The pattern operators (`$contains`, `$like`, …) are not judged: their + * comparand is a text pattern, never bound to the column as a value, and they + * compile exactly as before. + */ +export function assertOracleUuidComparand( + operator: string, + field: string, + value: unknown, + subtree?: unknown, +): void { + if (!ORACLE_EMPTY_STRING_SENSITIVE_OPERATORS.has(operator)) return; + const members = Array.isArray(value) ? value : [value]; + if (members.every((m) => m === null || m === undefined || isOracleUuidText(m))) return; + throw withheldFilterError( + `This filter compares a uuid column with a value that ${NOT_A_UUID} The field is withheld from the message; ` + + 'the full diagnostic is in the server log.', + `Field "${field}" is compared with a value that ${NOT_A_UUID}`, + subtree, + ); +} + /** * The `RAW(16)` columns of one remote table, read from the catalog * (`ALL_TAB_COLUMNS`): the columns {@link oracleUuidRawBinding} binds. From 16b8d727e5a20880ed46f2c9346e22884aabb7ee Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 8 Nov 2026 17:07:13 +0000 Subject: [PATCH 5/6] refactor(driver-sql): keep the SqlDriver facade pure delegation for the oracle uuid bind The RAW(16) catalog priming now runs at the top of each door facet body (find, create, update, delete, bulk, aggregate, distinct, window functions, analyze), the catalog read and the uuid binding live in FieldMappingFacet and FilterHelpersFacet, and registerExternalObject forgets a stale reading in its schema-sync body. SqlDriver keeps one-line forwards only. Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01ADHkmQ9H84XNocJ8waPS1P --- .../driver-sql/src/sql-driver-aggregation.ts | 7 +- .../src/sql-driver-bulk-operations.ts | 27 ++++- .../drivers/driver-sql/src/sql-driver-crud.ts | 12 ++- .../driver-sql/src/sql-driver-distinct.ts | 7 +- .../src/sql-driver-field-mapping.ts | 29 +++++ .../src/sql-driver-filter-helpers.ts | 10 ++ .../driver-sql/src/sql-driver-query-plan.ts | 7 +- .../driver-sql/src/sql-driver-schema-sync.ts | 6 +- .../src/sql-driver-sequence-semantics.ts | 11 +- .../src/sql-driver-window-functions.ts | 7 +- packages/drivers/driver-sql/src/sql-driver.ts | 102 +++++++----------- 11 files changed, 148 insertions(+), 77 deletions(-) diff --git a/packages/drivers/driver-sql/src/sql-driver-aggregation.ts b/packages/drivers/driver-sql/src/sql-driver-aggregation.ts index daedad219b9..75004eb6766 100644 --- a/packages/drivers/driver-sql/src/sql-driver-aggregation.ts +++ b/packages/drivers/driver-sql/src/sql-driver-aggregation.ts @@ -62,10 +62,12 @@ export interface AggregationHost { foldEmptyAggregateAnswers: SqlDriver['foldEmptyAggregateAnswers']; readonly fractionalNumericFields: SqlDriver['fractionalNumericFields']; getBuilder: SqlDriver['getBuilder']; + readonly isOracle: SqlDriver['isOracle']; readonly knex: SqlDriver['knex']; mapAggregateFunc: SqlDriver['mapAggregateFunc']; readonly numericFields: SqlDriver['numericFields']; presentReadColumns: SqlDriver['presentReadColumns']; + primeOracleRawUuidColumns: SqlDriver['primeOracleRawUuidColumns']; readPresentationKind: SqlDriver['readPresentationKind']; remoteColumn: SqlDriver['remoteColumn']; } @@ -73,7 +75,10 @@ export interface AggregationHost { /** 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[]> { + // [#31390] On Oracle a federated object's RAW(16) uuid columns are read from + // the remote catalog before a comparand or a written value is bound. + if (this.isOracle) await this.primeOracleRawUuidColumns(object); 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 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 11b22e30441..73f91fea1c7 100644 --- a/packages/drivers/driver-sql/src/sql-driver-bulk-operations.ts +++ b/packages/drivers/driver-sql/src/sql-driver-bulk-operations.ts @@ -59,9 +59,11 @@ export interface BulkOperationsHost { injectTenantOnInsert: SqlDriver['injectTenantOnInsert']; readonly insertReturnsStoredRows: SqlDriver['insertReturnsStoredRows']; readonly isMssql: SqlDriver['isMssql']; + readonly isOracle: SqlDriver['isOracle']; keepSuppliedUpdatedAt: SqlDriver['keepSuppliedUpdatedAt']; readonly knex: SqlDriver['knex']; oracleUuidBinding: SqlDriver['oracleUuidBinding']; + primeOracleRawUuidColumns: SqlDriver['primeOracleRawUuidColumns']; readBackInsertedRows: SqlDriver['readBackInsertedRows']; resyncSequenceToDataMax: SqlDriver['resyncSequenceToDataMax']; remoteColumn: SqlDriver['remoteColumn']; @@ -79,7 +81,10 @@ export interface BulkOperationsHost { /** The bodies of the "Bulk & Batch Operations" section of `SqlDriver`: a stateless facet, called by the class's stubs. */ export class BulkOperationsFacet { /** The body of `SqlDriver#bulkCreate`; the method's docblock there is its contract. */ - static async bulkCreate(this: Pick, object: string, data: any[], options?: DriverOptions): Promise[]> { + static async bulkCreate(this: Pick, object: string, data: any[], options?: DriverOptions): Promise[]> { + // [#31390] On Oracle a federated object's RAW(16) uuid columns are read from + // the remote catalog before a comparand or a written value is bound. + if (this.isOracle) await this.primeOracleRawUuidColumns(object); // Same client-side id assignment as create() (id/_id normalization, // nanoid fallback when neither is supplied) — a row missing an id must // not be silently inserted with a NULL primary key just because the @@ -262,7 +267,10 @@ 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 { + // [#31390] On Oracle a federated object's RAW(16) uuid columns are read from + // the remote catalog before a comparand or a written value is bound. + if (this.isOracle) await this.primeOracleRawUuidColumns(object); this.auditMissingTenant(object, 'bulkDelete', options); for (const target of this.rotationShardsOf(object) ?? [object]) { // The primary key's column: the `external.columnMap` remote column on a @@ -276,7 +284,10 @@ export class BulkOperationsFacet { } /** The body of `SqlDriver#updateMany`; the method's docblock there is its contract. */ - static async updateMany(this: Pick, object: string, query: DriverQuery, data: any, options?: DriverOptions): Promise { + static async updateMany(this: Pick, object: string, query: DriverQuery, data: any, options?: DriverOptions): Promise { + // [#31390] On Oracle a federated object's RAW(16) uuid columns are read from + // the remote catalog before a comparand or a written value is bound. + if (this.isOracle) await this.primeOracleRawUuidColumns(object); this.auditMissingTenant(object, 'updateMany', options); // `data ?? {}` keeps the nullish tolerance this door already had on the @@ -318,7 +329,10 @@ export class BulkOperationsFacet { } /** The body of `SqlDriver#deleteMany`; the method's docblock there is its contract. */ - static async deleteMany(this: Pick, object: string, query: DriverQuery, options?: DriverOptions): Promise { + static async deleteMany(this: Pick, object: string, query: DriverQuery, options?: DriverOptions): Promise { + // [#31390] On Oracle a federated object's RAW(16) uuid columns are read from + // the remote catalog before a comparand or a written value is bound. + if (this.isOracle) await this.primeOracleRawUuidColumns(object); this.auditMissingTenant(object, 'deleteMany', options); let total = 0; for (const target of this.rotationShardsOf(object) ?? [object]) { @@ -361,7 +375,10 @@ export class BulkOperationsFacet { } /** The body of `SqlDriver#count`; the method's docblock there is its contract. */ - static async count(this: Pick, object: string, query?: DriverQuery, options?: DriverOptions): Promise { + static async count(this: Pick, object: string, query?: DriverQuery, options?: DriverOptions): Promise { + // [#31390] On Oracle a federated object's RAW(16) uuid columns are read from + // the remote catalog before a comparand or a written value is bound. + if (this.isOracle) await this.primeOracleRawUuidColumns(object); const builder = this.getBuilder(object, options); this.applyTenantScope(builder, object, options); diff --git a/packages/drivers/driver-sql/src/sql-driver-crud.ts b/packages/drivers/driver-sql/src/sql-driver-crud.ts index 85cfb314696..7878352c3c8 100644 --- a/packages/drivers/driver-sql/src/sql-driver-crud.ts +++ b/packages/drivers/driver-sql/src/sql-driver-crud.ts @@ -66,12 +66,14 @@ export interface CrudHost { injectTenantOnInsert: SqlDriver['injectTenantOnInsert']; readonly insertReturnsStoredRows: SqlDriver['insertReturnsStoredRows']; readonly isMssql: SqlDriver['isMssql']; + readonly isOracle: SqlDriver['isOracle']; readonly isSqlite: SqlDriver['isSqlite']; readonly knex: SqlDriver['knex']; mapSortField: SqlDriver['mapSortField']; oracleUuidBinding: SqlDriver['oracleUuidBinding']; orderKeysFor: SqlDriver['orderKeysFor']; primeMssqlPagingKey: SqlDriver['primeMssqlPagingKey']; + primeOracleRawUuidColumns: SqlDriver['primeOracleRawUuidColumns']; readBackInsertedRows: SqlDriver['readBackInsertedRows']; remoteColumn: SqlDriver['remoteColumn']; resolveTenantField: SqlDriver['resolveTenantField']; @@ -118,7 +120,10 @@ export class CrudFacet { * cited that as agreement, which it was not; objectstack#4419.) The * obligation the contract states is on `find`, and this keeps it there. */ - static async findRows(this: Pick, object: string, query: DriverQuery, options?: DriverOptions, singleRowLookup = false): Promise { + static async findRows(this: Pick, object: string, query: DriverQuery, options?: DriverOptions, singleRowLookup = false): Promise { + // [#31390] On Oracle a federated object's RAW(16) uuid columns are read from + // the remote catalog before a comparand or a written value is bound. + if (this.isOracle) await this.primeOracleRawUuidColumns(object); // [#31327] On SQL Server a federated object's paging key is read from the // remote catalog before the ORDER BY is decided (`primeMssqlPagingKey`). if (this.isMssql) await this.primeMssqlPagingKey(object); @@ -273,7 +278,10 @@ export class CrudFacet { } /** The body of `SqlDriver#create`; the method's docblock there is its contract. */ - static async create(this: Pick, object: string, data: Record, options?: DriverOptions): Promise> { + static async create(this: Pick, object: string, data: Record, options?: DriverOptions): Promise> { + // [#31390] On Oracle a federated object's RAW(16) uuid columns are read from + // the remote catalog before a comparand or a written value is bound. + if (this.isOracle) await this.primeOracleRawUuidColumns(object); const { _id, ...rest } = data; const toInsert = { ...rest }; diff --git a/packages/drivers/driver-sql/src/sql-driver-distinct.ts b/packages/drivers/driver-sql/src/sql-driver-distinct.ts index 68c98f20de0..06b469a895c 100644 --- a/packages/drivers/driver-sql/src/sql-driver-distinct.ts +++ b/packages/drivers/driver-sql/src/sql-driver-distinct.ts @@ -44,7 +44,9 @@ export interface DistinctHost { coercionKey: SqlDriver['coercionKey']; distinctBackendFault: SqlDriver['distinctBackendFault']; getBuilder: SqlDriver['getBuilder']; + readonly isOracle: SqlDriver['isOracle']; presentReadValue: SqlDriver['presentReadValue']; + primeOracleRawUuidColumns: SqlDriver['primeOracleRawUuidColumns']; readPresentationKind: SqlDriver['readPresentationKind']; remoteColumn: SqlDriver['remoteColumn']; } @@ -52,7 +54,10 @@ export interface DistinctHost { /** 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 { + // [#31390] On Oracle a federated object's RAW(16) uuid columns are read from + // the remote catalog before a comparand or a written value is bound. + if (this.isOracle) await this.primeOracleRawUuidColumns(object); 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 — …, diff --git a/packages/drivers/driver-sql/src/sql-driver-field-mapping.ts b/packages/drivers/driver-sql/src/sql-driver-field-mapping.ts index bee7b32a43f..adbd730ee6c 100644 --- a/packages/drivers/driver-sql/src/sql-driver-field-mapping.ts +++ b/packages/drivers/driver-sql/src/sql-driver-field-mapping.ts @@ -34,6 +34,7 @@ import { StorageNameMapping } from '@objectstack/spec/system'; import { SQL_AGGREGATE_FUNCTIONS, refuseAggregateFunction } from './sql-driver-top-level.js'; import type { SqlAggregateLowering } from './sql-driver-top-level.js'; import type { SqlDriver } from './sql-driver.js'; +import { oracleRawUuidColumns } from './sql-driver-oracle-dialect.js'; /** * The `SqlDriver` members the bodies of {@link FieldMappingFacet} read — every one of @@ -46,17 +47,45 @@ export interface FieldMappingHost { readonly columnFieldByObject: SqlDriver['columnFieldByObject']; readonly fieldColumnByObject: SqlDriver['fieldColumnByObject']; introspectPrimaryKeys: SqlDriver['introspectPrimaryKeys']; + readonly isOracle: SqlDriver['isOracle']; + readonly knex: SqlDriver['knex']; readonly logger: SqlDriver['logger']; readonly managedObjectFields: SqlDriver['managedObjectFields']; readonly mssqlPagingKeyByObject: SqlDriver['mssqlPagingKeyByObject']; readonly nondeterministicPagingWarned: SqlDriver['nondeterministicPagingWarned']; + readonly oracleRawUuidFieldsByObject: SqlDriver['oracleRawUuidFieldsByObject']; paginationTieBreaker: SqlDriver['paginationTieBreaker']; readonly physicalSchemaByObject: SqlDriver['physicalSchemaByObject']; readonly physicalTableByObject: SqlDriver['physicalTableByObject']; + readOracleRawUuidColumns: SqlDriver['readOracleRawUuidColumns']; } /** The bodies of the "Field mapping" section of `SqlDriver`: a stateless facet, called by the class's stubs. */ export class FieldMappingFacet { + /** The body of `SqlDriver#primeOracleRawUuidColumns`; the method's docblock there is its contract. */ + static async primeOracleRawUuidColumns(this: Pick, object: string): Promise { + if (!this.isOracle || this.oracleRawUuidFieldsByObject.has(object)) return; + // Only a federated object names a remote table; a platform-created table + // never holds a RAW(16) uuid column, so there is nothing to read. + const remoteTable = this.physicalTableByObject[object]; + if (remoteTable === undefined) return; + let columns: string[]; + try { + columns = await this.readOracleRawUuidColumns(remoteTable, this.physicalSchemaByObject[object]); + } catch { + // A catalog that cannot be read leaves nothing recorded: every value + // keeps today's text bind, and the next door asks again. + return; + } + const colToField = this.columnFieldByObject[object]; + this.oracleRawUuidFieldsByObject.set(object, new Set(columns.map((column) => colToField?.[column] ?? column))); + } + + /** The body of `SqlDriver#readOracleRawUuidColumns`; the method's docblock there is its contract. */ + static readOracleRawUuidColumns(this: Pick, remoteTable: string, remoteSchema: string | undefined): Promise { + return oracleRawUuidColumns(this.knex, remoteTable, remoteSchema); + } + /** The body of `SqlDriver#mapSortField`; the method's docblock there is its contract. */ static mapSortField(field: string): string { if (field === 'createdAt') return 'created_at'; diff --git a/packages/drivers/driver-sql/src/sql-driver-filter-helpers.ts b/packages/drivers/driver-sql/src/sql-driver-filter-helpers.ts index 1a706ad76e9..8e12c3c7b0e 100644 --- a/packages/drivers/driver-sql/src/sql-driver-filter-helpers.ts +++ b/packages/drivers/driver-sql/src/sql-driver-filter-helpers.ts @@ -61,7 +61,9 @@ import { isOracleUuidText, oracleDayBinding, oracleInstantBinding, + oracleUuidRawBinding, } from './sql-driver-oracle-dialect.js'; +import type { OracleUuidBindingRole } from './sql-driver-oracle-dialect.js'; import { jsonMembershipUnsupportedOnOracleError } from './sql-driver-predicate-emitters.js'; import type { ReadPresentationKind } from './sql-driver-top-level.js'; import type { SqlDriver } from './sql-driver.js'; @@ -104,6 +106,7 @@ export interface FilterHelpersHost { readonly isSqlite: SqlDriver['isSqlite']; jsonColumnFieldClass: SqlDriver['jsonColumnFieldClass']; readonly jsonFields: SqlDriver['jsonFields']; + readonly knex: SqlDriver['knex']; logWithheldFilterDiagnostic: SqlDriver['logWithheldFilterDiagnostic']; readonly logger: SqlDriver['logger']; readonly managedObjectFields: SqlDriver['managedObjectFields']; @@ -135,6 +138,13 @@ export interface FilterHelpersHost { /** The bodies of the "Filter helpers" section of `SqlDriver`: a stateless facet, called by the class's stubs. */ export class FilterHelpersFacet { + /** The body of `SqlDriver#oracleUuidBinding`; the method's docblock there is its contract. */ + static oracleUuidBinding(this: Pick, object: string | null | undefined, field: string, value: unknown, role: OracleUuidBindingRole): unknown { + if (!this.isOracle || !object || value === null || value === undefined) return value; + if (this.oracleRawUuidFieldsByObject.get(object)?.has(field) !== true) return value; + return oracleUuidRawBinding(this.knex, field, value, role); + } + /** The body of `SqlDriver#tableNameForBuilder`; the method's docblock there is its contract. */ static tableNameForBuilder(builder: any): string | null { const t = builder?._single?.table; diff --git a/packages/drivers/driver-sql/src/sql-driver-query-plan.ts b/packages/drivers/driver-sql/src/sql-driver-query-plan.ts index 36f6babcd52..a876644c2dd 100644 --- a/packages/drivers/driver-sql/src/sql-driver-query-plan.ts +++ b/packages/drivers/driver-sql/src/sql-driver-query-plan.ts @@ -46,10 +46,12 @@ export interface QueryPlanHost { readonly config: SqlDriver['config']; getBuilder: SqlDriver['getBuilder']; readonly isMysql: SqlDriver['isMysql']; + readonly isOracle: SqlDriver['isOracle']; readonly isPostgres: SqlDriver['isPostgres']; readonly isSqlite: SqlDriver['isSqlite']; readonly knex: SqlDriver['knex']; mapSortField: SqlDriver['mapSortField']; + primeOracleRawUuidColumns: SqlDriver['primeOracleRawUuidColumns']; } /** The bodies of the "Query Plan Analysis" section of `SqlDriver`: a stateless facet, called by the class's stubs. */ @@ -60,7 +62,10 @@ export class QueryPlanFacet { } /** The body of `SqlDriver#analyzeQuery`; the method's docblock there is its contract. */ - static async analyzeQuery(this: Pick, object: string, query: DriverQuery, options?: DriverOptions): Promise { + static async analyzeQuery(this: Pick, object: string, query: DriverQuery, options?: DriverOptions): Promise { + // [#31390] On Oracle a federated object's RAW(16) uuid columns are read from + // the remote catalog before a comparand or a written value is bound. + if (this.isOracle) await this.primeOracleRawUuidColumns(object); const builder = this.getBuilder(object, options); // A PLAN, not rows — so this is a smaller fix than the one above, and it is // made on its own merits rather than riding in on that one (#6792). It is diff --git a/packages/drivers/driver-sql/src/sql-driver-schema-sync.ts b/packages/drivers/driver-sql/src/sql-driver-schema-sync.ts index 15e7117aadd..9176cb528d2 100644 --- a/packages/drivers/driver-sql/src/sql-driver-schema-sync.ts +++ b/packages/drivers/driver-sql/src/sql-driver-schema-sync.ts @@ -240,6 +240,7 @@ export interface SchemaSyncHost { readonly numericFields: SqlDriver['numericFields']; readonly numericValueFields: SqlDriver['numericValueFields']; readonly objectByPhysicalTable: SqlDriver['objectByPhysicalTable']; + readonly oracleRawUuidFieldsByObject: SqlDriver['oracleRawUuidFieldsByObject']; readonly physicalSchemaByObject: SqlDriver['physicalSchemaByObject']; readonly physicalTableByObject: SqlDriver['physicalTableByObject']; planDeclaredRenames: SqlDriver['planDeclaredRenames']; @@ -1856,7 +1857,7 @@ export function rotationColumnList(obj: { fields?: Record }): strin } /** The body of `SqlDriver#registerExternalObject`; the method's docblock there is its contract. */ -export function registerExternalObject(this: Pick, schema: { +export function registerExternalObject(this: Pick, schema: { name: string; fields?: Record; tenancy?: any; @@ -1866,6 +1867,9 @@ export function registerExternalObject(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> { + // [#31390] On Oracle a federated object's RAW(16) uuid columns are read from + // the remote catalog before a comparand or a written value is bound. + if (this.isOracle) await this.primeOracleRawUuidColumns(object); this.auditMissingTenant(object, 'update', options); const rotationShards = this.rotationShardsOf(object); if (rotationShards) return this.rotatedUpdateById(object, rotationShards, id, data, options); @@ -938,7 +942,10 @@ 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 { + // [#31390] On Oracle a federated object's RAW(16) uuid columns are read from + // the remote catalog before a comparand or a written value is bound. + if (this.isOracle) await this.primeOracleRawUuidColumns(object); this.auditMissingTenant(object, 'delete', options); const rotationShards = this.rotationShardsOf(object); if (rotationShards) { diff --git a/packages/drivers/driver-sql/src/sql-driver-window-functions.ts b/packages/drivers/driver-sql/src/sql-driver-window-functions.ts index 0d7b870bc39..90b34d7e177 100644 --- a/packages/drivers/driver-sql/src/sql-driver-window-functions.ts +++ b/packages/drivers/driver-sql/src/sql-driver-window-functions.ts @@ -46,14 +46,19 @@ export interface WindowFunctionsHost { buildWindowFunction: SqlDriver['buildWindowFunction']; formatOutput: SqlDriver['formatOutput']; getBuilder: SqlDriver['getBuilder']; + readonly isOracle: SqlDriver['isOracle']; readonly knex: SqlDriver['knex']; mapSortField: SqlDriver['mapSortField']; + primeOracleRawUuidColumns: SqlDriver['primeOracleRawUuidColumns']; } /** The bodies of the "Window Functions" section of `SqlDriver`: a stateless facet, called by the class's stubs. */ export class WindowFunctionsFacet { /** The body of `SqlDriver#findWithWindowFunctions`; the method's docblock there is its contract. */ - static async findWithWindowFunctions(this: Pick, object: string, query: SqlWindowFunctionQuery, options?: DriverOptions): Promise { + static async findWithWindowFunctions(this: Pick, object: string, query: SqlWindowFunctionQuery, options?: DriverOptions): Promise { + // [#31390] On Oracle a federated object's RAW(16) uuid columns are read from + // the remote catalog before a comparand or a written value is bound. + if (this.isOracle) await this.primeOracleRawUuidColumns(object); const builder = this.getBuilder(object, options); // ROWS, so this is the read-side wall itself — not a consistency tidy-up // (#6792). This door returned every tenant's rows to a caller that passed diff --git a/packages/drivers/driver-sql/src/sql-driver.ts b/packages/drivers/driver-sql/src/sql-driver.ts index f9f669d525d..30736896e9d 100644 --- a/packages/drivers/driver-sql/src/sql-driver.ts +++ b/packages/drivers/driver-sql/src/sql-driver.ts @@ -294,12 +294,7 @@ import { SqliteSerialisationFacet } from './sql-driver-sqlite-serialisation.js'; // [cloud#3652 D3] Declared renames: the methods of the same names below hand the bodies what they read (`DeclaredRenameHost`). import { DeclaredRenameFacet } from './sql-driver-declared-rename.js'; import type { DeclaredRenameCarry, DeclaredRenamePlan } from './declared-rename.js'; -import { - oracleRawUuidColumns, - oracleUuidRawBinding, - withOracleFederationClient, - type OracleUuidBindingRole, -} from './sql-driver-oracle-dialect.js'; +import { withOracleFederationClient, type OracleUuidBindingRole } from './sql-driver-oracle-dialect.js'; // [#29520 codemod] The facets' hosts, one per driver, which the static block at the end of the class builds. import { aggregationHost, bulkOperationsHost, classHeadHost, columnCreationHost, crudHost, databaseHelpersHost, @@ -1801,8 +1796,7 @@ export class SqlDriver implements IDataDriver { // `sql-driver-doors-declared-types.test.ts`. find(object: string, query: DriverQuery, options?: DriverOptions): Promise[]> { // [#29520 codemod] The body moved to `sql-driver-crud.ts` (see `CrudHost`). - // [#31390] Oracle learns the object's RAW(16) uuid columns first; any other dialect runs as before. - return this.withOracleRawUuidColumns(object, () => CrudFacet.find.call(crudHost.of(this), object, query, options)); + return CrudFacet.find.call(crudHost.of(this), object, query, options); } private async findRows( @@ -1856,22 +1850,12 @@ export class SqlDriver implements IDataDriver { * for an object that was never registered as external. */ protected async primeOracleRawUuidColumns(object: string): Promise { - if (!this.isOracle || this.oracleRawUuidFieldsByObject.has(object)) return; - const remoteTable = this.physicalTableByObject[object]; - if (remoteTable === undefined) return; - let columns: string[]; - try { - columns = await this.readOracleRawUuidColumns(remoteTable, this.physicalSchemaByObject[object]); - } catch { - return; - } - const colToField = this.columnFieldByObject[object]; - this.oracleRawUuidFieldsByObject.set(object, new Set(columns.map((column) => colToField?.[column] ?? column))); + return FieldMappingFacet.primeOracleRawUuidColumns.call(fieldMappingHost.of(this), object); } /** The catalog read behind {@link primeOracleRawUuidColumns}: the remote table's `RAW(16)` column names. */ protected readOracleRawUuidColumns(remoteTable: string, remoteSchema: string | undefined): Promise { - return oracleRawUuidColumns(this.knex, remoteTable, remoteSchema); + return FieldMappingFacet.readOracleRawUuidColumns.call(fieldMappingHost.of(this), remoteTable, remoteSchema); } /** @@ -1888,19 +1872,7 @@ export class SqlDriver implements IDataDriver { value: unknown, role: OracleUuidBindingRole, ): unknown { - if (!this.isOracle || !object || value === null || value === undefined) return value; - if (this.oracleRawUuidFieldsByObject.get(object)?.has(field) !== true) return value; - return oracleUuidRawBinding(this.knex, field, value, role); - } - - /** - * Run a door that compiles comparands or written values for `object` after - * {@link primeOracleRawUuidColumns}. On every other dialect `run` is called - * at once, synchronously, exactly as the door did before. - */ - private withOracleRawUuidColumns(object: string, run: () => Promise): Promise { - if (!this.isOracle) return run(); - return this.primeOracleRawUuidColumns(object).then(run); + return FilterHelpersFacet.oracleUuidBinding.call(filterHelpersHost.of(this), object, field, value, role); } /** @@ -1928,8 +1900,7 @@ export class SqlDriver implements IDataDriver { */ findOne(object: string, query: DriverQuery, options?: DriverOptions): Promise | null> { // [#29520 codemod] The body moved to `sql-driver-crud.ts` (see `CrudHost`). - // [#31390] Oracle learns the object's RAW(16) uuid columns first; any other dialect runs as before. - return this.withOracleRawUuidColumns(object, () => CrudFacet.findOne.call(crudHost.of(this), object, query, options)); + return CrudFacet.findOne.call(crudHost.of(this), object, query, options); } // `findStream` was removed with the contract method in 17.0.0 (#4484). This driver's @@ -1952,8 +1923,7 @@ export class SqlDriver implements IDataDriver { */ create(object: string, data: Record, options?: DriverOptions): Promise> { // [#29520 codemod] The body moved to `sql-driver-crud.ts` (see `CrudHost`). - // [#31390] Oracle learns the object's RAW(16) uuid columns first; any other dialect runs as before. - return this.withOracleRawUuidColumns(object, () => CrudFacet.create.call(crudHost.of(this), object, data, options)); + return CrudFacet.create.call(crudHost.of(this), object, data, options); } private readBackInsertedRows( @@ -2825,8 +2795,7 @@ export class SqlDriver implements IDataDriver { */ update(object: string, id: string | number, data: Record, options?: DriverOptions): Promise | null> { // [#29520 codemod] The body moved to `sql-driver-sequence-semantics.ts` (see `SequenceSemanticsHost`). - // [#31390] Oracle learns the object's RAW(16) uuid columns first; any other dialect runs as before. - return this.withOracleRawUuidColumns(object, () => SequenceSemanticsFacet.update.call(sequenceSemanticsHost.of(this), object, id, data, options)); + return SequenceSemanticsFacet.update.call(sequenceSemanticsHost.of(this), object, id, data, options); } /** @@ -3196,8 +3165,7 @@ export class SqlDriver implements IDataDriver { delete(object: string, id: string | number, options?: DriverOptions): Promise { // [#29520 codemod] The body moved to `sql-driver-sequence-semantics.ts` (see `SequenceSemanticsHost`). - // [#31390] Oracle learns the object's RAW(16) uuid columns first; any other dialect runs as before. - return this.withOracleRawUuidColumns(object, () => SequenceSemanticsFacet.delete.call(sequenceSemanticsHost.of(this), object, id, options)); + return SequenceSemanticsFacet.delete.call(sequenceSemanticsHost.of(this), object, id, options); } // =================================== @@ -3213,8 +3181,7 @@ export class SqlDriver implements IDataDriver { */ bulkCreate(object: string, data: any[], options?: DriverOptions): Promise[]> { // [#29520 codemod] The body moved to `sql-driver-bulk-operations.ts` (see `BulkOperationsHost`). - // [#31390] Oracle learns the object's RAW(16) uuid columns first; any other dialect runs as before. - return this.withOracleRawUuidColumns(object, () => BulkOperationsFacet.bulkCreate.call(bulkOperationsHost.of(this), object, data, options)); + return BulkOperationsFacet.bulkCreate.call(bulkOperationsHost.of(this), object, data, options); } /** @@ -3285,8 +3252,7 @@ export class SqlDriver implements IDataDriver { bulkDelete(object: string, ids: Array, options?: DriverOptions): Promise { // [#29520 codemod] The body moved to `sql-driver-bulk-operations.ts` (see `BulkOperationsHost`). - // [#31390] Oracle learns the object's RAW(16) uuid columns first; any other dialect runs as before. - return this.withOracleRawUuidColumns(object, () => BulkOperationsFacet.bulkDelete.call(bulkOperationsHost.of(this), object, ids, options)); + return BulkOperationsFacet.bulkDelete.call(bulkOperationsHost.of(this), object, ids, options); } /** @@ -3341,14 +3307,12 @@ export class SqlDriver implements IDataDriver { */ updateMany(object: string, query: DriverQuery, data: any, options?: DriverOptions): Promise { // [#29520 codemod] The body moved to `sql-driver-bulk-operations.ts` (see `BulkOperationsHost`). - // [#31390] Oracle learns the object's RAW(16) uuid columns first; any other dialect runs as before. - return this.withOracleRawUuidColumns(object, () => BulkOperationsFacet.updateMany.call(bulkOperationsHost.of(this), object, query, data, options)); + return BulkOperationsFacet.updateMany.call(bulkOperationsHost.of(this), object, query, data, options); } deleteMany(object: string, query: DriverQuery, options?: DriverOptions): Promise { // [#29520 codemod] The body moved to `sql-driver-bulk-operations.ts` (see `BulkOperationsHost`). - // [#31390] Oracle learns the object's RAW(16) uuid columns first; any other dialect runs as before. - return this.withOracleRawUuidColumns(object, () => BulkOperationsFacet.deleteMany.call(bulkOperationsHost.of(this), object, query, options)); + return BulkOperationsFacet.deleteMany.call(bulkOperationsHost.of(this), object, query, options); } /** By-id update for a rotation-managed object: the row lives in exactly one @@ -3464,8 +3428,7 @@ export class SqlDriver implements IDataDriver { count(object: string, query?: DriverQuery, options?: DriverOptions): Promise { // [#29520 codemod] The body moved to `sql-driver-bulk-operations.ts` (see `BulkOperationsHost`). - // [#31390] Oracle learns the object's RAW(16) uuid columns first; any other dialect runs as before. - return this.withOracleRawUuidColumns(object, () => BulkOperationsFacet.count.call(bulkOperationsHost.of(this), object, query, options)); + return BulkOperationsFacet.count.call(bulkOperationsHost.of(this), object, query, options); } // =================================== @@ -3683,8 +3646,7 @@ export class SqlDriver implements IDataDriver { */ aggregate(object: string, query: DriverQuery, options?: DriverOptions): Promise[]> { // [#29520 codemod] The body moved to `sql-driver-aggregation.ts` (see `AggregationHost`). - // [#31390] Oracle learns the object's RAW(16) uuid columns first; any other dialect runs as before. - return this.withOracleRawUuidColumns(object, () => AggregationFacet.aggregate.call(aggregationHost.of(this), object, query, options)); + return AggregationFacet.aggregate.call(aggregationHost.of(this), object, query, options); } /** @@ -3913,8 +3875,7 @@ export class SqlDriver implements IDataDriver { */ distinct(object: string, field: string, filters?: FilterCondition, options?: DriverOptions): Promise { // [#29520 codemod] The body moved to `sql-driver-distinct.ts` (see `DistinctHost`). - // [#31390] Oracle learns the object's RAW(16) uuid columns first; any other dialect runs as before. - return this.withOracleRawUuidColumns(object, () => DistinctFacet.distinct.call(distinctHost.of(this), object, field, filters, options)); + return DistinctFacet.distinct.call(distinctHost.of(this), object, field, filters, options); } /** @@ -4074,8 +4035,7 @@ export class SqlDriver implements IDataDriver { */ findWithWindowFunctions(object: string, query: SqlWindowFunctionQuery, options?: DriverOptions): Promise { // [#29520 codemod] The body moved to `sql-driver-window-functions.ts` (see `WindowFunctionsHost`). - // [#31390] Oracle learns the object's RAW(16) uuid columns first; any other dialect runs as before. - return this.withOracleRawUuidColumns(object, () => WindowFunctionsFacet.findWithWindowFunctions.call(windowFunctionsHost.of(this), object, query, options)); + return WindowFunctionsFacet.findWithWindowFunctions.call(windowFunctionsHost.of(this), object, query, options); } // =================================== @@ -4095,8 +4055,7 @@ export class SqlDriver implements IDataDriver { */ explain(object: string, query: DriverQuery, options?: DriverOptions): Promise { // [#29520 codemod] The body moved to `sql-driver-query-plan.ts` (see `QueryPlanHost`). - // [#31390] Oracle learns the object's RAW(16) uuid columns first; any other dialect runs as before. - return this.withOracleRawUuidColumns(object, () => QueryPlanFacet.explain.call(queryPlanHost.of(this), object, query, options)); + return QueryPlanFacet.explain.call(queryPlanHost.of(this), object, query, options); } /** @@ -4107,8 +4066,7 @@ export class SqlDriver implements IDataDriver { */ analyzeQuery(object: string, query: DriverQuery, options?: DriverOptions): Promise { // [#29520 codemod] The body moved to `sql-driver-query-plan.ts` (see `QueryPlanHost`). - // [#31390] Oracle learns the object's RAW(16) uuid columns first; any other dialect runs as before. - return this.withOracleRawUuidColumns(object, () => QueryPlanFacet.analyzeQuery.call(queryPlanHost.of(this), object, query, options)); + return QueryPlanFacet.analyzeQuery.call(queryPlanHost.of(this), object, query, options); } // =================================== @@ -4410,8 +4368,6 @@ export class SqlDriver implements IDataDriver { external?: { remoteName?: string; remoteSchema?: string; columnMap?: Record }; }): void { // [#25521 cut 17] The body moved to `sql-driver-schema-sync.ts` (see `SchemaSyncHost`). - // [#31390] A re-registration may name another remote table: its RAW(16) columns are read again. - this.oracleRawUuidFieldsByObject.delete(schema.name); const readAutoNumberFields = () => this.autoNumberFields; const readBooleanFields = () => this.booleanFields; const readColumnFieldByObject = () => this.columnFieldByObject; @@ -4426,6 +4382,7 @@ export class SqlDriver implements IDataDriver { const readNumericFields = () => this.numericFields; const readNumericValueFields = () => this.numericValueFields; const readObjectByPhysicalTable = () => this.objectByPhysicalTable; + const readOracleRawUuidFieldsByObject = () => this.oracleRawUuidFieldsByObject; const readPhysicalSchemaByObject = () => this.physicalSchemaByObject; const readPhysicalTableByObject = () => this.physicalTableByObject; const readTenantFieldByTable = () => this.tenantFieldByTable; @@ -4448,6 +4405,7 @@ export class SqlDriver implements IDataDriver { get numericFields() { return readNumericFields(); }, get numericValueFields() { return readNumericValueFields(); }, get objectByPhysicalTable() { return readObjectByPhysicalTable(); }, + get oracleRawUuidFieldsByObject() { return readOracleRawUuidFieldsByObject(); }, get physicalSchemaByObject() { return readPhysicalSchemaByObject(); }, get physicalTableByObject() { return readPhysicalTableByObject(); }, get tenantFieldByTable() { return readTenantFieldByTable(); }, @@ -9185,10 +9143,12 @@ export class SqlDriver implements IDataDriver { foldEmptyAggregateAnswers: (...a) => driver.foldEmptyAggregateAnswers(...a), get fractionalNumericFields() { return driver.fractionalNumericFields; }, get getBuilder() { return driver.getBuilder.bind(driver); }, + get isOracle() { return driver.isOracle; }, get knex() { return driver.knex; }, mapAggregateFunc: (...a) => driver.mapAggregateFunc(...a), get numericFields() { return driver.numericFields; }, presentReadColumns: (...a) => driver.presentReadColumns(...a), + primeOracleRawUuidColumns: (...a) => driver.primeOracleRawUuidColumns(...a), readPresentationKind: (...a) => driver.readPresentationKind(...a), remoteColumn: (...a) => driver.remoteColumn(...a), })); @@ -9207,9 +9167,11 @@ export class SqlDriver implements IDataDriver { injectTenantOnInsert: (...a) => driver.injectTenantOnInsert(...a), get insertReturnsStoredRows() { return driver.insertReturnsStoredRows; }, get isMssql() { return driver.isMssql; }, + get isOracle() { return driver.isOracle; }, keepSuppliedUpdatedAt: (...a) => driver.keepSuppliedUpdatedAt(...a), get knex() { return driver.knex; }, oracleUuidBinding: (...a) => driver.oracleUuidBinding(...a), + primeOracleRawUuidColumns: (...a) => driver.primeOracleRawUuidColumns(...a), readBackInsertedRows: (...a) => driver.readBackInsertedRows(...a), resyncSequenceToDataMax: (...a) => driver.resyncSequenceToDataMax(...a), remoteColumn: (...a) => driver.remoteColumn(...a), @@ -9278,12 +9240,14 @@ export class SqlDriver implements IDataDriver { injectTenantOnInsert: (...a) => driver.injectTenantOnInsert(...a), get insertReturnsStoredRows() { return driver.insertReturnsStoredRows; }, get isMssql() { return driver.isMssql; }, + get isOracle() { return driver.isOracle; }, get isSqlite() { return driver.isSqlite; }, get knex() { return driver.knex; }, mapSortField: (...a) => driver.mapSortField(...a), oracleUuidBinding: (...a) => driver.oracleUuidBinding(...a), orderKeysFor: (...a) => driver.orderKeysFor(...a), primeMssqlPagingKey: (...a) => driver.primeMssqlPagingKey(...a), + primeOracleRawUuidColumns: (...a) => driver.primeOracleRawUuidColumns(...a), readBackInsertedRows: (...a) => driver.readBackInsertedRows(...a), remoteColumn: (...a) => driver.remoteColumn(...a), resolveTenantField: (...a) => driver.resolveTenantField(...a), @@ -9355,7 +9319,9 @@ export class SqlDriver implements IDataDriver { coercionKey: (...a) => driver.coercionKey(...a), distinctBackendFault: (...a) => driver.distinctBackendFault(...a), get getBuilder() { return driver.getBuilder.bind(driver); }, + get isOracle() { return driver.isOracle; }, presentReadValue: (...a) => driver.presentReadValue(...a), + primeOracleRawUuidColumns: (...a) => driver.primeOracleRawUuidColumns(...a), readPresentationKind: (...a) => driver.readPresentationKind(...a), remoteColumn: (...a) => driver.remoteColumn(...a), })); @@ -9363,13 +9329,17 @@ export class SqlDriver implements IDataDriver { get columnFieldByObject() { return driver.columnFieldByObject; }, get fieldColumnByObject() { return driver.fieldColumnByObject; }, introspectPrimaryKeys: (...a) => driver.introspectPrimaryKeys(...a), + get isOracle() { return driver.isOracle; }, + get knex() { return driver.knex; }, get logger() { return driver.logger; }, get managedObjectFields() { return driver.managedObjectFields; }, get mssqlPagingKeyByObject() { return driver.mssqlPagingKeyByObject; }, get nondeterministicPagingWarned() { return driver.nondeterministicPagingWarned; }, + get oracleRawUuidFieldsByObject() { return driver.oracleRawUuidFieldsByObject; }, paginationTieBreaker: (...a) => driver.paginationTieBreaker(...a), get physicalSchemaByObject() { return driver.physicalSchemaByObject; }, get physicalTableByObject() { return driver.physicalTableByObject; }, + readOracleRawUuidColumns: (...a) => driver.readOracleRawUuidColumns(...a), })); filterHelpersHost.install((driver) => ({ applyContainsLike: (...a) => driver.applyContainsLike(...a), @@ -9402,6 +9372,7 @@ export class SqlDriver implements IDataDriver { get isSqlite() { return driver.isSqlite; }, jsonColumnFieldClass: (...a) => driver.jsonColumnFieldClass(...a), get jsonFields() { return driver.jsonFields; }, + get knex() { return driver.knex; }, logWithheldFilterDiagnostic: (...a) => driver.logWithheldFilterDiagnostic(...a), get logger() { return driver.logger; }, get managedObjectFields() { return driver.managedObjectFields; }, @@ -9477,10 +9448,12 @@ export class SqlDriver implements IDataDriver { get config() { return driver.config; }, get getBuilder() { return driver.getBuilder.bind(driver); }, get isMysql() { return driver.isMysql; }, + get isOracle() { return driver.isOracle; }, get isPostgres() { return driver.isPostgres; }, get isSqlite() { return driver.isSqlite; }, get knex() { return driver.knex; }, mapSortField: (...a) => driver.mapSortField(...a), + primeOracleRawUuidColumns: (...a) => driver.primeOracleRawUuidColumns(...a), })); rotationHost.install((driver) => ({ assertSchemaMutable: (...a) => driver.assertSchemaMutable(...a), @@ -9588,6 +9561,7 @@ export class SqlDriver implements IDataDriver { oracleUuidBinding: (...a) => driver.oracleUuidBinding(...a), get organizationObjectRegistered() { return driver.organizationObjectRegistered; }, get physicalTableByObject() { return driver.physicalTableByObject; }, + primeOracleRawUuidColumns: (...a) => driver.primeOracleRawUuidColumns(...a), remoteColumn: (...a) => driver.remoteColumn(...a), resolveSequenceTenantId: (...a) => driver.resolveSequenceTenantId(...a), resolveTenantField: (...a) => driver.resolveTenantField(...a), @@ -9646,8 +9620,10 @@ export class SqlDriver implements IDataDriver { buildWindowFunction: (...a) => driver.buildWindowFunction(...a), formatOutput: (...a) => driver.formatOutput(...a), get getBuilder() { return driver.getBuilder.bind(driver); }, + get isOracle() { return driver.isOracle; }, get knex() { return driver.knex; }, mapSortField: (...a) => driver.mapSortField(...a), + primeOracleRawUuidColumns: (...a) => driver.primeOracleRawUuidColumns(...a), })); } } From a535d01808057b7c921d5b50a4b0567aa7ad391a Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 8 Nov 2026 18:00:36 +0000 Subject: [PATCH 6/6] test(driver-sql): type the query bags in the oracle uuid tests The find and count calls pass a plain where bag that the driver's query type already accepts, so the any-casts only grew the query-options erasure test surface. Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01ADHkmQ9H84XNocJ8waPS1P --- .../src/sql-driver-oracle-dialect.test.ts | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/packages/drivers/driver-sql/src/sql-driver-oracle-dialect.test.ts b/packages/drivers/driver-sql/src/sql-driver-oracle-dialect.test.ts index 6bd618634a3..af5346873f7 100644 --- a/packages/drivers/driver-sql/src/sql-driver-oracle-dialect.test.ts +++ b/packages/drivers/driver-sql/src/sql-driver-oracle-dialect.test.ts @@ -462,7 +462,7 @@ describe('#31390 a comparand that is not uuid text is INVALID_FILTER, never sent it('through the find door: refused, and no statement reaches the database', async () => { const p = await primed(); - await expect(p.find('ord', { where: { account: 'not-a-uuid' } } as any)).rejects.toMatchObject({ + await expect(p.find('ord', { where: { account: 'not-a-uuid' } })).rejects.toMatchObject({ code: 'INVALID_FILTER', status: 400, }); @@ -530,26 +530,26 @@ describe('#31390 a written RAW(16) uuid value binds as HEXTORAW(?)', () => { describe('#31390 which columns: read from the catalog, once per object', () => { it('the doors read the catalog once per object, not once per statement', async () => { const p = new OracleUuidProbe(CATALOG); - await p.find('ord', { where: { account: UUID } } as any); - await p.count('ord', { where: { account: UUID } } as any); - await p.find('acct', { where: { id: UUID } } as any); - await p.find('ord', { where: { account: UUID_2 } } as any); + await p.find('ord', { where: { account: UUID } }); + await p.count('ord', { where: { account: UUID } }); + await p.find('acct', { where: { id: UUID } }); + await p.find('ord', { where: { account: UUID_2 } }); expect(p.catalogReads).toEqual(['ORD', 'ACCT']); expect(p.sent.every((s) => s.sql.includes('HEXTORAW('))).toBe(true); }); it('a failed catalog read records nothing: the statement binds text as before, and the next door asks again', async () => { const p = new OracleUuidProbe({}); - await p.find('ord', { where: { account: UUID } } as any); + await p.find('ord', { where: { account: UUID } }); expect(p.sent[0]).toMatchObject({ sql: 'select * from "ORD" where "ACCT_REF" = :1', bindings: [UUID] }); - await p.find('ord', { where: { account: UUID } } as any); + await p.find('ord', { where: { account: UUID } }); expect(p.catalogReads).toEqual(['ORD', 'ORD']); }); it('an empty catalog answer (no RAW(16) column) binds text, and is not asked again', async () => { const p = new OracleUuidProbe({ ORD: [] }); - await p.find('ord', { where: { account: UUID } } as any); - await p.find('ord', { where: { account: 'not-a-uuid' } } as any); + await p.find('ord', { where: { account: UUID } }); + await p.find('ord', { where: { account: 'not-a-uuid' } }); expect(p.sent.map((s) => s.bindings)).toEqual([[UUID], ['not-a-uuid']]); expect(p.catalogReads).toEqual(['ORD']); });