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..c76ed7a147a --- /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 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/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..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 @@ -26,10 +26,17 @@ * 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, 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`. * - * 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 +53,8 @@ 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 { 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'; import type { DriverQuery } from '@objectstack/spec/contracts'; @@ -847,6 +855,303 @@ 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 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. + * + * 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' }; +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: ORA_RAW_PROJECTION_SQL, + }, + { + 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 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 [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 () => { + await knex(ORA_GRANTS) + .whereIn('recipient_id', [...REFUSED.map((_, i) => recipient('bad', i)), ...ADMITTED.map((_, i) => recipient('ok', i))]) + .del(); + }); + + 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); + }); + } + + 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 +1244,61 @@ 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: 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); + // 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. + 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..6d19d493cf4 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,17 @@ 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, 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. */ - 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 +231,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..b0439b33d13 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,69 @@ export function oracleUuidRawBinding( throw err; } +/** + * {@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(CASE WHEN REGEXP_LIKE("record_id", '', 'i') + * THEN REPLACE("record_id", '-', '') + * ELSE 'not-a-uuid' END) + * FROM "sys_record_share" WHERE …) + * ``` + * + * - **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. + * + * 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(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}. */ 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..c6d7ae3dc3f 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, Oracle + // (RAW(16), NUMBER) (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..d3643b9f6f2 --- /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, 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." +}