Skip to content

Commit b481820

Browse files
committed
refactor(objectql): move execute and the transaction-routing bodies out of engine.ts
Cut 7 of the engine.ts split. The bodies of `execute`, `warnTransactionUnsupported` and `enforceTransactionOrigin` move unedited into `engine-execute-transactions.ts`; each method stays on `ObjectQL` and hands its body the members it reads through `ExecuteTransactionsHost` (fields as getters, methods as late-bound closures). The engine.ts ADR anchor paragraph describes `enforceTransactionOrigin`, so the new module carries that paragraph in its own `scripts/adr-anchors/` entry. Claude-Session: https://claude.ai/code/session_017XKjAUHgJooyUifvSi4RjW Co-authored-by: Claude <noreply@anthropic.com>
1 parent a6e8f95 commit b481820

3 files changed

Lines changed: 239 additions & 107 deletions

File tree

Lines changed: 199 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,199 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [#25522 cut 7] The raw-command and transaction-routing bodies of `ObjectQL`,
5+
* moved out of `engine.ts` whole: `execute` (the driver a raw command goes to,
6+
* its two call shapes, and the redaction of a driver fault it propagates),
7+
* `warnTransactionUnsupported` (the once-per-driver report of ADR-0119's
8+
* declared degrade) and `enforceTransactionOrigin` (what a write routed to a
9+
* driver the open transaction does not cover gets: refused, or, for an
10+
* append-only system ledger under ADR-0057, executed outside it).
11+
*
12+
* A MOVE, not a redesign. Each exported function below is the body of the
13+
* `ObjectQL` method of the same name as it stood, re-indented one level and
14+
* otherwise unedited: the same driver-selection order, the same two refusals
15+
* before any command is sent, the same once-per-name warning and its two
16+
* causes, the same refusal before hooks run and the same once-per-transaction
17+
* debug line. Each method's docblock stays on the method in `engine.ts`, which
18+
* is still the contract.
19+
*
20+
* What stays in the class: `transaction`, because ADR-0119 cites it by
21+
* `engine.ts#transaction` and ADR-0067's join lives in it; `runOpenedUnit`,
22+
* `isClosedUnitHandle`, `newTransactionScope` and `datasourceNameOf`, whose
23+
* bodies are shorter than the host literal moving them would cost.
24+
*
25+
* ## How the moved bodies reach the class
26+
*
27+
* The shape #23050 set for `rest-server.ts` (its `data-action-routes.ts`
28+
* header carries the full reasoning), applied per method as
29+
* `engine-hook-dispatch.ts` applies it. The class keeps all three methods —
30+
* the published `.d.ts` lists each one's name and position, and `execute` is
31+
* public — and each body is one literal of exactly the
32+
* {@link ExecuteTransactionsHost} members that method reads, plus a `.call`.
33+
* The fields the bodies read (`drivers`, `defaultDriver`, `txStore`,
34+
* `transactionUnsupportedReported`, `logger`) go as GETTERS, so each read
35+
* happens when the body makes it: `registerDriver` changes the driver map and
36+
* the default, and a body sees whatever is installed at the moment it reads,
37+
* as it did. The methods they call (`getDriver`, `datasourceNameOf`,
38+
* `isSystemLedgerObject`) go as late-bound closures over the instance, so a
39+
* double or spy set on the engine is still the one a call reaches.
40+
*
41+
* This module imports the engine only as a TYPE, so there is no module cycle
42+
* at run time, and nothing re-exports it, so the published surface does not
43+
* move.
44+
*/
45+
46+
import type { IDataDriver } from '@objectstack/core';
47+
import { redactPropagatedDriverFault } from '@objectstack/types';
48+
import { CrossDatasourceTransactionWriteError } from './transaction-errors.js';
49+
import type { ObjectQL } from './engine.js';
50+
51+
/**
52+
* The `ObjectQL` members the functions below read — every one of them, and no
53+
* other; each function's `this` is the `Pick` of the members IT reads. Each is
54+
* typed AS the class member (an indexed access on the class), so a change to a
55+
* member's type on the class is a change here too, and naming a member the
56+
* class does not have is a compile error. See the module header for which
57+
* members are getters.
58+
*/
59+
export interface ExecuteTransactionsHost {
60+
readonly drivers: ObjectQL['drivers'];
61+
readonly defaultDriver: ObjectQL['defaultDriver'];
62+
readonly txStore: ObjectQL['txStore'];
63+
readonly transactionUnsupportedReported: ObjectQL['transactionUnsupportedReported'];
64+
readonly logger: ObjectQL['logger'];
65+
getDriver: ObjectQL['getDriver'];
66+
datasourceNameOf: ObjectQL['datasourceNameOf'];
67+
isSystemLedgerObject: ObjectQL['isSystemLedgerObject'];
68+
}
69+
70+
/** The body of `ObjectQL#execute`; the method's docblock there is its contract. */
71+
export async function execute(
72+
this: Pick<ExecuteTransactionsHost, 'getDriver' | 'drivers' | 'defaultDriver'>,
73+
command: any,
74+
options?: Record<string, any>,
75+
): Promise<any> {
76+
// Driver selection priority:
77+
// 1. options.object → route via getDriver(objectName)
78+
// 2. options.datasource → explicit driver name
79+
// 3. default driver (set via datasourceMapping or defaultDriver)
80+
// This lets system services (e.g. PackageService, AuditService) issue raw
81+
// SQL against the control-plane / default DB without having to know the
82+
// object name behind every CREATE TABLE / SELECT statement.
83+
let driver: IDataDriver | undefined;
84+
if (options?.object) {
85+
driver = this.getDriver(options.object);
86+
} else if (options?.datasource && this.drivers.has(options.datasource)) {
87+
driver = this.drivers.get(options.datasource);
88+
} else if (this.defaultDriver && this.drivers.has(this.defaultDriver)) {
89+
driver = this.drivers.get(this.defaultDriver);
90+
} else if (this.drivers.size === 1) {
91+
// Single registered driver — unambiguously the right one.
92+
driver = this.drivers.values().next().value;
93+
}
94+
95+
if (!driver) {
96+
throw new Error(
97+
'Execute requires options.object to select a driver, or a default driver to be configured. ' +
98+
'Configure datasourceMapping with `default: true` or pass `{ object }` / `{ datasource }` in options.',
99+
);
100+
}
101+
if (!driver.execute) {
102+
throw new Error('Selected driver does not implement execute()');
103+
}
104+
105+
// Support both call shapes:
106+
// execute('SELECT ...', { args: [...] })
107+
// execute({ sql: 'SELECT ...', args: [...] })
108+
let rawCommand: any = command;
109+
let params: any[] | undefined = options?.args ?? options?.params;
110+
if (command && typeof command === 'object' && !Array.isArray(command) && 'sql' in command) {
111+
rawCommand = command.sql;
112+
if (params === undefined) {
113+
params = command.args ?? command.params;
114+
}
115+
}
116+
117+
// [#21274] A boundary outside the middleware seam: the raw command's
118+
// bound `params` are the caller's values, and the driver's refusal
119+
// carries the dialect error on its `cause`.
120+
//
121+
// [#21345] And the one door whose statement the engine did not compose:
122+
// it may open with a word the shared leak predicate does not list (a
123+
// common-table-expression form, a dialect's upsert or merge verb), so
124+
// the cut must not wait for the predicate to recognise it. The door
125+
// knows it sent a statement, and says so.
126+
try {
127+
return await driver.execute(rawCommand, params, options);
128+
} catch (e) {
129+
throw redactPropagatedDriverFault(e, { statementSent: true });
130+
}
131+
}
132+
133+
/** The body of `ObjectQL#warnTransactionUnsupported`; the method's docblock there is its contract. */
134+
export function warnTransactionUnsupported(
135+
this: Pick<ExecuteTransactionsHost, 'transactionUnsupportedReported' | 'logger'>,
136+
datasource: string | undefined,
137+
declaredUnsupported = false,
138+
): void {
139+
const name = datasource ?? '<no default datasource>';
140+
if (this.transactionUnsupportedReported.has(name)) return;
141+
this.transactionUnsupportedReported.add(name);
142+
// [#18063] The two reasons reach the same degrade and must not read the
143+
// same. Telling an operator a Turso REMOTE datasource "has no
144+
// beginTransaction" sends them looking for a missing method on a class that
145+
// publishes one; the fix for that reason is a different transport, not a
146+
// different driver.
147+
const cause = declaredUnsupported
148+
? `driver '${name}' declares supports.transactionsUnsupported — its transport cannot carry a ` +
149+
'transaction handle even though it inherits beginTransaction'
150+
: `driver '${name}' has no beginTransaction`;
151+
const remedy = declaredUnsupported
152+
? 'Point this datasource at a transport that honours transactions (for libSQL: the local or ' +
153+
'embedded-replica mode rather than the remote one), or have the caller fail '
154+
: 'Register a driver that implements beginTransaction for this datasource, or have the caller fail ';
155+
this.logger.warn(
156+
`transaction() requested a transaction but ${cause} — ` +
157+
'running WITHOUT transaction or rollback. Every write the callback makes commits as it executes, ' +
158+
'so a later throw leaves the earlier ones PERSISTED even though the call rejects as if the whole ' +
159+
'unit of work had been undone; no caller is told, and the records stay behind. ' +
160+
remedy +
161+
"closed itself when it cannot tolerate losing atomicity (batchData's atomic gate, ADR-0119 D4, is " +
162+
'the pattern). Reported once per driver per engine instance.',
163+
{ datasource: name, declaredUnsupported },
164+
);
165+
}
166+
167+
/** The body of `ObjectQL#enforceTransactionOrigin`; the method's docblock there is its contract. */
168+
export function enforceTransactionOrigin(
169+
this: Pick<ExecuteTransactionsHost, 'txStore' | 'datasourceNameOf' | 'isSystemLedgerObject' | 'logger'>,
170+
objectName: string,
171+
driver: IDataDriver,
172+
operation: 'insert' | 'update' | 'delete',
173+
): void {
174+
const scope = this.txStore.getStore()?.scope;
175+
// No engine-owned transaction in scope (or a handle threaded explicitly by
176+
// the sandbox trio, which this store never sees) — nothing to be outside
177+
// of. See `transactionCoversDriverFor` for why that limit is declared.
178+
if (!scope) return;
179+
// Identity, not name: this is about riding the same connection.
180+
if (driver === scope.driver) return;
181+
const target = this.datasourceNameOf(driver);
182+
183+
if (!this.isSystemLedgerObject(objectName)) {
184+
throw new CrossDatasourceTransactionWriteError(objectName, operation, target, scope.datasource);
185+
}
186+
187+
if (scope.reportedOutOfScope.has(target)) return;
188+
scope.reportedOutOfScope.add(target);
189+
this.logger.debug(
190+
`${operation} of '${objectName}' inside transaction() is routed to datasource '${target}' while the ` +
191+
`transaction is open on '${scope.datasource}' — executing it OUTSIDE the transaction, on its own ` +
192+
'connection (ADR-0057 §3.6 system ledger — the one class carved out of the cross-datasource write ' +
193+
'refusal). It commits independently and will ' +
194+
'SURVIVE a rollback of this transaction: an audit/telemetry/event row may describe a write that was ' +
195+
'undone. That is the decided direction of error for an append-only ledger — an extra reconcilable ' +
196+
'row beats a missing row for a write that did commit. Said once per transaction per datasource.',
197+
{ object: objectName, operation, datasource: target, transactionDatasource: scope.datasource },
198+
);
199+
}

