Skip to content

Commit 99e085e

Browse files
committed
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 <noreply@anthropic.com>
1 parent c7cc4e2 commit 99e085e

14 files changed

Lines changed: 183 additions & 77 deletions

‎.changeset/35906-pg-share-grant-key-type.md‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,5 +12,6 @@ No visible change on its own: nothing writes a `SharedRecordIds` leaf yet. The s
1212
- **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 <type>)`. 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.
1313
- **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.
1414
- **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.
15-
- **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.
16-
- **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.
15+
- **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.
16+
- **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.
17+
- **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.

‎packages/drivers/driver-sql/src/fixed-read-leaf-key-type.test.ts‎

Lines changed: 29 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111

1212
import { describe, it, expect, vi } from 'vitest';
1313
import type { Knex } from 'knex';
14-
import { ReadableIds, SharedRecordIds, type FilterCondition } from '@objectstack/spec/data';
14+
import { ReadableIds, SharedRecordIds, type DriverOptions, type FilterCondition } from '@objectstack/spec/data';
1515
import { SqlDriver, type SqlDriverConfig } from './sql-driver.js';
1616
import { primeFixedReadLeafKeyTypes } from './fixed-read-leaf-key-type.js';
1717

@@ -20,12 +20,12 @@ const CHILD = 'srid_child';
2020

2121
class Probe extends SqlDriver {
2222
/** The prime, through this driver's own `getBuilder`, as a door calls it. */
23-
prime(object: string, where: unknown): Promise<void> {
24-
return primeFixedReadLeafKeyTypes({ getBuilder: (o) => this.getBuilder(o) }, object, where);
23+
prime(object: string, where: unknown, options?: DriverOptions): Promise<void> {
24+
return primeFixedReadLeafKeyTypes({ getBuilder: (o) => this.getBuilder(o) }, object, where, options);
2525
}
26-
compile(object: string, where: unknown): { sql: string; bindings: readonly unknown[] } {
26+
compile(object: string, where: unknown, options?: DriverOptions): { sql: string; bindings: readonly unknown[] } {
2727
const builder: Knex.QueryBuilder = this.getBuilder(object);
28-
this.applyFilters(builder, where);
28+
this.applyFilters(builder, where, options);
2929
const native = builder.toSQL().toNative();
3030
return { sql: native.sql, bindings: native.bindings };
3131
}
@@ -124,6 +124,30 @@ describe('[ADR-0155 O2] the catalog prime and the cast it puts on the inner read
124124
expect(probe.compile(EXT, leafWhere()).sql).toContain('AS "pg_catalog"."int8"');
125125
});
126126

127+
it('in a transaction the catalog is read in a savepoint on it, and the reading is kept for that transaction only', async () => {
128+
const { probe, raw } = pgProbe(() => ({ rows: [row('id', 'pg_catalog', 'int4')] }));
129+
const savepointRaw = vi.fn(async (..._args: unknown[]) => ({ rows: [row('id', 'pg_catalog', 'int8')] }));
130+
// A stand-in for the caller's knex transaction: `transaction(handler)` opens the savepoint.
131+
const savepoints = vi.fn(async (handler: (sp: { raw: typeof savepointRaw }) => unknown) => handler({ raw: savepointRaw }));
132+
const trx = Object.assign(() => undefined, { transaction: savepoints });
133+
const inTrx: DriverOptions = { transaction: trx };
134+
await probe.prime(EXT, leafWhere(), inTrx);
135+
expect(raw).not.toHaveBeenCalled();
136+
expect(savepoints).toHaveBeenCalledTimes(1);
137+
expect(savepointRaw.mock.calls[0][1]).toEqual([EXT]);
138+
// Read once per table for this transaction.
139+
await probe.prime(EXT, leafWhere(), inTrx);
140+
expect(savepoints).toHaveBeenCalledTimes(1);
141+
expect(probe.compile(EXT, leafWhere(), inTrx).sql).toContain('AS "pg_catalog"."int8"');
142+
// Outside that transaction there is no reading: refused, never the transaction's.
143+
expectRefused(() => probe.compile(EXT, leafWhere()), 'holds no reading');
144+
// A failed savepoint read records nothing for the transaction either.
145+
const failing = Object.assign(() => undefined, { transaction: vi.fn(async () => { throw new Error('savepoint rolled back'); }) });
146+
const inFailing: DriverOptions = { transaction: failing };
147+
await probe.prime(EXT, leafWhere(), inFailing);
148+
expectRefused(() => probe.compile(EXT, leafWhere(), inFailing), 'holds no reading');
149+
});
150+
127151
it('a column the read table does not have takes no cast: the database names the missing column itself', async () => {
128152
const { probe } = pgProbe(() => ({ rows: [row('label', 'pg_catalog', 'text')] }));
129153
await probe.prime(EXT, leafWhere());

‎packages/drivers/driver-sql/src/fixed-read-leaf-key-type.ts‎

Lines changed: 57 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -39,14 +39,20 @@
3939
* (`INTERNAL_ERROR` / 500, logged at `error` once per knex client), never
4040
* compiled uncast. Uncast, `record_id` meets the key as text: an integer or
4141
* uuid key fails (42883), but a `character(n)` key silently misses a padded
42-
* grant, which ADR-0155 D2 forbids. "No reading" is kept apart from "read:
42+
* grant, which ADR-0155 D2 forbids. "No reading" is kept apart from "read:
4343
* a text key" (which takes no cast). A table has no reading when no door
44-
* primed it, when the catalog read failed (it runs on a pooled connection,
45-
* so a saturated pool's acquire timeout is a failure), or when the relation
46-
* is not visible to that connection (created in the caller's uncommitted
47-
* transaction). A failed or empty read records nothing, so the next
48-
* statement asks again. A type knex cannot spell as one identifier is
49-
* refused the same way.
44+
* primed it, or when the catalog read failed or found no relation. A failed
45+
* or empty read records nothing, so the next statement asks again. A type
46+
* knex cannot spell as one identifier is refused the same way.
47+
* - **Read where the statement runs (ADR-0155 D-0).** A door running in the
48+
* caller's transaction reads the catalog ON that transaction's connection,
49+
* inside a savepoint (a knex nested transaction): it sees a table the
50+
* transaction created, it needs no second pooled connection (a pool the
51+
* transaction holds cannot time it out), and a failed read rolls back the
52+
* savepoint alone, never the caller's transaction. That reading is kept
53+
* for that transaction only (it may describe a table that never commits).
54+
* A door with no transaction reads on the pool and keeps the reading for
55+
* the knex client's life.
5056
*
5157
* ## When the catalog is read
5258
*
@@ -87,15 +93,25 @@ export interface FixedReadLeafKeySource {
8793
getBuilder(object: string): Knex.QueryBuilder;
8894
}
8995

96+
/** The caller's knex transaction, when a door's options carry one this module can open a savepoint on. */
97+
function savepointHost(transaction: unknown): Knex.Transaction | undefined {
98+
// A knex transaction is a function object (it builds queries when called).
99+
if (transaction === null || (typeof transaction !== 'object' && typeof transaction !== 'function')) return undefined;
100+
return typeof (transaction as { transaction?: unknown }).transaction === 'function' ? (transaction as Knex.Transaction) : undefined;
101+
}
102+
90103
/** A column whose base type knex cannot spell as one identifier: refused, never cast or left uncast. */
91104
const UNSPELLABLE = Object.freeze({ unspellable: true as const });
92105

93106
/** One column's reading: the cast, `null` for a text key (no cast), or {@link UNSPELLABLE}. */
94107
type ColumnReading = FixedReadLeafKeyCast | null | typeof UNSPELLABLE;
95108

96-
/** Per knex client: the physical table's key → each column's reading. A table with no entry has NO reading. */
109+
/** Per knex client: the physical table's key → each column's reading, read on the pool. A table with no entry has NO reading. */
97110
const castsByClient = new WeakMap<object, Map<string, ReadonlyMap<string, ColumnReading>>>();
98111

112+
/** Per caller transaction: the readings taken on its own connection, which may describe tables it has not committed. */
113+
const castsByTransaction = new WeakMap<object, Map<string, ReadonlyMap<string, ColumnReading>>>();
114+
99115
/** Per knex client: whether a no-reading refusal was logged (once per client, its own flag). */
100116
const refusalLogByClient = new WeakMap<object, { logged: boolean }>();
101117

@@ -127,11 +143,11 @@ function tableKey(schema: string | undefined, table: string): string {
127143
return JSON.stringify([schema ?? null, table]);
128144
}
129145

130-
function cacheOf(client: object): Map<string, ReadonlyMap<string, ColumnReading>> {
131-
let cache = castsByClient.get(client);
146+
function cacheOf(owner: object, caches: WeakMap<object, Map<string, ReadonlyMap<string, ColumnReading>>> = castsByClient): Map<string, ReadonlyMap<string, ColumnReading>> {
147+
let cache = caches.get(owner);
132148
if (cache === undefined) {
133149
cache = new Map();
134-
castsByClient.set(client, cache);
150+
caches.set(owner, cache);
135151
}
136152
return cache;
137153
}
@@ -177,32 +193,45 @@ function collectLeafKeyObjects(node: unknown, object: string, out: Set<string>,
177193
* fixed-read leaf in `where` is compared with, so the filter compiler can
178194
* cast `record_id` to the key's base type (see the module docblock). A no-op
179195
* on every dialect but PostgreSQL, and for a `where` holding no leaf.
196+
* `options.transaction`, when present, is where the catalog is read: on the
197+
* caller's connection, inside a savepoint.
180198
*/
181-
export async function primeFixedReadLeafKeyTypes(source: FixedReadLeafKeySource, object: string, where: unknown): Promise<void> {
199+
export async function primeFixedReadLeafKeyTypes(
200+
source: FixedReadLeafKeySource,
201+
object: string,
202+
where: unknown,
203+
options?: { readonly transaction?: unknown },
204+
): Promise<void> {
182205
const objects = new Set<string>();
183206
collectLeafKeyObjects(where, object, objects, new Set());
207+
const trx = savepointHost(options?.transaction);
184208
for (const target of objects) {
209+
// No options: the root client is the cache's key, as the compile site reads it.
185210
const builder = source.getBuilder(target) as Knex.QueryBuilder & { _single?: { table?: unknown; schema?: unknown } };
186211
const client = builder.client;
187212
if (client.dialect !== 'postgresql') return;
188213
const table = builder._single?.table;
189214
if (typeof table !== 'string') continue;
190215
const schema = typeof builder._single?.schema === 'string' ? builder._single.schema : undefined;
191-
const cache = cacheOf(client);
192216
const key = tableKey(schema, table);
193-
if (cache.has(key)) continue;
217+
if (cacheOf(client).has(key)) continue;
218+
if (trx !== undefined && castsByTransaction.get(trx)?.has(key)) continue;
194219
let rows: { column_name: string; type_schema: string; type_name: string }[];
195220
try {
196221
const relation = schema === undefined ? `format('%I', ?::text)` : `format('%I.%I', ?::text, ?::text)`;
197222
const bindings = schema === undefined ? [table] : [schema, table];
198-
const result = await client.raw(COLUMN_BASE_TYPES_SQL.replace('%RELATION%', relation), bindings);
223+
const sql = COLUMN_BASE_TYPES_SQL.replace('%RELATION%', relation);
224+
const result = trx === undefined
225+
? await client.raw(sql, bindings)
226+
: await trx.transaction((savepoint) => savepoint.raw(sql, bindings));
199227
rows = result.rows;
200228
} catch {
201229
// A catalog that cannot be read records nothing: the leaf is refused
202-
// at compile (no reading), and the next door asks again.
230+
// at compile (no reading), and the next door asks again. In a
231+
// transaction the savepoint, not the caller's transaction, rolled back.
203232
continue;
204233
}
205-
// No row: the relation is not visible to this session (yet). Nothing is recorded.
234+
// No row: the relation is not visible to this session. Nothing is recorded.
206235
if (!Array.isArray(rows) || rows.length === 0) continue;
207236
const columns = new Map<string, ColumnReading>();
208237
for (const row of rows) {
@@ -212,7 +241,7 @@ export async function primeFixedReadLeafKeyTypes(source: FixedReadLeafKeySource,
212241
else reading = Object.freeze({ schema: row.type_schema, type: row.type_name });
213242
columns.set(row.column_name, reading);
214243
}
215-
cache.set(key, columns);
244+
(trx === undefined ? cacheOf(client) : cacheOf(trx, castsByTransaction)).set(key, columns);
216245
}
217246
}
218247

@@ -225,7 +254,8 @@ export type FixedReadLeafKeyReading =
225254

226255
/**
227256
* What {@link primeFixedReadLeafKeyTypes} recorded for `column` of the
228-
* physical table `schema.table` on this knex client:
257+
* physical table `schema.table` on this knex client, or on `transaction`
258+
* (the caller's, when the door ran in one):
229259
*
230260
* - `cast`: a base type that is not text;
231261
* - `uncast`: a text or varchar key, or a column the read table does not
@@ -240,8 +270,11 @@ export function fixedReadLeafKeyReading(
240270
schema: string | undefined,
241271
table: string,
242272
column: string,
273+
transaction?: unknown,
243274
): FixedReadLeafKeyReading {
244-
const columns = castsByClient.get(client)?.get(tableKey(schema, table));
275+
const key = tableKey(schema, table);
276+
const trx = savepointHost(transaction);
277+
const columns = castsByClient.get(client)?.get(key) ?? (trx === undefined ? undefined : castsByTransaction.get(trx)?.get(key));
245278
if (columns === undefined) return { kind: 'unread' };
246279
const reading = columns.get(column);
247280
if (reading === undefined || reading === null) return { kind: 'uncast' };
@@ -272,14 +305,14 @@ export function refuseFixedReadLeafKey(
272305
}
273306
const at = `the $in of column '${column}' of '${object ?? '(no object)'}'`;
274307
const why = kind === 'unread'
275-
? 'whose type this driver holds no reading of from the PostgreSQL catalog: the catalog read failed, '
276-
+ 'or the table is not visible to the pooled connection that reads it (created inside a transaction '
277-
+ 'that has not committed)'
308+
? 'whose type this driver holds no reading of from the PostgreSQL catalog: the catalog read failed '
309+
+ '(on the pool, or in a savepoint on the caller\'s transaction, which stays usable), or found no such '
310+
+ 'relation from the connection that read it'
278311
: 'whose type the PostgreSQL catalog names with a spelling this driver cannot bind as one identifier';
279312
const message = `${describeFixedReadLeaf(at, leaf)}, compared with a column ${why}. Uncast, record_id would `
280313
+ 'meet the key as text, which fails on an integer or uuid key and silently misses a padded id on a '
281314
+ 'character(n) key (ADR-0155 D2, O2). The statement was NOT run. The next statement reads the catalog '
282-
+ 'again; a table created inside a transaction is read once that transaction commits.';
315+
+ 'again.';
283316
return refuseFixedReadLeafOnce(evaluator, message, logger, state, object ?? undefined);
284317
}
285318

‎packages/drivers/driver-sql/src/sql-driver-aggregation.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -126,14 +126,15 @@ export class AggregationFacet {
126126
this,
127127
object,
128128
measureFilters.length > 0 ? { $and: [...(query.where ? [query.where] : []), ...measureFilters] } : query.where,
129+
options,
129130
);
130131
// …and the same primes for each joined related object, whose scope
131132
// compiles against its own table.
132133
for (const join of relationJoins ?? []) {
133134
if (join.parent === null) continue;
134135
if (this.isMssql) await this.primeMssqlGuidColumns(join.parent.object, join.parent.scope);
135136
if (this.isOracle) await this.primeOracleRawUuidColumns(join.parent.object);
136-
await primeFixedReadLeafKeyTypes(this, join.parent.object, join.parent.scope);
137+
await primeFixedReadLeafKeyTypes(this, join.parent.object, join.parent.scope, options);
137138
}
138139
const builder = this.getBuilder(object, options);
139140
// The column a FIELD names in this statement: its `external.columnMap`

0 commit comments

Comments
 (0)