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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions .changeset/35960-oracle-raw-prime-composed-scope.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
---
'@objectstack/driver-sql': patch
---

fix(driver-sql): on Oracle, a read scoped by a parent with a RAW(16) uuid key answers its rows on a driver that has not read the parent yet

Clause-②: no
Metadata-protocol: none

A child read whose composed `ReadableIds` scope names a federated parent with a `RAW(16)` uuid key, such as the read plugin-security derives for a `controlled_by_parent` object, answered no row on Oracle, and its negation answered every row, with no error. It recovered only once something had read the parent on that driver. The driver reads a federated table's `RAW(16)` columns from the Oracle catalog before it binds a comparand, and it read them for the door's own object only, so the parent's ids bound as text and Oracle compared them with the column's upper-case hex.

Each door that compiles a filter (`find`, `findOne`, `count`, `distinct`, `aggregate`, its measure filters and its joined parents, `updateMany`, `deleteMany`, `findWithWindowFunctions` and `analyzeQuery`) now also reads the `RAW(16)` columns of every object a composed `ReadableIds` scope in that filter names, at any depth. The parent's ids bind through `HEXTORAW`, for a list of ids and for the share-grant subquery alike. Nothing changes for any other dialect.
20 changes: 6 additions & 14 deletions packages/drivers/driver-sql/src/sql-driver-aggregation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,31 +109,23 @@ export class AggregationFacet {
const measureFilters = (query.aggregations ?? [])
.map((agg) => agg.filter)
.filter((filter): filter is NonNullable<typeof filter> => !!filter && Object.keys(filter).length > 0);
// Every condition this statement compiles, folded into one `where` for the primes below.
const primedWhere = measureFilters.length > 0 ? { $and: [...(query.where ? [query.where] : []), ...measureFilters] } : query.where;
// [#31395] SQL Server: which columns are GUIDs, before a text operator compiles.
if (this.isMssql) {
await this.primeMssqlGuidColumns(
object,
measureFilters.length > 0 ? { $and: [...(query.where ? [query.where] : []), ...measureFilters] } : query.where,
);
}
if (this.isMssql) await this.primeMssqlGuidColumns(object, primedWhere);
// [#31390] On Oracle a federated object's RAW(16) uuid columns are read from
// the remote catalog before a comparand or a written value is bound.
if (this.isOracle) await this.primeOracleRawUuidColumns(object);
if (this.isOracle) await this.primeOracleRawUuidColumns(object, primedWhere);
// [ADR-0155 O2] PostgreSQL: the key type a fixed-read leaf's inner read is cast to.
// The measure filters compile with the same where compiler, so they are
// walked too, folded as the SQL Server prime folds them.
await primeFixedReadLeafKeyTypes(
this,
object,
measureFilters.length > 0 ? { $and: [...(query.where ? [query.where] : []), ...measureFilters] } : query.where,
options,
);
await primeFixedReadLeafKeyTypes(this, object, primedWhere, options);
// …and the same primes for each joined related object, whose scope
// compiles against its own table.
for (const join of relationJoins ?? []) {
if (join.parent === null) continue;
if (this.isMssql) await this.primeMssqlGuidColumns(join.parent.object, join.parent.scope);
if (this.isOracle) await this.primeOracleRawUuidColumns(join.parent.object);
if (this.isOracle) await this.primeOracleRawUuidColumns(join.parent.object, join.parent.scope);
await primeFixedReadLeafKeyTypes(this, join.parent.object, join.parent.scope, options);
}
const builder = this.getBuilder(object, options);
Expand Down
6 changes: 3 additions & 3 deletions packages/drivers/driver-sql/src/sql-driver-bulk-operations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -293,7 +293,7 @@ export class BulkOperationsFacet {
await primeFixedReadLeafKeyTypes(this, object, query.where, options);
// [#31390] On Oracle a federated object's RAW(16) uuid columns are read from
// the remote catalog before a comparand or a written value is bound.
if (this.isOracle) await this.primeOracleRawUuidColumns(object);
if (this.isOracle) await this.primeOracleRawUuidColumns(object, query.where);
this.auditMissingTenant(object, 'updateMany', options);

// `data ?? {}` keeps the nullish tolerance this door already had on the
Expand Down Expand Up @@ -342,7 +342,7 @@ export class BulkOperationsFacet {
await primeFixedReadLeafKeyTypes(this, object, query.where, options);
// [#31390] On Oracle a federated object's RAW(16) uuid columns are read from
// the remote catalog before a comparand or a written value is bound.
if (this.isOracle) await this.primeOracleRawUuidColumns(object);
if (this.isOracle) await this.primeOracleRawUuidColumns(object, query.where);
this.auditMissingTenant(object, 'deleteMany', options);
let total = 0;
for (const target of this.rotationShardsOf(object) ?? [object]) {
Expand Down Expand Up @@ -392,7 +392,7 @@ export class BulkOperationsFacet {
await primeFixedReadLeafKeyTypes(this, object, query?.where, options);
// [#31390] On Oracle a federated object's RAW(16) uuid columns are read from
// the remote catalog before a comparand or a written value is bound.
if (this.isOracle) await this.primeOracleRawUuidColumns(object);
if (this.isOracle) await this.primeOracleRawUuidColumns(object, query?.where);
const builder = this.getBuilder(object, options);
this.applyTenantScope(builder, object, options);

Expand Down
2 changes: 1 addition & 1 deletion packages/drivers/driver-sql/src/sql-driver-crud.ts
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ export class CrudFacet {
static async findRows(this: Pick<CrudHost, 'applyFilters' | 'applyTenantScope' | 'backendStatementFault' | 'formatOutput' | 'getBuilder' | 'isMssql' | 'isOracle' | 'knex' | 'mapSortField' | 'orderKeysFor' | 'primeMssqlGuidColumns' | 'primeMssqlPagingKey' | 'primeOracleRawUuidColumns' | 'remoteColumn' | 'unresolvableFilterColumnRefusal'>, object: string, query: DriverQuery, options?: DriverOptions, singleRowLookup = false): Promise<any[]> {
// [#31390] On Oracle a federated object's RAW(16) uuid columns are read from
// the remote catalog before a comparand or a written value is bound.
if (this.isOracle) await this.primeOracleRawUuidColumns(object);
if (this.isOracle) await this.primeOracleRawUuidColumns(object, query.where);
// [#31327] On SQL Server a federated object's paging key is read from the
// remote catalog before the ORDER BY is decided (`primeMssqlPagingKey`).
if (this.isMssql) await this.primeMssqlPagingKey(object);
Expand Down
2 changes: 1 addition & 1 deletion packages/drivers/driver-sql/src/sql-driver-distinct.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ export class DistinctFacet {
await primeFixedReadLeafKeyTypes(this, object, filters, options);
// [#31390] On Oracle a federated object's RAW(16) uuid columns are read from
// the remote catalog before a comparand or a written value is bound.
if (this.isOracle) await this.primeOracleRawUuidColumns(object);
if (this.isOracle) await this.primeOracleRawUuidColumns(object, filters);
const builder = this.getBuilder(object, options);
// The third read door that skipped the chokepoint, and the one #6792 does
// NOT name — the card asserts the opposite ("called at 13 sites — …,
Expand Down
42 changes: 26 additions & 16 deletions packages/drivers/driver-sql/src/sql-driver-field-mapping.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,22 +66,30 @@ export interface FieldMappingHost {
/** The bodies of the "Field mapping" section of `SqlDriver`: a stateless facet, called by the class's stubs. */
export class FieldMappingFacet {
/** The body of `SqlDriver#primeOracleRawUuidColumns`; the method's docblock there is its contract. */
static async primeOracleRawUuidColumns(this: Pick<FieldMappingHost, 'columnFieldByObject' | 'isOracle' | 'oracleRawUuidFieldsByObject' | 'physicalSchemaByObject' | 'physicalTableByObject' | 'readOracleRawUuidColumns'>, object: string): Promise<void> {
if (!this.isOracle || this.oracleRawUuidFieldsByObject.has(object)) return;
// Only a federated object names a remote table; a platform-created table
// never holds a RAW(16) uuid column, so there is nothing to read.
const remoteTable = this.physicalTableByObject[object];
if (remoteTable === undefined) return;
let columns: string[];
try {
columns = await this.readOracleRawUuidColumns(remoteTable, this.physicalSchemaByObject[object]);
} catch {
// A catalog that cannot be read leaves nothing recorded: every value
// keeps today's text bind, and the next door asks again.
return;
static async primeOracleRawUuidColumns(this: Pick<FieldMappingHost, 'columnFieldByObject' | 'isOracle' | 'oracleRawUuidFieldsByObject' | 'physicalSchemaByObject' | 'physicalTableByObject' | 'readOracleRawUuidColumns'>, object: string, where?: unknown): Promise<void> {
if (!this.isOracle) return;
// The door's own object, and the object of every composed `ReadableIds`
// leaf in its `where`: each leaf's scope compiles against that object's
// own table, so its comparands bind by that table's columns.
const objects = new Set<string>([object]);
collectTextMatchObjects(where, objects);
for (const target of objects) {
if (this.oracleRawUuidFieldsByObject.has(target)) continue;
// Only a federated object names a remote table; a platform-created table
// never holds a RAW(16) uuid column, so there is nothing to read.
const remoteTable = this.physicalTableByObject[target];
if (remoteTable === undefined) continue;
let columns: string[];
try {
columns = await this.readOracleRawUuidColumns(remoteTable, this.physicalSchemaByObject[target]);
} catch {
// A catalog that cannot be read leaves nothing recorded: every value
// keeps today's text bind, and the next door asks again.
continue;
}
const colToField = this.columnFieldByObject[target];
this.oracleRawUuidFieldsByObject.set(target, new Set(columns.map((column) => colToField?.[column] ?? column)));
}
const colToField = this.columnFieldByObject[object];
this.oracleRawUuidFieldsByObject.set(object, new Set(columns.map((column) => colToField?.[column] ?? column)));
}

/** The body of `SqlDriver#readOracleRawUuidColumns`; the method's docblock there is its contract. */
Expand Down Expand Up @@ -220,7 +228,9 @@ export class FieldMappingFacet {
* [#31395] Walk a `where` tree for what {@link FieldMappingFacet.primeMssqlGuidColumns}
* needs: whether any key in it is a text operator (`TEXT_OPERATORS`), and the
* object of every composed `ReadableIds` leaf in it, added to `objects` (each
* leaf's subquery compiles its scope against that object's own table). Reads
* leaf's subquery compiles its scope against that object's own table).
* {@link FieldMappingFacet.primeOracleRawUuidColumns} reads the same objects
* and ignores the answer: one walk names the tables a scope compiles against. Reads
* plain objects and arrays only; a `Date`, a binary comparand or any other
* value is a comparand, not a node. Answers whether a text operator was found.
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -944,6 +944,22 @@ async function oracleAnswer(p: Promise<unknown[]>): Promise<{ rows: string[] } |
}
}

/** Bind the key-type suite's remote tables on `d`: the RAW(16) and NUMBER parents, and the child whose `parent` is a RAW(16) lookup. */
function registerOracleKeyTypeObjects(d: SqlDriver): void {
for (const fx of [ORA_RAW, ORA_NUM]) {
(d as any).registerExternalObject({
name: fx.object,
external: { remoteName: fx.table, columnMap: { ID: 'id', LABEL: 'label' } },
fields: { label: { type: 'text' } },
});
}
(d 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' } },
});
}

function declareOracleKeyTypePins(cell: FederationDialectCell): void {
describe(`[ADR-0155 O2] driver-sql — SharedRecordIds on Oracle key types (${cell.label})`, () => {
let driver: SqlDriver;
Expand Down Expand Up @@ -975,18 +991,7 @@ function declareOracleKeyTypePins(cell: FederationDialectCell): void {
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' } },
});
registerOracleKeyTypeObjects(driver);
for (const c of ORACLE_KEY_CASES) await knex(ORA_GRANTS).insert(grantRows(c));
}, 120_000);

Expand Down Expand Up @@ -1044,9 +1049,8 @@ function declareOracleKeyTypePins(cell: FederationDialectCell): void {
}

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);
// The child's door primes the parent's RAW(16) columns, for the list and
// the leaf alike (a fresh driver per door: the describe below).
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));
Expand All @@ -1055,6 +1059,102 @@ function declareOracleKeyTypePins(cell: FederationDialectCell): void {
expect(await driver.count(ORA_CHILD.object, { where: scoped({ id: { $in: SharedRecordIds.read(ORA_RAW.object, 'u9') } }) }, ORA_BYPASS)).toBe(2);
});

/**
* A composed `ReadableIds` scope compiles against its parent's table, so
* the parent's RAW(16) columns must be known before it binds. The child's
* own door primes them, on a fresh driver whose first statement is the
* child read: nothing has read the parent on it. Before, the door primed
* the child alone, so the parent's comparands bound as text and Oracle
* compared the RAW column as its upper-case hex text: the read answered no
* row and its negation every row, with no error (measured on Oracle Free
* 23ai), until something had read the parent on that driver.
*/
describe('a composed scope\'s RAW(16) parent is primed by the child\'s own door: a fresh driver, the child read first', () => {
const FORMS: readonly { name: string; scope: () => unknown }[] = [
{ name: 'the list (U1 upper-case, U2)', scope: () => ({ id: { $in: [ORA_U1.toUpperCase(), ORA_U2] } }) },
{ name: 'the share-grant leaf', scope: () => ({ id: { $in: SharedRecordIds.read(ORA_RAW.object, 'u9') } }) },
];
/** `door` as the first statement of a fresh driver: nothing has read the parent on it. */
async function firstOnFresh<T>(door: (d: SqlDriver) => Promise<T>): Promise<T> {
const fresh = new SqlDriver(cell.config());
await fresh.connect();
registerOracleKeyTypeObjects(fresh);
try {
return await door(fresh);
} finally {
await fresh.disconnect?.();
}
}
const countOf = (out: unknown[]) => Number((out[0] as any).n ?? (out[0] as any).N);

for (const f of FORMS) {
describe(f.name, () => {
const scopedRaw = () => ({ parent: { $in: ReadableIds.compose(ReadableIds.of(ORA_RAW.object), f.scope() as FilterCondition) } });
const where = () => seamed(scopedRaw());
const negated = () => seamed({ $not: scopedRaw() });

it('find answers [c1, c2]', async () => {
expect(sortedIds(await firstOnFresh((d) => d.find(ORA_CHILD.object, { where: where() }, ORA_BYPASS)))).toEqual(['c1', 'c2']);
});

it('the negation answers [c4], never every row', async () => {
expect(sortedIds(await firstOnFresh((d) => d.find(ORA_CHILD.object, { where: negated() }, ORA_BYPASS)))).toEqual(['c4']);
});

it('count answers 2', async () => {
expect(await firstOnFresh((d) => d.count(ORA_CHILD.object, { where: where() }, ORA_BYPASS))).toBe(2);
});

it('count of the negation answers 1', async () => {
expect(await firstOnFresh((d) => d.count(ORA_CHILD.object, { where: negated() }, ORA_BYPASS))).toBe(1);
});

it('distinct answers [c1, c2]', async () => {
const out = await firstOnFresh((d) => d.distinct(ORA_CHILD.object, 'id', where(), ORA_BYPASS));
expect(out.map(String).sort()).toEqual(['c1', 'c2']);
});

it('aggregate answers 2, in its where and in a measure filter', async () => {
expect(countOf(await firstOnFresh((d) => d.aggregate(ORA_CHILD.object, { where: where(), aggregations: [{ function: 'count', alias: 'n' }] }, ORA_BYPASS)))).toBe(2);
expect(countOf(await firstOnFresh((d) => d.aggregate(ORA_CHILD.object, { aggregations: [{ function: 'count', alias: 'n', filter: where() }] }, ORA_BYPASS)))).toBe(2);
});

it('findWithWindowFunctions answers [c1, c2]', async () => {
// Oracle requires an ORDER BY in ROW_NUMBER's window, and a window
// spec names its column as stored (not through `columnMap`): `ID`.
const out = await firstOnFresh((d) => d.findWithWindowFunctions(ORA_CHILD.object, { where: where(), windowFunctions: [{ function: 'row_number', alias: 'rn', orderBy: [{ field: 'ID' }] }] }, ORA_BYPASS));
expect(sortedIds(out)).toEqual(['c1', 'c2']);
});

it('analyzeQuery plans the statement find runs: the parent\'s key is compared through HEXTORAW', async () => {
const out = await firstOnFresh((d) => d.analyzeQuery(ORA_CHILD.object, { where: where() }, ORA_BYPASS));
expect(String(out.sql)).toContain('HEXTORAW(');
});

it('updateMany touches [c1, c2]', async () => {
try {
expect(await firstOnFresh((d) => d.updateMany(ORA_CHILD.object, { where: where() }, { label: 'touched' }, ORA_BYPASS))).toBe(2);
expect(sortedIds(await knex(ORA_CHILD.table).where('LABEL', 'touched').select({ id: 'ID' }))).toEqual(['c1', 'c2']);
} finally {
await knex(ORA_CHILD.table).update({ LABEL: 'x' });
}
});

it('deleteMany removes [c1, c2] and leaves [c4]', async () => {
try {
expect(await firstOnFresh((d) => d.deleteMany(ORA_CHILD.object, { where: where() }, ORA_BYPASS))).toBe(2);
expect(sortedIds(await knex(ORA_CHILD.table).select({ id: 'ID' }))).toEqual(['c4']);
} finally {
await knex(ORA_CHILD.table).del();
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)]);
}
}
});
});
}
});

it('aggregate agrees with find on a RAW(16) key', async () => {
const raw = ORACLE_KEY_CASES[0];
const out = await driver.aggregate(
Expand Down
2 changes: 1 addition & 1 deletion packages/drivers/driver-sql/src/sql-driver-query-plan.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ export class QueryPlanFacet {
await primeFixedReadLeafKeyTypes(this, object, query.where, options);
// [#31390] On Oracle a federated object's RAW(16) uuid columns are read from
// the remote catalog before a comparand or a written value is bound.
if (this.isOracle) await this.primeOracleRawUuidColumns(object);
if (this.isOracle) await this.primeOracleRawUuidColumns(object, query.where);
const builder = this.getBuilder(object, options);
// A PLAN, not rows — so this is a smaller fix than the one above, and it is
// made on its own merits rather than riding in on that one (#6792). It is
Expand Down
Loading
Loading