‎packages/objectql/src/engine.ts‎

Lines changed: 31 additions & 107 deletions
Original file line numberDiff line numberDiff line change
@@ -133,6 +133,9 @@ import {
133133
dispatchPerRowBeforeHooks,
134134
inAfterAbortUnit,
135135
} from './engine-hook-dispatch.js';
136+
// [#25522 cut 7] The raw-command and transaction-routing bodies; the methods of
137+
// the same names below hand each body the members it reads (`ExecuteTransactionsHost`).
138+
import { enforceTransactionOrigin, execute, warnTransactionUnsupported } from './engine-execute-transactions.js';
136139
import { ExecutionContext, ExecutionContextSchema, type InstalledPackageSource } from '@objectstack/spec/kernel';
137140
import { isStoredMetadataBodyObject } from '@objectstack/spec/kernel';
138141
import type { FlowFunctionEffect } from '@objectstack/spec/automation';
@@ -184,7 +187,7 @@ import {
184187
import { WriteEpoch, isWriteEpochOperation } from './write-epoch.js';
185188
import { bridgeAuthzInvalidation } from './authz-invalidation-bridge.js';
186189
import { SummaryRecomputeError, type SummaryRecomputeFailure } from './summary-errors.js';
187-
import { CrossDatasourceTransactionWriteError, TransactionUnsupportedError } from './transaction-errors.js';
190+
import { TransactionUnsupportedError } from './transaction-errors.js';
188191
import {
189192
aggregateSummaryValue,
190193
summaryEmptySetValue,
@@ -21773,61 +21776,15 @@ export class ObjectQL implements IObjectQLEngine {
2177321776
* whenever feasible — they auto-apply tenancy + soft-delete + audit warnings.
2177421777
*/
2177521778
async execute(command: any, options?: Record<string, any>): Promise<any> {
21776-
// Driver selection priority:
21777-
// 1. options.object → route via getDriver(objectName)
21778-
// 2. options.datasource → explicit driver name
21779-
// 3. default driver (set via datasourceMapping or defaultDriver)
21780-
// This lets system services (e.g. PackageService, AuditService) issue raw
21781-
// SQL against the control-plane / default DB without having to know the
21782-
// object name behind every CREATE TABLE / SELECT statement.
21783-
let driver: IDataDriver | undefined;
21784-
if (options?.object) {
21785-
driver = this.getDriver(options.object);
21786-
} else if (options?.datasource && this.drivers.has(options.datasource)) {
21787-
driver = this.drivers.get(options.datasource);
21788-
} else if (this.defaultDriver && this.drivers.has(this.defaultDriver)) {
21789-
driver = this.drivers.get(this.defaultDriver);
21790-
} else if (this.drivers.size === 1) {
21791-
// Single registered driver — unambiguously the right one.
21792-
driver = this.drivers.values().next().value;
21793-
}
21794-
21795-
if (!driver) {
21796-
throw new Error(
21797-
'Execute requires options.object to select a driver, or a default driver to be configured. ' +
21798-
'Configure datasourceMapping with `default: true` or pass `{ object }` / `{ datasource }` in options.',
21799-
);
21800-
}
21801-
if (!driver.execute) {
21802-
throw new Error('Selected driver does not implement execute()');
21803-
}
21804-
21805-
// Support both call shapes:
21806-
// execute('SELECT ...', { args: [...] })
21807-
// execute({ sql: 'SELECT ...', args: [...] })
21808-
let rawCommand: any = command;
21809-
let params: any[] | undefined = options?.args ?? options?.params;
21810-
if (command && typeof command === 'object' && !Array.isArray(command) && 'sql' in command) {
21811-
rawCommand = command.sql;
21812-
if (params === undefined) {
21813-
params = command.args ?? command.params;
21814-
}
21815-
}
21816-
21817-
// [#21274] A boundary outside the middleware seam: the raw command's
21818-
// bound `params` are the caller's values, and the driver's refusal
21819-
// carries the dialect error on its `cause`.
21820-
//
21821-
// [#21345] And the one door whose statement the engine did not compose:
21822-
// it may open with a word the shared leak predicate does not list (a
21823-
// common-table-expression form, a dialect's upsert or merge verb), so
21824-
// the cut must not wait for the predicate to recognise it. The door
21825-
// knows it sent a statement, and says so.
21826-
try {
21827-
return await driver.execute(rawCommand, params, options);
21828-
} catch (e) {
21829-
throw redactPropagatedDriverFault(e, { statementSent: true });
21830-
}
21779+
// [#25522 cut 7] The body moved to `engine-execute-transactions.ts` (see `ExecuteTransactionsHost`).
21780+
const readDrivers = () => this.drivers;
21781+
const readDefaultDriver = () => this.defaultDriver;
21782+
const host: ThisParameterType<typeof execute> = {
21783+
getDriver: (...a) => this.getDriver(...a),
21784+
get drivers() { return readDrivers(); },
21785+
get defaultDriver() { return readDefaultDriver(); },
21786+
};
21787+
return execute.call(host, command, options);
2183121788
}
2183221789

2183321790
/**
@@ -22044,32 +22001,14 @@ export class ObjectQL implements IObjectQLEngine {
2204422001
* doubles, foreign engines) reach it on EVERY call.
2204522002
*/
2204622003
private warnTransactionUnsupported(datasource: string | undefined, declaredUnsupported = false): void {
22047-
const name = datasource ?? '<no default datasource>';
22048-
if (this.transactionUnsupportedReported.has(name)) return;
22049-
this.transactionUnsupportedReported.add(name);
22050-
// [#18063] The two reasons reach the same degrade and must not read the
22051-
// same. Telling an operator a Turso REMOTE datasource "has no
22052-
// beginTransaction" sends them looking for a missing method on a class that
22053-
// publishes one; the fix for that reason is a different transport, not a
22054-
// different driver.
22055-
const cause = declaredUnsupported
22056-
? `driver '${name}' declares supports.transactionsUnsupported — its transport cannot carry a ` +
22057-
'transaction handle even though it inherits beginTransaction'
22058-
: `driver '${name}' has no beginTransaction`;
22059-
const remedy = declaredUnsupported
22060-
? 'Point this datasource at a transport that honours transactions (for libSQL: the local or ' +
22061-
'embedded-replica mode rather than the remote one), or have the caller fail '
22062-
: 'Register a driver that implements beginTransaction for this datasource, or have the caller fail ';
22063-
this.logger.warn(
22064-
`transaction() requested a transaction but ${cause} — ` +
22065-
'running WITHOUT transaction or rollback. Every write the callback makes commits as it executes, ' +
22066-
'so a later throw leaves the earlier ones PERSISTED even though the call rejects as if the whole ' +
22067-
'unit of work had been undone; no caller is told, and the records stay behind. ' +
22068-
remedy +
22069-
"closed itself when it cannot tolerate losing atomicity (batchData's atomic gate, ADR-0119 D4, is " +
22070-
'the pattern). Reported once per driver per engine instance.',
22071-
{ datasource: name, declaredUnsupported },
22072-
);
22004+
// [#25522 cut 7] The body moved to `engine-execute-transactions.ts` (see `ExecuteTransactionsHost`).
22005+
const readTransactionUnsupportedReported = () => this.transactionUnsupportedReported;
22006+
const readLogger = () => this.logger;
22007+
const host: ThisParameterType<typeof warnTransactionUnsupported> = {
22008+
get transactionUnsupportedReported() { return readTransactionUnsupportedReported(); },
22009+
get logger() { return readLogger(); },
22010+
};
22011+
return warnTransactionUnsupported.call(host, datasource, declaredUnsupported);
2207322012
}
2207422013

2207522014
/**
@@ -22121,31 +22060,16 @@ export class ObjectQL implements IObjectQLEngine {
2212122060
driver: IDataDriver,
2212222061
operation: 'insert' | 'update' | 'delete',
2212322062
): void {
22124-
const scope = this.txStore.getStore()?.scope;
22125-
// No engine-owned transaction in scope (or a handle threaded explicitly by
22126-
// the sandbox trio, which this store never sees) — nothing to be outside
22127-
// of. See `transactionCoversDriverFor` for why that limit is declared.
22128-
if (!scope) return;
22129-
// Identity, not name: this is about riding the same connection.
22130-
if (driver === scope.driver) return;
22131-
const target = this.datasourceNameOf(driver);
22132-
22133-
if (!this.isSystemLedgerObject(objectName)) {
22134-
throw new CrossDatasourceTransactionWriteError(objectName, operation, target, scope.datasource);
22135-
}
22136-
22137-
if (scope.reportedOutOfScope.has(target)) return;
22138-
scope.reportedOutOfScope.add(target);
22139-
this.logger.debug(
22140-
`${operation} of '${objectName}' inside transaction() is routed to datasource '${target}' while the ` +
22141-
`transaction is open on '${scope.datasource}' — executing it OUTSIDE the transaction, on its own ` +
22142-
'connection (ADR-0057 §3.6 system ledger — the one class carved out of the cross-datasource write ' +
22143-
'refusal). It commits independently and will ' +
22144-
'SURVIVE a rollback of this transaction: an audit/telemetry/event row may describe a write that was ' +
22145-
'undone. That is the decided direction of error for an append-only ledger — an extra reconcilable ' +
22146-
'row beats a missing row for a write that did commit. Said once per transaction per datasource.',
22147-
{ object: objectName, operation, datasource: target, transactionDatasource: scope.datasource },
22148-
);
22063+
// [#25522 cut 7] The body moved to `engine-execute-transactions.ts` (see `ExecuteTransactionsHost`).
22064+
const readTxStore = () => this.txStore;
22065+
const readLogger = () => this.logger;
22066+
const host: ThisParameterType<typeof enforceTransactionOrigin> = {
22067+
get txStore() { return readTxStore(); },
22068+
datasourceNameOf: (...a) => this.datasourceNameOf(...a),
22069+
isSystemLedgerObject: (...a) => this.isSystemLedgerObject(...a),
22070+
get logger() { return readLogger(); },
22071+
};
22072+
return enforceTransactionOrigin.call(host, objectName, driver, operation);
2214922073
}
2215022074

2215122075
// ============================================

0 commit comments

Comments
 (0)