From ca269e1fa4bdd987cebe514c92ea26862794f05b Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 23:13:07 +0000 Subject: [PATCH 1/2] feat(driver-sql): convert record_id as the list binds a RAW(16) uuid key in the share-grant subquery on Oracle (ADR-0155 O2) On Oracle, where the outer column is a RAW(16) uuid column by the catalog prime the id list's HEXTORAW(?) binding reads, the fixed-read leaf's inner read projects HEXTORAW(REPLACE(record_id, '-', '')), so each grant is the same 16 bytes the list binds and the leaf answers the list's rows. Before, Oracle compared the column as its upper-case hex text and the leaf matched no row (its negation every row), with no error. Any other Oracle key and every other dialect keep their statement. Live pins on the Oracle cell hold the leaf to the list for a RAW(16) and a NUMBER key, and state both envelopes for grants the list refuses before SQL. Claude-Session: https://claude.ai/code/session_01L9qibvMi1U7R2kBd3JbTPu Co-authored-by: Claude --- .../35952-oracle-raw-share-grant-key.md | 14 + .../src/fixed-read-leaf-key-type.ts | 5 +- .../src/sql-driver-filter-helpers.ts | 6 +- ...driver-fixed-read-leaf-conformance.test.ts | 299 +++++++++++++++++- .../src/sql-driver-internal-helpers.ts | 30 +- .../src/sql-driver-oracle-dialect.ts | 27 ++ packages/drivers/driver-sql/src/sql-driver.ts | 8 +- ...ql__src__sql-driver-oracle-dialect.ts.json | 7 + 8 files changed, 385 insertions(+), 11 deletions(-) create mode 100644 .changeset/35952-oracle-raw-share-grant-key.md create mode 100644 scripts/adr-anchors/packages__drivers__driver-sql__src__sql-driver-oracle-dialect.ts.json diff --git a/.changeset/35952-oracle-raw-share-grant-key.md b/.changeset/35952-oracle-raw-share-grant-key.md new file mode 100644 index 00000000000..be1be07feaf --- /dev/null +++ b/.changeset/35952-oracle-raw-share-grant-key.md @@ -0,0 +1,14 @@ +--- +'@objectstack/driver-sql': patch +--- + +feat(driver-sql): on Oracle the share-grant subquery converts `record_id` the way the id list binds a `RAW(16)` uuid key (ADR-0155 O2) + +Clause-②: yes +Metadata-protocol: none + +No visible change on its own: nothing writes a `SharedRecordIds` leaf yet. The sharing plugin starts writing it at ADR-0155's last step, and this makes that step answer the right rows on Oracle tables keyed by a `RAW(16)` uuid (`SYS_GUID()` keys). + +- **Oracle, a `RAW(16)` uuid key.** The compiled subquery `id IN (SELECT record_id FROM sys_record_share WHERE …)` now projects `HEXTORAW(REPLACE(record_id, '-', ''))` when the compared column is a `RAW(16)` uuid column, the same catalog reading that makes the id list bind its members as `HEXTORAW(?)`. A grant in upper or lower case, dashed or undashed, names the same row it names in the list. Before, Oracle compared the column as its upper-case hex text: the subquery matched no row and its negation every row, with no error. +- **A grant the id list refuses.** The list refuses a value that is not uuid text before any statement (`INVALID_FILTER` / 400). A stored grant that is not hex (`not-a-uuid`, a braced uuid) fails the subquery's statement with `DATABASE_ERROR` / 500 (ORA-01465); hex of another length names no row. +- **Unchanged.** Any other Oracle key compiles exactly as before; a `NUMBER` key converts each grant as it converts the list's text binds (measured: the same rows, and the same ORA-01722 for a grant that is not a number). Every other dialect compiles exactly as before. diff --git a/packages/drivers/driver-sql/src/fixed-read-leaf-key-type.ts b/packages/drivers/driver-sql/src/fixed-read-leaf-key-type.ts index 275148e8fbb..98376dfd6e6 100644 --- a/packages/drivers/driver-sql/src/fixed-read-leaf-key-type.ts +++ b/packages/drivers/driver-sql/src/fixed-read-leaf-key-type.ts @@ -72,8 +72,9 @@ * old type until restart. * * Every other dialect is untouched: SQLite compares by column affinity (the - * same rows, measured on step 3), and MySQL, SQL Server and Oracle are named - * as left in the O2 card's report. + * same rows, measured on step 3), MySQL and SQL Server are named as left in + * the O2 card's report, and Oracle converts a `RAW(16)` uuid key's grants + * itself (`oracleUuidRawProjection`, `sql-driver-oracle-dialect.ts`). */ import type { Knex } from 'knex'; 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 bbc4a3a3dd7..4f7a57e2865 100644 --- a/packages/drivers/driver-sql/src/sql-driver-filter-helpers.ts +++ b/packages/drivers/driver-sql/src/sql-driver-filter-helpers.ts @@ -860,10 +860,12 @@ export class FilterHelpersFacet { // `field IN (SELECT …)` (`SqlDriver#fixedReadLeafSubquery`), under the // outer statement's own wall and nothing else. `applyFilters` refused // it at every other position. The object and column it is compared - // with type the inner read on PostgreSQL (ADR-0155 O2). + // with type the inner read on PostgreSQL (ADR-0155 O2); on Oracle a + // RAW(16) uuid column, read as the list's `HEXTORAW` binding reads it. if (rawOp === '$in' && isFixedReadLeaf(opValue)) { const mIn = logicalOp === 'or' ? 'orWhereIn' : 'whereIn'; - (builder as any)[mIn](field, this.fixedReadLeafSubquery(opValue, { object: table, column: field, evaluator: this.readableIdsDriverName, transaction: options?.transaction })); + const oracleRawUuid = this.isOracle && this.oracleRawUuidFieldsByObject.get(table ?? '')?.has(localField) === true; + (builder as any)[mIn](field, this.fixedReadLeafSubquery(opValue, { object: table, column: field, evaluator: this.readableIdsDriverName, oracleRawUuid, transaction: options?.transaction })); continue; } // #5222 — a `{ $field }` that is the WHOLE comparand of a scalar diff --git a/packages/drivers/driver-sql/src/sql-driver-fixed-read-leaf-conformance.test.ts b/packages/drivers/driver-sql/src/sql-driver-fixed-read-leaf-conformance.test.ts index 0404cfb007d..4bb554965d6 100644 --- a/packages/drivers/driver-sql/src/sql-driver-fixed-read-leaf-conformance.test.ts +++ b/packages/drivers/driver-sql/src/sql-driver-fixed-read-leaf-conformance.test.ts @@ -26,10 +26,16 @@ * bigint, uuid, `character(n)` or a domain answers the list's rows, because * the inner read casts `record_id` to the key's base type * (`fixed-read-leaf-key-type.ts`); a text key keeps step 3's statement; + * - **O2 on Oracle (ruling A carried to Oracle)**: a federated table keyed by + * `RAW(16)` uuid answers the list's rows, because the inner read converts + * `record_id` as the list binds a member (`HEXTORAW` over the undashed hex, + * `oracleUuidRawProjection`); a `NUMBER` key keeps step 3's statement. Its + * own cell (`ORACLE_CELL`, federation-only: raw DDL, no `initObjects`); * - the declaration, the absence of a tenant scope in the statement, the * bindings, and the refusals with `code` and `status`. * - * MSSQL and Oracle are pinned by the compiled statement (no server here). + * MSSQL is pinned by the compiled statement (no server here); Oracle by the + * compiled statement and by its live cell. */ import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest'; @@ -46,7 +52,7 @@ import { type FixedReadLeafRow, } from '@objectstack/spec/data'; import { SqlDriver, type SqlDriverConfig } from './sql-driver.js'; -import { DIALECT_CELLS, PG_CELL, currentLiveSchema, declareDialectCell, type DialectCell } from './live-dialect-matrix.testkit.js'; +import { DIALECT_CELLS, ORACLE_CELL, PG_CELL, currentLiveSchema, declareDialectCell, type DialectCell, type FederationDialectCell } from './live-dialect-matrix.testkit.js'; import { RELATION_GROUP_JOINS, type RelationGroupJoin } from './sql-driver-aggregation.js'; import { primeFixedReadLeafKeyTypes } from './fixed-read-leaf-key-type.js'; import type { DriverQuery } from '@objectstack/spec/contracts'; @@ -847,6 +853,251 @@ function declarePgKeyTypePins(driverOf: () => SqlDriver, knexOf: () => Knex): vo for (const cell of DIALECT_CELLS) declareDialectCell(cell, 'SharedRecordIds conformance', declareFixedReadLeafSweep); +// ── O2 on Oracle: a RAW(16) uuid key, ruling A carried to Oracle ──────────── + +/** + * [ADR-0155 O2, ruling 7051669729 (A) carried to Oracle] Oracle is + * federation-only, so its cell builds the remote tables by raw DDL (the grant + * table included) and binds them with `registerExternalObject`, as + * `sql-driver-oracle-federation-conformance.test.ts` does. + * + * Where the outer key is a `RAW(16)` uuid column (the catalog prime the list's + * `HEXTORAW(?)` binding reads), the inner read projects + * `HEXTORAW(REPLACE(record_id, '-', ''))` (`oracleUuidRawProjection`). Before + * it, Oracle compared the column as its upper-case hex text: the leaf answered + * no row and its negation every row, with no error (measured on Oracle Free + * 23ai). Each pin holds the leaf to the rows TODAY'S LIST of the same grants + * answers (D-0); a `NUMBER` key keeps step 3's statement and converts the + * grants as it converts the list's text binds. + * + * The grants the list refuses before any statement (not uuid text) have no + * refusal in the leaf, which reads stored rows: those pins state both + * envelopes as measured, the difference reported for the maintainer's word. + */ +const ORA_GRANTS = 'sys_record_share'; +const ORA_RAW = { table: 'SRIDO_RAW', object: 'srido_raw' }; +const ORA_NUM = { table: 'SRIDO_NUM', object: 'srido_num' }; +const ORA_CHILD = { table: 'SRIDO_CHILD', object: 'srido_child' }; +const ORA_BYPASS = { bypassTenantAudit: true } as const; +const ORA_U1 = '8a1f0c3e-1b2c-4d5e-8f90-123456789abc'; +const ORA_U2 = '00000000-0000-0000-0000-000000000001'; +const ORA_U3 = '00000000-0000-0000-0000-000000000002'; +const ORA_U4 = '00000000-0000-0000-0000-000000000003'; + +interface OracleKeyCase { + readonly name: string; + readonly object: string; + /** Grant `record_id`s for u9, as today's list would bind them. */ + readonly grants: readonly string[]; + /** The ids both forms answer, as the driver reads them back (sorted text). */ + readonly expected: readonly string[]; + /** The rows the negation answers: the complement, never every row. */ + readonly complement: readonly string[]; + /** The projection the compiled inner read carries. */ + readonly projection: string; +} + +const ORACLE_KEY_CASES: readonly OracleKeyCase[] = [ + { + // Upper-case dashed, lower-case dashed and undashed: the uuid text the list accepts. + name: 'RAW(16) uuid', + object: ORA_RAW.object, + grants: [ORA_U1.toUpperCase(), ORA_U2, ORA_U3.replace(/-/g, '')], + expected: [ORA_U2, ORA_U3, ORA_U1].sort(), + complement: [ORA_U4], + projection: `HEXTORAW(REPLACE("record_id", '-', ''))`, + }, + { + name: 'NUMBER(10)', + object: ORA_NUM.object, + grants: ['42', '07', ' 7'], + expected: ['42', '7'], + complement: ['43'], + projection: '"record_id"', + }, +]; + +async function dropOracleTable(knex: Knex, table: string): Promise { + await knex.raw( + `BEGIN EXECUTE IMMEDIATE 'DROP TABLE "${table}" PURGE'; EXCEPTION WHEN OTHERS THEN IF SQLCODE != -942 THEN RAISE; END IF; END;`, + ); +} + +/** A refusal's envelope, or the rows: what each form answered. */ +async function oracleAnswer(p: Promise): Promise<{ rows: string[] } | { code: unknown; status: unknown; ora: string | null }> { + try { + return { rows: sortedIds(await p) }; + } catch (e) { + const err = e as { code?: unknown; status?: unknown; message?: unknown; cause?: { message?: unknown } }; + const ora = /ORA-\d{5}/.exec(`${String(err.message)} ${String(err.cause?.message ?? '')}`)?.[0] ?? null; + return { code: err.code, status: err.status, ora }; + } +} + +function declareOracleKeyTypePins(cell: FederationDialectCell): void { + describe(`[ADR-0155 O2] driver-sql — SharedRecordIds on Oracle key types (${cell.label})`, () => { + let driver: SqlDriver; + let knex: Knex; + const tables = [ORA_GRANTS, ORA_RAW.table, ORA_NUM.table, ORA_CHILD.table]; + const grantRows = (c: OracleKeyCase, recipient = 'u9', grants: readonly string[] = c.grants) => [ + ...grants.map((g, i) => ({ id: `${c.object}_${recipient}_g${i}`, object_name: c.object, recipient_type: 'user', recipient_id: recipient, record_id: g, access_level: 'lvl_edit', organization_id: 'org_a' })), + // N4's witness on a typed key: a blank grant (stored as NULL here) the projection never sees as a value. + { id: `${c.object}_${recipient}_blank`, object_name: c.object, recipient_type: 'user', recipient_id: recipient, record_id: '', access_level: 'lvl_edit', organization_id: 'org_a' }, + ]; + const hex = (u: string) => u.replace(/-/g, '').toUpperCase(); + + beforeAll(async () => { + driver = new SqlDriver(cell.config()); + await driver.connect(); + knex = driver.getKnex(); + for (const t of tables) await dropOracleTable(knex, t); + await knex.raw( + `CREATE TABLE "${ORA_GRANTS}" ("id" VARCHAR2(64) PRIMARY KEY, "object_name" VARCHAR2(200), "recipient_type" VARCHAR2(200), ` + + `"recipient_id" VARCHAR2(200), "record_id" VARCHAR2(200), "access_level" VARCHAR2(200), "organization_id" VARCHAR2(200))`, + ); + await knex.raw(`CREATE TABLE "${ORA_RAW.table}" ("ID" RAW(16) PRIMARY KEY, "LABEL" VARCHAR2(100))`); + await knex.raw(`CREATE TABLE "${ORA_NUM.table}" ("ID" NUMBER(10) PRIMARY KEY, "LABEL" VARCHAR2(100))`); + await knex.raw(`CREATE TABLE "${ORA_CHILD.table}" ("ID" VARCHAR2(10) PRIMARY KEY, "PARENT" RAW(16), "LABEL" VARCHAR2(100))`); + for (const u of [ORA_U1, ORA_U2, ORA_U3, ORA_U4]) { + await knex.raw(`INSERT INTO "${ORA_RAW.table}" ("ID", "LABEL") VALUES (HEXTORAW(?), 'x')`, [hex(u)]); + } + for (const n of [7, 42, 43]) await knex.raw(`INSERT INTO "${ORA_NUM.table}" ("ID", "LABEL") VALUES (?, 'x')`, [n]); + for (const [id, parent] of [['c1', ORA_U1], ['c2', ORA_U2], ['c4', ORA_U4]] as const) { + await knex.raw(`INSERT INTO "${ORA_CHILD.table}" ("ID", "PARENT", "LABEL") VALUES (?, HEXTORAW(?), 'x')`, [id, hex(parent)]); + } + for (const fx of [ORA_RAW, ORA_NUM]) { + (driver as any).registerExternalObject({ + name: fx.object, + external: { remoteName: fx.table, columnMap: { ID: 'id', LABEL: 'label' } }, + fields: { label: { type: 'text' } }, + }); + } + (driver as any).registerExternalObject({ + name: ORA_CHILD.object, + external: { remoteName: ORA_CHILD.table, columnMap: { ID: 'id', PARENT: 'parent', LABEL: 'label' } }, + fields: { parent: { type: 'lookup', reference: ORA_RAW.object }, label: { type: 'text' } }, + }); + for (const c of ORACLE_KEY_CASES) await knex(ORA_GRANTS).insert(grantRows(c)); + }, 120_000); + + afterAll(async () => { + for (const t of tables) await dropOracleTable(knex, t).catch(() => {}); + await driver?.disconnect?.(); + }); + + for (const c of ORACLE_KEY_CASES) { + describe(`${c.name} key`, () => { + const leaf = () => seamed({ id: { $in: SharedRecordIds.read(c.object, 'u9') } }); + const list = () => seamed({ id: { $in: [...c.grants] } }); + + it('find and count: the leaf answers the rows today\'s list answers', async () => { + const viaList = sortedIds(await driver.find(c.object, { where: list() }, ORA_BYPASS)); + expect(viaList).toEqual([...c.expected]); + expect(sortedIds(await driver.find(c.object, { where: leaf() }, ORA_BYPASS))).toEqual(viaList); + expect(await driver.count(c.object, { where: leaf() }, ORA_BYPASS)).toBe(viaList.length); + }); + + it('the negation and an $or position answer as the list does', async () => { + const notLeaf = sortedIds(await driver.find(c.object, { where: seamed({ $not: { id: { $in: SharedRecordIds.read(c.object, 'u9') } } }) }, ORA_BYPASS)); + const notList = sortedIds(await driver.find(c.object, { where: seamed({ $not: { id: { $in: [...c.grants] } } }) }, ORA_BYPASS)); + expect(notList).toEqual([...c.complement]); + // The complement, not every row: before the projection a RAW key's negation answered all of them. + expect(notLeaf).toEqual(notList); + const orLeaf = seamed({ $or: [{ id: { $in: SharedRecordIds.read(c.object, 'u9') } }, { label: 'none' }] }); + const orList = seamed({ $or: [{ id: { $in: [...c.grants] } }, { label: 'none' }] }); + expect(sortedIds(await driver.find(c.object, { where: orLeaf }, ORA_BYPASS))).toEqual(sortedIds(await driver.find(c.object, { where: orList }, ORA_BYPASS))); + }); + + it('the predicate update: the write form touches the list\'s rows', async () => { + const where = seamed({ id: { $in: SharedRecordIds.write(c.object, 'u9', ['lvl_edit', 'lvl_full']) } }); + try { + expect(await driver.updateMany(c.object, { where }, { label: 'touched' }, ORA_BYPASS)).toBe(c.expected.length); + expect(sortedIds(await driver.find(c.object, { where: { label: 'touched' } }, ORA_BYPASS))).toEqual([...c.expected]); + } finally { + await knex(c.object === ORA_RAW.object ? ORA_RAW.table : ORA_NUM.table).update({ LABEL: 'x' }); + } + }); + + it(`the statement projects ${c.projection}`, async () => { + const seen: string[] = []; + const onQuery = (q: { sql: string }) => { if (q.sql.includes(ORA_GRANTS)) seen.push(q.sql); }; + knex.on('query', onQuery); + try { + await driver.find(c.object, { where: leaf() }, ORA_BYPASS); + } finally { + knex.removeListener('query', onQuery); + } + expect(seen).toHaveLength(1); + expect(seen[0]).toContain(`"ID" in (select ${c.projection} from "${ORA_GRANTS}"`); + }); + }); + } + + it('nested under a composed ReadableIds scope: the RAW parent\'s grants are converted as its list is', async () => { + // The child's door primes the child alone; a read of the parent primes its + // RAW(16) columns, for the list and the leaf alike. + await driver.find(ORA_RAW.object, { where: { label: 'none' } as any }, ORA_BYPASS); + const raw = ORACLE_KEY_CASES[0]; + const scoped = (scope: unknown) => seamed({ parent: { $in: ReadableIds.compose(ReadableIds.of(ORA_RAW.object), scope as FilterCondition) } }); + const viaList = sortedIds(await driver.find(ORA_CHILD.object, { where: scoped({ id: { $in: [...raw.grants] } }) }, ORA_BYPASS)); + expect(viaList).toEqual(['c1', 'c2']); + expect(sortedIds(await driver.find(ORA_CHILD.object, { where: scoped({ id: { $in: SharedRecordIds.read(ORA_RAW.object, 'u9') } }) }, ORA_BYPASS))).toEqual(viaList); + expect(await driver.count(ORA_CHILD.object, { where: scoped({ id: { $in: SharedRecordIds.read(ORA_RAW.object, 'u9') } }) }, ORA_BYPASS)).toBe(2); + }); + + it('aggregate agrees with find on a RAW(16) key', async () => { + const raw = ORACLE_KEY_CASES[0]; + const out = await driver.aggregate( + raw.object, + { where: seamed({ id: { $in: SharedRecordIds.read(raw.object, 'u9') } }), aggregations: [{ function: 'count', alias: 'n' }] }, + ORA_BYPASS, + ); + expect(Number((out[0] as any).n ?? (out[0] as any).N)).toBe(raw.expected.length); + }); + + describe('a grant the list refuses: both envelopes, as measured (the D-0 difference reported, never a new refusal)', () => { + /** Each malformed grant sits beside a valid one, as one recipient's grants. */ + const MALFORMED: readonly { name: string; recipient: string; grant: string; leaf: { rows: string[] } | { code: string; status: number; ora: string } }[] = [ + { name: 'not hex (`not-a-uuid`)', recipient: 'u_bad', grant: 'not-a-uuid', leaf: { code: 'DATABASE_ERROR', status: 500, ora: 'ORA-01465' } }, + { name: 'braced uuid text', recipient: 'u_brace', grant: `{${ORA_U2}}`, leaf: { code: 'DATABASE_ERROR', status: 500, ora: 'ORA-01465' } }, + // Valid hex of another length converts to bytes no RAW(16) key holds: it names no row. + { name: 'hex of another length (`0123`)', recipient: 'u_short', grant: '0123', leaf: { rows: [ORA_U1] } }, + ]; + const raw = ORACLE_KEY_CASES[0]; + + beforeAll(async () => { + for (const m of MALFORMED) await knex(ORA_GRANTS).insert(grantRows(raw, m.recipient, [m.grant, ORA_U1])); + }); + afterAll(async () => { + for (const m of MALFORMED) await knex(ORA_GRANTS).where('recipient_id', m.recipient).del(); + }); + + for (const m of MALFORMED) { + it(`${m.name}: the list answers INVALID_FILTER / 400 before any statement; the leaf answers ${'rows' in m.leaf ? 'the other grant\'s rows' : `${m.leaf.code} / ${m.leaf.status} (${m.leaf.ora})`}`, async () => { + const viaList = await oracleAnswer(driver.find(raw.object, { where: seamed({ id: { $in: [m.grant, ORA_U1] } }) }, ORA_BYPASS)); + expect(viaList).toEqual({ code: 'INVALID_FILTER', status: 400, ora: null }); + const viaLeaf = await oracleAnswer(driver.find(raw.object, { where: seamed({ id: { $in: SharedRecordIds.read(raw.object, m.recipient) } }) }, ORA_BYPASS)); + expect(viaLeaf).toEqual(m.leaf); + }); + } + + it('a NUMBER key: a grant that is not a number fails both forms alike (DATABASE_ERROR / 500, ORA-01722)', async () => { + const num = ORACLE_KEY_CASES[1]; + await knex(ORA_GRANTS).insert(grantRows(num, 'u_nan', ['abc', '42'])); + try { + const viaList = await oracleAnswer(driver.find(num.object, { where: seamed({ id: { $in: ['abc', '42'] } }) }, ORA_BYPASS)); + expect(viaList).toEqual({ code: 'DATABASE_ERROR', status: 500, ora: 'ORA-01722' }); + expect(await oracleAnswer(driver.find(num.object, { where: seamed({ id: { $in: SharedRecordIds.read(num.object, 'u_nan') } }) }, ORA_BYPASS))).toEqual(viaList); + } finally { + await knex(ORA_GRANTS).where('recipient_id', 'u_nan').del(); + } + }); + }); + }); +} + +declareDialectCell(ORACLE_CELL, 'SharedRecordIds conformance on Oracle key types', declareOracleKeyTypePins); + // ── The compiled statement, on every dialect driver-sql ships ─────────────── class CompileProbe extends SqlDriver { @@ -939,4 +1190,48 @@ describe('[ADR-0155 step 3] the compiled fixed inner read, per dialect (no serve expect((caught as { code?: unknown }).code).toBe('INTERNAL_ERROR'); expect((caught as { status?: unknown }).status).toBe(500); }); + + // [ADR-0155 O2 on Oracle] The RAW(16) reading the list's `HEXTORAW(?)` binding + // reads (`oracleRawUuidFieldsByObject`, primed from the catalog at every door), + // set by hand: the compile never dials. + const withRawId = (config: SqlDriverConfig): CompileProbe => { + const probe = new CompileProbe(config); + (probe as any).oracleRawUuidFieldsByObject.set(DOC, new Set(['id'])); + return probe; + }; + + it('oracle, a RAW(16) uuid key: the inner read projects the list\'s conversion, HEXTORAW over the undashed text', () => { + const probe = withRawId(COMPILE_CONFIGS.oracle); + const projected = (sql: string) => sql.replace('select "record_id" from', `select HEXTORAW(REPLACE("record_id", '-', '')) from`); + const read = probe.compileWhere({ id: { $in: SharedRecordIds.read(DOC, 'u1') } } as unknown as FilterCondition); + expect(read.sql).toBe(projected(COMPILED.oracle.read)); + // The guard and the predicates still read the stored text; no binding is added. + expect(read.bindings).toEqual([DOC, 'user', 'u1']); + const write = probe.compileWhere({ id: { $in: SharedRecordIds.write(DOC, 'u1', ['lvl_edit', 'lvl_full']) } } as unknown as FilterCondition); + expect(write.sql).toBe(projected(COMPILED.oracle.write)); + }); + + it('oracle: a column the reading does not name keeps step 3\'s statement', () => { + const probe = withRawId(COMPILE_CONFIGS.oracle); + const read = probe.compileWhere({ owner: { $in: SharedRecordIds.read(DOC, 'u1') } } as unknown as FilterCondition); + expect(read.sql).toBe(COMPILED.oracle.read.replace('where "id" in', 'where "owner" in')); + }); + + it('oracle: a key with no RAW(16) reading at all (never primed) compiles step 3\'s statement; PostgreSQL\'s no-reading refusal is never Oracle\'s', () => { + // Oracle's list binds an unprimed key's members as text and answers; the + // leaf compiles as that list does, never INTERNAL_ERROR / 500. + const probe = new CompileProbe(COMPILE_CONFIGS.oracle); + expect((probe as any).oracleRawUuidFieldsByObject.has(DOC)).toBe(false); + const read = probe.compileWhere({ id: { $in: SharedRecordIds.read(DOC, 'u1') } } as unknown as FilterCondition); + expect(read.sql).toBe(COMPILED.oracle.read); + }); + + for (const dialect of ['sqlite', 'pg', 'mysql', 'mssql'] as const) { + it(`${dialect}: a RAW(16) reading, which only Oracle primes, changes nothing`, async () => { + const probe = withRawId(COMPILE_CONFIGS[dialect]); + await probe.prime({ id: { $in: SharedRecordIds.read(DOC, 'u1') } } as unknown as FilterCondition); + const read = probe.compileWhere({ id: { $in: SharedRecordIds.read(DOC, 'u1') } } as unknown as FilterCondition); + expect(read.sql).toBe(COMPILED[dialect].read); + }); + } }); diff --git a/packages/drivers/driver-sql/src/sql-driver-internal-helpers.ts b/packages/drivers/driver-sql/src/sql-driver-internal-helpers.ts index fb55cbba36f..5ac34e69fcf 100644 --- a/packages/drivers/driver-sql/src/sql-driver-internal-helpers.ts +++ b/packages/drivers/driver-sql/src/sql-driver-internal-helpers.ts @@ -40,6 +40,25 @@ import type { Knex } from 'knex'; import type { SqlDriver } from './sql-driver.js'; import { fixedInnerReadPredicates } from './fixed-read-leaf-compile.js'; import { castFixedReadLeafColumn, fixedReadLeafKeyReading, refuseFixedReadLeafKey } from './fixed-read-leaf-key-type.js'; +import { oracleUuidRawProjection } from './sql-driver-oracle-dialect.js'; + +/** What a fixed-read leaf's `$in` arm says of the outer column the subquery is compared with. */ +export interface FixedReadLeafOuter { + /** The outer object (the filter compiler's coercion key), `null` when unknown. */ + readonly object: string | null; + /** The outer column, as the statement spells it. */ + readonly column: string; + /** The driver named as the evaluator in a PostgreSQL no-reading refusal (`refuseFixedReadLeafKey`). */ + readonly evaluator?: string; + /** PostgreSQL: the caller's transaction, on whose connection the key type is read (`fixedReadLeafKeyReading`). */ + readonly transaction?: unknown; + /** + * Oracle: the outer column is a `RAW(16)` uuid column, the same reading + * (`oracleRawUuidFieldsByObject`, same object and field) that makes the + * list bind its members as `HEXTORAW(?)`. + */ + readonly oracleRawUuid?: boolean; +} /** * The `SqlDriver` members the bodies of {@link InternalHelpersFacet} read — every one of @@ -185,8 +204,15 @@ export class InternalHelpersFacet { * connection, `outer.transaction`) is refused, ADR-0139 D3's * envelope (`INTERNAL_ERROR` / 500, logged once), ⛔ never compiled * uncast: a `character(n)` key would miss a padded grant silently (D2). + * - **Oracle, a `RAW(16)` uuid key (O2, ruling A carried to Oracle).** Where + * `outer.oracleRawUuid` says the list binds its members as `HEXTORAW(?)`, + * the projection is the same conversion over the column, + * `HEXTORAW(REPLACE(record_id, '-', ''))` (`oracleUuidRawProjection`). + * Any other Oracle key projects `record_id` as before (a `NUMBER` key + * converts it the way it converts the list's text binds). Oracle has no + * no-reading refusal: an unprimed key compiles as the list's text binds do. */ - static fixedReadLeafSubquery(this: Pick, leaf: FixedReadLeaf, outer?: { readonly object: string | null; readonly column: string; readonly evaluator?: string; readonly transaction?: unknown }): Knex.QueryBuilder { + static fixedReadLeafSubquery(this: Pick, leaf: FixedReadLeaf, outer?: FixedReadLeafOuter): Knex.QueryBuilder { const read = fixedInnerReadPredicates(leaf, { emptyStringIsNull: this.isOracle }); let projection: string | Knex.Raw = read.column; // [ADR-0155 O2] PostgreSQL only: the physical table as `getBuilder` @@ -203,6 +229,8 @@ export class InternalHelpersFacet { } if (reading.kind === 'cast') projection = castFixedReadLeafColumn(this.knex, read.column, reading.cast); } + // [ADR-0155 O2, ruling A carried to Oracle] A RAW(16) uuid key: the list's `HEXTORAW` conversion over the column. + if (this.isOracle && outer?.oracleRawUuid === true) projection = oracleUuidRawProjection(this.knex, read.column); const inner = this.getBuilder(read.table).select(projection); for (const [column, value] of read.equals) inner.where(column, value); for (const [column, values] of read.memberOf) inner.whereIn(column, [...values]); 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 2040f511a7f..8f6449090d5 100644 --- a/packages/drivers/driver-sql/src/sql-driver-oracle-dialect.ts +++ b/packages/drivers/driver-sql/src/sql-driver-oracle-dialect.ts @@ -204,6 +204,33 @@ export function oracleUuidRawBinding( throw err; } +/** + * [ADR-0155 O2, ruling A on Oracle] {@link oracleUuidRawBinding}'s conversion + * written over a text COLUMN instead of a bound value: the projection of a + * fixed-read leaf's inner read (`record_id`, `VARCHAR2`) when the outer column + * it is compared with is a `RAW(16)` uuid column, as the catalog reports it + * (`SqlDriver#primeOracleRawUuidColumns`, the prime the list's binding reads). + * + * ```sql + * "ID" IN (SELECT HEXTORAW(REPLACE("record_id", '-', '')) FROM "sys_record_share" WHERE …) + * ``` + * + * Without it Oracle compares the two by converting the `RAW` column to its + * upper-case hex text, which no dashed (or lower-case) uuid grant equals: the + * leaf answers no row and its negation every row, with no error (measured on + * Oracle Free 23ai). With it each grant is the same 16 bytes the list binds + * for the same uuid text, dashed or not, either case. + * + * What the list refuses before any statement (`INVALID_FILTER` / 400, a + * grant that is not uuid text) has no refusal here: the grant is a stored + * row, not a comparand. A grant that is not hex fails the statement + * (ORA-01465, `DATABASE_ERROR` / 500); hex of another length is 16 bytes of + * nothing and matches no row. + */ +export function oracleUuidRawProjection(knexInstance: Knex, column: string): Knex.Raw { + return knexInstance.raw(`HEXTORAW(REPLACE(??, '-', ''))`, [column]); +} + /** 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); diff --git a/packages/drivers/driver-sql/src/sql-driver.ts b/packages/drivers/driver-sql/src/sql-driver.ts index add1378c84c..0269478ed84 100644 --- a/packages/drivers/driver-sql/src/sql-driver.ts +++ b/packages/drivers/driver-sql/src/sql-driver.ts @@ -280,7 +280,7 @@ import { ManagedDriftFacet } from './sql-driver-managed-drift.js'; // [#29520 codemod] Schema Introspection: the methods of the same names below hand the bodies what they read (`SchemaIntrospectionHost`). import { SchemaIntrospectionFacet } from './sql-driver-schema-introspection.js'; // [#29520 codemod] Internal helpers: the methods of the same names below hand the bodies what they read (`InternalHelpersHost`). -import { InternalHelpersFacet } from './sql-driver-internal-helpers.js'; +import { InternalHelpersFacet, type FixedReadLeafOuter } from './sql-driver-internal-helpers.js'; // [#29520 codemod] Filter helpers: the methods of the same names below hand the bodies what they read (`FilterHelpersHost`). import { FilterHelpersFacet } from './sql-driver-filter-helpers.js'; // [#29520 codemod] Field mapping: the methods of the same names below hand the bodies what they read (`FieldMappingHost`). @@ -414,8 +414,8 @@ export class SqlDriver implements IDataDriver { // (Turso's remote transport compiles the leaf with its own compiler). readableIdsLeaf: true, // [ADR-0155 D4] One subquery per `SharedRecordIds` leaf (`applyFilterCondition`) - // on every dialect; same rows as the id list measured on SQLite and PostgreSQL - // only (O2: `fixed-read-leaf-key-type.ts`). Turso's remote transport has its own. + // on every dialect; same rows as the id list measured on SQLite, PostgreSQL and + // Oracle (O2: `fixed-read-leaf-key-type.ts`, `oracleUuidRawProjection`). Turso: its own. fixedReadLeaves: ['SharedRecordIds' as const], }; } @@ -6525,7 +6525,7 @@ export class SqlDriver implements IDataDriver { return InternalHelpersFacet.readableIdsSubquery.call(internalHelpersHost.of(this), leaf, options); } - private fixedReadLeafSubquery(leaf: FixedReadLeaf, outer?: { readonly object: string | null; readonly column: string; readonly evaluator?: string; readonly transaction?: unknown }): Knex.QueryBuilder { + private fixedReadLeafSubquery(leaf: FixedReadLeaf, outer?: FixedReadLeafOuter): Knex.QueryBuilder { // [ADR-0155 D2, O2] The body lives in `sql-driver-internal-helpers.ts`, its docblock with it. return InternalHelpersFacet.fixedReadLeafSubquery.call(internalHelpersHost.of(this), leaf, outer); } diff --git a/scripts/adr-anchors/packages__drivers__driver-sql__src__sql-driver-oracle-dialect.ts.json b/scripts/adr-anchors/packages__drivers__driver-sql__src__sql-driver-oracle-dialect.ts.json new file mode 100644 index 00000000000..50fd54a470f --- /dev/null +++ b/scripts/adr-anchors/packages__drivers__driver-sql__src__sql-driver-oracle-dialect.ts.json @@ -0,0 +1,7 @@ +{ + "file": "packages/drivers/driver-sql/src/sql-driver-oracle-dialect.ts", + "adrs": [ + "ADR-0155" + ], + "invariant": "ADR-0155 D-0, O2 (ruling A carried to Oracle): where the outer column is a RAW(16) uuid column by the catalog prime the list's HEXTORAW(?) binding reads (`oracleRawUuidFieldsByObject`, same object and field), the fixed-read leaf's inner read projects `oracleUuidRawProjection`, HEXTORAW(REPLACE(record_id, '-', '')), so each grant is the same 16 bytes the list binds for the same uuid text and the leaf answers the list's rows. Without it Oracle compares the RAW column as its upper-case hex text and the leaf silently answers no row (its negation every row). Any other Oracle key keeps step 3's statement. A grant the list refuses before SQL has no refusal here (not hex: ORA-01465, DATABASE_ERROR / 500; hex of another length: names no row)." +} From 869573acbdc023bd64e70dbaa3db7a0761683711 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 05:50:48 +0000 Subject: [PATCH 2/2] fix(driver-sql): gate the Oracle RAW(16) share-grant projection on the list's own uuid-text check (ADR-0155 O2, D2) The projection HEXTORAW(REPLACE(record_id, '-', '')) was laxer than the list's UUID_TEXT gate. Measured on Oracle Free 23ai: 32 hex digits with misplaced dashes matched a row the list refuses, a 31-digit grant was left-padded to 16 bytes and matched another row, a dash-only grant projected NULL so the negation answered no row, and short hex answered the sibling grant's rows. The projection now converts only text the list's gate admits (REGEXP_LIKE over ORACLE_UUID_TEXT_PATTERN, derived from UUID_TEXT) and projects 'not-a-uuid' for anything else, so every grant the list refuses before SQL fails the statement with ORA-01465 on the read and its negation. Every admitted form answers the list's rows unchanged. Docblock, anchor and changeset now state that partition. Claude-Session: https://claude.ai/code/session_01L9qibvMi1U7R2kBd3JbTPu Co-authored-by: Claude --- .../35952-oracle-raw-share-grant-key.md | 4 +- ...driver-fixed-read-leaf-conformance.test.ts | 119 ++++++++++++++---- .../src/sql-driver-internal-helpers.ts | 6 +- .../src/sql-driver-oracle-dialect.ts | 70 ++++++++--- packages/drivers/driver-sql/src/sql-driver.ts | 4 +- ...ql__src__sql-driver-oracle-dialect.ts.json | 2 +- 6 files changed, 155 insertions(+), 50 deletions(-) diff --git a/.changeset/35952-oracle-raw-share-grant-key.md b/.changeset/35952-oracle-raw-share-grant-key.md index be1be07feaf..c76ed7a147a 100644 --- a/.changeset/35952-oracle-raw-share-grant-key.md +++ b/.changeset/35952-oracle-raw-share-grant-key.md @@ -9,6 +9,6 @@ Metadata-protocol: none No visible change on its own: nothing writes a `SharedRecordIds` leaf yet. The sharing plugin starts writing it at ADR-0155's last step, and this makes that step answer the right rows on Oracle tables keyed by a `RAW(16)` uuid (`SYS_GUID()` keys). -- **Oracle, a `RAW(16)` uuid key.** The compiled subquery `id IN (SELECT record_id FROM sys_record_share WHERE …)` now projects `HEXTORAW(REPLACE(record_id, '-', ''))` when the compared column is a `RAW(16)` uuid column, the same catalog reading that makes the id list bind its members as `HEXTORAW(?)`. A grant in upper or lower case, dashed or undashed, names the same row it names in the list. Before, Oracle compared the column as its upper-case hex text: the subquery matched no row and its negation every row, with no error. -- **A grant the id list refuses.** The list refuses a value that is not uuid text before any statement (`INVALID_FILTER` / 400). A stored grant that is not hex (`not-a-uuid`, a braced uuid) fails the subquery's statement with `DATABASE_ERROR` / 500 (ORA-01465); hex of another length names no row. +- **Oracle, a `RAW(16)` uuid key.** The compiled subquery `id IN (SELECT record_id FROM sys_record_share WHERE …)` now projects the id list's own conversion when the compared column is a `RAW(16)` uuid column, the same catalog reading that makes the list bind its members as `HEXTORAW(?)`: `HEXTORAW(CASE WHEN REGEXP_LIKE(record_id, UUID_PATTERN, 'i') THEN REPLACE(record_id, '-', '') ELSE 'not-a-uuid' END)`. A grant in upper, lower or mixed case, dashed (8-4-4-4-12) or as 32 undashed digits, names the same row it names in the list. `UUID_PATTERN` is the list's own uuid-text check, written for Oracle from the same constant. Before, Oracle compared the column as its upper-case hex text: the subquery matched no row and its negation every row, with no error. +- **A grant the id list refuses fails the statement.** The list refuses a value that is not uuid text before any statement (`INVALID_FILTER` / 400). Every such stored grant fails the subquery's statement instead, with `DATABASE_ERROR` / 500 (ORA-01465), on the read and on its negation: hex of another length (31 or 33 digits, `0123`), 32 digits with dashes out of place, a grant of dashes only, a blank or a padded uuid, a braced uuid, or text that is not hex. None of them answers a row, and none empties a negation. - **Unchanged.** Any other Oracle key compiles exactly as before; a `NUMBER` key converts each grant as it converts the list's text binds (measured: the same rows, and the same ORA-01722 for a grant that is not a number). Every other dialect compiles exactly as before. diff --git a/packages/drivers/driver-sql/src/sql-driver-fixed-read-leaf-conformance.test.ts b/packages/drivers/driver-sql/src/sql-driver-fixed-read-leaf-conformance.test.ts index 4bb554965d6..6299e8aabe6 100644 --- a/packages/drivers/driver-sql/src/sql-driver-fixed-read-leaf-conformance.test.ts +++ b/packages/drivers/driver-sql/src/sql-driver-fixed-read-leaf-conformance.test.ts @@ -28,8 +28,9 @@ * (`fixed-read-leaf-key-type.ts`); a text key keeps step 3's statement; * - **O2 on Oracle (ruling A carried to Oracle)**: a federated table keyed by * `RAW(16)` uuid answers the list's rows, because the inner read converts - * `record_id` as the list binds a member (`HEXTORAW` over the undashed hex, - * `oracleUuidRawProjection`); a `NUMBER` key keeps step 3's statement. Its + * `record_id` as the list binds a member, behind the list's own `UUID_TEXT` + * gate (`oracleUuidRawProjection`), and every grant the list refuses fails + * the statement; a `NUMBER` key keeps step 3's statement. Its * own cell (`ORACLE_CELL`, federation-only: raw DDL, no `initObjects`); * - the declaration, the absence of a tenant scope in the statement, the * bindings, and the refusals with `code` and `status`. @@ -52,6 +53,7 @@ import { type FixedReadLeafRow, } from '@objectstack/spec/data'; import { SqlDriver, type SqlDriverConfig } from './sql-driver.js'; +import { ORACLE_UUID_TEXT_MATCH, ORACLE_UUID_TEXT_PATTERN, isOracleUuidText } from './sql-driver-oracle-dialect.js'; import { DIALECT_CELLS, ORACLE_CELL, PG_CELL, currentLiveSchema, declareDialectCell, type DialectCell, type FederationDialectCell } from './live-dialect-matrix.testkit.js'; import { RELATION_GROUP_JOINS, type RelationGroupJoin } from './sql-driver-aggregation.js'; import { primeFixedReadLeafKeyTypes } from './fixed-read-leaf-key-type.js'; @@ -862,19 +864,27 @@ for (const cell of DIALECT_CELLS) declareDialectCell(cell, 'SharedRecordIds conf * `sql-driver-oracle-federation-conformance.test.ts` does. * * Where the outer key is a `RAW(16)` uuid column (the catalog prime the list's - * `HEXTORAW(?)` binding reads), the inner read projects - * `HEXTORAW(REPLACE(record_id, '-', ''))` (`oracleUuidRawProjection`). Before + * `HEXTORAW(?)` binding reads), the inner read projects the list's + * conversion behind the list's own gate (`oracleUuidRawProjection`): uuid text + * as `UUID_TEXT` admits it converts as `HEXTORAW` over the undashed hex, and + * any other grant projects `'not-a-uuid'`, which fails the statement. Before * it, Oracle compared the column as its upper-case hex text: the leaf answered * no row and its negation every row, with no error (measured on Oracle Free * 23ai). Each pin holds the leaf to the rows TODAY'S LIST of the same grants * answers (D-0); a `NUMBER` key keeps step 3's statement and converts the * grants as it converts the list's text binds. * - * The grants the list refuses before any statement (not uuid text) have no - * refusal in the leaf, which reads stored rows: those pins state both - * envelopes as measured, the difference reported for the maintainer's word. + * Every grant the list refuses before any statement (`INVALID_FILTER` / 400) + * fails the leaf's statement instead (`DATABASE_ERROR` / 500, ORA-01465): the + * same refusal, moved into the statement (ADR-0155 Consequences, ruling A's + * "a malformed grant id fails the statement"), on `find` and on the negation, + * never rows and never a silently empty negation. */ const ORA_GRANTS = 'sys_record_share'; +/** The RAW(16) projection as Oracle receives it: `UUID_TEXT` spelled for `REGEXP_LIKE`, written out so a drift in either is a red pin. */ +const ORA_RAW_PROJECTION_SQL = + `HEXTORAW(CASE WHEN REGEXP_LIKE("record_id", '^([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') ` + + `THEN REPLACE("record_id", '-', '') ELSE 'not-a-uuid' END)`; const ORA_RAW = { table: 'SRIDO_RAW', object: 'srido_raw' }; const ORA_NUM = { table: 'SRIDO_NUM', object: 'srido_num' }; const ORA_CHILD = { table: 'SRIDO_CHILD', object: 'srido_child' }; @@ -905,7 +915,7 @@ const ORACLE_KEY_CASES: readonly OracleKeyCase[] = [ grants: [ORA_U1.toUpperCase(), ORA_U2, ORA_U3.replace(/-/g, '')], expected: [ORA_U2, ORA_U3, ORA_U1].sort(), complement: [ORA_U4], - projection: `HEXTORAW(REPLACE("record_id", '-', ''))`, + projection: ORA_RAW_PROJECTION_SQL, }, { name: 'NUMBER(10)', @@ -1055,29 +1065,73 @@ function declareOracleKeyTypePins(cell: FederationDialectCell): void { expect(Number((out[0] as any).n ?? (out[0] as any).N)).toBe(raw.expected.length); }); - describe('a grant the list refuses: both envelopes, as measured (the D-0 difference reported, never a new refusal)', () => { - /** Each malformed grant sits beside a valid one, as one recipient's grants. */ - const MALFORMED: readonly { name: string; recipient: string; grant: string; leaf: { rows: string[] } | { code: string; status: number; ora: string } }[] = [ - { name: 'not hex (`not-a-uuid`)', recipient: 'u_bad', grant: 'not-a-uuid', leaf: { code: 'DATABASE_ERROR', status: 500, ora: 'ORA-01465' } }, - { name: 'braced uuid text', recipient: 'u_brace', grant: `{${ORA_U2}}`, leaf: { code: 'DATABASE_ERROR', status: 500, ora: 'ORA-01465' } }, - // Valid hex of another length converts to bytes no RAW(16) key holds: it names no row. - { name: 'hex of another length (`0123`)', recipient: 'u_short', grant: '0123', leaf: { rows: [ORA_U1] } }, - ]; + describe('a grant the list refuses fails the leaf\'s statement; every form the list admits answers its rows', () => { const raw = ORACLE_KEY_CASES[0]; + const hex1 = ORA_U1.replace(/-/g, ''); + /** + * Each grant sits beside a valid one (U2), as one recipient's grants, so + * a projection that answered rows for it would show them. Measured on + * Oracle Free 23ai before the gate: 31 digits left-padded to 16 bytes + * and matched U3, misplaced dashes matched U1, a dash-only grant + * projected NULL and the negation answered no row; the short hex forms + * answered the sibling's row. + */ + const REFUSED: readonly { name: string; grant: string }[] = [ + { name: '31 hex digits (left-padded by HEXTORAW to a key)', grant: '0000000000000000000000000000002' }, + { name: '31 hex digits', grant: hex1.slice(1) }, + { name: '33 hex digits', grant: `${hex1}0` }, + { name: '32 hex digits with misplaced dashes', grant: '8a1f0c3e1b2c-4d5e8f90123456789abc' }, + { name: 'a dash-only grant', grant: '-' }, + { name: 'a padded blank', grant: ' ' }, + { name: 'uuid text with a leading blank', grant: ` ${ORA_U1}` }, + { name: 'hex of another length (`0123`)', grant: '0123' }, + { name: 'an odd number of hex digits (`abc`)', grant: 'abc' }, + { name: 'not hex (`not-a-uuid`)', grant: 'not-a-uuid' }, + { name: 'braced uuid text', grant: `{${ORA_U1}}` }, + ]; + /** Every form `UUID_TEXT` admits: the leaf answers exactly the list's rows, on find and the negation. */ + const ADMITTED: readonly { name: string; grant: string }[] = [ + { name: 'lower-case dashed', grant: ORA_U1 }, + { name: 'upper-case dashed', grant: ORA_U1.toUpperCase() }, + { name: 'mixed-case dashed', grant: '8A1f0C3e-1B2c-4D5e-8F90-123456789AbC' }, + { name: 'lower-case undashed', grant: hex1 }, + { name: 'upper-case undashed', grant: hex1.toUpperCase() }, + ]; + const recipient = (kind: string, i: number) => `u_${kind}${i}`; + const LOUD = { code: 'DATABASE_ERROR', status: 500, ora: 'ORA-01465' }; + const REFUSED_BY_LIST = { code: 'INVALID_FILTER', status: 400, ora: null }; beforeAll(async () => { - for (const m of MALFORMED) await knex(ORA_GRANTS).insert(grantRows(raw, m.recipient, [m.grant, ORA_U1])); + for (const [i, m] of REFUSED.entries()) await knex(ORA_GRANTS).insert(grantRows(raw, recipient('bad', i), [m.grant, ORA_U2])); + for (const [i, m] of ADMITTED.entries()) await knex(ORA_GRANTS).insert(grantRows(raw, recipient('ok', i), [m.grant, ORA_U2])); }); afterAll(async () => { - for (const m of MALFORMED) await knex(ORA_GRANTS).where('recipient_id', m.recipient).del(); + await knex(ORA_GRANTS) + .whereIn('recipient_id', [...REFUSED.map((_, i) => recipient('bad', i)), ...ADMITTED.map((_, i) => recipient('ok', i))]) + .del(); }); - for (const m of MALFORMED) { - it(`${m.name}: the list answers INVALID_FILTER / 400 before any statement; the leaf answers ${'rows' in m.leaf ? 'the other grant\'s rows' : `${m.leaf.code} / ${m.leaf.status} (${m.leaf.ora})`}`, async () => { - const viaList = await oracleAnswer(driver.find(raw.object, { where: seamed({ id: { $in: [m.grant, ORA_U1] } }) }, ORA_BYPASS)); - expect(viaList).toEqual({ code: 'INVALID_FILTER', status: 400, ora: null }); - const viaLeaf = await oracleAnswer(driver.find(raw.object, { where: seamed({ id: { $in: SharedRecordIds.read(raw.object, m.recipient) } }) }, ORA_BYPASS)); - expect(viaLeaf).toEqual(m.leaf); + for (const [i, m] of REFUSED.entries()) { + it(`${m.name}: the list refuses it (INVALID_FILTER / 400); the leaf fails its statement (DATABASE_ERROR / 500, ORA-01465), on find and on the negation`, async () => { + const leaf = () => ({ id: { $in: SharedRecordIds.read(raw.object, recipient('bad', i)) } }); + const list = () => ({ id: { $in: [m.grant, ORA_U2] } }); + expect(await oracleAnswer(driver.find(raw.object, { where: seamed(list()) }, ORA_BYPASS))).toEqual(REFUSED_BY_LIST); + expect(await oracleAnswer(driver.find(raw.object, { where: seamed({ $not: list() }) }, ORA_BYPASS))).toEqual(REFUSED_BY_LIST); + expect(await oracleAnswer(driver.find(raw.object, { where: seamed(leaf()) }, ORA_BYPASS))).toEqual(LOUD); + expect(await oracleAnswer(driver.find(raw.object, { where: seamed({ $not: leaf() }) }, ORA_BYPASS))).toEqual(LOUD); + }); + } + + for (const [i, m] of ADMITTED.entries()) { + it(`${m.name}: the leaf answers the list's rows, on find and on the negation`, async () => { + const leaf = () => ({ id: { $in: SharedRecordIds.read(raw.object, recipient('ok', i)) } }); + const list = () => ({ id: { $in: [m.grant, ORA_U2] } }); + const viaList = await oracleAnswer(driver.find(raw.object, { where: seamed(list()) }, ORA_BYPASS)); + expect(viaList).toEqual({ rows: [ORA_U2, ORA_U1].sort() }); + expect(await oracleAnswer(driver.find(raw.object, { where: seamed(leaf()) }, ORA_BYPASS))).toEqual(viaList); + const notList = await oracleAnswer(driver.find(raw.object, { where: seamed({ $not: list() }) }, ORA_BYPASS)); + expect(notList).toEqual({ rows: [ORA_U3, ORA_U4].sort() }); + expect(await oracleAnswer(driver.find(raw.object, { where: seamed({ $not: leaf() }) }, ORA_BYPASS))).toEqual(notList); }); } @@ -1200,9 +1254,22 @@ describe('[ADR-0155 step 3] the compiled fixed inner read, per dialect (no serve return probe; }; - it('oracle, a RAW(16) uuid key: the inner read projects the list\'s conversion, HEXTORAW over the undashed text', () => { + it('oracle: the REGEXP_LIKE spelling of UUID_TEXT admits exactly the uuid text the list admits', () => { + const oracleGate = new RegExp(ORACLE_UUID_TEXT_PATTERN, ORACLE_UUID_TEXT_MATCH); + const corpus = [ + '8a1f0c3e-1b2c-4d5e-8f90-123456789abc', '8A1F0C3E-1B2C-4D5E-8F90-123456789ABC', '8a1f0c3e1b2c4d5e8f90123456789abc', + '8a1f0c3e1b2c4d5e8f90123456789ab', '8a1f0c3e1b2c4d5e8f90123456789abc0', '8a1f0c3e1b2c-4d5e8f90123456789abc', '-', ' ', '', + ' 8a1f0c3e-1b2c-4d5e-8f90-123456789abc', '{8a1f0c3e-1b2c-4d5e-8f90-123456789abc}', '0123', 'abc', 'not-a-uuid', + 'g a1f0c3e-1b2c-4d5e-8f90-123456789abc', '8a1f0c3e-1b2c-4d5e-8f90-123456789abc\n', + ]; + for (const text of corpus) expect(oracleGate.test(text), JSON.stringify(text)).toBe(isOracleUuidText(text)); + expect(corpus.filter((t) => isOracleUuidText(t))).toHaveLength(3); + }); + + it('oracle, a RAW(16) uuid key: the inner read projects the list\'s conversion behind the list\'s gate', () => { const probe = withRawId(COMPILE_CONFIGS.oracle); - const projected = (sql: string) => sql.replace('select "record_id" from', `select HEXTORAW(REPLACE("record_id", '-', '')) from`); + // A function replacer: the pattern's `$'` would read as a replacement token in a string. + const projected = (sql: string) => sql.replace('select "record_id" from', () => `select ${ORA_RAW_PROJECTION_SQL} from`); const read = probe.compileWhere({ id: { $in: SharedRecordIds.read(DOC, 'u1') } } as unknown as FilterCondition); expect(read.sql).toBe(projected(COMPILED.oracle.read)); // The guard and the predicates still read the stored text; no binding is added. diff --git a/packages/drivers/driver-sql/src/sql-driver-internal-helpers.ts b/packages/drivers/driver-sql/src/sql-driver-internal-helpers.ts index 5ac34e69fcf..6d19d493cf4 100644 --- a/packages/drivers/driver-sql/src/sql-driver-internal-helpers.ts +++ b/packages/drivers/driver-sql/src/sql-driver-internal-helpers.ts @@ -206,8 +206,10 @@ export class InternalHelpersFacet { * uncast: a `character(n)` key would miss a padded grant silently (D2). * - **Oracle, a `RAW(16)` uuid key (O2, ruling A carried to Oracle).** Where * `outer.oracleRawUuid` says the list binds its members as `HEXTORAW(?)`, - * the projection is the same conversion over the column, - * `HEXTORAW(REPLACE(record_id, '-', ''))` (`oracleUuidRawProjection`). + * the projection is the same conversion over the column, behind the + * list's own gate (`oracleUuidRawProjection`): a grant `UUID_TEXT` admits + * is the 16 bytes the list binds; any other grant fails the statement + * (ORA-01465), as the list refuses it before SQL. * Any other Oracle key projects `record_id` as before (a `NUMBER` key * converts it the way it converts the list's text binds). Oracle has no * no-reading refusal: an unprimed key compiles as the list's text binds do. 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 8f6449090d5..b0439b33d13 100644 --- a/packages/drivers/driver-sql/src/sql-driver-oracle-dialect.ts +++ b/packages/drivers/driver-sql/src/sql-driver-oracle-dialect.ts @@ -205,30 +205,66 @@ export function oracleUuidRawBinding( } /** - * [ADR-0155 O2, ruling A on Oracle] {@link oracleUuidRawBinding}'s conversion - * written over a text COLUMN instead of a bound value: the projection of a - * fixed-read leaf's inner read (`record_id`, `VARCHAR2`) when the outer column - * it is compared with is a `RAW(16)` uuid column, as the catalog reports it - * (`SqlDriver#primeOracleRawUuidColumns`, the prime the list's binding reads). + * {@link UUID_TEXT} as an Oracle regular expression, for `REGEXP_LIKE` with + * the match parameter {@link ORACLE_UUID_TEXT_MATCH}: derived from the one + * constant, never restated, so the subquery's gate and the list's gate cannot + * drift. Oracle's POSIX syntax has no `(?:…)`, so each non-capturing group is + * written as a plain one (the same language). A pattern this derivation cannot + * carry (a flag other than `i`, a `?` knex would read as a binding, a quote + * that would end the SQL literal, a construct still Perl-only) throws at load. + */ +export const ORACLE_UUID_TEXT_PATTERN = oracleRegexFrom(UUID_TEXT, 'i'); + +/** `REGEXP_LIKE`'s match parameter for {@link ORACLE_UUID_TEXT_PATTERN}: {@link UUID_TEXT}'s `i` flag. */ +export const ORACLE_UUID_TEXT_MATCH = 'i'; + +function oracleRegexFrom(re: RegExp, flags: string): string { + const pattern = re.source.replace(/\(\?:/g, '('); + if (re.flags !== flags || /[?'\\]/.test(pattern)) { + throw new Error(`[driver-sql] UUID_TEXT (/${re.source}/${re.flags}) has no Oracle REGEXP_LIKE spelling here: extend oracleRegexFrom.`); + } + return pattern; +} + +/** + * [ADR-0155 O2, ruling A carried to Oracle] {@link oracleUuidRawBinding}'s + * conversion written over a text COLUMN instead of a bound value: the + * projection of a fixed-read leaf's inner read (`record_id`, `VARCHAR2`) when + * the outer column it is compared with is a `RAW(16)` uuid column, as the + * catalog reports it (`SqlDriver#primeOracleRawUuidColumns`, the prime the + * list's binding reads). * * ```sql - * "ID" IN (SELECT HEXTORAW(REPLACE("record_id", '-', '')) FROM "sys_record_share" WHERE …) + * "ID" IN (SELECT HEXTORAW(CASE WHEN REGEXP_LIKE("record_id", '', 'i') + * THEN REPLACE("record_id", '-', '') + * ELSE 'not-a-uuid' END) + * FROM "sys_record_share" WHERE …) * ``` * - * Without it Oracle compares the two by converting the `RAW` column to its - * upper-case hex text, which no dashed (or lower-case) uuid grant equals: the - * leaf answers no row and its negation every row, with no error (measured on - * Oracle Free 23ai). With it each grant is the same 16 bytes the list binds - * for the same uuid text, dashed or not, either case. + * - **Uuid text converts as the list binds it.** A grant {@link UUID_TEXT} + * admits (8-4-4-4-12 or 32 undashed hex digits, either case) is the same 16 + * bytes `HEXTORAW(?)` binds for it in the list, so the leaf answers the + * list's rows. + * - **Anything else fails the statement, loudly.** Every grant the list + * refuses before SQL (`INVALID_FILTER` / 400) projects `'not-a-uuid'`, which + * `HEXTORAW` refuses: ORA-01465, `DATABASE_ERROR` / 500, the statement's + * failure in place of the list's (ADR-0155 Consequences; option A: "a + * malformed grant id fails the statement"). ⛔ Never a bare + * `HEXTORAW(REPLACE(…))`: measured on Oracle Free 23ai, it converts 32 + * digits with misplaced dashes to a full key (a row the list refuses), left + * pads 31 digits to 16 bytes (a row the list refuses), and turns a dash-only + * grant into NULL, under which the negation answers no row. * - * What the list refuses before any statement (`INVALID_FILTER` / 400, a - * grant that is not uuid text) has no refusal here: the grant is a stored - * row, not a comparand. A grant that is not hex fails the statement - * (ORA-01465, `DATABASE_ERROR` / 500); hex of another length is 16 bytes of - * nothing and matches no row. + * Without any projection Oracle compares the `RAW` column as its upper-case + * hex text, which no dashed or lower-case grant equals: the leaf answers no row + * and its negation every row, with no error. */ export function oracleUuidRawProjection(knexInstance: Knex, column: string): Knex.Raw { - return knexInstance.raw(`HEXTORAW(REPLACE(??, '-', ''))`, [column]); + return knexInstance.raw( + `HEXTORAW(CASE WHEN REGEXP_LIKE(??, '${ORACLE_UUID_TEXT_PATTERN}', '${ORACLE_UUID_TEXT_MATCH}') ` + + `THEN REPLACE(??, '-', '') ELSE 'not-a-uuid' END)`, + [column, column], + ); } /** Whether `value` is uuid text a `RAW(16)` column can be bound to — see {@link UUID_TEXT}. */ diff --git a/packages/drivers/driver-sql/src/sql-driver.ts b/packages/drivers/driver-sql/src/sql-driver.ts index 0269478ed84..c6d7ae3dc3f 100644 --- a/packages/drivers/driver-sql/src/sql-driver.ts +++ b/packages/drivers/driver-sql/src/sql-driver.ts @@ -414,8 +414,8 @@ export class SqlDriver implements IDataDriver { // (Turso's remote transport compiles the leaf with its own compiler). readableIdsLeaf: true, // [ADR-0155 D4] One subquery per `SharedRecordIds` leaf (`applyFilterCondition`) - // on every dialect; same rows as the id list measured on SQLite, PostgreSQL and - // Oracle (O2: `fixed-read-leaf-key-type.ts`, `oracleUuidRawProjection`). Turso: its own. + // on every dialect; same rows as the id list measured on SQLite, PostgreSQL, Oracle + // (RAW(16), NUMBER) (O2: `fixed-read-leaf-key-type.ts`, `oracleUuidRawProjection`). Turso: its own. fixedReadLeaves: ['SharedRecordIds' as const], }; } diff --git a/scripts/adr-anchors/packages__drivers__driver-sql__src__sql-driver-oracle-dialect.ts.json b/scripts/adr-anchors/packages__drivers__driver-sql__src__sql-driver-oracle-dialect.ts.json index 50fd54a470f..d3643b9f6f2 100644 --- a/scripts/adr-anchors/packages__drivers__driver-sql__src__sql-driver-oracle-dialect.ts.json +++ b/scripts/adr-anchors/packages__drivers__driver-sql__src__sql-driver-oracle-dialect.ts.json @@ -3,5 +3,5 @@ "adrs": [ "ADR-0155" ], - "invariant": "ADR-0155 D-0, O2 (ruling A carried to Oracle): where the outer column is a RAW(16) uuid column by the catalog prime the list's HEXTORAW(?) binding reads (`oracleRawUuidFieldsByObject`, same object and field), the fixed-read leaf's inner read projects `oracleUuidRawProjection`, HEXTORAW(REPLACE(record_id, '-', '')), so each grant is the same 16 bytes the list binds for the same uuid text and the leaf answers the list's rows. Without it Oracle compares the RAW column as its upper-case hex text and the leaf silently answers no row (its negation every row). Any other Oracle key keeps step 3's statement. A grant the list refuses before SQL has no refusal here (not hex: ORA-01465, DATABASE_ERROR / 500; hex of another length: names no row)." + "invariant": "ADR-0155 D-0, D2, O2 (ruling A carried to Oracle): where the outer column is a RAW(16) uuid column by the catalog prime the list's HEXTORAW(?) binding reads (`oracleRawUuidFieldsByObject`, same object and field), the fixed-read leaf's inner read projects `oracleUuidRawProjection`: HEXTORAW(CASE WHEN REGEXP_LIKE(record_id, ORACLE_UUID_TEXT_PATTERN, 'i') THEN REPLACE(record_id, '-', '') ELSE 'not-a-uuid' END), the pattern derived from the list's own UUID_TEXT gate. A grant UUID_TEXT admits is the same 16 bytes the list binds, so the leaf answers the list's rows; every grant the list refuses before SQL (INVALID_FILTER / 400) fails the statement (ORA-01465, DATABASE_ERROR / 500) on the read and its negation. A bare HEXTORAW(REPLACE(...)) is not the gate: it matches misplaced-dash and left-padded 31-digit grants and turns a dash-only grant into NULL, emptying the negation. Without any projection Oracle compares the RAW column as its upper-case hex text and the leaf silently answers no row (its negation every row). Any other Oracle key keeps step 3's statement." }