From f00b6312c789e2cd414b11e1b1fb56952c01ba07 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 22:19:48 +0000 Subject: [PATCH 1/7] feat(driver-sql): cast record_id to the outer key's base type in the share-grant subquery on PostgreSQL (ADR-0155 O2) On PostgreSQL the fixed-read leaf's inner read now projects record_id cast to the outer key column's base type, read once per table from the catalog and cached per knex client, so an integer, bigint, uuid, character(n) or domain key answers the rows today's id list answers. Text and varchar keys keep step 3's statement. Every door that compiles a where primes the type beside its other catalog primes; other dialects read nothing. Claude-Session: https://claude.ai/code/session_01L9qibyXo4gSy8DJPNz4ANz Co-authored-by: Claude --- .../src/fixed-read-leaf-key-type.test.ts | 147 ++++++++++++ .../src/fixed-read-leaf-key-type.ts | 215 +++++++++++++++++ .../driver-sql/src/sql-driver-aggregation.ts | 6 +- .../src/sql-driver-bulk-operations.ts | 7 + .../drivers/driver-sql/src/sql-driver-crud.ts | 3 + .../driver-sql/src/sql-driver-distinct.ts | 3 + .../src/sql-driver-filter-helpers.ts | 5 +- ...driver-fixed-read-leaf-conformance.test.ts | 219 +++++++++++++++++- .../src/sql-driver-internal-helpers.ts | 15 +- .../driver-sql/src/sql-driver-query-plan.ts | 3 + .../src/sql-driver-window-functions.ts | 3 + packages/drivers/driver-sql/src/sql-driver.ts | 12 +- 12 files changed, 626 insertions(+), 12 deletions(-) create mode 100644 packages/drivers/driver-sql/src/fixed-read-leaf-key-type.test.ts create mode 100644 packages/drivers/driver-sql/src/fixed-read-leaf-key-type.ts diff --git a/packages/drivers/driver-sql/src/fixed-read-leaf-key-type.test.ts b/packages/drivers/driver-sql/src/fixed-read-leaf-key-type.test.ts new file mode 100644 index 00000000000..da979f248b3 --- /dev/null +++ b/packages/drivers/driver-sql/src/fixed-read-leaf-key-type.test.ts @@ -0,0 +1,147 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0155 O2, ruled A] `fixed-read-leaf-key-type.ts` without a server: what + * the catalog prime reads, what it records, and the statement the filter + * compiler then emits. Each driver here is configured and never dialled; the + * PostgreSQL catalog read is answered by a stub on the knex client. The live + * pins per key type are in `sql-driver-fixed-read-leaf-conformance.test.ts` + * (the PostgreSQL cell). + */ + +import { describe, it, expect, vi } from 'vitest'; +import type { Knex } from 'knex'; +import { ReadableIds, SharedRecordIds, type FilterCondition } from '@objectstack/spec/data'; +import { SqlDriver, type SqlDriverConfig } from './sql-driver.js'; +import { primeFixedReadLeafKeyTypes } from './fixed-read-leaf-key-type.js'; + +const EXT = 'srid_ext'; +const CHILD = 'srid_child'; + +class Probe extends SqlDriver { + /** The prime, through this driver's own `getBuilder`, as a door calls it. */ + prime(object: string, where: unknown): Promise { + return primeFixedReadLeafKeyTypes({ getBuilder: (o) => this.getBuilder(o) }, object, where); + } + compile(object: string, where: unknown): { sql: string; bindings: readonly unknown[] } { + const builder: Knex.QueryBuilder = this.getBuilder(object); + this.applyFilters(builder, where); + const native = builder.toSQL().toNative(); + return { sql: native.sql, bindings: native.bindings }; + } +} + +const PG: SqlDriverConfig = { client: 'pg', connection: {} } as unknown as SqlDriverConfig; + +/** A never-dialled PostgreSQL probe whose catalog read answers `answer` (rows, or a thrown error). */ +function pgProbe(answer: () => unknown): { probe: Probe; raw: ReturnType } { + const probe = new Probe(PG); + const client = (probe as any).knex.client as { raw: (...args: unknown[]) => unknown }; + const original = client.raw.bind(client); + // Only the catalog read is answered here; every other raw (the cast itself) is knex's own. + const raw = vi.fn(async (..._args: unknown[]) => answer()); + client.raw = (...args: unknown[]) => (String(args[0]).includes('pg_attribute') ? raw(...args) : original(...args)); + return { probe, raw }; +} + +const row = (column_name: string, type_schema: string, type_name: string) => ({ column_name, type_schema, type_name }); +const leafWhere = (object = EXT) => ({ id: { $in: SharedRecordIds.read(object, 'u9') } }); + +describe('[ADR-0155 O2] the catalog prime and the cast it puts on the inner read', () => { + it('an integer key: one catalog read, then the inner read casts record_id to int4', async () => { + const { probe, raw } = pgProbe(() => ({ rows: [row('id', 'pg_catalog', 'int4'), row('label', 'pg_catalog', 'text')] })); + await probe.prime(EXT, leafWhere()); + expect(raw).toHaveBeenCalledTimes(1); + expect(raw.mock.calls[0][1]).toEqual([EXT]); + const { sql, bindings } = probe.compile(EXT, leafWhere()); + expect(sql).toBe( + 'select * from "srid_ext" where "id" in (select CAST(NULLIF("record_id", \'\') AS "pg_catalog"."int4") from "sys_record_share" ' + + 'where "object_name" = $1 and "recipient_type" = $2 and "recipient_id" = $3 and "record_id" is not null and "record_id" <> $4)', + ); + // The cast adds no parameter: the inner read binds what step 3's does. + expect(bindings).toEqual([EXT, 'user', 'u9', '']); + // Recorded once per table: the next door reads nothing. + await probe.prime(EXT, leafWhere()); + expect(raw).toHaveBeenCalledTimes(1); + }); + + it('an external object with a remote schema and table is read and keyed by its physical name', async () => { + const { probe, raw } = pgProbe(() => ({ rows: [row('ext_id', 'pg_catalog', 'uuid')] })); + probe.registerExternalObject({ name: EXT, fields: {}, external: { remoteName: 'remote_t', remoteSchema: 'crm', columnMap: { ext_id: 'id' } } } as any); + await probe.prime(EXT, leafWhere()); + expect(raw.mock.calls[0][0]).toContain("format('%I.%I', ?::text, ?::text)"); + expect(raw.mock.calls[0][1]).toEqual(['crm', 'remote_t']); + expect(probe.compile(EXT, leafWhere()).sql).toContain( + '"ext_id" in (select CAST(NULLIF("record_id", \'\') AS "pg_catalog"."uuid") from "sys_record_share"', + ); + }); + + it('a text or varchar key takes no cast: step 3\'s statement, byte for byte', async () => { + for (const type of ['text', 'varchar']) { + const { probe } = pgProbe(() => ({ rows: [row('id', 'pg_catalog', type)] })); + await probe.prime(EXT, leafWhere()); + expect(probe.compile(EXT, leafWhere()).sql).toContain('"id" in (select "record_id" from "sys_record_share"'); + } + }); + + it('a type name knex cannot bind as one identifier is not cast (the statement compiles as before)', async () => { + const { probe } = pgProbe(() => ({ rows: [row('id', 'odd.schema', 'int4')] })); + await probe.prime(EXT, leafWhere()); + expect(probe.compile(EXT, leafWhere()).sql).toContain('"id" in (select "record_id" from'); + }); + + it('a failed or empty catalog read records nothing, and the next door asks again', async () => { + let answer: () => unknown = () => { throw new Error('catalog unavailable'); }; + const { probe, raw } = pgProbe(() => answer()); + await probe.prime(EXT, leafWhere()); + expect(probe.compile(EXT, leafWhere()).sql).not.toMatch(/CAST\(/); + answer = () => ({ rows: [] }); // the relation is not visible to this session yet + await probe.prime(EXT, leafWhere()); + expect(probe.compile(EXT, leafWhere()).sql).not.toMatch(/CAST\(/); + answer = () => ({ rows: [row('id', 'pg_catalog', 'int8')] }); + await probe.prime(EXT, leafWhere()); + expect(raw).toHaveBeenCalledTimes(3); + expect(probe.compile(EXT, leafWhere()).sql).toContain('AS "pg_catalog"."int8"'); + }); + + it('a where with no leaf reads nothing', async () => { + const { probe, raw } = pgProbe(() => ({ rows: [row('id', 'pg_catalog', 'int4')] })); + await probe.prime(EXT, { id: { $in: ['7', '42'] }, label: 'x' }); + await probe.prime(EXT, undefined); + expect(raw).not.toHaveBeenCalled(); + }); + + it('a leaf under a composed ReadableIds scope primes the parent object\'s table, and is cast there', async () => { + const { probe, raw } = pgProbe(() => ({ rows: [row('id', 'pg_catalog', 'int4')] })); + const where = { parent: { $in: ReadableIds.compose(ReadableIds.of(EXT), leafWhere() as unknown as FilterCondition) } }; + await probe.prime(CHILD, where); + expect(raw).toHaveBeenCalledTimes(1); + expect(raw.mock.calls[0][1]).toEqual([EXT]); + const { sql } = probe.compile(CHILD, where); + expect(sql).toContain('"parent" in (select "id" from "srid_ext" where "id" in (select CAST(NULLIF("record_id", \'\') AS "pg_catalog"."int4")'); + }); + + it('a leaf in an $or group is cast too (the group compiles on a builder with no table of its own)', async () => { + const { probe } = pgProbe(() => ({ rows: [row('id', 'pg_catalog', 'int4')] })); + const where = { $or: [leafWhere(), { label: 'x' }] }; + await probe.prime(EXT, where); + expect(probe.compile(EXT, where).sql).toContain('"id" in (select CAST(NULLIF("record_id", \'\') AS "pg_catalog"."int4")'); + }); + + it('every other dialect reads no catalog and compiles step 3\'s statement', async () => { + const configs: Record = { + sqlite: { client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true } as SqlDriverConfig, + mysql: { client: 'mysql2', connection: {} } as unknown as SqlDriverConfig, + mssql: { client: 'mssql', connection: {}, schemaMode: 'external' } as unknown as SqlDriverConfig, + }; + for (const [dialect, config] of Object.entries(configs)) { + const probe = new Probe(config); + const client = (probe as any).knex.client as { raw: (...args: unknown[]) => unknown }; + const raw = vi.spyOn(client, 'raw'); + await probe.prime(EXT, leafWhere()); + expect(raw, dialect).not.toHaveBeenCalled(); + expect(probe.compile(EXT, leafWhere()).sql, dialect).not.toMatch(/CAST\(/); + await probe.disconnect?.(); + } + }); +}); 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 new file mode 100644 index 00000000000..310686b47c7 --- /dev/null +++ b/packages/drivers/driver-sql/src/fixed-read-leaf-key-type.ts @@ -0,0 +1,215 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0155 D-0, D2, O2] The outer key's type, for a fixed-read leaf's inner + * read on PostgreSQL. + * + * A `SharedRecordIds` leaf compiles to `field IN (SELECT record_id FROM + * sys_record_share WHERE …)` (`fixed-read-leaf-compile.ts`). `record_id` is a + * text column. Today's id list binds each member as a string the server types + * by the column it meets, so `07` names the integer 7 and an upper-case uuid + * names its lower-case twin. A column compared with a column gets no such + * typing: PostgreSQL has no `integer = text` or `uuid = text` operator and + * refuses the statement (42883), and a `character(n)` key is compared as text, + * which drops the padding the list's comparison ignores (a silent miss). + * + * So, on PostgreSQL only, the inner read projects `record_id` cast to the + * outer key column's BASE type (a domain resolved to the type under it), read + * once per table from the catalog and cached (ruling 7051669729 on the O2 + * card, option A): + * + * ```sql + * id IN (SELECT CAST(NULLIF(record_id, '') AS "pg_catalog"."int4") FROM sys_record_share WHERE …) + * ``` + * + * - **The same conversion as the list.** A text-to-type cast runs the type's + * input function, the one a string bound against the column runs, without + * the column's typmod (a bound parameter has none either), so `character(4)` + * is cast to `bpchar` and a long value is compared, never truncated. A + * malformed grant id (`abc` against an integer key) fails the statement as + * a list member does today (22P02), ⛔ never a silent miss. + * - **`NULLIF(record_id, '')`.** The blank-id guard in the `WHERE` keeps an + * empty id out of the set; the `NULLIF` keeps the cast total on one even if + * a planner evaluates the projection first. NULL is in no `IN` set. + * - **Text keys keep step 3's statement.** A `text` or `varchar` key (every + * table the platform manages) is cast to nothing: `record_id` already + * compares as the list's members do. + * - **No cast without a reading.** A table the catalog has not answered for + * (no door primed it, the read failed, the relation is not visible yet) is + * compiled as before, and a non-text key then fails loudly (42883), never + * silently. A failed or empty read records nothing, so the next door asks + * again. + * + * ## When the catalog is read + * + * The filter compiler is synchronous, so the read happens before it: every + * door that compiles a `where` calls {@link primeFixedReadLeafKeyTypes} beside + * its other catalog primes (`primeMssqlGuidColumns`). It walks the `where` + * for a leaf in a field's `$in`; a statement with none costs a walk and no + * read. For each object a leaf compares against (the door's own, and the + * object of every composed `ReadableIds` leaf it sits under) it reads the + * column types of that object's table, once per table for the life of the + * driver's knex client. The key is the PHYSICAL table, as `getBuilder` + * addresses it, so a re-bound external object meets its new table's entry. + * Nothing invalidates an entry: the driver never changes a key column's type, + * and DDL made elsewhere is not observable here (as with the Oracle and SQL + * Server catalog primes). A key retyped elsewhere fails loudly 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. + */ + +import type { Knex } from 'knex'; +import { isComposedReadableIds, isFixedReadLeaf } from '@objectstack/spec/data'; + +/** The PostgreSQL type a leaf's inner read casts `record_id` to: the outer key's base type. */ +export interface FixedReadLeafKeyCast { + /** The type's schema (`pg_catalog` for a built-in type). */ + readonly schema: string; + /** The type's catalog name (`int4`, `uuid`, `bpchar`), without a typmod. */ + readonly type: string; +} + +/** What a door hands {@link primeFixedReadLeafKeyTypes}: its own `getBuilder`. */ +export interface FixedReadLeafKeySource { + getBuilder(object: string): Knex.QueryBuilder; +} + +/** Per knex client: the physical table's key → each column's cast, `null` for none. */ +const castsByClient = new WeakMap>>(); + +/** Base types `record_id` (text) already compares as today's list members do. */ +const UNCAST_BASE_TYPES = new Set(['pg_catalog.text', 'pg_catalog.varchar']); + +/** + * One catalog read per table: each live column's base type. A domain is + * walked down to the type under it. `to_regclass` answers NULL for a relation + * this session cannot see, so the read answers no row rather than an error. + */ +const COLUMN_BASE_TYPES_SQL = ` +WITH RECURSIVE col AS ( + SELECT a.attname::text AS column_name, a.atttypid AS type_oid + FROM pg_catalog.pg_attribute a + WHERE a.attrelid = to_regclass(%RELATION%) AND a.attnum > 0 AND NOT a.attisdropped + UNION ALL + SELECT col.column_name, t.typbasetype + FROM col JOIN pg_catalog.pg_type t ON t.oid = col.type_oid + WHERE t.typtype = 'd' +) +SELECT col.column_name, n.nspname::text AS type_schema, t.typname::text AS type_name + FROM col + JOIN pg_catalog.pg_type t ON t.oid = col.type_oid + JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace + WHERE t.typtype <> 'd'`; + +function tableKey(schema: string | undefined, table: string): string { + return JSON.stringify([schema ?? null, table]); +} + +function cacheOf(client: object): Map> { + let cache = castsByClient.get(client); + if (cache === undefined) { + cache = new Map(); + castsByClient.set(client, cache); + } + return cache; +} + +/** + * Whether a catalog name can be spelled as one `??` identifier binding: knex + * splits an identifier on `.` and on ` as `, so a name holding either is not + * cast (the statement then compiles as before and fails loudly). + */ +function bindableIdentifier(name: string): boolean { + return name.length > 0 && !name.includes('.') && !/\sas\s/i.test(name); +} + +/** + * Add to `out` every object whose key a fixed-read leaf in `node` is compared + * with: `object` for a leaf in a field's `$in` at this level, and a composed + * `ReadableIds` leaf's object for one inside its scope (the scope compiles + * against that object's table). Over-collecting is harmless; a misplaced leaf + * is refused by `applyFilters` before anything compiles. + */ +function collectLeafKeyObjects(node: unknown, object: string, out: Set, seen: Set): void { + if (node === null || typeof node !== 'object' || isFixedReadLeaf(node)) return; + if (seen.has(node)) return; + seen.add(node); + if (isComposedReadableIds(node)) { + if (node.scope !== undefined) collectLeafKeyObjects(node.scope, node.object, out, seen); + return; + } + if (Array.isArray(node)) { + for (const member of node) collectLeafKeyObjects(member, object, out, seen); + return; + } + const proto = Object.getPrototypeOf(node); + if (proto !== Object.prototype && proto !== null) return; + for (const [key, value] of Object.entries(node)) { + if (key === '$in' && isFixedReadLeaf(value)) out.add(object); + else collectLeafKeyObjects(value, object, out, seen); + } +} + +/** + * [ADR-0155 O2] Read, once per table, the column types of every table a + * fixed-read leaf in `where` is compared with, so the filter compiler can + * cast `record_id` to the key's base type (see the module docblock). A no-op + * on every dialect but PostgreSQL, and for a `where` holding no leaf. + */ +export async function primeFixedReadLeafKeyTypes(source: FixedReadLeafKeySource, object: string, where: unknown): Promise { + const objects = new Set(); + collectLeafKeyObjects(where, object, objects, new Set()); + for (const target of objects) { + const builder = source.getBuilder(target) as Knex.QueryBuilder & { _single?: { table?: unknown; schema?: unknown } }; + const client = builder.client; + if (client.dialect !== 'postgresql') return; + const table = builder._single?.table; + if (typeof table !== 'string') continue; + const schema = typeof builder._single?.schema === 'string' ? builder._single.schema : undefined; + const cache = cacheOf(client); + const key = tableKey(schema, table); + if (cache.has(key)) continue; + let rows: { column_name: string; type_schema: string; type_name: string }[]; + try { + const relation = schema === undefined ? `format('%I', ?::text)` : `format('%I.%I', ?::text, ?::text)`; + const bindings = schema === undefined ? [table] : [schema, table]; + const result = await client.raw(COLUMN_BASE_TYPES_SQL.replace('%RELATION%', relation), bindings); + rows = result.rows; + } catch { + // A catalog that cannot be read records nothing: the statement compiles + // as before, and the next door asks again. + continue; + } + // No row: the relation is not visible to this session (yet). Nothing is recorded. + if (!Array.isArray(rows) || rows.length === 0) continue; + const columns = new Map(); + for (const row of rows) { + const uncast = UNCAST_BASE_TYPES.has(`${row.type_schema}.${row.type_name}`) + || !bindableIdentifier(row.type_schema) + || !bindableIdentifier(row.type_name); + columns.set(row.column_name, uncast ? null : Object.freeze({ schema: row.type_schema, type: row.type_name })); + } + cache.set(key, columns); + } +} + +/** + * The cast {@link primeFixedReadLeafKeyTypes} recorded for `column` of the + * physical table `schema.table` on this knex client, or `null`: no reading, + * or a text key, which takes no cast. + */ +export function fixedReadLeafKeyCast( + client: object, + schema: string | undefined, + table: string, + column: string, +): FixedReadLeafKeyCast | null { + return castsByClient.get(client)?.get(tableKey(schema, table))?.get(column) ?? null; +} + +/** The inner read's projection under a cast: `CAST(NULLIF(record_id, '') AS "schema"."type")`. */ +export function castFixedReadLeafColumn(knexInstance: Knex, column: string, cast: FixedReadLeafKeyCast): Knex.Raw { + return knexInstance.raw(`CAST(NULLIF(??, '') AS ??.??)`, [column, cast.schema, cast.type]); +} diff --git a/packages/drivers/driver-sql/src/sql-driver-aggregation.ts b/packages/drivers/driver-sql/src/sql-driver-aggregation.ts index a75a6004df2..5ef96863d06 100644 --- a/packages/drivers/driver-sql/src/sql-driver-aggregation.ts +++ b/packages/drivers/driver-sql/src/sql-driver-aggregation.ts @@ -40,6 +40,7 @@ import { } from './sql-driver-top-level.js'; import type { ReadPresentationKind } from './sql-driver-top-level.js'; import type { SqlDriver } from './sql-driver.js'; +import { primeFixedReadLeafKeyTypes } from './fixed-read-leaf-key-type.js'; /** * The `SqlDriver` members the bodies of {@link AggregationFacet} read — every one of @@ -118,12 +119,15 @@ export class AggregationFacet { // [#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); - // …and the same two primes for each joined related object, whose scope + // [ADR-0155 O2] PostgreSQL: the key type a fixed-read leaf's inner read is cast to. + await primeFixedReadLeafKeyTypes(this, object, query.where); + // …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); + await primeFixedReadLeafKeyTypes(this, join.parent.object, join.parent.scope); } const builder = this.getBuilder(object, options); // The column a FIELD names in this statement: its `external.columnMap` diff --git a/packages/drivers/driver-sql/src/sql-driver-bulk-operations.ts b/packages/drivers/driver-sql/src/sql-driver-bulk-operations.ts index 9cf0f2b6b7a..ce87676970f 100644 --- a/packages/drivers/driver-sql/src/sql-driver-bulk-operations.ts +++ b/packages/drivers/driver-sql/src/sql-driver-bulk-operations.ts @@ -36,6 +36,7 @@ import { nanoid } from 'nanoid'; import { AUTONUMBER_COLLISION_RETRIES, DEFAULT_ID_LENGTH, isUnresolvableColumnError } from './sql-driver-top-level.js'; import type { AutoNumberReservation } from './sql-driver-top-level.js'; import type { SqlDriver } from './sql-driver.js'; +import { primeFixedReadLeafKeyTypes } from './fixed-read-leaf-key-type.js'; /** * The `SqlDriver` members the bodies of {@link BulkOperationsFacet} read — every one of @@ -288,6 +289,8 @@ export class BulkOperationsFacet { static async updateMany(this: Pick, object: string, query: DriverQuery, data: any, options?: DriverOptions): Promise { // [#31395] SQL Server: which columns are GUIDs, before a text operator compiles. if (this.isMssql) await this.primeMssqlGuidColumns(object, query.where); + // [ADR-0155 O2] PostgreSQL: the key type a fixed-read leaf's inner read is cast to. + await primeFixedReadLeafKeyTypes(this, object, query.where); // [#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); @@ -335,6 +338,8 @@ export class BulkOperationsFacet { static async deleteMany(this: Pick, object: string, query: DriverQuery, options?: DriverOptions): Promise { // [#31395] SQL Server: which columns are GUIDs, before a text operator compiles. if (this.isMssql) await this.primeMssqlGuidColumns(object, query.where); + // [ADR-0155 O2] PostgreSQL: the key type a fixed-read leaf's inner read is cast to. + await primeFixedReadLeafKeyTypes(this, object, query.where); // [#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); @@ -383,6 +388,8 @@ export class BulkOperationsFacet { static async count(this: Pick, object: string, query?: DriverQuery, options?: DriverOptions): Promise { // [#31395] SQL Server: which columns are GUIDs, before a text operator compiles. if (this.isMssql) await this.primeMssqlGuidColumns(object, query?.where); + // [ADR-0155 O2] PostgreSQL: the key type a fixed-read leaf's inner read is cast to. + await primeFixedReadLeafKeyTypes(this, object, query?.where); // [#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); diff --git a/packages/drivers/driver-sql/src/sql-driver-crud.ts b/packages/drivers/driver-sql/src/sql-driver-crud.ts index ddd18cc8471..20b5d538c0a 100644 --- a/packages/drivers/driver-sql/src/sql-driver-crud.ts +++ b/packages/drivers/driver-sql/src/sql-driver-crud.ts @@ -42,6 +42,7 @@ import type { SqlDriver } from './sql-driver.js'; import { oracleUuidReadForm } from './sql-driver-oracle-dialect.js'; import { StandardErrorCode } from '@objectstack/spec/api'; import { latestPerDirectiveOf, latestPerIdSubquery } from './sql-driver-latest-per.js'; +import { primeFixedReadLeafKeyTypes } from './fixed-read-leaf-key-type.js'; /** * [`DriverOptions.lockRows`] Lock the rows a `find()` returns until its @@ -164,6 +165,8 @@ export class CrudFacet { if (this.isMssql) await this.primeMssqlPagingKey(object); // [#31395] …and which of its columns are GUIDs, before a text operator compiles. if (this.isMssql) await this.primeMssqlGuidColumns(object, query.where); + // [ADR-0155 O2] PostgreSQL: the key type a fixed-read leaf's inner read is cast to. + await primeFixedReadLeafKeyTypes(this, object, query.where); // The whole ORDER BY, decided once: the caller's keys plus whatever this // driver has to add to make a paged read deterministic. Derived out here // rather than inside `buildBase` so the recovery ladder below can ask diff --git a/packages/drivers/driver-sql/src/sql-driver-distinct.ts b/packages/drivers/driver-sql/src/sql-driver-distinct.ts index 48795c04db0..975161cf223 100644 --- a/packages/drivers/driver-sql/src/sql-driver-distinct.ts +++ b/packages/drivers/driver-sql/src/sql-driver-distinct.ts @@ -30,6 +30,7 @@ import type { DriverOptions, FilterCondition } from '@objectstack/spec/data'; import type { SqlDriver } from './sql-driver.js'; +import { primeFixedReadLeafKeyTypes } from './fixed-read-leaf-key-type.js'; /** * The `SqlDriver` members the bodies of {@link DistinctFacet} read — every one of @@ -59,6 +60,8 @@ export class DistinctFacet { static async distinct(this: Pick, object: string, field: string, filters?: FilterCondition, options?: DriverOptions): Promise { // [#31395] SQL Server: which columns are GUIDs, before a text operator compiles. if (this.isMssql) await this.primeMssqlGuidColumns(object, filters); + // [ADR-0155 O2] PostgreSQL: the key type a fixed-read leaf's inner read is cast to. + await primeFixedReadLeafKeyTypes(this, object, filters); // [#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); 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 8dbf613e04b..3af261241eb 100644 --- a/packages/drivers/driver-sql/src/sql-driver-filter-helpers.ts +++ b/packages/drivers/driver-sql/src/sql-driver-filter-helpers.ts @@ -859,10 +859,11 @@ export class FilterHelpersFacet { // hold, compiles to its fixed inner read in the list's own position, // `field IN (SELECT …)` (`SqlDriver#fixedReadLeafSubquery`), under the // outer statement's own wall and nothing else. `applyFilters` refused - // it at every other position. + // it at every other position. The object and column it is compared + // with type the inner read on PostgreSQL (ADR-0155 O2). if (rawOp === '$in' && isFixedReadLeaf(opValue)) { const mIn = logicalOp === 'or' ? 'orWhereIn' : 'whereIn'; - (builder as any)[mIn](field, this.fixedReadLeafSubquery(opValue)); + (builder as any)[mIn](field, this.fixedReadLeafSubquery(opValue, { object: table, column: field })); 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 a30c8e511f5..3d0ac9a832f 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 @@ -22,6 +22,10 @@ * - **O2**: the comparison is the outer column's against `record_id` under the * dialect's own collation, exactly as today's list binds it, so the leaf and * the list answer the same rows for case and padding variants too; + * - **O2 on PostgreSQL (ruled A)**: a federated table keyed by integer, + * 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; * - the declaration, the absence of a tenant scope in the statement, the * bindings, and the refusals with `code` and `status`. * @@ -41,7 +45,7 @@ import { type FixedReadLeafRow, } from '@objectstack/spec/data'; import { SqlDriver, type SqlDriverConfig } from './sql-driver.js'; -import { DIALECT_CELLS, declareDialectCell, type DialectCell } from './live-dialect-matrix.testkit.js'; +import { DIALECT_CELLS, PG_CELL, currentLiveSchema, declareDialectCell, type DialectCell } from './live-dialect-matrix.testkit.js'; const set = SHARED_RECORD_IDS_CASE_SET; const seamed = (where: unknown): any => lowerFilterCondition(where, { isDatetimeColumn: () => false }); @@ -253,6 +257,8 @@ function declareFixedReadLeafSweep(cell: DialectCell): void { } }); } + + if (cell.id === 'pg') declarePgKeyTypePins(() => driver, () => knex); }); describe('the statement', () => { @@ -321,6 +327,217 @@ function declareFixedReadLeafSweep(cell: DialectCell): void { }); } +// ── O2 on PostgreSQL: the outer key's base type (ruled A) ─────────────────── + +/** + * [ADR-0155 O2, ruling 7051669729 (A)] On PostgreSQL the inner read projects + * `record_id` cast to the outer key column's base type, read once per table + * from the catalog (`fixed-read-leaf-key-type.ts`). Each key type here is a + * federated table made by raw DDL and bound with `registerExternalObject`, + * the way a sharing-scoped external object meets the leaf, and each pin holds + * the leaf to the rows TODAY'S LIST of the same grants answers (D-0), on + * `find`, `count` and the predicate update, plus the `$or` and nested + * `ReadableIds` positions. A malformed grant id fails the statement in the + * list's own envelope. + */ +interface PgKeyCase { + readonly name: string; + /** The `id` column's DDL type. */ + readonly ddl: string; + /** Row ids, as inserted. */ + readonly ids: readonly 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 cast the compiled inner read carries, `null` for none. */ + readonly cast: string | null; + /** Bind the table with `external.remoteSchema` (the schema-qualified catalog read). */ + readonly qualified?: boolean; +} + +const PG_KEY_CASES: readonly PgKeyCase[] = [ + { name: 'integer', ddl: 'integer', ids: ['7', '42', '43'], grants: ['42', '07', ' 7'], expected: ['42', '7'], cast: '"pg_catalog"."int4"' }, + { name: 'bigint', ddl: 'bigint', ids: ['7', '9007199254740993', '9007199254740994'], grants: ['07', '9007199254740993'], expected: ['7', '9007199254740993'], cast: '"pg_catalog"."int8"' }, + { + name: 'uuid', + ddl: 'uuid', + ids: ['8a1f0c3e-1b2c-4d5e-8f90-123456789abc', '00000000-0000-0000-0000-000000000001', '00000000-0000-0000-0000-000000000002'], + grants: ['8A1F0C3E-1B2C-4D5E-8F90-123456789ABC', '{00000000-0000-0000-0000-000000000001}'], + expected: ['00000000-0000-0000-0000-000000000001', '8a1f0c3e-1b2c-4d5e-8f90-123456789abc'], + cast: '"pg_catalog"."uuid"', + qualified: true, + }, + // A string key that is not text: the list compares as `bpchar` (padding + // ignored), so the inner read is cast to `bpchar` too, with no length. + { name: 'character(4)', ddl: 'character(4)', ids: ['k1', 'k2', 'k3'], grants: ['k1 ', 'k2'], expected: ['k1 ', 'k2 '], cast: '"pg_catalog"."bpchar"' }, + // A domain is cast to the type under it. + { name: 'a domain over integer', ddl: 'srid_pk_dom', ids: ['7', '42', '43'], grants: ['07', '42'], expected: ['42', '7'], cast: '"pg_catalog"."int4"' }, + // Every table the platform manages: no cast, step 3's statement. + { name: 'text', ddl: 'text', ids: ['k1', 'k2', 'k3'], grants: ['k1', 'k2 '], expected: ['k1'], cast: null }, +]; + +function declarePgKeyTypePins(driverOf: () => SqlDriver, knexOf: () => Knex): void { + describe('O2 on PostgreSQL: record_id is cast to the outer key\'s base type (ruled A)', () => { + const EXT = (c: PgKeyCase) => `srid_pk_${c.name.replace(/[^a-z0-9]+/g, '_')}`; + const CHILD = 'srid_pk_child'; + const grantRows = (c: PgKeyCase) => [ + ...c.grants.map((g, i) => ({ id: `${EXT(c)}_g${i}`, object_name: EXT(c), recipient_type: 'user', recipient_id: 'u9', record_id: g, access_level: 'lvl_edit', organization_id: 'org_a' })), + // N4's witness on a typed key: a blank grant the cast must never see as a value. + { id: `${EXT(c)}_blank`, object_name: EXT(c), recipient_type: 'user', recipient_id: 'u9', record_id: '', access_level: 'lvl_edit', organization_id: 'org_a' }, + ]; + + beforeAll(async () => { + const driver = driverOf(); + const knex = knexOf(); + await driver.execute('drop domain if exists srid_pk_dom cascade').catch(() => {}); + await driver.execute('create domain srid_pk_dom as integer check (value > 0)'); + const schema = currentLiveSchema(); + for (const c of PG_KEY_CASES) { + await driver.execute(`drop table if exists ${EXT(c)}`); + await driver.execute(`create table ${EXT(c)} (id ${c.ddl} primary key, label text)`); + await knex(EXT(c)).insert(c.ids.map((id) => ({ id, label: 'x' }))); + await knex(GRANTS).insert(grantRows(c)); + driver.registerExternalObject({ + name: EXT(c), + fields: { label: { type: 'text' } }, + ...(c.qualified ? { external: { remoteName: EXT(c), remoteSchema: schema } } : {}), + } as any); + } + await driver.execute(`drop table if exists ${CHILD}`); + await driver.execute(`create table ${CHILD} (id text primary key, parent integer, label text)`); + await knex(CHILD).insert([{ id: 'c7', parent: 7 }, { id: 'c42', parent: 42 }, { id: 'c43', parent: 43 }]); + driver.registerExternalObject({ name: CHILD, fields: { parent: { type: 'number' }, label: { type: 'text' } } } as any); + }, 60_000); + + afterAll(async () => { + const driver = driverOf(); + const knex = knexOf(); + for (const c of PG_KEY_CASES) { + await knex(GRANTS).where('object_name', EXT(c)).del().catch(() => {}); + await driver.execute(`drop table if exists ${EXT(c)}`).catch(() => {}); + } + await driver.execute(`drop table if exists ${CHILD}`).catch(() => {}); + await driver.execute('drop domain if exists srid_pk_dom cascade').catch(() => {}); + }); + + for (const c of PG_KEY_CASES) { + describe(`${c.name} key`, () => { + const leaf = () => seamed({ id: { $in: SharedRecordIds.read(EXT(c), 'u9') } }); + const list = () => seamed({ id: { $in: [...c.grants] } }); + + it('find and count: the leaf answers the rows today\'s list answers', async () => { + const driver = driverOf(); + const viaList = sortedIds(await driver.find(EXT(c), { where: list() })); + expect(viaList).toEqual([...c.expected]); + expect(sortedIds(await driver.find(EXT(c), { where: leaf() }))).toEqual(viaList); + expect(await driver.count(EXT(c), { where: leaf() })).toBe(viaList.length); + }); + + it('the negation and an $or position answer as the list does', async () => { + const driver = driverOf(); + const not = sortedIds(await driver.find(EXT(c), { where: seamed({ $not: { id: { $in: SharedRecordIds.read(EXT(c), 'u9') } } }) })); + expect(not).toEqual(sortedIds(await driver.find(EXT(c), { where: seamed({ $not: { id: { $in: [...c.grants] } } }) }))); + const orLeaf = seamed({ $or: [{ id: { $in: SharedRecordIds.read(EXT(c), 'u9') } }, { label: 'none' }] }); + const orList = seamed({ $or: [{ id: { $in: [...c.grants] } }, { label: 'none' }] }); + expect(sortedIds(await driver.find(EXT(c), { where: orLeaf }))).toEqual(sortedIds(await driver.find(EXT(c), { where: orList }))); + }); + + it('the predicate update: the write form touches the list\'s rows', async () => { + const driver = driverOf(); + const knex = knexOf(); + const where = seamed({ id: { $in: SharedRecordIds.write(EXT(c), 'u9', ['lvl_edit', 'lvl_full']) } }); + try { + expect(await driver.updateMany(EXT(c), { where }, { label: 'touched' })).toBe(c.expected.length); + expect(sortedIds(await knex(EXT(c)).where('label', 'touched').select('id'))).toEqual([...c.expected]); + } finally { + await knex(EXT(c)).update({ label: 'x' }); + } + }); + + it(c.cast === null ? 'the statement is step 3\'s: no cast' : `the statement casts record_id to ${c.cast}`, async () => { + const knex = knexOf(); + const seen: string[] = []; + const onQuery = (q: { sql: string }) => { if (q.sql.includes(GRANTS)) seen.push(q.sql); }; + knex.on('query', onQuery); + try { + await driverOf().find(EXT(c), { where: leaf() }); + } finally { + knex.removeListener('query', onQuery); + } + expect(seen).toHaveLength(1); + if (c.cast === null) { + expect(seen[0]).toContain('in (select "record_id" from "sys_record_share"'); + expect(seen[0]).not.toMatch(/CAST\(/i); + } else { + expect(seen[0]).toContain(`in (select CAST(NULLIF("record_id", '') AS ${c.cast}) from "sys_record_share"`); + } + }); + }); + } + + it('nested under a composed ReadableIds scope: the parent\'s key type is the one cast to', async () => { + const driver = driverOf(); + const intCase = PG_KEY_CASES[0]; + const scoped = (scope: unknown) => seamed({ parent: { $in: ReadableIds.compose(ReadableIds.of(EXT(intCase)), scope as FilterCondition) } }); + const viaList = sortedIds(await driver.find(CHILD, { where: scoped({ id: { $in: [...intCase.grants] } }) })); + expect(viaList).toEqual(['c42', 'c7']); + expect(sortedIds(await driver.find(CHILD, { where: scoped({ id: { $in: SharedRecordIds.read(EXT(intCase), 'u9') } }) }))).toEqual(viaList); + expect(await driver.count(CHILD, { where: scoped({ id: { $in: SharedRecordIds.read(EXT(intCase), 'u9') } }) })).toBe(2); + }); + + it('aggregate agrees with find on a typed key', async () => { + const intCase = PG_KEY_CASES[0]; + const out = await driverOf().aggregate( + EXT(intCase), + { where: seamed({ id: { $in: SharedRecordIds.read(EXT(intCase), 'u9') } }), aggregations: [{ function: 'count', alias: 'n' }] }, + ); + expect(Number((out[0] as any).n)).toBe(intCase.expected.length); + }); + + it('a malformed grant id fails the statement in the envelope today\'s list fails it in', async () => { + const driver = driverOf(); + const knex = knexOf(); + const intCase = PG_KEY_CASES[0]; + await knex(GRANTS).insert({ id: 'srid_pk_bad', object_name: EXT(intCase), recipient_type: 'user', recipient_id: 'u9', record_id: 'abc', access_level: 'lvl_edit', organization_id: 'org_a' }); + try { + const viaList = await driver.find(EXT(intCase), { where: seamed({ id: { $in: [...intCase.grants, 'abc'] } }) }).catch((e) => e); + const viaLeaf = await driver.find(EXT(intCase), { where: seamed({ id: { $in: SharedRecordIds.read(EXT(intCase), 'u9') } }) }).catch((e) => e); + expect(viaList).toMatchObject({ code: 'DATABASE_ERROR', status: 500 }); + expect(viaLeaf).toMatchObject({ code: viaList.code, status: viaList.status }); + // The same database refusal: invalid input for the key's type (22P02), not a missing operator (42883). + expect(String(viaLeaf.cause?.code ?? viaLeaf.message)).toMatch(/22P02|invalid input syntax for type integer/); + } finally { + await knex(GRANTS).where('id', 'srid_pk_bad').del(); + } + }); + + it('reads the catalog once per table: a second statement and another verb ask it nothing', async () => { + const fresh = new SqlDriver(PG_CELL.config()); + const knex: Knex = (fresh as any).knex; + const intCase = PG_KEY_CASES[0]; + fresh.registerExternalObject({ name: EXT(intCase), fields: { label: { type: 'text' } } } as any); + const catalogReads: string[] = []; + const onQuery = (q: { sql: string }) => { if (q.sql.includes('pg_attribute')) catalogReads.push(q.sql); }; + knex.on('query', onQuery); + try { + const where = seamed({ id: { $in: SharedRecordIds.read(EXT(intCase), 'u9') } }); + expect(sortedIds(await fresh.find(EXT(intCase), { where }))).toEqual([...intCase.expected]); + expect(catalogReads).toHaveLength(1); + await fresh.find(EXT(intCase), { where }); + await fresh.count(EXT(intCase), { where }); + expect(catalogReads).toHaveLength(1); + // A statement with no leaf reads nothing. + await fresh.find(EXT(intCase), { where: { label: 'x' } as any }); + expect(catalogReads).toHaveLength(1); + } finally { + knex.removeListener('query', onQuery); + await fresh.disconnect?.(); + } + }); + }); +} + for (const cell of DIALECT_CELLS) declareDialectCell(cell, 'SharedRecordIds conformance', declareFixedReadLeafSweep); // ── The compiled statement, on every dialect driver-sql ships ─────────────── 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 bd8d9c663c2..f584fa2998e 100644 --- a/packages/drivers/driver-sql/src/sql-driver-internal-helpers.ts +++ b/packages/drivers/driver-sql/src/sql-driver-internal-helpers.ts @@ -39,6 +39,7 @@ import { postureEnforcesWall } from '@objectstack/spec/security'; import type { Knex } from 'knex'; import type { SqlDriver } from './sql-driver.js'; import { fixedInnerReadPredicates } from './fixed-read-leaf-compile.js'; +import { castFixedReadLeafColumn, fixedReadLeafKeyCast } from './fixed-read-leaf-key-type.js'; /** * The `SqlDriver` members the bodies of {@link InternalHelpersFacet} read — every one of @@ -173,10 +174,20 @@ export class InternalHelpersFacet { * another datasource before any driver is called. * - **One statement.** No transaction of its own (it is part of the outer * statement), no cap, no ordering, ⛔ no `EXISTS`, no correlation, no join. + * - **The outer key's type (O2, ruled A).** `outer` names the object and the + * column the subquery is compared with. On PostgreSQL, where that column's + * base type is not text, the projection is `record_id` cast to it, as the + * catalog read primed it (`fixed-read-leaf-key-type.ts`), so an integer or + * uuid key answers the rows today's list answers. A text key, any other + * dialect, or a table no door primed projects `record_id` as before. */ - static fixedReadLeafSubquery(this: Pick, leaf: FixedReadLeaf): Knex.QueryBuilder { + static fixedReadLeafSubquery(this: Pick, leaf: FixedReadLeaf, outer?: { readonly object: string | null; readonly column: string }): Knex.QueryBuilder { const read = fixedInnerReadPredicates(leaf, { emptyStringIsNull: this.isOracle }); - const inner = this.getBuilder(read.table).select(read.column); + // The physical table as `getBuilder` addresses it: the key the prime recorded under. + const cast = outer?.object + ? fixedReadLeafKeyCast(this.knex.client, this.physicalSchemaByObject[outer.object], this.physicalTableByObject[outer.object] ?? outer.object, outer.column) + : null; + const inner = this.getBuilder(read.table).select(cast === null ? read.column : castFixedReadLeafColumn(this.knex, read.column, cast)); for (const [column, value] of read.equals) inner.where(column, value); for (const [column, values] of read.memberOf) inner.whereIn(column, [...values]); inner.whereNotNull(read.column); diff --git a/packages/drivers/driver-sql/src/sql-driver-query-plan.ts b/packages/drivers/driver-sql/src/sql-driver-query-plan.ts index 47b2f3f0405..3a5010f7234 100644 --- a/packages/drivers/driver-sql/src/sql-driver-query-plan.ts +++ b/packages/drivers/driver-sql/src/sql-driver-query-plan.ts @@ -31,6 +31,7 @@ import type { DriverOptions } from '@objectstack/spec/data'; import type { DriverQuery } from '@objectstack/spec/contracts'; import type { SqlDriver } from './sql-driver.js'; +import { primeFixedReadLeafKeyTypes } from './fixed-read-leaf-key-type.js'; /** * The `SqlDriver` members the bodies of {@link QueryPlanFacet} read — every one of @@ -67,6 +68,8 @@ export class QueryPlanFacet { static async analyzeQuery(this: Pick, object: string, query: DriverQuery, options?: DriverOptions): Promise { // [#31395] SQL Server: which columns are GUIDs, before a text operator compiles. if (this.isMssql) await this.primeMssqlGuidColumns(object, query.where); + // [ADR-0155 O2] PostgreSQL: the key type a fixed-read leaf's inner read is cast to. + await primeFixedReadLeafKeyTypes(this, object, query.where); // [#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); diff --git a/packages/drivers/driver-sql/src/sql-driver-window-functions.ts b/packages/drivers/driver-sql/src/sql-driver-window-functions.ts index b8811398e14..125b016c7ea 100644 --- a/packages/drivers/driver-sql/src/sql-driver-window-functions.ts +++ b/packages/drivers/driver-sql/src/sql-driver-window-functions.ts @@ -31,6 +31,7 @@ import type { DriverOptions } from '@objectstack/spec/data'; import type { SqlWindowFunctionQuery } from './sql-driver-top-level.js'; import type { SqlDriver } from './sql-driver.js'; +import { primeFixedReadLeafKeyTypes } from './fixed-read-leaf-key-type.js'; /** * The `SqlDriver` members the bodies of {@link WindowFunctionsFacet} read — every one of @@ -60,6 +61,8 @@ export class WindowFunctionsFacet { static async findWithWindowFunctions(this: Pick, object: string, query: SqlWindowFunctionQuery, options?: DriverOptions): Promise { // [#31395] SQL Server: which columns are GUIDs, before a text operator compiles. if (this.isMssql) await this.primeMssqlGuidColumns(object, query.where); + // [ADR-0155 O2] PostgreSQL: the key type a fixed-read leaf's inner read is cast to. + await primeFixedReadLeafKeyTypes(this, object, query.where); // [#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); diff --git a/packages/drivers/driver-sql/src/sql-driver.ts b/packages/drivers/driver-sql/src/sql-driver.ts index 0298fbdebb5..4fdc1f2d009 100644 --- a/packages/drivers/driver-sql/src/sql-driver.ts +++ b/packages/drivers/driver-sql/src/sql-driver.ts @@ -413,9 +413,9 @@ export class SqlDriver implements IDataDriver { // here. Every dialect; `SqliteWasmDriver` and `TursoDriver` inherit it // (Turso's remote transport compiles the leaf with its own compiler). readableIdsLeaf: true, - // [ADR-0155 D4] The filter compiler compiles a `SharedRecordIds` leaf to its - // fixed inner read as one subquery (`applyFilterCondition`), every dialect; - // TursoDriver's remote transport compiles it with its own compiler. + // [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. fixedReadLeaves: ['SharedRecordIds' as const], }; } @@ -6525,9 +6525,9 @@ export class SqlDriver implements IDataDriver { return InternalHelpersFacet.readableIdsSubquery.call(internalHelpersHost.of(this), leaf, options); } - private fixedReadLeafSubquery(leaf: FixedReadLeaf): Knex.QueryBuilder { - // [ADR-0155 D2] The body lives in `sql-driver-internal-helpers.ts`, its docblock with it. - return InternalHelpersFacet.fixedReadLeafSubquery.call(internalHelpersHost.of(this), leaf); + private fixedReadLeafSubquery(leaf: FixedReadLeaf, outer?: { readonly object: string | null; readonly column: string }): 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); } /** From 0f3e1d467ef0c2829523b188f48220bb141d1ec8 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 22:20:08 +0000 Subject: [PATCH 2/7] chore(driver-sql): changeset and ADR anchor for the PostgreSQL share-grant key cast (ADR-0155 O2) Claude-Session: https://claude.ai/code/session_01L9qibyXo4gSy8DJPNz4ANz Co-authored-by: Claude --- .changeset/35906-pg-share-grant-key-type.md | 15 +++++++++++++++ ...ver-sql__src__fixed-read-leaf-key-type.ts.json | 7 +++++++ 2 files changed, 22 insertions(+) create mode 100644 .changeset/35906-pg-share-grant-key-type.md create mode 100644 scripts/adr-anchors/packages__drivers__driver-sql__src__fixed-read-leaf-key-type.ts.json diff --git a/.changeset/35906-pg-share-grant-key-type.md b/.changeset/35906-pg-share-grant-key-type.md new file mode 100644 index 00000000000..eab0ed79af0 --- /dev/null +++ b/.changeset/35906-pg-share-grant-key-type.md @@ -0,0 +1,15 @@ +--- +'@objectstack/driver-sql': patch +--- + +feat(driver-sql): on PostgreSQL the share-grant subquery compares `record_id` as the outer key's own type (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 safe on PostgreSQL tables whose key is not text. + +- **PostgreSQL, a key that is not text.** The compiled subquery `id IN (SELECT record_id FROM sys_record_share WHERE …)` now projects `record_id` cast to the base type of the column it is compared with: `CAST(NULLIF(record_id, '') AS )`. A federated table keyed by `integer`, `bigint`, `smallint`, `numeric`, `uuid`, `character(n)` or a domain over one of them answers the same rows as the id list of the same grants: `07` names 7, an upper-case or braced uuid names its lower-case twin, and a padded grant names a `character(n)` key. Before, an integer or uuid key failed the statement with `DATABASE_ERROR` (42883), and a `character(n)` key silently missed a padded grant. +- **A malformed grant id** (`abc` against an integer key) fails the statement with `DATABASE_ERROR` / 500, the same answer the id list gives for it. +- **How the type is known.** The driver reads the column types of the compared table from `pg_catalog` once, the first time a statement holding the leaf reaches that table, and keeps the answer for the life of the driver. A statement with no leaf reads nothing. A failed catalog read records nothing and is asked again by the next statement. +- **Unchanged.** A `text` or `varchar` key, which is every table the platform creates, compiles exactly as before. SQLite, MySQL, SQL Server and Oracle compile exactly as before; SQLite answers the list's rows by column affinity. MySQL, SQL Server and Oracle `RAW(16)` keys are not measured against a live server yet. diff --git a/scripts/adr-anchors/packages__drivers__driver-sql__src__fixed-read-leaf-key-type.ts.json b/scripts/adr-anchors/packages__drivers__driver-sql__src__fixed-read-leaf-key-type.ts.json new file mode 100644 index 00000000000..2c51389c6b3 --- /dev/null +++ b/scripts/adr-anchors/packages__drivers__driver-sql__src__fixed-read-leaf-key-type.ts.json @@ -0,0 +1,7 @@ +{ + "file": "packages/drivers/driver-sql/src/fixed-read-leaf-key-type.ts", + "adrs": [ + "ADR-0155" + ], + "invariant": "ADR-0155 D-0, O2 (ruled A): on PostgreSQL the fixed-read leaf's inner read projects `record_id` cast to the BASE type of the outer key column (a domain resolved to the type under it, no typmod), read once per physical table from the catalog by `primeFixedReadLeafKeyTypes` before the synchronous compile, so an integer, uuid or character(n) key answers the rows today's id list answers and a malformed grant id fails the statement as a list member does. A text or varchar key takes no cast (step 3's statement); a table with no reading compiles as before and fails loudly, never silently. Every door that compiles a `where` calls the prime beside its other catalog primes: a door that skips it compiles an uncast subquery." +} From 707ffb5cc201c98dc8ee99b02d65a4f89811b838 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 01:31:00 +0000 Subject: [PATCH 3/7] test(driver-sql): pin every door's key-type prime as a fresh driver's first statement; smallint and numeric key pins (ADR-0155 O2) Each where-compiling door (count, updateMany, deleteMany, distinct, aggregate, the aggregate's joined parent, analyzeQuery, findWithWindowFunctions) now runs as the first statement of a fresh driver on a character(4) key, so a door that skips the prime answers wrong rows and loses the cast. Adds smallint and numeric(10,2) to the per-type pins. aggregate folds its measure filters into the prime as the SQL Server prime does. Docblock, anchor and changeset state that an unprimed or retyped character(n) key compares silently differently, and that an Oracle RAW(16) key is expected to fail. Claude-Session: https://claude.ai/code/session_01L9qibyXo4gSy8DJPNz4ANz Co-authored-by: Claude --- .changeset/35906-pg-share-grant-key-type.md | 2 +- .../src/fixed-read-leaf-key-type.ts | 14 +- .../driver-sql/src/sql-driver-aggregation.ts | 8 +- ...driver-fixed-read-leaf-conformance.test.ts | 129 ++++++++++++++++++ ...sql__src__fixed-read-leaf-key-type.ts.json | 2 +- 5 files changed, 146 insertions(+), 9 deletions(-) diff --git a/.changeset/35906-pg-share-grant-key-type.md b/.changeset/35906-pg-share-grant-key-type.md index eab0ed79af0..09c6b901efa 100644 --- a/.changeset/35906-pg-share-grant-key-type.md +++ b/.changeset/35906-pg-share-grant-key-type.md @@ -12,4 +12,4 @@ No visible change on its own: nothing writes a `SharedRecordIds` leaf yet. The s - **PostgreSQL, a key that is not text.** The compiled subquery `id IN (SELECT record_id FROM sys_record_share WHERE …)` now projects `record_id` cast to the base type of the column it is compared with: `CAST(NULLIF(record_id, '') AS )`. A federated table keyed by `integer`, `bigint`, `smallint`, `numeric`, `uuid`, `character(n)` or a domain over one of them answers the same rows as the id list of the same grants: `07` names 7, an upper-case or braced uuid names its lower-case twin, and a padded grant names a `character(n)` key. Before, an integer or uuid key failed the statement with `DATABASE_ERROR` (42883), and a `character(n)` key silently missed a padded grant. - **A malformed grant id** (`abc` against an integer key) fails the statement with `DATABASE_ERROR` / 500, the same answer the id list gives for it. - **How the type is known.** The driver reads the column types of the compared table from `pg_catalog` once, the first time a statement holding the leaf reaches that table, and keeps the answer for the life of the driver. A statement with no leaf reads nothing. A failed catalog read records nothing and is asked again by the next statement. -- **Unchanged.** A `text` or `varchar` key, which is every table the platform creates, compiles exactly as before. SQLite, MySQL, SQL Server and Oracle compile exactly as before; SQLite answers the list's rows by column affinity. MySQL, SQL Server and Oracle `RAW(16)` keys are not measured against a live server yet. +- **Unchanged.** A `text` or `varchar` key, which is every table the platform creates, compiles exactly as before. SQLite, MySQL, SQL Server and Oracle compile exactly as before; SQLite answers the list's rows by column affinity. MySQL and SQL Server keys are not measured against a live server yet. An Oracle `RAW(16)` uuid key is expected to fail the statement (ORA-01465, by reading: the subquery converts a dashed uuid grant to `RAW` implicitly, where the id list binds its undashed hex); it is not measured, and is tracked on #35952. 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 310686b47c7..131f78f7d07 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 @@ -36,24 +36,26 @@ * compares as the list's members do. * - **No cast without a reading.** A table the catalog has not answered for * (no door primed it, the read failed, the relation is not visible yet) is - * compiled as before, and a non-text key then fails loudly (42883), never - * silently. A failed or empty read records nothing, so the next door asks - * again. + * compiled as before: an integer or uuid key fails loudly (42883), but a + * `character(n)` key compares as text and misses a padded grant silently, + * which is why every door primes. A failed or empty read records nothing, + * so the next door asks again. * * ## When the catalog is read * * The filter compiler is synchronous, so the read happens before it: every * door that compiles a `where` calls {@link primeFixedReadLeafKeyTypes} beside * its other catalog primes (`primeMssqlGuidColumns`). It walks the `where` - * for a leaf in a field's `$in`; a statement with none costs a walk and no - * read. For each object a leaf compares against (the door's own, and the + * for a leaf in a field's `$in` (in `aggregate`, its measure filters too); a + * statement with none costs a walk and no read. For each object a leaf compares against (the door's own, and the * object of every composed `ReadableIds` leaf it sits under) it reads the * column types of that object's table, once per table for the life of the * driver's knex client. The key is the PHYSICAL table, as `getBuilder` * addresses it, so a re-bound external object meets its new table's entry. * Nothing invalidates an entry: the driver never changes a key column's type, * and DDL made elsewhere is not observable here (as with the Oracle and SQL - * Server catalog primes). A key retyped elsewhere fails loudly until restart. + * Server catalog primes). A key retyped elsewhere fails or compares as its + * 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 diff --git a/packages/drivers/driver-sql/src/sql-driver-aggregation.ts b/packages/drivers/driver-sql/src/sql-driver-aggregation.ts index 5ef96863d06..f60b9a26587 100644 --- a/packages/drivers/driver-sql/src/sql-driver-aggregation.ts +++ b/packages/drivers/driver-sql/src/sql-driver-aggregation.ts @@ -120,7 +120,13 @@ export class AggregationFacet { // the remote catalog before a comparand or a written value is bound. if (this.isOracle) await this.primeOracleRawUuidColumns(object); // [ADR-0155 O2] PostgreSQL: the key type a fixed-read leaf's inner read is cast to. - await primeFixedReadLeafKeyTypes(this, object, query.where); + // 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, + ); // …and the same primes for each joined related object, whose scope // compiles against its own table. for (const join of relationJoins ?? []) { 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 3d0ac9a832f..bf7b1fdc612 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 @@ -46,6 +46,8 @@ import { } 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 { RELATION_GROUP_JOINS, type RelationGroupJoin } from './sql-driver-aggregation.js'; +import type { DriverQuery } from '@objectstack/spec/contracts'; const set = SHARED_RECORD_IDS_CASE_SET; const seamed = (where: unknown): any => lowerFilterCondition(where, { isDatetimeColumn: () => false }); @@ -358,6 +360,9 @@ interface PgKeyCase { const PG_KEY_CASES: readonly PgKeyCase[] = [ { name: 'integer', ddl: 'integer', ids: ['7', '42', '43'], grants: ['42', '07', ' 7'], expected: ['42', '7'], cast: '"pg_catalog"."int4"' }, + { name: 'smallint', ddl: 'smallint', ids: ['7', '42', '43'], grants: ['07', '42'], expected: ['42', '7'], cast: '"pg_catalog"."int2"' }, + // Scale is the column's typmod, which the cast leaves off: `42.0` names 42.00, as a bound member does. + { name: 'numeric(10,2)', ddl: 'numeric(10,2)', ids: ['7', '42', '8.5'], grants: ['7', '07', '42.0'], expected: ['42.00', '7.00'], cast: '"pg_catalog"."numeric"' }, { name: 'bigint', ddl: 'bigint', ids: ['7', '9007199254740993', '9007199254740994'], grants: ['07', '9007199254740993'], expected: ['7', '9007199254740993'], cast: '"pg_catalog"."int8"' }, { name: 'uuid', @@ -381,6 +386,7 @@ function declarePgKeyTypePins(driverOf: () => SqlDriver, knexOf: () => Knex): vo describe('O2 on PostgreSQL: record_id is cast to the outer key\'s base type (ruled A)', () => { const EXT = (c: PgKeyCase) => `srid_pk_${c.name.replace(/[^a-z0-9]+/g, '_')}`; const CHILD = 'srid_pk_child'; + const CHAR_CHILD = 'srid_pk_char_child'; const grantRows = (c: PgKeyCase) => [ ...c.grants.map((g, i) => ({ id: `${EXT(c)}_g${i}`, object_name: EXT(c), recipient_type: 'user', recipient_id: 'u9', record_id: g, access_level: 'lvl_edit', organization_id: 'org_a' })), // N4's witness on a typed key: a blank grant the cast must never see as a value. @@ -404,6 +410,9 @@ function declarePgKeyTypePins(driverOf: () => SqlDriver, knexOf: () => Knex): vo ...(c.qualified ? { external: { remoteName: EXT(c), remoteSchema: schema } } : {}), } as any); } + await driver.execute(`drop table if exists ${CHAR_CHILD}`); + await driver.execute(`create table ${CHAR_CHILD} (id text primary key, parent character(4), label text)`); + await knex(CHAR_CHILD).insert([{ id: 'cc1', parent: 'k1' }, { id: 'cc2', parent: 'k2' }, { id: 'cc3', parent: 'k3' }]); await driver.execute(`drop table if exists ${CHILD}`); await driver.execute(`create table ${CHILD} (id text primary key, parent integer, label text)`); await knex(CHILD).insert([{ id: 'c7', parent: 7 }, { id: 'c42', parent: 42 }, { id: 'c43', parent: 43 }]); @@ -417,6 +426,7 @@ function declarePgKeyTypePins(driverOf: () => SqlDriver, knexOf: () => Knex): vo await knex(GRANTS).where('object_name', EXT(c)).del().catch(() => {}); await driver.execute(`drop table if exists ${EXT(c)}`).catch(() => {}); } + await driver.execute(`drop table if exists ${CHAR_CHILD}`).catch(() => {}); await driver.execute(`drop table if exists ${CHILD}`).catch(() => {}); await driver.execute('drop domain if exists srid_pk_dom cascade').catch(() => {}); }); @@ -512,6 +522,125 @@ function declarePgKeyTypePins(driverOf: () => SqlDriver, knexOf: () => Knex): vo } }); + /** + * Every door primes for itself. Each pin below makes its door the FIRST + * statement a fresh driver (a fresh knex client, so an empty cache) runs, + * on the `character(4)` key, where a missed prime is a silent miss rather + * than an error: the answer must be the list's and the statement must + * carry the cast. `find` opens every per-key describe above. + */ + describe('each door primes the key type itself: its first statement on a fresh driver', () => { + const charCase = () => PG_KEY_CASES.find((c) => c.ddl === 'character(4)')!; + const leafOf = (c: PgKeyCase) => seamed({ id: { $in: SharedRecordIds.read(EXT(c), 'u9') } }); + const CAST = `CAST(NULLIF("record_id", '') AS "pg_catalog"."bpchar")`; + + /** Run `door` as the first statement of a fresh driver; answer its result and every statement reading the grants. */ + async function firstOnFresh(door: (fresh: SqlDriver) => Promise): Promise<{ out: T; statements: string[] }> { + const fresh = new SqlDriver(PG_CELL.config()); + const knex: Knex = (fresh as any).knex; + for (const c of PG_KEY_CASES) fresh.registerExternalObject({ name: EXT(c), fields: { label: { type: 'text' } } } as any); + fresh.registerExternalObject({ name: CHAR_CHILD, fields: { parent: { type: 'text' }, label: { type: 'text' } } } as any); + const statements: string[] = []; + const onQuery = (q: { sql: string }) => { if (q.sql.includes(GRANTS)) statements.push(q.sql); }; + knex.on('query', onQuery); + try { + return { out: await door(fresh), statements }; + } finally { + knex.removeListener('query', onQuery); + await fresh.disconnect?.(); + } + } + const castIn = (statements: string[]) => { + expect(statements.length).toBeGreaterThanOrEqual(1); + for (const sql of statements) expect(sql).toContain(CAST); + }; + + it('count', async () => { + const c = charCase(); + const { out, statements } = await firstOnFresh((d) => d.count(EXT(c), { where: leafOf(c) })); + expect(out).toBe(c.expected.length); + castIn(statements); + }); + + it('updateMany (the predicate update\'s write)', async () => { + const c = charCase(); + const knex = knexOf(); + try { + const where = seamed({ id: { $in: SharedRecordIds.write(EXT(c), 'u9', ['lvl_edit', 'lvl_full']) } }); + const { out, statements } = await firstOnFresh((d) => d.updateMany(EXT(c), { where }, { label: 'touched' })); + expect(out).toBe(c.expected.length); + expect(sortedIds(await knex(EXT(c)).where('label', 'touched').select('id'))).toEqual([...c.expected]); + castIn(statements); + } finally { + await knex(EXT(c)).update({ label: 'x' }); + } + }); + + it('deleteMany', async () => { + const c = charCase(); + const knex = knexOf(); + try { + const { out, statements } = await firstOnFresh((d) => d.deleteMany(EXT(c), { where: leafOf(c) })); + expect(out).toBe(c.expected.length); + expect(sortedIds(await knex(EXT(c)).select('id'))).toEqual(['k3 ']); + castIn(statements); + } finally { + await knex(EXT(c)).del(); + await knex(EXT(c)).insert(c.ids.map((id) => ({ id, label: 'x' }))); + } + }); + + it('distinct', async () => { + const c = charCase(); + const { out, statements } = await firstOnFresh((d) => d.distinct(EXT(c), 'id', leafOf(c))); + expect(out.map(String).sort()).toEqual([...c.expected]); + castIn(statements); + }); + + it('aggregate', async () => { + const c = charCase(); + const { out, statements } = await firstOnFresh((d) => + d.aggregate(EXT(c), { where: leafOf(c), aggregations: [{ function: 'count', alias: 'n' }] })); + expect(Number((out[0] as any).n)).toBe(c.expected.length); + castIn(statements); + }); + + it('aggregate\'s joined parent (a relation group join whose composed scope holds the leaf)', async () => { + const c = charCase(); + const join: RelationGroupJoin = { + field: 'parent', + parent: ReadableIds.compose(ReadableIds.of(EXT(c)), leafOf(c) as FilterCondition), + attrs: [{ attr: 'label', alias: 'rg_label' }], + resolvedAlias: 'rg_resolved', + }; + // No leaf in the aggregated object's own where: only the joined parent's prime can type it. + const query = { aggregations: [{ function: 'count', alias: 'n' }], [RELATION_GROUP_JOINS]: [join] } as unknown as DriverQuery; + const { out, statements } = await firstOnFresh((d) => d.aggregate(CHAR_CHILD, query)); + const byResolved = Object.fromEntries(out.map((r: any) => [Number(r.rg_resolved), Number(r.n)])); + // cc1 (parent k1, granted padded) and cc2 (parent k2) join a readable parent; cc3 (k3) does not. + expect(byResolved).toEqual({ 1: 2, 0: 1 }); + castIn(statements); + }); + + it('analyzeQuery (the plan is of the statement find runs)', async () => { + const c = charCase(); + const { out, statements } = await firstOnFresh((d) => d.analyzeQuery(EXT(c), { where: leafOf(c) })); + expect(out.error).toBeUndefined(); + expect(out.sql).toContain(CAST); + // EXPLAIN ANALYZE ran it: the top node's actual rows are the list's count. + expect(out.plan.rows[0]['QUERY PLAN'][0].Plan['Actual Rows']).toBe(c.expected.length); + castIn(statements); + }); + + it('findWithWindowFunctions', async () => { + const c = charCase(); + const { out, statements } = await firstOnFresh((d) => + d.findWithWindowFunctions(EXT(c), { where: leafOf(c), windowFunctions: [{ function: 'row_number', alias: 'rn' }] })); + expect(sortedIds(out)).toEqual([...c.expected]); + castIn(statements); + }); + }); + it('reads the catalog once per table: a second statement and another verb ask it nothing', async () => { const fresh = new SqlDriver(PG_CELL.config()); const knex: Knex = (fresh as any).knex; diff --git a/scripts/adr-anchors/packages__drivers__driver-sql__src__fixed-read-leaf-key-type.ts.json b/scripts/adr-anchors/packages__drivers__driver-sql__src__fixed-read-leaf-key-type.ts.json index 2c51389c6b3..7208a6eab72 100644 --- a/scripts/adr-anchors/packages__drivers__driver-sql__src__fixed-read-leaf-key-type.ts.json +++ b/scripts/adr-anchors/packages__drivers__driver-sql__src__fixed-read-leaf-key-type.ts.json @@ -3,5 +3,5 @@ "adrs": [ "ADR-0155" ], - "invariant": "ADR-0155 D-0, O2 (ruled A): on PostgreSQL the fixed-read leaf's inner read projects `record_id` cast to the BASE type of the outer key column (a domain resolved to the type under it, no typmod), read once per physical table from the catalog by `primeFixedReadLeafKeyTypes` before the synchronous compile, so an integer, uuid or character(n) key answers the rows today's id list answers and a malformed grant id fails the statement as a list member does. A text or varchar key takes no cast (step 3's statement); a table with no reading compiles as before and fails loudly, never silently. Every door that compiles a `where` calls the prime beside its other catalog primes: a door that skips it compiles an uncast subquery." + "invariant": "ADR-0155 D-0, O2 (ruled A): on PostgreSQL the fixed-read leaf's inner read projects `record_id` cast to the BASE type of the outer key column (a domain resolved to the type under it, no typmod), read once per physical table from the catalog by `primeFixedReadLeafKeyTypes` before the synchronous compile, so an integer, uuid or character(n) key answers the rows today's id list answers and a malformed grant id fails the statement as a list member does. A text or varchar key takes no cast (step 3's statement). A table with no reading compiles as before: an integer or uuid key fails loudly (42883), a character(n) key misses a padded grant silently. Every door that compiles a `where` calls the prime beside its other catalog primes, so a door that skips it compiles an uncast subquery; each door is pinned as the first statement of a fresh driver." } From 7f4974aac83bf55f19810c6260ed58a72c77a442 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 01:39:05 +0000 Subject: [PATCH 4/7] fix(driver-sql): refuse a share-grant leaf on PostgreSQL when the key table has no catalog reading (ADR-0155 O2, D2) "No reading" is now kept apart from "read: a text key". A failed or empty catalog read still records nothing, and a leaf compared with a table the driver holds no reading of is refused in ADR-0139 D3's envelope (INTERNAL_ERROR / 500, logged once per knex client) instead of compiling uncast, which on a character(n) key missed a padded grant silently. A type name knex cannot bind as one identifier is refused the same way. Live PG pins: a pool the caller's transaction holds times the catalog read out (find, count, updateMany refuse, nothing written, logged once, the next statement reads again), and a table created in the caller's uncommitted transaction is refused. Claude-Session: https://claude.ai/code/session_01L9qibyXo4gSy8DJPNz4ANz Co-authored-by: Claude --- .changeset/35906-pg-share-grant-key-type.md | 3 +- .../src/fixed-read-leaf-key-type.test.ts | 38 +++++- .../src/fixed-read-leaf-key-type.ts | 120 ++++++++++++++---- .../src/sql-driver-filter-helpers.ts | 4 +- ...driver-fixed-read-leaf-conformance.test.ts | 101 ++++++++++++++- .../src/sql-driver-internal-helpers.ts | 33 +++-- packages/drivers/driver-sql/src/sql-driver.ts | 2 +- ...sql__src__fixed-read-leaf-key-type.ts.json | 2 +- 8 files changed, 258 insertions(+), 45 deletions(-) diff --git a/.changeset/35906-pg-share-grant-key-type.md b/.changeset/35906-pg-share-grant-key-type.md index 09c6b901efa..a77a2138eb4 100644 --- a/.changeset/35906-pg-share-grant-key-type.md +++ b/.changeset/35906-pg-share-grant-key-type.md @@ -11,5 +11,6 @@ No visible change on its own: nothing writes a `SharedRecordIds` leaf yet. The s - **PostgreSQL, a key that is not text.** The compiled subquery `id IN (SELECT record_id FROM sys_record_share WHERE …)` now projects `record_id` cast to the base type of the column it is compared with: `CAST(NULLIF(record_id, '') AS )`. A federated table keyed by `integer`, `bigint`, `smallint`, `numeric`, `uuid`, `character(n)` or a domain over one of them answers the same rows as the id list of the same grants: `07` names 7, an upper-case or braced uuid names its lower-case twin, and a padded grant names a `character(n)` key. Before, an integer or uuid key failed the statement with `DATABASE_ERROR` (42883), and a `character(n)` key silently missed a padded grant. - **A malformed grant id** (`abc` against an integer key) fails the statement with `DATABASE_ERROR` / 500, the same answer the id list gives for it. -- **How the type is known.** The driver reads the column types of the compared table from `pg_catalog` once, the first time a statement holding the leaf reaches that table, and keeps the answer for the life of the driver. A statement with no leaf reads nothing. A failed catalog read records nothing and is asked again by the next statement. +- **How the type is known.** The driver reads the column types of the compared table from `pg_catalog` once, the first time a statement holding the leaf reaches that table, and keeps the answer for the life of the driver. A statement with no leaf reads nothing. A failed or empty catalog read records nothing and is asked again by the next statement. +- **No reading, no statement.** On PostgreSQL a statement whose leaf is compared with a table the driver holds no catalog reading of is refused with `INTERNAL_ERROR` / 500 (logged once), and never runs uncast, which on a `character(n)` key would miss a padded grant silently. A table has no reading when the catalog read fails (it runs on a pooled connection, so a pool the caller's own transaction holds times it out) or when the table was created in the caller's transaction that has not committed yet; the next statement reads the catalog again. - **Unchanged.** A `text` or `varchar` key, which is every table the platform creates, compiles exactly as before. SQLite, MySQL, SQL Server and Oracle compile exactly as before; SQLite answers the list's rows by column affinity. MySQL and SQL Server keys are not measured against a live server yet. An Oracle `RAW(16)` uuid key is expected to fail the statement (ORA-01465, by reading: the subquery converts a dashed uuid grant to `RAW` implicitly, where the id list binds its undashed hex); it is not measured, and is tracked on #35952. diff --git a/packages/drivers/driver-sql/src/fixed-read-leaf-key-type.test.ts b/packages/drivers/driver-sql/src/fixed-read-leaf-key-type.test.ts index da979f248b3..329b8d558b2 100644 --- a/packages/drivers/driver-sql/src/fixed-read-leaf-key-type.test.ts +++ b/packages/drivers/driver-sql/src/fixed-read-leaf-key-type.test.ts @@ -44,6 +44,16 @@ function pgProbe(answer: () => unknown): { probe: Probe; raw: ReturnType unknown, why: string): void { + let caught: unknown; + try { run(); } catch (err) { caught = err; } + expect(caught, 'refused').toBeInstanceOf(Error); + expect((caught as { code?: unknown }).code).toBe('INTERNAL_ERROR'); + expect((caught as { status?: unknown }).status).toBe(500); + expect((caught as Error).message).toContain(why); +} + const row = (column_name: string, type_schema: string, type_name: string) => ({ column_name, type_schema, type_name }); const leafWhere = (object = EXT) => ({ id: { $in: SharedRecordIds.read(object, 'u9') } }); @@ -84,26 +94,42 @@ describe('[ADR-0155 O2] the catalog prime and the cast it puts on the inner read } }); - it('a type name knex cannot bind as one identifier is not cast (the statement compiles as before)', async () => { + it('a type name knex cannot bind as one identifier is refused, never cast or left uncast', async () => { const { probe } = pgProbe(() => ({ rows: [row('id', 'odd.schema', 'int4')] })); await probe.prime(EXT, leafWhere()); - expect(probe.compile(EXT, leafWhere()).sql).toContain('"id" in (select "record_id" from'); + expectRefused(() => probe.compile(EXT, leafWhere()), 'cannot bind as one identifier'); }); - it('a failed or empty catalog read records nothing, and the next door asks again', async () => { + it('no reading is refused (INTERNAL_ERROR / 500, logged once), never compiled uncast; a failed or empty read records nothing and the next door asks again', async () => { let answer: () => unknown = () => { throw new Error('catalog unavailable'); }; const { probe, raw } = pgProbe(() => answer()); + const logger = { warn: vi.fn(), info: vi.fn(), error: vi.fn(), debug: vi.fn() }; + (probe as any).logger = logger; + // Never primed: no reading at all. + expectRefused(() => probe.compile(EXT, leafWhere()), 'holds no reading'); + // The catalog read failed (a pooled connection's acquire timeout is one). await probe.prime(EXT, leafWhere()); - expect(probe.compile(EXT, leafWhere()).sql).not.toMatch(/CAST\(/); - answer = () => ({ rows: [] }); // the relation is not visible to this session yet + expectRefused(() => probe.compile(EXT, leafWhere()), 'holds no reading'); + // The relation is not visible to the pooled connection (an uncommitted CREATE). + answer = () => ({ rows: [] }); await probe.prime(EXT, leafWhere()); - expect(probe.compile(EXT, leafWhere()).sql).not.toMatch(/CAST\(/); + expectRefused(() => probe.compile(EXT, leafWhere()), 'holds no reading'); + // Logged at error once for this client; the caller saw all three. + expect(logger.error).toHaveBeenCalledTimes(1); + expect(String(logger.error.mock.calls[0][0])).toContain("[driver-sql] the $in of column 'id' of 'srid_ext' holds a SharedRecordIds leaf"); + expect(String(logger.error.mock.calls[0][0])).not.toContain('u9'); answer = () => ({ rows: [row('id', 'pg_catalog', 'int8')] }); await probe.prime(EXT, leafWhere()); expect(raw).toHaveBeenCalledTimes(3); expect(probe.compile(EXT, leafWhere()).sql).toContain('AS "pg_catalog"."int8"'); }); + it('a column the read table does not have takes no cast: the database names the missing column itself', async () => { + const { probe } = pgProbe(() => ({ rows: [row('label', 'pg_catalog', 'text')] })); + await probe.prime(EXT, leafWhere()); + expect(probe.compile(EXT, leafWhere()).sql).toContain('"id" in (select "record_id" from "sys_record_share"'); + }); + it('a where with no leaf reads nothing', async () => { const { probe, raw } = pgProbe(() => ({ rows: [row('id', 'pg_catalog', 'int4')] })); await probe.prime(EXT, { id: { $in: ['7', '42'] }, label: 'x' }); 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 131f78f7d07..2d986e3e0e4 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 @@ -34,12 +34,19 @@ * - **Text keys keep step 3's statement.** A `text` or `varchar` key (every * table the platform manages) is cast to nothing: `record_id` already * compares as the list's members do. - * - **No cast without a reading.** A table the catalog has not answered for - * (no door primed it, the read failed, the relation is not visible yet) is - * compiled as before: an integer or uuid key fails loudly (42883), but a - * `character(n)` key compares as text and misses a padded grant silently, - * which is why every door primes. A failed or empty read records nothing, - * so the next door asks again. + * - **No reading, no statement.** On PostgreSQL a leaf compared with a table + * the catalog has not answered for is REFUSED, in ADR-0139 D3's envelope + * (`INTERNAL_ERROR` / 500, logged at `error` once per knex client), never + * compiled uncast. Uncast, `record_id` meets the key as text: an integer or + * uuid key fails (42883), but a `character(n)` key silently misses a padded + * grant, which ADR-0155 D2 forbids. "No reading" is kept apart from "read: + * a text key" (which takes no cast). A table has no reading when no door + * primed it, when the catalog read failed (it runs on a pooled connection, + * so a saturated pool's acquire timeout is a failure), or when the relation + * is not visible to that connection (created in the caller's uncommitted + * transaction). A failed or empty read records nothing, so the next + * statement asks again. A type knex cannot spell as one identifier is + * refused the same way. * * ## When the catalog is read * @@ -63,6 +70,8 @@ */ import type { Knex } from 'knex'; +import { describeFixedReadLeaf, refuseFixedReadLeafOnce } from '@objectstack/core'; +import type { ReadableIdsRefusalLog } from '@objectstack/core'; import { isComposedReadableIds, isFixedReadLeaf } from '@objectstack/spec/data'; /** The PostgreSQL type a leaf's inner read casts `record_id` to: the outer key's base type. */ @@ -78,8 +87,17 @@ export interface FixedReadLeafKeySource { getBuilder(object: string): Knex.QueryBuilder; } -/** Per knex client: the physical table's key → each column's cast, `null` for none. */ -const castsByClient = new WeakMap>>(); +/** A column whose base type knex cannot spell as one identifier: refused, never cast or left uncast. */ +const UNSPELLABLE = Object.freeze({ unspellable: true as const }); + +/** One column's reading: the cast, `null` for a text key (no cast), or {@link UNSPELLABLE}. */ +type ColumnReading = FixedReadLeafKeyCast | null | typeof UNSPELLABLE; + +/** Per knex client: the physical table's key → each column's reading. A table with no entry has NO reading. */ +const castsByClient = new WeakMap>>(); + +/** Per knex client: whether a no-reading refusal was logged (once per client, its own flag). */ +const refusalLogByClient = new WeakMap(); /** Base types `record_id` (text) already compares as today's list members do. */ const UNCAST_BASE_TYPES = new Set(['pg_catalog.text', 'pg_catalog.varchar']); @@ -109,7 +127,7 @@ function tableKey(schema: string | undefined, table: string): string { return JSON.stringify([schema ?? null, table]); } -function cacheOf(client: object): Map> { +function cacheOf(client: object): Map> { let cache = castsByClient.get(client); if (cache === undefined) { cache = new Map(); @@ -120,8 +138,8 @@ function cacheOf(client: object): Map 0 && !name.includes('.') && !/\sas\s/i.test(name); @@ -180,35 +198,89 @@ export async function primeFixedReadLeafKeyTypes(source: FixedReadLeafKeySource, const result = await client.raw(COLUMN_BASE_TYPES_SQL.replace('%RELATION%', relation), bindings); rows = result.rows; } catch { - // A catalog that cannot be read records nothing: the statement compiles - // as before, and the next door asks again. + // A catalog that cannot be read records nothing: the leaf is refused + // at compile (no reading), and the next door asks again. continue; } // No row: the relation is not visible to this session (yet). Nothing is recorded. if (!Array.isArray(rows) || rows.length === 0) continue; - const columns = new Map(); + const columns = new Map(); for (const row of rows) { - const uncast = UNCAST_BASE_TYPES.has(`${row.type_schema}.${row.type_name}`) - || !bindableIdentifier(row.type_schema) - || !bindableIdentifier(row.type_name); - columns.set(row.column_name, uncast ? null : Object.freeze({ schema: row.type_schema, type: row.type_name })); + let reading: ColumnReading; + if (UNCAST_BASE_TYPES.has(`${row.type_schema}.${row.type_name}`)) reading = null; + else if (!bindableIdentifier(row.type_schema) || !bindableIdentifier(row.type_name)) reading = UNSPELLABLE; + else reading = Object.freeze({ schema: row.type_schema, type: row.type_name }); + columns.set(row.column_name, reading); } cache.set(key, columns); } } +/** What the compile does with `record_id` for one outer column, per {@link fixedReadLeafKeyReading}. */ +export type FixedReadLeafKeyReading = + | { readonly kind: 'cast'; readonly cast: FixedReadLeafKeyCast } + | { readonly kind: 'uncast' } + | { readonly kind: 'unread' } + | { readonly kind: 'unspellable' }; + /** - * The cast {@link primeFixedReadLeafKeyTypes} recorded for `column` of the - * physical table `schema.table` on this knex client, or `null`: no reading, - * or a text key, which takes no cast. + * What {@link primeFixedReadLeafKeyTypes} recorded for `column` of the + * physical table `schema.table` on this knex client: + * + * - `cast`: a base type that is not text; + * - `uncast`: a text or varchar key, or a column the read table does not + * have (the database then names the missing column itself); + * - `unread`: no reading of the table at all; + * - `unspellable`: a type knex cannot spell as one identifier. + * + * On PostgreSQL the last two are refused ({@link refuseFixedReadLeafKey}). */ -export function fixedReadLeafKeyCast( +export function fixedReadLeafKeyReading( client: object, schema: string | undefined, table: string, column: string, -): FixedReadLeafKeyCast | null { - return castsByClient.get(client)?.get(tableKey(schema, table))?.get(column) ?? null; +): FixedReadLeafKeyReading { + const columns = castsByClient.get(client)?.get(tableKey(schema, table)); + if (columns === undefined) return { kind: 'unread' }; + const reading = columns.get(column); + if (reading === undefined || reading === null) return { kind: 'uncast' }; + if (reading === UNSPELLABLE) return { kind: 'unspellable' }; + return { kind: 'cast', cast: reading as FixedReadLeafKeyCast }; +} + +/** + * [ADR-0155 D2, O2] The refusal of a leaf compared with a column this driver + * cannot type on PostgreSQL: ADR-0139 D3's envelope, `INTERNAL_ERROR` / 500, + * logged at `error` once per knex client. The message names the leaf (by + * name and table, never its recipient), the object and column, why, and the + * remedy. + */ +export function refuseFixedReadLeafKey( + evaluator: string, + leaf: unknown, + object: string | null, + column: string, + kind: 'unread' | 'unspellable', + logger: ReadableIdsRefusalLog | undefined, + client: object, +): Error { + let state = refusalLogByClient.get(client); + if (state === undefined) { + state = { logged: false }; + refusalLogByClient.set(client, state); + } + const at = `the $in of column '${column}' of '${object ?? '(no object)'}'`; + const why = kind === 'unread' + ? 'whose type this driver holds no reading of from the PostgreSQL catalog: the catalog read failed, ' + + 'or the table is not visible to the pooled connection that reads it (created inside a transaction ' + + 'that has not committed)' + : 'whose type the PostgreSQL catalog names with a spelling this driver cannot bind as one identifier'; + const message = `${describeFixedReadLeaf(at, leaf)}, compared with a column ${why}. Uncast, record_id would ` + + 'meet the key as text, which fails on an integer or uuid key and silently misses a padded id on a ' + + 'character(n) key (ADR-0155 D2, O2). The statement was NOT run. The next statement reads the catalog ' + + 'again; a table created inside a transaction is read once that transaction commits.'; + return refuseFixedReadLeafOnce(evaluator, message, logger, state, object ?? undefined); } /** The inner read's projection under a cast: `CAST(NULLIF(record_id, '') AS "schema"."type")`. */ 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 3af261241eb..8a6f5772993 100644 --- a/packages/drivers/driver-sql/src/sql-driver-filter-helpers.ts +++ b/packages/drivers/driver-sql/src/sql-driver-filter-helpers.ts @@ -707,7 +707,7 @@ export class FilterHelpersFacet { } /** The body of `SqlDriver#applyFilterCondition`; the method's docblock there is its contract. */ - static applyFilterCondition(this: Pick, + static applyFilterCondition(this: Pick, builder: Knex.QueryBuilder, condition: any, logicalOp: 'and' | 'or' = 'and', @@ -863,7 +863,7 @@ export class FilterHelpersFacet { // with type the inner read on PostgreSQL (ADR-0155 O2). if (rawOp === '$in' && isFixedReadLeaf(opValue)) { const mIn = logicalOp === 'or' ? 'orWhereIn' : 'whereIn'; - (builder as any)[mIn](field, this.fixedReadLeafSubquery(opValue, { object: table, column: field })); + (builder as any)[mIn](field, this.fixedReadLeafSubquery(opValue, { object: table, column: field, evaluator: this.readableIdsDriverName })); 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 bf7b1fdc612..8a4fe38df3b 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 @@ -47,6 +47,7 @@ import { import { SqlDriver, type SqlDriverConfig } from './sql-driver.js'; import { DIALECT_CELLS, PG_CELL, currentLiveSchema, declareDialectCell, type DialectCell } 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'; const set = SHARED_RECORD_IDS_CASE_SET; @@ -641,6 +642,75 @@ function declarePgKeyTypePins(driverOf: () => SqlDriver, knexOf: () => Knex): vo }); }); + /** + * F1: a table this driver holds no reading of is REFUSED on PostgreSQL + * (ADR-0139 D3's envelope, `INTERNAL_ERROR` / 500, logged once), never + * compiled uncast: uncast, a `character(n)` key misses a padded grant + * silently. The catalog read runs on a pooled connection, so (a) a pool + * the caller's own transaction holds times the read out, and (b) a table + * created in the caller's uncommitted transaction is not visible to it. + */ + describe('no reading is refused, never compiled uncast (ADR-0155 D2)', () => { + const charCase = () => PG_KEY_CASES.find((c) => c.ddl === 'character(4)')!; + const leafOf = (object: string) => seamed({ id: { $in: SharedRecordIds.read(object, 'u9') } }); + const refused = (err: unknown) => { + expect(err, 'refused').toBeInstanceOf(Error); + expect(err).toMatchObject({ code: 'INTERNAL_ERROR', status: 500 }); + expect((err as Error).message).toContain('holds no reading'); + }; + + it('(a) the catalog read times out on a saturated pool: find, count and updateMany refuse, nothing is written, logged once; the next statement asks again', async () => { + const c = charCase(); + const fresh = new SqlDriver({ ...PG_CELL.config(), pool: { min: 0, max: 1 }, acquireConnectionTimeout: 1000 } as SqlDriverConfig); + const logger = { warn: vi.fn(), info: vi.fn(), error: vi.fn(), debug: vi.fn() }; + (fresh as any).logger = logger; + fresh.registerExternalObject({ name: EXT(c), fields: { label: { type: 'text' } } } as any); + const knex: Knex = (fresh as any).knex; + const statements: string[] = []; + const onQuery = (q: { sql: string }) => { if (q.sql.includes(GRANTS)) statements.push(q.sql); }; + knex.on('query', onQuery); + try { + // The caller's transaction holds the pool's one connection. + const trx = await fresh.beginTransaction(); + try { + refused(await fresh.find(EXT(c), { where: leafOf(EXT(c)) }, { transaction: trx } as any).catch((e) => e)); + refused(await fresh.count(EXT(c), { where: leafOf(EXT(c)) }, { transaction: trx } as any).catch((e) => e)); + refused(await fresh.updateMany(EXT(c), { where: leafOf(EXT(c)) }, { label: 'touched' }, { transaction: trx } as any).catch((e) => e)); + } finally { + await trx.rollback(); + } + expect(statements).toEqual([]); + expect(await knexOf()(EXT(c)).where('label', 'touched').count({ n: '*' })).toEqual([{ n: '0' }]); + expect(logger.error).toHaveBeenCalledTimes(1); + // Nothing was cached: with the connection back, the next statement reads the catalog and answers the list's rows. + expect(sortedIds(await fresh.find(EXT(c), { where: leafOf(EXT(c)) }))).toEqual([...c.expected]); + for (const sql of statements) expect(sql).toContain(`CAST(NULLIF("record_id", '') AS "pg_catalog"."bpchar")`); + } finally { + knex.removeListener('query', onQuery); + await fresh.disconnect?.(); + } + }); + + it('(b) a table created in the caller\'s uncommitted transaction: refused, then rolled back', async () => { + const TXN = 'srid_pk_txn'; + const fresh = new SqlDriver(PG_CELL.config()); + fresh.registerExternalObject({ name: TXN, fields: { label: { type: 'text' } } } as any); + const trx = await fresh.beginTransaction(); + try { + await trx.raw(`create table ${TXN} (id character(4) primary key, label text)`); + await trx(TXN).insert([{ id: 'k1', label: 'x' }, { id: 'k2', label: 'x' }]); + await trx(GRANTS).insert({ id: 'srid_pk_txn_g0', object_name: TXN, recipient_type: 'user', recipient_id: 'u9', record_id: 'k1 ', access_level: 'lvl_edit', organization_id: 'org_a' }); + // Today's list, in the same transaction, answers k1: the leaf must not answer anything else. + expect(sortedIds(await fresh.find(TXN, { where: seamed({ id: { $in: ['k1 '] } }) }, { transaction: trx } as any))).toEqual(['k1 ']); + refused(await fresh.find(TXN, { where: leafOf(TXN) }, { transaction: trx } as any).catch((e) => e)); + refused(await fresh.count(TXN, { where: leafOf(TXN) }, { transaction: trx } as any).catch((e) => e)); + } finally { + await trx.rollback(); + await fresh.disconnect?.(); + } + }); + }); + it('reads the catalog once per table: a second statement and another verb ask it nothing', async () => { const fresh = new SqlDriver(PG_CELL.config()); const knex: Knex = (fresh as any).knex; @@ -672,6 +742,22 @@ for (const cell of DIALECT_CELLS) declareDialectCell(cell, 'SharedRecordIds conf // ── The compiled statement, on every dialect driver-sql ships ─────────────── class CompileProbe extends SqlDriver { + /** + * The door's catalog prime (ADR-0155 O2). On PostgreSQL the read is + * answered by a stub (a text key, which takes no cast): a leaf compiled + * with no reading is refused, so the statement needs one. Every other + * dialect reads nothing. + */ + async prime(where: FilterCondition): Promise { + const client = (this as any).knex.client as { dialect?: string; raw: (...args: unknown[]) => unknown }; + if (client.dialect === 'postgresql') { + const original = client.raw.bind(client); + client.raw = (...args: unknown[]) => (String(args[0]).includes('pg_attribute') + ? Promise.resolve({ rows: [{ column_name: 'id', type_schema: 'pg_catalog', type_name: 'text' }] }) + : original(...args)); + } + await primeFixedReadLeafKeyTypes({ getBuilder: (o) => this.getBuilder(o) }, DOC, where); + } compileWhere(where: FilterCondition): { sql: string; bindings: readonly unknown[] } { const builder: Knex.QueryBuilder = this.getKnex()(DOC); this.applyFilters(builder, where); @@ -719,9 +805,10 @@ const COMPILED: Record = { describe('[ADR-0155 step 3] the compiled fixed inner read, per dialect (no server)', () => { for (const [dialect, config] of Object.entries(COMPILE_CONFIGS)) { - it(`${dialect}: one subquery in the list's position, every value bound, no tenant scope inside it`, () => { + it(`${dialect}: one subquery in the list's position, every value bound, no tenant scope inside it`, async () => { const probe = new CompileProbe(config); expect(probe.supports.fixedReadLeaves).toEqual(['SharedRecordIds']); + 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); expect(read.bindings).toEqual(dialect === 'oracle' ? [DOC, 'user', 'u1'] : [DOC, 'user', 'u1', '']); @@ -732,4 +819,16 @@ describe('[ADR-0155 step 3] the compiled fixed inner read, per dialect (no serve ); }); } + + it('pg: a leaf compared with a table the catalog has not answered for is refused (INTERNAL_ERROR / 500), never compiled uncast', () => { + const probe = new CompileProbe(COMPILE_CONFIGS.pg); + let caught: unknown; + try { + probe.compileWhere({ id: { $in: SharedRecordIds.read(DOC, 'u1') } } as unknown as FilterCondition); + } catch (err) { + caught = err; + } + expect((caught as { code?: unknown }).code).toBe('INTERNAL_ERROR'); + expect((caught as { status?: unknown }).status).toBe(500); + }); }); 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 f584fa2998e..c3f4688b975 100644 --- a/packages/drivers/driver-sql/src/sql-driver-internal-helpers.ts +++ b/packages/drivers/driver-sql/src/sql-driver-internal-helpers.ts @@ -39,7 +39,7 @@ import { postureEnforcesWall } from '@objectstack/spec/security'; import type { Knex } from 'knex'; import type { SqlDriver } from './sql-driver.js'; import { fixedInnerReadPredicates } from './fixed-read-leaf-compile.js'; -import { castFixedReadLeafColumn, fixedReadLeafKeyCast } from './fixed-read-leaf-key-type.js'; +import { castFixedReadLeafColumn, fixedReadLeafKeyReading, refuseFixedReadLeafKey } from './fixed-read-leaf-key-type.js'; /** * The `SqlDriver` members the bodies of {@link InternalHelpersFacet} read — every one of @@ -178,16 +178,31 @@ export class InternalHelpersFacet { * column the subquery is compared with. On PostgreSQL, where that column's * base type is not text, the projection is `record_id` cast to it, as the * catalog read primed it (`fixed-read-leaf-key-type.ts`), so an integer or - * uuid key answers the rows today's list answers. A text key, any other - * dialect, or a table no door primed projects `record_id` as before. + * uuid key answers the rows today's list answers. A text key or any + * other dialect projects `record_id` as before. On PostgreSQL a table + * with NO reading (no door primed it, the catalog read failed, the table + * is not visible to the pooled connection) 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). */ - static fixedReadLeafSubquery(this: Pick, leaf: FixedReadLeaf, outer?: { readonly object: string | null; readonly column: string }): Knex.QueryBuilder { + static fixedReadLeafSubquery(this: Pick, leaf: FixedReadLeaf, outer?: { readonly object: string | null; readonly column: string; readonly evaluator?: string }): Knex.QueryBuilder { const read = fixedInnerReadPredicates(leaf, { emptyStringIsNull: this.isOracle }); - // The physical table as `getBuilder` addresses it: the key the prime recorded under. - const cast = outer?.object - ? fixedReadLeafKeyCast(this.knex.client, this.physicalSchemaByObject[outer.object], this.physicalTableByObject[outer.object] ?? outer.object, outer.column) - : null; - const inner = this.getBuilder(read.table).select(cast === null ? read.column : castFixedReadLeafColumn(this.knex, read.column, cast)); + let projection: string | Knex.Raw = read.column; + // [ADR-0155 O2] PostgreSQL only: the physical table as `getBuilder` + // addresses it, the key the prime recorded under. No reading is refused, + // never compiled uncast (a `character(n)` key would miss silently). + if ((this.knex.client as { dialect?: string }).dialect === 'postgresql') { + const object = outer?.object ?? null; + const column = outer?.column ?? read.column; + const reading = object === null + ? { kind: 'unread' as const } + : fixedReadLeafKeyReading(this.knex.client, this.physicalSchemaByObject[object], this.physicalTableByObject[object] ?? object, column); + if (reading.kind === 'unread' || reading.kind === 'unspellable') { + throw refuseFixedReadLeafKey(outer?.evaluator ?? 'driver-sql', leaf, object, column, reading.kind, this.logger, this.knex.client); + } + if (reading.kind === 'cast') projection = castFixedReadLeafColumn(this.knex, read.column, reading.cast); + } + 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]); inner.whereNotNull(read.column); diff --git a/packages/drivers/driver-sql/src/sql-driver.ts b/packages/drivers/driver-sql/src/sql-driver.ts index 4fdc1f2d009..184dd175b2a 100644 --- a/packages/drivers/driver-sql/src/sql-driver.ts +++ b/packages/drivers/driver-sql/src/sql-driver.ts @@ -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 }): Knex.QueryBuilder { + private fixedReadLeafSubquery(leaf: FixedReadLeaf, outer?: { readonly object: string | null; readonly column: string; readonly evaluator?: string }): 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__fixed-read-leaf-key-type.ts.json b/scripts/adr-anchors/packages__drivers__driver-sql__src__fixed-read-leaf-key-type.ts.json index 7208a6eab72..3f94d23dd2e 100644 --- a/scripts/adr-anchors/packages__drivers__driver-sql__src__fixed-read-leaf-key-type.ts.json +++ b/scripts/adr-anchors/packages__drivers__driver-sql__src__fixed-read-leaf-key-type.ts.json @@ -3,5 +3,5 @@ "adrs": [ "ADR-0155" ], - "invariant": "ADR-0155 D-0, O2 (ruled A): on PostgreSQL the fixed-read leaf's inner read projects `record_id` cast to the BASE type of the outer key column (a domain resolved to the type under it, no typmod), read once per physical table from the catalog by `primeFixedReadLeafKeyTypes` before the synchronous compile, so an integer, uuid or character(n) key answers the rows today's id list answers and a malformed grant id fails the statement as a list member does. A text or varchar key takes no cast (step 3's statement). A table with no reading compiles as before: an integer or uuid key fails loudly (42883), a character(n) key misses a padded grant silently. Every door that compiles a `where` calls the prime beside its other catalog primes, so a door that skips it compiles an uncast subquery; each door is pinned as the first statement of a fresh driver." + "invariant": "ADR-0155 D-0, D2, O2 (ruled A): on PostgreSQL the fixed-read leaf's inner read projects `record_id` cast to the BASE type of the outer key column (a domain resolved to the type under it, no typmod), read once per physical table from the catalog by `primeFixedReadLeafKeyTypes` before the synchronous compile, so an integer, uuid or character(n) key answers the rows today's id list answers and a malformed grant id fails the statement as a list member does. A text or varchar key takes no cast (step 3's statement). \"No reading\" is kept apart from \"read: a text key\": a failed or empty catalog read records nothing, and a leaf compared with a table that has no reading (no door primed it, the read failed or timed out on the pool, the table is not visible to the pooled connection) or whose type cannot be spelled as one identifier is REFUSED in ADR-0139 D3's envelope (INTERNAL_ERROR / 500, logged once per knex client), never compiled uncast. Every door that compiles a `where` calls the prime beside its other catalog primes, so a door that skips it refuses every leaf; each door is pinned as the first statement of a fresh driver." } From c7cc4e28cacbee343a4582276955247169d99fea Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 02:17:48 +0000 Subject: [PATCH 5/7] test(driver-sql): type the transaction options in the no-reading refusal pins Claude-Session: https://claude.ai/code/session_01L9qibyXo4gSy8DJPNz4ANz Co-authored-by: Claude --- .../sql-driver-fixed-read-leaf-conformance.test.ts | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) 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 8a4fe38df3b..ad17b728add 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 @@ -42,6 +42,7 @@ import { isSharedRecordIds, lowerFilterCondition, type FilterCondition, + type DriverOptions, type FixedReadLeafRow, } from '@objectstack/spec/data'; import { SqlDriver, type SqlDriverConfig } from './sql-driver.js'; @@ -653,6 +654,7 @@ function declarePgKeyTypePins(driverOf: () => SqlDriver, knexOf: () => Knex): vo describe('no reading is refused, never compiled uncast (ADR-0155 D2)', () => { const charCase = () => PG_KEY_CASES.find((c) => c.ddl === 'character(4)')!; const leafOf = (object: string) => seamed({ id: { $in: SharedRecordIds.read(object, 'u9') } }); + const inTrx = (transaction: Knex.Transaction): DriverOptions => ({ transaction }); const refused = (err: unknown) => { expect(err, 'refused').toBeInstanceOf(Error); expect(err).toMatchObject({ code: 'INTERNAL_ERROR', status: 500 }); @@ -673,9 +675,9 @@ function declarePgKeyTypePins(driverOf: () => SqlDriver, knexOf: () => Knex): vo // The caller's transaction holds the pool's one connection. const trx = await fresh.beginTransaction(); try { - refused(await fresh.find(EXT(c), { where: leafOf(EXT(c)) }, { transaction: trx } as any).catch((e) => e)); - refused(await fresh.count(EXT(c), { where: leafOf(EXT(c)) }, { transaction: trx } as any).catch((e) => e)); - refused(await fresh.updateMany(EXT(c), { where: leafOf(EXT(c)) }, { label: 'touched' }, { transaction: trx } as any).catch((e) => e)); + refused(await fresh.find(EXT(c), { where: leafOf(EXT(c)) }, inTrx(trx)).catch((e) => e)); + refused(await fresh.count(EXT(c), { where: leafOf(EXT(c)) }, inTrx(trx)).catch((e) => e)); + refused(await fresh.updateMany(EXT(c), { where: leafOf(EXT(c)) }, { label: 'touched' }, inTrx(trx)).catch((e) => e)); } finally { await trx.rollback(); } @@ -701,9 +703,9 @@ function declarePgKeyTypePins(driverOf: () => SqlDriver, knexOf: () => Knex): vo await trx(TXN).insert([{ id: 'k1', label: 'x' }, { id: 'k2', label: 'x' }]); await trx(GRANTS).insert({ id: 'srid_pk_txn_g0', object_name: TXN, recipient_type: 'user', recipient_id: 'u9', record_id: 'k1 ', access_level: 'lvl_edit', organization_id: 'org_a' }); // Today's list, in the same transaction, answers k1: the leaf must not answer anything else. - expect(sortedIds(await fresh.find(TXN, { where: seamed({ id: { $in: ['k1 '] } }) }, { transaction: trx } as any))).toEqual(['k1 ']); - refused(await fresh.find(TXN, { where: leafOf(TXN) }, { transaction: trx } as any).catch((e) => e)); - refused(await fresh.count(TXN, { where: leafOf(TXN) }, { transaction: trx } as any).catch((e) => e)); + expect(sortedIds(await fresh.find(TXN, { where: seamed({ id: { $in: ['k1 '] } }) }, inTrx(trx)))).toEqual(['k1 ']); + refused(await fresh.find(TXN, { where: leafOf(TXN) }, inTrx(trx)).catch((e) => e)); + refused(await fresh.count(TXN, { where: leafOf(TXN) }, inTrx(trx)).catch((e) => e)); } finally { await trx.rollback(); await fresh.disconnect?.(); From 99e085ec967230d4fdcdd47408f76d69f4b1b8fd Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 02:59:46 +0000 Subject: [PATCH 6/7] fix(driver-sql): read the key type on the caller's transaction, under a savepoint (ADR-0155 D-0, O2) A door running in the caller's transaction now reads the PostgreSQL catalog on that transaction's own connection, inside a knex nested transaction (a savepoint), instead of on a second pooled connection. A pool the transaction holds can no longer time the read out, a table the transaction created is read, and a failed read rolls back the savepoint alone, leaving the caller's transaction usable. That reading is kept for that transaction only. Outside a transaction the read stays on the pool. A failed or empty read still records nothing, and no reading is still refused (500, logged once). Live PG pins: a held single-connection pool answers the list's rows, cast, on find, count and updateMany; a character(4) table created in the uncommitted transaction answers [k1], cast; a catalog read failing inside the transaction is refused while the transaction stays usable. Claude-Session: https://claude.ai/code/session_01L9qibyXo4gSy8DJPNz4ANz Co-authored-by: Claude --- .changeset/35906-pg-share-grant-key-type.md | 5 +- .../src/fixed-read-leaf-key-type.test.ts | 34 +++++- .../src/fixed-read-leaf-key-type.ts | 81 +++++++++---- .../driver-sql/src/sql-driver-aggregation.ts | 3 +- .../src/sql-driver-bulk-operations.ts | 6 +- .../drivers/driver-sql/src/sql-driver-crud.ts | 2 +- .../driver-sql/src/sql-driver-distinct.ts | 2 +- .../src/sql-driver-filter-helpers.ts | 2 +- ...driver-fixed-read-leaf-conformance.test.ts | 108 +++++++++++++----- .../src/sql-driver-internal-helpers.ts | 9 +- .../driver-sql/src/sql-driver-query-plan.ts | 2 +- .../src/sql-driver-window-functions.ts | 2 +- packages/drivers/driver-sql/src/sql-driver.ts | 2 +- ...sql__src__fixed-read-leaf-key-type.ts.json | 2 +- 14 files changed, 183 insertions(+), 77 deletions(-) diff --git a/.changeset/35906-pg-share-grant-key-type.md b/.changeset/35906-pg-share-grant-key-type.md index a77a2138eb4..1c09eca4875 100644 --- a/.changeset/35906-pg-share-grant-key-type.md +++ b/.changeset/35906-pg-share-grant-key-type.md @@ -12,5 +12,6 @@ No visible change on its own: nothing writes a `SharedRecordIds` leaf yet. The s - **PostgreSQL, a key that is not text.** The compiled subquery `id IN (SELECT record_id FROM sys_record_share WHERE …)` now projects `record_id` cast to the base type of the column it is compared with: `CAST(NULLIF(record_id, '') AS )`. A federated table keyed by `integer`, `bigint`, `smallint`, `numeric`, `uuid`, `character(n)` or a domain over one of them answers the same rows as the id list of the same grants: `07` names 7, an upper-case or braced uuid names its lower-case twin, and a padded grant names a `character(n)` key. Before, an integer or uuid key failed the statement with `DATABASE_ERROR` (42883), and a `character(n)` key silently missed a padded grant. - **A malformed grant id** (`abc` against an integer key) fails the statement with `DATABASE_ERROR` / 500, the same answer the id list gives for it. - **How the type is known.** The driver reads the column types of the compared table from `pg_catalog` once, the first time a statement holding the leaf reaches that table, and keeps the answer for the life of the driver. A statement with no leaf reads nothing. A failed or empty catalog read records nothing and is asked again by the next statement. -- **No reading, no statement.** On PostgreSQL a statement whose leaf is compared with a table the driver holds no catalog reading of is refused with `INTERNAL_ERROR` / 500 (logged once), and never runs uncast, which on a `character(n)` key would miss a padded grant silently. A table has no reading when the catalog read fails (it runs on a pooled connection, so a pool the caller's own transaction holds times it out) or when the table was created in the caller's transaction that has not committed yet; the next statement reads the catalog again. -- **Unchanged.** A `text` or `varchar` key, which is every table the platform creates, compiles exactly as before. SQLite, MySQL, SQL Server and Oracle compile exactly as before; SQLite answers the list's rows by column affinity. MySQL and SQL Server keys are not measured against a live server yet. An Oracle `RAW(16)` uuid key is expected to fail the statement (ORA-01465, by reading: the subquery converts a dashed uuid grant to `RAW` implicitly, where the id list binds its undashed hex); it is not measured, and is tracked on #35952. +- **No reading, no statement.** On PostgreSQL a statement whose leaf is compared with a table the driver holds no catalog reading of is refused with `INTERNAL_ERROR` / 500 (logged once), and never runs uncast, which on a `character(n)` key would miss a padded grant silently. A table has no reading when the catalog read fails or finds no such relation; nothing is recorded, and the next statement reads the catalog again. +- **Read where the statement runs.** A statement in the caller's transaction reads the catalog on that transaction's own connection, inside a savepoint: it needs no second pooled connection, it sees a table the transaction created, and a failed read rolls back the savepoint alone, so the caller's transaction stays usable. That reading is kept for that transaction only. A statement outside a transaction reads on the pool and the reading is kept for the life of the driver. +- **Unchanged, and what text keys get.** A `text` or `varchar` key, which is every table the platform creates, compiles to exactly step 3's statement, with no cast. What is new for it: the first leaf statement on that table (once per driver, or once per transaction inside one) is preceded by the catalog read, and if that read fails, or finds no such relation, the statement is refused with `INTERNAL_ERROR` / 500 instead of being run. SQLite, MySQL, SQL Server and Oracle compile exactly as before and read no catalog; SQLite answers the list's rows by column affinity. MySQL and SQL Server keys are not measured against a live server yet. An Oracle `RAW(16)` uuid key is expected to fail the statement (ORA-01465, by reading: the subquery converts a dashed uuid grant to `RAW` implicitly, where the id list binds its undashed hex); it is not measured, and is tracked on #35952. diff --git a/packages/drivers/driver-sql/src/fixed-read-leaf-key-type.test.ts b/packages/drivers/driver-sql/src/fixed-read-leaf-key-type.test.ts index 329b8d558b2..3782a037071 100644 --- a/packages/drivers/driver-sql/src/fixed-read-leaf-key-type.test.ts +++ b/packages/drivers/driver-sql/src/fixed-read-leaf-key-type.test.ts @@ -11,7 +11,7 @@ import { describe, it, expect, vi } from 'vitest'; import type { Knex } from 'knex'; -import { ReadableIds, SharedRecordIds, type FilterCondition } from '@objectstack/spec/data'; +import { ReadableIds, SharedRecordIds, type DriverOptions, type FilterCondition } from '@objectstack/spec/data'; import { SqlDriver, type SqlDriverConfig } from './sql-driver.js'; import { primeFixedReadLeafKeyTypes } from './fixed-read-leaf-key-type.js'; @@ -20,12 +20,12 @@ const CHILD = 'srid_child'; class Probe extends SqlDriver { /** The prime, through this driver's own `getBuilder`, as a door calls it. */ - prime(object: string, where: unknown): Promise { - return primeFixedReadLeafKeyTypes({ getBuilder: (o) => this.getBuilder(o) }, object, where); + prime(object: string, where: unknown, options?: DriverOptions): Promise { + return primeFixedReadLeafKeyTypes({ getBuilder: (o) => this.getBuilder(o) }, object, where, options); } - compile(object: string, where: unknown): { sql: string; bindings: readonly unknown[] } { + compile(object: string, where: unknown, options?: DriverOptions): { sql: string; bindings: readonly unknown[] } { const builder: Knex.QueryBuilder = this.getBuilder(object); - this.applyFilters(builder, where); + this.applyFilters(builder, where, options); const native = builder.toSQL().toNative(); return { sql: native.sql, bindings: native.bindings }; } @@ -124,6 +124,30 @@ describe('[ADR-0155 O2] the catalog prime and the cast it puts on the inner read expect(probe.compile(EXT, leafWhere()).sql).toContain('AS "pg_catalog"."int8"'); }); + it('in a transaction the catalog is read in a savepoint on it, and the reading is kept for that transaction only', async () => { + const { probe, raw } = pgProbe(() => ({ rows: [row('id', 'pg_catalog', 'int4')] })); + const savepointRaw = vi.fn(async (..._args: unknown[]) => ({ rows: [row('id', 'pg_catalog', 'int8')] })); + // A stand-in for the caller's knex transaction: `transaction(handler)` opens the savepoint. + const savepoints = vi.fn(async (handler: (sp: { raw: typeof savepointRaw }) => unknown) => handler({ raw: savepointRaw })); + const trx = Object.assign(() => undefined, { transaction: savepoints }); + const inTrx: DriverOptions = { transaction: trx }; + await probe.prime(EXT, leafWhere(), inTrx); + expect(raw).not.toHaveBeenCalled(); + expect(savepoints).toHaveBeenCalledTimes(1); + expect(savepointRaw.mock.calls[0][1]).toEqual([EXT]); + // Read once per table for this transaction. + await probe.prime(EXT, leafWhere(), inTrx); + expect(savepoints).toHaveBeenCalledTimes(1); + expect(probe.compile(EXT, leafWhere(), inTrx).sql).toContain('AS "pg_catalog"."int8"'); + // Outside that transaction there is no reading: refused, never the transaction's. + expectRefused(() => probe.compile(EXT, leafWhere()), 'holds no reading'); + // A failed savepoint read records nothing for the transaction either. + const failing = Object.assign(() => undefined, { transaction: vi.fn(async () => { throw new Error('savepoint rolled back'); }) }); + const inFailing: DriverOptions = { transaction: failing }; + await probe.prime(EXT, leafWhere(), inFailing); + expectRefused(() => probe.compile(EXT, leafWhere(), inFailing), 'holds no reading'); + }); + it('a column the read table does not have takes no cast: the database names the missing column itself', async () => { const { probe } = pgProbe(() => ({ rows: [row('label', 'pg_catalog', 'text')] })); await probe.prime(EXT, leafWhere()); 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 2d986e3e0e4..ea84a5dd432 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 @@ -39,14 +39,20 @@ * (`INTERNAL_ERROR` / 500, logged at `error` once per knex client), never * compiled uncast. Uncast, `record_id` meets the key as text: an integer or * uuid key fails (42883), but a `character(n)` key silently misses a padded - * grant, which ADR-0155 D2 forbids. "No reading" is kept apart from "read: + * grant, which ADR-0155 D2 forbids. "No reading" is kept apart from "read: * a text key" (which takes no cast). A table has no reading when no door - * primed it, when the catalog read failed (it runs on a pooled connection, - * so a saturated pool's acquire timeout is a failure), or when the relation - * is not visible to that connection (created in the caller's uncommitted - * transaction). A failed or empty read records nothing, so the next - * statement asks again. A type knex cannot spell as one identifier is - * refused the same way. + * primed it, or when the catalog read failed or found no relation. A failed + * or empty read records nothing, so the next statement asks again. A type + * knex cannot spell as one identifier is refused the same way. + * - **Read where the statement runs (ADR-0155 D-0).** A door running in the + * caller's transaction reads the catalog ON that transaction's connection, + * inside a savepoint (a knex nested transaction): it sees a table the + * transaction created, it needs no second pooled connection (a pool the + * transaction holds cannot time it out), and a failed read rolls back the + * savepoint alone, never the caller's transaction. That reading is kept + * for that transaction only (it may describe a table that never commits). + * A door with no transaction reads on the pool and keeps the reading for + * the knex client's life. * * ## When the catalog is read * @@ -87,15 +93,25 @@ export interface FixedReadLeafKeySource { getBuilder(object: string): Knex.QueryBuilder; } +/** The caller's knex transaction, when a door's options carry one this module can open a savepoint on. */ +function savepointHost(transaction: unknown): Knex.Transaction | undefined { + // A knex transaction is a function object (it builds queries when called). + if (transaction === null || (typeof transaction !== 'object' && typeof transaction !== 'function')) return undefined; + return typeof (transaction as { transaction?: unknown }).transaction === 'function' ? (transaction as Knex.Transaction) : undefined; +} + /** A column whose base type knex cannot spell as one identifier: refused, never cast or left uncast. */ const UNSPELLABLE = Object.freeze({ unspellable: true as const }); /** One column's reading: the cast, `null` for a text key (no cast), or {@link UNSPELLABLE}. */ type ColumnReading = FixedReadLeafKeyCast | null | typeof UNSPELLABLE; -/** Per knex client: the physical table's key → each column's reading. A table with no entry has NO reading. */ +/** Per knex client: the physical table's key → each column's reading, read on the pool. A table with no entry has NO reading. */ const castsByClient = new WeakMap>>(); +/** Per caller transaction: the readings taken on its own connection, which may describe tables it has not committed. */ +const castsByTransaction = new WeakMap>>(); + /** Per knex client: whether a no-reading refusal was logged (once per client, its own flag). */ const refusalLogByClient = new WeakMap(); @@ -127,11 +143,11 @@ function tableKey(schema: string | undefined, table: string): string { return JSON.stringify([schema ?? null, table]); } -function cacheOf(client: object): Map> { - let cache = castsByClient.get(client); +function cacheOf(owner: object, caches: WeakMap>> = castsByClient): Map> { + let cache = caches.get(owner); if (cache === undefined) { cache = new Map(); - castsByClient.set(client, cache); + caches.set(owner, cache); } return cache; } @@ -177,32 +193,45 @@ function collectLeafKeyObjects(node: unknown, object: string, out: Set, * fixed-read leaf in `where` is compared with, so the filter compiler can * cast `record_id` to the key's base type (see the module docblock). A no-op * on every dialect but PostgreSQL, and for a `where` holding no leaf. + * `options.transaction`, when present, is where the catalog is read: on the + * caller's connection, inside a savepoint. */ -export async function primeFixedReadLeafKeyTypes(source: FixedReadLeafKeySource, object: string, where: unknown): Promise { +export async function primeFixedReadLeafKeyTypes( + source: FixedReadLeafKeySource, + object: string, + where: unknown, + options?: { readonly transaction?: unknown }, +): Promise { const objects = new Set(); collectLeafKeyObjects(where, object, objects, new Set()); + const trx = savepointHost(options?.transaction); for (const target of objects) { + // No options: the root client is the cache's key, as the compile site reads it. const builder = source.getBuilder(target) as Knex.QueryBuilder & { _single?: { table?: unknown; schema?: unknown } }; const client = builder.client; if (client.dialect !== 'postgresql') return; const table = builder._single?.table; if (typeof table !== 'string') continue; const schema = typeof builder._single?.schema === 'string' ? builder._single.schema : undefined; - const cache = cacheOf(client); const key = tableKey(schema, table); - if (cache.has(key)) continue; + if (cacheOf(client).has(key)) continue; + if (trx !== undefined && castsByTransaction.get(trx)?.has(key)) continue; let rows: { column_name: string; type_schema: string; type_name: string }[]; try { const relation = schema === undefined ? `format('%I', ?::text)` : `format('%I.%I', ?::text, ?::text)`; const bindings = schema === undefined ? [table] : [schema, table]; - const result = await client.raw(COLUMN_BASE_TYPES_SQL.replace('%RELATION%', relation), bindings); + const sql = COLUMN_BASE_TYPES_SQL.replace('%RELATION%', relation); + const result = trx === undefined + ? await client.raw(sql, bindings) + : await trx.transaction((savepoint) => savepoint.raw(sql, bindings)); rows = result.rows; } catch { // A catalog that cannot be read records nothing: the leaf is refused - // at compile (no reading), and the next door asks again. + // at compile (no reading), and the next door asks again. In a + // transaction the savepoint, not the caller's transaction, rolled back. continue; } - // No row: the relation is not visible to this session (yet). Nothing is recorded. + // No row: the relation is not visible to this session. Nothing is recorded. if (!Array.isArray(rows) || rows.length === 0) continue; const columns = new Map(); for (const row of rows) { @@ -212,7 +241,7 @@ export async function primeFixedReadLeafKeyTypes(source: FixedReadLeafKeySource, else reading = Object.freeze({ schema: row.type_schema, type: row.type_name }); columns.set(row.column_name, reading); } - cache.set(key, columns); + (trx === undefined ? cacheOf(client) : cacheOf(trx, castsByTransaction)).set(key, columns); } } @@ -225,7 +254,8 @@ export type FixedReadLeafKeyReading = /** * What {@link primeFixedReadLeafKeyTypes} recorded for `column` of the - * physical table `schema.table` on this knex client: + * physical table `schema.table` on this knex client, or on `transaction` + * (the caller's, when the door ran in one): * * - `cast`: a base type that is not text; * - `uncast`: a text or varchar key, or a column the read table does not @@ -240,8 +270,11 @@ export function fixedReadLeafKeyReading( schema: string | undefined, table: string, column: string, + transaction?: unknown, ): FixedReadLeafKeyReading { - const columns = castsByClient.get(client)?.get(tableKey(schema, table)); + const key = tableKey(schema, table); + const trx = savepointHost(transaction); + const columns = castsByClient.get(client)?.get(key) ?? (trx === undefined ? undefined : castsByTransaction.get(trx)?.get(key)); if (columns === undefined) return { kind: 'unread' }; const reading = columns.get(column); if (reading === undefined || reading === null) return { kind: 'uncast' }; @@ -272,14 +305,14 @@ export function refuseFixedReadLeafKey( } const at = `the $in of column '${column}' of '${object ?? '(no object)'}'`; const why = kind === 'unread' - ? 'whose type this driver holds no reading of from the PostgreSQL catalog: the catalog read failed, ' - + 'or the table is not visible to the pooled connection that reads it (created inside a transaction ' - + 'that has not committed)' + ? 'whose type this driver holds no reading of from the PostgreSQL catalog: the catalog read failed ' + + '(on the pool, or in a savepoint on the caller\'s transaction, which stays usable), or found no such ' + + 'relation from the connection that read it' : 'whose type the PostgreSQL catalog names with a spelling this driver cannot bind as one identifier'; const message = `${describeFixedReadLeaf(at, leaf)}, compared with a column ${why}. Uncast, record_id would ` + 'meet the key as text, which fails on an integer or uuid key and silently misses a padded id on a ' + 'character(n) key (ADR-0155 D2, O2). The statement was NOT run. The next statement reads the catalog ' - + 'again; a table created inside a transaction is read once that transaction commits.'; + + 'again.'; return refuseFixedReadLeafOnce(evaluator, message, logger, state, object ?? undefined); } diff --git a/packages/drivers/driver-sql/src/sql-driver-aggregation.ts b/packages/drivers/driver-sql/src/sql-driver-aggregation.ts index f60b9a26587..c730721a2f7 100644 --- a/packages/drivers/driver-sql/src/sql-driver-aggregation.ts +++ b/packages/drivers/driver-sql/src/sql-driver-aggregation.ts @@ -126,6 +126,7 @@ export class AggregationFacet { this, object, measureFilters.length > 0 ? { $and: [...(query.where ? [query.where] : []), ...measureFilters] } : query.where, + options, ); // …and the same primes for each joined related object, whose scope // compiles against its own table. @@ -133,7 +134,7 @@ export class AggregationFacet { 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); - await primeFixedReadLeafKeyTypes(this, join.parent.object, join.parent.scope); + await primeFixedReadLeafKeyTypes(this, join.parent.object, join.parent.scope, options); } const builder = this.getBuilder(object, options); // The column a FIELD names in this statement: its `external.columnMap` diff --git a/packages/drivers/driver-sql/src/sql-driver-bulk-operations.ts b/packages/drivers/driver-sql/src/sql-driver-bulk-operations.ts index ce87676970f..a70150e9a62 100644 --- a/packages/drivers/driver-sql/src/sql-driver-bulk-operations.ts +++ b/packages/drivers/driver-sql/src/sql-driver-bulk-operations.ts @@ -290,7 +290,7 @@ export class BulkOperationsFacet { // [#31395] SQL Server: which columns are GUIDs, before a text operator compiles. if (this.isMssql) await this.primeMssqlGuidColumns(object, query.where); // [ADR-0155 O2] PostgreSQL: the key type a fixed-read leaf's inner read is cast to. - await primeFixedReadLeafKeyTypes(this, object, query.where); + 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); @@ -339,7 +339,7 @@ export class BulkOperationsFacet { // [#31395] SQL Server: which columns are GUIDs, before a text operator compiles. if (this.isMssql) await this.primeMssqlGuidColumns(object, query.where); // [ADR-0155 O2] PostgreSQL: the key type a fixed-read leaf's inner read is cast to. - await primeFixedReadLeafKeyTypes(this, object, query.where); + 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); @@ -389,7 +389,7 @@ export class BulkOperationsFacet { // [#31395] SQL Server: which columns are GUIDs, before a text operator compiles. if (this.isMssql) await this.primeMssqlGuidColumns(object, query?.where); // [ADR-0155 O2] PostgreSQL: the key type a fixed-read leaf's inner read is cast to. - await primeFixedReadLeafKeyTypes(this, object, query?.where); + 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); diff --git a/packages/drivers/driver-sql/src/sql-driver-crud.ts b/packages/drivers/driver-sql/src/sql-driver-crud.ts index 20b5d538c0a..bccba9abf59 100644 --- a/packages/drivers/driver-sql/src/sql-driver-crud.ts +++ b/packages/drivers/driver-sql/src/sql-driver-crud.ts @@ -166,7 +166,7 @@ export class CrudFacet { // [#31395] …and which of its columns are GUIDs, before a text operator compiles. if (this.isMssql) await this.primeMssqlGuidColumns(object, query.where); // [ADR-0155 O2] PostgreSQL: the key type a fixed-read leaf's inner read is cast to. - await primeFixedReadLeafKeyTypes(this, object, query.where); + await primeFixedReadLeafKeyTypes(this, object, query.where, options); // The whole ORDER BY, decided once: the caller's keys plus whatever this // driver has to add to make a paged read deterministic. Derived out here // rather than inside `buildBase` so the recovery ladder below can ask diff --git a/packages/drivers/driver-sql/src/sql-driver-distinct.ts b/packages/drivers/driver-sql/src/sql-driver-distinct.ts index 975161cf223..b46092b15e3 100644 --- a/packages/drivers/driver-sql/src/sql-driver-distinct.ts +++ b/packages/drivers/driver-sql/src/sql-driver-distinct.ts @@ -61,7 +61,7 @@ export class DistinctFacet { // [#31395] SQL Server: which columns are GUIDs, before a text operator compiles. if (this.isMssql) await this.primeMssqlGuidColumns(object, filters); // [ADR-0155 O2] PostgreSQL: the key type a fixed-read leaf's inner read is cast to. - await primeFixedReadLeafKeyTypes(this, object, filters); + 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); 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 8a6f5772993..bbc4a3a3dd7 100644 --- a/packages/drivers/driver-sql/src/sql-driver-filter-helpers.ts +++ b/packages/drivers/driver-sql/src/sql-driver-filter-helpers.ts @@ -863,7 +863,7 @@ export class FilterHelpersFacet { // with type the inner read on PostgreSQL (ADR-0155 O2). 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 })); + (builder as any)[mIn](field, this.fixedReadLeafSubquery(opValue, { object: table, column: field, evaluator: this.readableIdsDriverName, 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 ad17b728add..bbbda9840b2 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 @@ -644,56 +644,58 @@ function declarePgKeyTypePins(driverOf: () => SqlDriver, knexOf: () => Knex): vo }); /** - * F1: a table this driver holds no reading of is REFUSED on PostgreSQL - * (ADR-0139 D3's envelope, `INTERNAL_ERROR` / 500, logged once), never - * compiled uncast: uncast, a `character(n)` key misses a padded grant - * silently. The catalog read runs on a pooled connection, so (a) a pool - * the caller's own transaction holds times the read out, and (b) a table - * created in the caller's uncommitted transaction is not visible to it. + * In the caller's transaction the catalog is read ON that transaction's + * connection, inside a savepoint (ADR-0155 D-0: the leaf answers the + * list's rows wherever the list does). So (a) a pool the transaction + * holds cannot time the read out, (b) a table the transaction created is + * read, and (c) a catalog read that fails there is refused + * (`INTERNAL_ERROR` / 500, logged once, F1) while the caller's + * transaction stays usable: the savepoint, not the transaction, rolled back. */ - describe('no reading is refused, never compiled uncast (ADR-0155 D2)', () => { + describe('in the caller\'s transaction the catalog is read on its connection, under a savepoint', () => { const charCase = () => PG_KEY_CASES.find((c) => c.ddl === 'character(4)')!; const leafOf = (object: string) => seamed({ id: { $in: SharedRecordIds.read(object, 'u9') } }); const inTrx = (transaction: Knex.Transaction): DriverOptions => ({ transaction }); - const refused = (err: unknown) => { - expect(err, 'refused').toBeInstanceOf(Error); - expect(err).toMatchObject({ code: 'INTERNAL_ERROR', status: 500 }); - expect((err as Error).message).toContain('holds no reading'); + const CAST = `CAST(NULLIF("record_id", '') AS "pg_catalog"."bpchar")`; + /** Every statement `trx` runs that reads the grants. */ + const grantStatementsOf = (trx: Knex.Transaction): string[] => { + const statements: string[] = []; + trx.on('query', (q: { sql: string }) => { if (q.sql.includes(GRANTS)) statements.push(q.sql); }); + return statements; + }; + const castIn = (statements: string[], n: number) => { + expect(statements).toHaveLength(n); + for (const sql of statements) expect(sql).toContain(CAST); }; - it('(a) the catalog read times out on a saturated pool: find, count and updateMany refuse, nothing is written, logged once; the next statement asks again', async () => { + it('(a) a single-connection pool the transaction holds: find, count and updateMany answer the list\'s rows, cast', async () => { const c = charCase(); const fresh = new SqlDriver({ ...PG_CELL.config(), pool: { min: 0, max: 1 }, acquireConnectionTimeout: 1000 } as SqlDriverConfig); const logger = { warn: vi.fn(), info: vi.fn(), error: vi.fn(), debug: vi.fn() }; (fresh as any).logger = logger; fresh.registerExternalObject({ name: EXT(c), fields: { label: { type: 'text' } } } as any); - const knex: Knex = (fresh as any).knex; - const statements: string[] = []; - const onQuery = (q: { sql: string }) => { if (q.sql.includes(GRANTS)) statements.push(q.sql); }; - knex.on('query', onQuery); try { - // The caller's transaction holds the pool's one connection. + // The caller's transaction holds the pool's one connection: a pooled catalog read would time out. const trx = await fresh.beginTransaction(); try { - refused(await fresh.find(EXT(c), { where: leafOf(EXT(c)) }, inTrx(trx)).catch((e) => e)); - refused(await fresh.count(EXT(c), { where: leafOf(EXT(c)) }, inTrx(trx)).catch((e) => e)); - refused(await fresh.updateMany(EXT(c), { where: leafOf(EXT(c)) }, { label: 'touched' }, inTrx(trx)).catch((e) => e)); + const statements = grantStatementsOf(trx); + const viaList = sortedIds(await fresh.find(EXT(c), { where: seamed({ id: { $in: [...c.grants] } }) }, inTrx(trx))); + expect(viaList).toEqual([...c.expected]); + expect(sortedIds(await fresh.find(EXT(c), { where: leafOf(EXT(c)) }, inTrx(trx)))).toEqual(viaList); + expect(await fresh.count(EXT(c), { where: leafOf(EXT(c)) }, inTrx(trx))).toBe(viaList.length); + expect(await fresh.updateMany(EXT(c), { where: leafOf(EXT(c)) }, { label: 'touched' }, inTrx(trx))).toBe(viaList.length); + expect(sortedIds(await trx(EXT(c)).where('label', 'touched').select('id'))).toEqual(viaList); + castIn(statements, 3); } finally { await trx.rollback(); } - expect(statements).toEqual([]); - expect(await knexOf()(EXT(c)).where('label', 'touched').count({ n: '*' })).toEqual([{ n: '0' }]); - expect(logger.error).toHaveBeenCalledTimes(1); - // Nothing was cached: with the connection back, the next statement reads the catalog and answers the list's rows. - expect(sortedIds(await fresh.find(EXT(c), { where: leafOf(EXT(c)) }))).toEqual([...c.expected]); - for (const sql of statements) expect(sql).toContain(`CAST(NULLIF("record_id", '') AS "pg_catalog"."bpchar")`); + expect(logger.error).not.toHaveBeenCalled(); } finally { - knex.removeListener('query', onQuery); await fresh.disconnect?.(); } }); - it('(b) a table created in the caller\'s uncommitted transaction: refused, then rolled back', async () => { + it('(b) a character(4) table created in the caller\'s uncommitted transaction: the leaf answers [k1], cast', async () => { const TXN = 'srid_pk_txn'; const fresh = new SqlDriver(PG_CELL.config()); fresh.registerExternalObject({ name: TXN, fields: { label: { type: 'text' } } } as any); @@ -702,10 +704,54 @@ function declarePgKeyTypePins(driverOf: () => SqlDriver, knexOf: () => Knex): vo await trx.raw(`create table ${TXN} (id character(4) primary key, label text)`); await trx(TXN).insert([{ id: 'k1', label: 'x' }, { id: 'k2', label: 'x' }]); await trx(GRANTS).insert({ id: 'srid_pk_txn_g0', object_name: TXN, recipient_type: 'user', recipient_id: 'u9', record_id: 'k1 ', access_level: 'lvl_edit', organization_id: 'org_a' }); - // Today's list, in the same transaction, answers k1: the leaf must not answer anything else. + const statements = grantStatementsOf(trx); expect(sortedIds(await fresh.find(TXN, { where: seamed({ id: { $in: ['k1 '] } }) }, inTrx(trx)))).toEqual(['k1 ']); - refused(await fresh.find(TXN, { where: leafOf(TXN) }, inTrx(trx)).catch((e) => e)); - refused(await fresh.count(TXN, { where: leafOf(TXN) }, inTrx(trx)).catch((e) => e)); + expect(sortedIds(await fresh.find(TXN, { where: leafOf(TXN) }, inTrx(trx)))).toEqual(['k1 ']); + expect(await fresh.count(TXN, { where: leafOf(TXN) }, inTrx(trx))).toBe(1); + castIn(statements, 2); + } finally { + await trx.rollback(); + await fresh.disconnect?.(); + } + }); + + it('(c) a catalog read that fails in the transaction is refused (500, logged once), and the caller\'s transaction stays usable', async () => { + const c = charCase(); + const fresh = new SqlDriver(PG_CELL.config()); + const logger = { warn: vi.fn(), info: vi.fn(), error: vi.fn(), debug: vi.fn() }; + (fresh as any).logger = logger; + fresh.registerExternalObject({ name: EXT(c), fields: { label: { type: 'text' } } } as any); + const trx = await fresh.beginTransaction(); + try { + // Test seam: inside the savepoint the catalog read becomes a statement PostgreSQL fails (22012), + // which aborts that savepoint on the caller's connection. + const ownTransaction = trx.transaction; + const openSavepoint = trx.transaction.bind(trx) as (handler: (sp: Knex.Transaction) => unknown) => Promise; + let failed = 0; + // knex defines both methods as configurable, non-writable properties. + const swap = (target: object, name: string, value: unknown) => Object.defineProperty(target, name, { value, configurable: true }); + swap(trx, 'transaction', (handler: (sp: Knex.Transaction) => unknown) => openSavepoint((sp) => { + const raw = sp.raw.bind(sp) as (...args: unknown[]) => unknown; + swap(sp, 'raw', (sql: unknown, bindings?: unknown) => { + if (!String(sql).includes('pg_attribute')) return raw(sql, bindings); + failed++; + return raw('select 1/0'); + }); + return handler(sp); + })); + const refusedFind = await fresh.find(EXT(c), { where: leafOf(EXT(c)) }, inTrx(trx)).catch((e) => e); + expect(refusedFind).toBeInstanceOf(Error); + expect(refusedFind).toMatchObject({ code: 'INTERNAL_ERROR', status: 500 }); + const refusedCount = await fresh.count(EXT(c), { where: leafOf(EXT(c)) }, inTrx(trx)).catch((e) => e); + expect(refusedCount).toMatchObject({ code: 'INTERNAL_ERROR', status: 500 }); + expect(failed).toBe(2); + expect(logger.error).toHaveBeenCalledTimes(1); + // The caller's transaction is not aborted: its next statements run. + expect((await trx.raw('select 1 as one')).rows).toEqual([{ one: 1 }]); + expect(sortedIds(await fresh.find(EXT(c), { where: seamed({ id: { $in: [...c.grants] } }) }, inTrx(trx)))).toEqual([...c.expected]); + // Nothing was cached: with the seam gone, the next leaf statement reads the catalog and answers the list's rows. + swap(trx, 'transaction', ownTransaction); + expect(sortedIds(await fresh.find(EXT(c), { where: leafOf(EXT(c)) }, inTrx(trx)))).toEqual([...c.expected]); } finally { await trx.rollback(); await fresh.disconnect?.(); 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 c3f4688b975..fb55cbba36f 100644 --- a/packages/drivers/driver-sql/src/sql-driver-internal-helpers.ts +++ b/packages/drivers/driver-sql/src/sql-driver-internal-helpers.ts @@ -180,12 +180,13 @@ export class InternalHelpersFacet { * catalog read primed it (`fixed-read-leaf-key-type.ts`), so an integer or * uuid key answers the rows today's list answers. A text key or any * other dialect projects `record_id` as before. On PostgreSQL a table - * with NO reading (no door primed it, the catalog read failed, the table - * is not visible to the pooled connection) is refused, ADR-0139 D3's + * with NO reading (no door primed it, the catalog read failed or found + * no relation; in a transaction it is read on that transaction's + * 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). */ - static fixedReadLeafSubquery(this: Pick, leaf: FixedReadLeaf, outer?: { readonly object: string | null; readonly column: string; readonly evaluator?: string }): Knex.QueryBuilder { + static fixedReadLeafSubquery(this: Pick, leaf: FixedReadLeaf, outer?: { readonly object: string | null; readonly column: string; readonly evaluator?: string; readonly transaction?: unknown }): 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` @@ -196,7 +197,7 @@ export class InternalHelpersFacet { const column = outer?.column ?? read.column; const reading = object === null ? { kind: 'unread' as const } - : fixedReadLeafKeyReading(this.knex.client, this.physicalSchemaByObject[object], this.physicalTableByObject[object] ?? object, column); + : fixedReadLeafKeyReading(this.knex.client, this.physicalSchemaByObject[object], this.physicalTableByObject[object] ?? object, column, outer?.transaction); if (reading.kind === 'unread' || reading.kind === 'unspellable') { throw refuseFixedReadLeafKey(outer?.evaluator ?? 'driver-sql', leaf, object, column, reading.kind, this.logger, this.knex.client); } diff --git a/packages/drivers/driver-sql/src/sql-driver-query-plan.ts b/packages/drivers/driver-sql/src/sql-driver-query-plan.ts index 3a5010f7234..79670448f4b 100644 --- a/packages/drivers/driver-sql/src/sql-driver-query-plan.ts +++ b/packages/drivers/driver-sql/src/sql-driver-query-plan.ts @@ -69,7 +69,7 @@ export class QueryPlanFacet { // [#31395] SQL Server: which columns are GUIDs, before a text operator compiles. if (this.isMssql) await this.primeMssqlGuidColumns(object, query.where); // [ADR-0155 O2] PostgreSQL: the key type a fixed-read leaf's inner read is cast to. - await primeFixedReadLeafKeyTypes(this, object, query.where); + 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); diff --git a/packages/drivers/driver-sql/src/sql-driver-window-functions.ts b/packages/drivers/driver-sql/src/sql-driver-window-functions.ts index 125b016c7ea..598d7a0772e 100644 --- a/packages/drivers/driver-sql/src/sql-driver-window-functions.ts +++ b/packages/drivers/driver-sql/src/sql-driver-window-functions.ts @@ -62,7 +62,7 @@ export class WindowFunctionsFacet { // [#31395] SQL Server: which columns are GUIDs, before a text operator compiles. if (this.isMssql) await this.primeMssqlGuidColumns(object, query.where); // [ADR-0155 O2] PostgreSQL: the key type a fixed-read leaf's inner read is cast to. - await primeFixedReadLeafKeyTypes(this, object, query.where); + 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); diff --git a/packages/drivers/driver-sql/src/sql-driver.ts b/packages/drivers/driver-sql/src/sql-driver.ts index 184dd175b2a..add1378c84c 100644 --- a/packages/drivers/driver-sql/src/sql-driver.ts +++ b/packages/drivers/driver-sql/src/sql-driver.ts @@ -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 }): Knex.QueryBuilder { + private fixedReadLeafSubquery(leaf: FixedReadLeaf, outer?: { readonly object: string | null; readonly column: string; readonly evaluator?: string; readonly transaction?: unknown }): 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__fixed-read-leaf-key-type.ts.json b/scripts/adr-anchors/packages__drivers__driver-sql__src__fixed-read-leaf-key-type.ts.json index 3f94d23dd2e..9eb16572bf0 100644 --- a/scripts/adr-anchors/packages__drivers__driver-sql__src__fixed-read-leaf-key-type.ts.json +++ b/scripts/adr-anchors/packages__drivers__driver-sql__src__fixed-read-leaf-key-type.ts.json @@ -3,5 +3,5 @@ "adrs": [ "ADR-0155" ], - "invariant": "ADR-0155 D-0, D2, O2 (ruled A): on PostgreSQL the fixed-read leaf's inner read projects `record_id` cast to the BASE type of the outer key column (a domain resolved to the type under it, no typmod), read once per physical table from the catalog by `primeFixedReadLeafKeyTypes` before the synchronous compile, so an integer, uuid or character(n) key answers the rows today's id list answers and a malformed grant id fails the statement as a list member does. A text or varchar key takes no cast (step 3's statement). \"No reading\" is kept apart from \"read: a text key\": a failed or empty catalog read records nothing, and a leaf compared with a table that has no reading (no door primed it, the read failed or timed out on the pool, the table is not visible to the pooled connection) or whose type cannot be spelled as one identifier is REFUSED in ADR-0139 D3's envelope (INTERNAL_ERROR / 500, logged once per knex client), never compiled uncast. Every door that compiles a `where` calls the prime beside its other catalog primes, so a door that skips it refuses every leaf; each door is pinned as the first statement of a fresh driver." + "invariant": "ADR-0155 D-0, D2, O2 (ruled A): on PostgreSQL the fixed-read leaf's inner read projects `record_id` cast to the BASE type of the outer key column (a domain resolved to the type under it, no typmod), read once per physical table from the catalog by `primeFixedReadLeafKeyTypes` before the synchronous compile, so an integer, uuid or character(n) key answers the rows today's id list answers and a malformed grant id fails the statement as a list member does. A text or varchar key takes no cast (step 3's statement). \"No reading\" is kept apart from \"read: a text key\": a failed or empty catalog read records nothing, and a leaf compared with a table that has no reading (no door primed it, the catalog read failed or found no relation) or whose type cannot be spelled as one identifier is REFUSED in ADR-0139 D3's envelope (INTERNAL_ERROR / 500, logged once per knex client), never compiled uncast. A door in the caller's transaction reads the catalog on that transaction's connection inside a savepoint (so a held pool cannot time it out, a table the transaction created is read, and a failed read leaves the transaction usable) and keeps that reading for that transaction only; with no transaction it reads on the pool. Every door that compiles a `where` calls the prime beside its other catalog primes, so a door that skips it refuses every leaf; each door is pinned as the first statement of a fresh driver." } From 1e61bf84ede6ce71a16f5c8a0c67958531dac589 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 03:46:51 +0000 Subject: [PATCH 7/7] fix(driver-sql): a savepoint derived from the caller's transaction reaches its key-type reading (ADR-0155 D-0, O2) updateMany on an object whose updated_at is only presumed issues its stamped attempt in a savepoint attemptWithoutPoisoning opens on the caller's transaction, so the leaf compiled under a transaction object the door never primed under and was refused (500) on every write, text keys included. The lookup and the prime now walk knex's parentTransaction chain: a savepoint sees what its parent sees, so the parent's reading holds there; a savepoint's own reading never reaches its parent. Live PG pin: on a fresh driver, a managed object in the presumed updated_at state, text and character(4) keys, a predicate updateMany with the write-form leaf in a caller transaction answers the list's rows and touches them. The changeset, the anchor and the prime's docblock say so, and the docblock names the savepoint's effect on concurrent statements on the same transaction. Claude-Session: https://claude.ai/code/session_01L9qibyXo4gSy8DJPNz4ANz Co-authored-by: Claude --- .changeset/35906-pg-share-grant-key-type.md | 4 +- .../src/fixed-read-leaf-key-type.test.ts | 27 +++++++++ .../src/fixed-read-leaf-key-type.ts | 30 ++++++++-- ...driver-fixed-read-leaf-conformance.test.ts | 60 +++++++++++++++++++ ...sql__src__fixed-read-leaf-key-type.ts.json | 2 +- 5 files changed, 116 insertions(+), 7 deletions(-) diff --git a/.changeset/35906-pg-share-grant-key-type.md b/.changeset/35906-pg-share-grant-key-type.md index 1c09eca4875..7e75612347d 100644 --- a/.changeset/35906-pg-share-grant-key-type.md +++ b/.changeset/35906-pg-share-grant-key-type.md @@ -11,7 +11,7 @@ No visible change on its own: nothing writes a `SharedRecordIds` leaf yet. The s - **PostgreSQL, a key that is not text.** The compiled subquery `id IN (SELECT record_id FROM sys_record_share WHERE …)` now projects `record_id` cast to the base type of the column it is compared with: `CAST(NULLIF(record_id, '') AS )`. A federated table keyed by `integer`, `bigint`, `smallint`, `numeric`, `uuid`, `character(n)` or a domain over one of them answers the same rows as the id list of the same grants: `07` names 7, an upper-case or braced uuid names its lower-case twin, and a padded grant names a `character(n)` key. Before, an integer or uuid key failed the statement with `DATABASE_ERROR` (42883), and a `character(n)` key silently missed a padded grant. - **A malformed grant id** (`abc` against an integer key) fails the statement with `DATABASE_ERROR` / 500, the same answer the id list gives for it. -- **How the type is known.** The driver reads the column types of the compared table from `pg_catalog` once, the first time a statement holding the leaf reaches that table, and keeps the answer for the life of the driver. A statement with no leaf reads nothing. A failed or empty catalog read records nothing and is asked again by the next statement. +- **How the type is known.** The driver reads the column types of the compared table from `pg_catalog` once, the first time a statement holding the leaf reaches that table, and outside a transaction keeps the answer for the life of the driver (inside one, see the next bullet). A statement with no leaf reads nothing. A failed or empty catalog read records nothing and is asked again by the next statement. - **No reading, no statement.** On PostgreSQL a statement whose leaf is compared with a table the driver holds no catalog reading of is refused with `INTERNAL_ERROR` / 500 (logged once), and never runs uncast, which on a `character(n)` key would miss a padded grant silently. A table has no reading when the catalog read fails or finds no such relation; nothing is recorded, and the next statement reads the catalog again. -- **Read where the statement runs.** A statement in the caller's transaction reads the catalog on that transaction's own connection, inside a savepoint: it needs no second pooled connection, it sees a table the transaction created, and a failed read rolls back the savepoint alone, so the caller's transaction stays usable. That reading is kept for that transaction only. A statement outside a transaction reads on the pool and the reading is kept for the life of the driver. +- **Read where the statement runs.** A statement in the caller's transaction reads the catalog on that transaction's own connection, inside a savepoint: it needs no second pooled connection, it sees a table the transaction created, and a failed read rolls back the savepoint alone, so the caller's transaction stays usable. That reading is kept for that transaction only, and reaches every savepoint derived from it, so a write the driver itself retries in a savepoint (an `updateMany` on an object whose `updated_at` column is only presumed) compiles with it; a reading a savepoint takes never reaches its parent. Each transaction therefore pays one savepoint and one catalog read per table it compares a leaf against. A statement outside a transaction reads on the pool and the reading is kept for the life of the driver. - **Unchanged, and what text keys get.** A `text` or `varchar` key, which is every table the platform creates, compiles to exactly step 3's statement, with no cast. What is new for it: the first leaf statement on that table (once per driver, or once per transaction inside one) is preceded by the catalog read, and if that read fails, or finds no such relation, the statement is refused with `INTERNAL_ERROR` / 500 instead of being run. SQLite, MySQL, SQL Server and Oracle compile exactly as before and read no catalog; SQLite answers the list's rows by column affinity. MySQL and SQL Server keys are not measured against a live server yet. An Oracle `RAW(16)` uuid key is expected to fail the statement (ORA-01465, by reading: the subquery converts a dashed uuid grant to `RAW` implicitly, where the id list binds its undashed hex); it is not measured, and is tracked on #35952. diff --git a/packages/drivers/driver-sql/src/fixed-read-leaf-key-type.test.ts b/packages/drivers/driver-sql/src/fixed-read-leaf-key-type.test.ts index 3782a037071..a6f19112012 100644 --- a/packages/drivers/driver-sql/src/fixed-read-leaf-key-type.test.ts +++ b/packages/drivers/driver-sql/src/fixed-read-leaf-key-type.test.ts @@ -148,6 +148,33 @@ describe('[ADR-0155 O2] the catalog prime and the cast it puts on the inner read expectRefused(() => probe.compile(EXT, leafWhere(), inFailing), 'holds no reading'); }); + it('a savepoint derived from the transaction reaches the transaction\'s reading; the transaction never reaches a savepoint\'s', async () => { + const { probe, raw } = pgProbe(() => ({ rows: [row('id', 'pg_catalog', 'int4')] })); + const fakeTrx = (rows: unknown[], parentTransaction?: unknown) => { + const savepointRaw = vi.fn(async () => ({ rows })); + return Object.assign(() => undefined, { + transaction: vi.fn(async (handler: (sp: { raw: typeof savepointRaw }) => unknown) => handler({ raw: savepointRaw })), + ...(parentTransaction === undefined ? {} : { parentTransaction }), + }); + }; + const parent = fakeTrx([row('id', 'pg_catalog', 'int8')]); + const inParent: DriverOptions = { transaction: parent }; + await probe.prime(EXT, leafWhere(), inParent); + // `attemptWithoutPoisoning`'s shape: a savepoint knex links to its parent. + const derived = fakeTrx([row('id', 'pg_catalog', 'uuid')], parent); + const inDerived: DriverOptions = { transaction: derived }; + expect(probe.compile(EXT, leafWhere(), inDerived).sql).toContain('AS "pg_catalog"."int8"'); + await probe.prime(EXT, leafWhere(), inDerived); + expect(derived.transaction).not.toHaveBeenCalled(); + // A reading a savepoint took is never its parent's. + const other = fakeTrx([row('id', 'pg_catalog', 'int8')]); + const sibling = fakeTrx([row('id', 'pg_catalog', 'uuid')], other); + await probe.prime(EXT, leafWhere(), { transaction: sibling }); + expect(sibling.transaction).toHaveBeenCalledTimes(1); + expectRefused(() => probe.compile(EXT, leafWhere(), { transaction: other }), 'holds no reading'); + expect(raw).not.toHaveBeenCalled(); + }); + it('a column the read table does not have takes no cast: the database names the missing column itself', async () => { const { probe } = pgProbe(() => ({ rows: [row('label', 'pg_catalog', 'text')] })); await probe.prime(EXT, leafWhere()); 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 ea84a5dd432..275148e8fbb 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 @@ -50,7 +50,8 @@ * transaction created, it needs no second pooled connection (a pool the * transaction holds cannot time it out), and a failed read rolls back the * savepoint alone, never the caller's transaction. That reading is kept - * for that transaction only (it may describe a table that never commits). + * for that transaction, and the savepoints derived from it, only (it may + * describe a table that never commits). * A door with no transaction reads on the pool and keeps the reading for * the knex client's life. * @@ -112,6 +113,24 @@ const castsByClient = new WeakMap>>(); +/** + * A transaction's reading of a table, or one an ENCLOSING transaction took: + * a savepoint derived from the caller's transaction (knex's + * `parentTransaction`, as `attemptWithoutPoisoning` opens for the presumed + * `updated_at` write) runs on the same connection and sees what its parent + * sees, so the parent's reading holds there. Never the reverse: a reading a + * savepoint took may describe a table that rolls back with it. + */ +function transactionReading(trx: Knex.Transaction, key: string): ReadonlyMap | undefined { + const seen = new Set(); + for (let at: Knex.Transaction | undefined = trx; at !== undefined && !seen.has(at); at = at.parentTransaction) { + seen.add(at); + const columns = castsByTransaction.get(at)?.get(key); + if (columns !== undefined) return columns; + } + return undefined; +} + /** Per knex client: whether a no-reading refusal was logged (once per client, its own flag). */ const refusalLogByClient = new WeakMap(); @@ -194,7 +213,10 @@ function collectLeafKeyObjects(node: unknown, object: string, out: Set, * cast `record_id` to the key's base type (see the module docblock). A no-op * on every dialect but PostgreSQL, and for a `where` holding no leaf. * `options.transaction`, when present, is where the catalog is read: on the - * caller's connection, inside a savepoint. + * caller's connection, inside a savepoint. While that savepoint is open, knex + * runs the caller's other concurrent statements on the same transaction + * inside it, so a catalog read that fails rolls back a concurrent write the + * caller made on that transaction during the read. */ export async function primeFixedReadLeafKeyTypes( source: FixedReadLeafKeySource, @@ -215,7 +237,7 @@ export async function primeFixedReadLeafKeyTypes( const schema = typeof builder._single?.schema === 'string' ? builder._single.schema : undefined; const key = tableKey(schema, table); if (cacheOf(client).has(key)) continue; - if (trx !== undefined && castsByTransaction.get(trx)?.has(key)) continue; + if (trx !== undefined && transactionReading(trx, key) !== undefined) continue; let rows: { column_name: string; type_schema: string; type_name: string }[]; try { const relation = schema === undefined ? `format('%I', ?::text)` : `format('%I.%I', ?::text, ?::text)`; @@ -274,7 +296,7 @@ export function fixedReadLeafKeyReading( ): FixedReadLeafKeyReading { const key = tableKey(schema, table); const trx = savepointHost(transaction); - const columns = castsByClient.get(client)?.get(key) ?? (trx === undefined ? undefined : castsByTransaction.get(trx)?.get(key)); + const columns = castsByClient.get(client)?.get(key) ?? (trx === undefined ? undefined : transactionReading(trx, key)); if (columns === undefined) return { kind: 'unread' }; const reading = columns.get(column); if (reading === undefined || reading === null) return { kind: 'uncast' }; 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 bbbda9840b2..0404cfb007d 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 @@ -757,6 +757,66 @@ function declarePgKeyTypePins(driverOf: () => SqlDriver, knexOf: () => Knex): vo await fresh.disconnect?.(); } }); + + /** + * `updateMany` on a managed object whose `updated_at` is only presumed + * issues its stamped attempt inside a savepoint DERIVED from the + * caller's transaction (`updateWithPresumedTimestamp` → + * `attemptWithoutPoisoning`), so the leaf compiles under a transaction + * object the door did not prime under: the reading taken on the + * caller's transaction must reach it. + */ + describe('(d) the presumed-updated_at write path compiles in a savepoint derived from the caller\'s transaction', () => { + const PRESUMED = [ + { table: 'srid_pk_presumed_text', ddl: 'text', grants: ['k1', 'k2'], expected: ['k1', 'k2'], cast: false }, + { table: 'srid_pk_presumed_char', ddl: 'character(4)', grants: ['k1 ', 'k2'], expected: ['k1 ', 'k2 '], cast: true }, + ] as const; + + beforeAll(async () => { + const driver = driverOf(); + const knex = knexOf(); + for (const p of PRESUMED) { + await driver.execute(`drop table if exists ${p.table}`); + await driver.execute(`create table ${p.table} (id ${p.ddl} primary key, label text, created_at timestamptz default now(), updated_at timestamptz default now())`); + await knex(p.table).insert([{ id: 'k1', label: 'x' }, { id: 'k2', label: 'x' }, { id: 'k3', label: 'x' }]); + await knex(GRANTS).insert(p.grants.map((g, i) => ({ id: `${p.table}_g${i}`, object_name: p.table, recipient_type: 'user', recipient_id: 'u9', record_id: g, access_level: 'lvl_edit', organization_id: 'org_a' }))); + } + }); + + afterAll(async () => { + const driver = driverOf(); + const knex = knexOf(); + for (const p of PRESUMED) { + await knex(GRANTS).where('object_name', p.table).del().catch(() => {}); + await driver.execute(`drop table if exists ${p.table}`).catch(() => {}); + } + }); + + for (const p of PRESUMED) { + it(`${p.ddl} key: a predicate updateMany with the write-form leaf answers the list's rows and touches them`, async () => { + const fresh = new SqlDriver(PG_CELL.config()); + // Managed metadata over a table this driver did not create: `updated_at` is presumed. + fresh.registerObjectMetadata([{ name: p.table, fields: { label: { type: 'text' } } } as any]); + expect((fresh as any).updatedAtStampIsPresumed(p.table)).toBe(true); + const trx = await fresh.beginTransaction(); + try { + const statements = grantStatementsOf(trx); + const where = seamed({ id: { $in: SharedRecordIds.write(p.table, 'u9', ['lvl_edit', 'lvl_full']) } }); + expect(await fresh.updateMany(p.table, { where }, { label: 'touched' }, inTrx(trx))).toBe(p.expected.length); + expect(sortedIds(await trx(p.table).where('label', 'touched').select('id'))).toEqual([...p.expected]); + // The list's rows, read in the same transaction after the write. + expect(sortedIds(await fresh.find(p.table, { where: seamed({ id: { $in: [...p.grants] } }) }, inTrx(trx)))).toEqual([...p.expected]); + // The stamped attempt landed, so the presumption settled. + expect((fresh as any).updatedAtStampIsPresumed(p.table)).toBe(false); + expect(statements.length).toBeGreaterThanOrEqual(1); + for (const sql of statements) expect(sql.includes(CAST)).toBe(p.cast); + } finally { + await trx.rollback(); + await fresh.disconnect?.(); + } + }); + } + }); }); it('reads the catalog once per table: a second statement and another verb ask it nothing', async () => { diff --git a/scripts/adr-anchors/packages__drivers__driver-sql__src__fixed-read-leaf-key-type.ts.json b/scripts/adr-anchors/packages__drivers__driver-sql__src__fixed-read-leaf-key-type.ts.json index 9eb16572bf0..87b52d4eb06 100644 --- a/scripts/adr-anchors/packages__drivers__driver-sql__src__fixed-read-leaf-key-type.ts.json +++ b/scripts/adr-anchors/packages__drivers__driver-sql__src__fixed-read-leaf-key-type.ts.json @@ -3,5 +3,5 @@ "adrs": [ "ADR-0155" ], - "invariant": "ADR-0155 D-0, D2, O2 (ruled A): on PostgreSQL the fixed-read leaf's inner read projects `record_id` cast to the BASE type of the outer key column (a domain resolved to the type under it, no typmod), read once per physical table from the catalog by `primeFixedReadLeafKeyTypes` before the synchronous compile, so an integer, uuid or character(n) key answers the rows today's id list answers and a malformed grant id fails the statement as a list member does. A text or varchar key takes no cast (step 3's statement). \"No reading\" is kept apart from \"read: a text key\": a failed or empty catalog read records nothing, and a leaf compared with a table that has no reading (no door primed it, the catalog read failed or found no relation) or whose type cannot be spelled as one identifier is REFUSED in ADR-0139 D3's envelope (INTERNAL_ERROR / 500, logged once per knex client), never compiled uncast. A door in the caller's transaction reads the catalog on that transaction's connection inside a savepoint (so a held pool cannot time it out, a table the transaction created is read, and a failed read leaves the transaction usable) and keeps that reading for that transaction only; with no transaction it reads on the pool. Every door that compiles a `where` calls the prime beside its other catalog primes, so a door that skips it refuses every leaf; each door is pinned as the first statement of a fresh driver." + "invariant": "ADR-0155 D-0, D2, O2 (ruled A): on PostgreSQL the fixed-read leaf's inner read projects `record_id` cast to the BASE type of the outer key column (a domain resolved to the type under it, no typmod), read once per physical table from the catalog by `primeFixedReadLeafKeyTypes` before the synchronous compile, so an integer, uuid or character(n) key answers the rows today's id list answers and a malformed grant id fails the statement as a list member does. A text or varchar key takes no cast (step 3's statement). \"No reading\" is kept apart from \"read: a text key\": a failed or empty catalog read records nothing, and a leaf compared with a table that has no reading (no door primed it, the catalog read failed or found no relation) or whose type cannot be spelled as one identifier is REFUSED in ADR-0139 D3's envelope (INTERNAL_ERROR / 500, logged once per knex client), never compiled uncast. A door in the caller's transaction reads the catalog on that transaction's connection inside a savepoint (so a held pool cannot time it out, a table the transaction created is read, and a failed read leaves the transaction usable) and keeps that reading for that transaction and the savepoints derived from it (knex `parentTransaction`, as the presumed-`updated_at` write path's `attemptWithoutPoisoning` opens), never the reverse; with no transaction it reads on the pool. Every door that compiles a `where` calls the prime beside its other catalog primes, so a door that skips it refuses every leaf; each door is pinned as the first statement of a fresh driver." }