Skip to content

Commit 0379b76

Browse files
committed
refactor(driver-sql): move the presumed-timestamp update out of sql-driver.ts into sql-driver-presumed-timestamp.ts
The bodies of updateWithPresumedTimestamp (the UPDATE whose updated_at stamp is a presumption, recovering once per table when the column is not there) and resolveUpdatedAtColumnPresence (the columnInfo() question that recovery asks) move unedited into a new seam module. Both methods stay on the class with their docblocks and signatures, and hand the bodies exactly the members they read through PresumedTimestampHost: knex, logger, physicalTableByObject, physicalSchemaByObject and updatedAtColumnState as getters, attemptWithoutPoisoning and resolveUpdatedAtColumnPresence as late-bound closures. Move-only: no behaviour change. Co-authored-by: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01FEkQ5oBtKR8pYepVfbCoGV
1 parent 1900c02 commit 0379b76

2 files changed

Lines changed: 154 additions & 58 deletions

File tree

Lines changed: 130 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,130 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [#25521 cut 21] The presumed-timestamp update of `SqlDriver`:
5+
* `updateWithPresumedTimestamp`, the UPDATE whose `updated_at` stamp is a
6+
* presumption and that recovers, once per table, when the column turns out not
7+
* to be there, and `resolveUpdatedAtColumnPresence`, the catalog question that
8+
* recovery asks. They moved out of `sql-driver.ts` whole.
9+
*
10+
* A MOVE, not a redesign. Each function below is the body of the `SqlDriver`
11+
* method of the same name as it stood, re-indented one level and otherwise
12+
* unedited: the same savepoint fence inside a caller transaction, the same
13+
* `columnInfo()` probe, the same `present` / `absent` settling and the same
14+
* warning.
15+
*
16+
* What did NOT move, and why:
17+
*
18+
* - Both methods' docblocks stay on the class: they are the contract, and the
19+
* published `dist/*.d.ts` carries them with the methods.
20+
* - The callers stay: `update` and `updateMany` hand the presumed-timestamp
21+
* update the `issue` callback that owns the WHERE and the tenant scope.
22+
* - `updatedAtStampIsPresumed`, `stampsUpdatedAt` and the other readers of
23+
* `updatedAtColumnState` stay; the state map itself stays a class field.
24+
* - `attemptWithoutPoisoning` is the sequence-counter path's fence too, and
25+
* subclasses may override it; the body reaches it through the host.
26+
*
27+
* ## How the moved bodies reach the class
28+
*
29+
* The shape the other seam modules apply, after #23050. The class keeps both
30+
* methods, because the published `dist/*.d.ts` lists their names and
31+
* positions, and because an instance spy or a subclass method of the same name
32+
* must still be the one `update` reaches. Each method is now one literal of
33+
* exactly the {@link PresumedTimestampHost} members its body reads, plus a
34+
* `.call`. Methods go as closures that call them on the driver at call time,
35+
* so `updateWithPresumedTimestamp` still reaches `resolveUpdatedAtColumnPresence`
36+
* through the driver, and a subclass override or an instance spy of either is
37+
* still the one it reaches; `knex`, `logger`, `physicalTableByObject`,
38+
* `physicalSchemaByObject` and `updatedAtColumnState` go as GETTERS, so each
39+
* is read when the body reads it, as it was on the class.
40+
*
41+
* The module imports `sql-driver.ts` for a type only, so the two modules form
42+
* no evaluation cycle. `index.ts` re-exports nothing from this module, so the
43+
* published surface does not move.
44+
*/
45+
46+
import type { DriverOptions } from '@objectstack/spec/data';
47+
import type { Knex } from 'knex';
48+
import type { SqlDriver } from './sql-driver.js';
49+
50+
/**
51+
* The `SqlDriver` members the functions below read — every one of them, and
52+
* no other. Each is typed AS the class member (an indexed access on the
53+
* class), so a change to a member's signature on the class is a change here
54+
* too, and naming a member the class does not have is a compile error. See
55+
* the module header for which members are getters.
56+
*/
57+
export interface PresumedTimestampHost {
58+
attemptWithoutPoisoning: SqlDriver['attemptWithoutPoisoning'];
59+
readonly knex: SqlDriver['knex'];
60+
readonly logger: SqlDriver['logger'];
61+
readonly physicalSchemaByObject: SqlDriver['physicalSchemaByObject'];
62+
readonly physicalTableByObject: SqlDriver['physicalTableByObject'];
63+
resolveUpdatedAtColumnPresence: SqlDriver['resolveUpdatedAtColumnPresence'];
64+
readonly updatedAtColumnState: SqlDriver['updatedAtColumnState'];
65+
}
66+
67+
/** The body of `SqlDriver#resolveUpdatedAtColumnPresence`; the method's docblock there is its contract. */
68+
export async function resolveUpdatedAtColumnPresence(this: Pick<PresumedTimestampHost, 'knex' | 'physicalSchemaByObject' | 'physicalTableByObject'>, object: string, trx?: Knex.Transaction): Promise<boolean | null> {
69+
const physical = this.physicalTableByObject[object] ?? object;
70+
const runner = trx ?? this.knex;
71+
let builder = runner(physical);
72+
const remoteSchema = this.physicalSchemaByObject[object];
73+
if (remoteSchema) builder = builder.withSchema(remoteSchema);
74+
let info: Record<string, unknown>;
75+
try {
76+
info = (await builder.columnInfo()) as Record<string, unknown>;
77+
} catch {
78+
// The probe itself failed — we learned nothing, so we may not claim the
79+
// column is absent. The caller rethrows the write's own error.
80+
return null;
81+
}
82+
const columns = Object.keys(info ?? {});
83+
if (columns.length === 0) return null;
84+
return columns.includes('updated_at');
85+
}
86+
87+
/** The body of `SqlDriver#updateWithPresumedTimestamp`; the method's docblock there is its contract. */
88+
export async function updateWithPresumedTimestamp(this: Pick<PresumedTimestampHost, 'attemptWithoutPoisoning' | 'logger' | 'resolveUpdatedAtColumnPresence' | 'updatedAtColumnState'>, object: string, formatted: Record<string, any>, options: DriverOptions | undefined, issue: (payload: Record<string, any>, options?: DriverOptions) => Promise<number>): Promise<number> {
89+
const unstamped = (): Record<string, any> => {
90+
const { updated_at: _dropped, ...rest } = formatted;
91+
return rest;
92+
};
93+
const settleAbsent = (): void => {
94+
this.updatedAtColumnState.set(object, 'absent');
95+
this.logger.warn(
96+
`[sql-driver] '${object}' has no physical 'updated_at' column, so this driver will not ` +
97+
'stamp one on update. The object is registered as managed, whose schema this ' +
98+
"driver's own DDL would give `created_at`/`updated_at` — a table migrated out-of-band " +
99+
'without them will keep a stale "last modified" for every consumer that reads it ' +
100+
'(list-view sorts, delta sync, cache invalidation, audit). Add the column, or accept ' +
101+
'that it is not tracked here.',
102+
);
103+
};
104+
105+
const parentTrx = options?.transaction as Knex.Transaction | undefined;
106+
if (parentTrx) {
107+
const attempt = await this.attemptWithoutPoisoning(parentTrx, (scoped) =>
108+
issue(formatted, { ...options, transaction: scoped }),
109+
);
110+
if (attempt.ok) {
111+
this.updatedAtColumnState.set(object, 'present');
112+
return attempt.value;
113+
}
114+
const present = await this.resolveUpdatedAtColumnPresence(object, parentTrx);
115+
if (present !== false) throw attempt.error;
116+
settleAbsent();
117+
return issue(unstamped(), options);
118+
}
119+
120+
try {
121+
const affected = await issue(formatted, options);
122+
this.updatedAtColumnState.set(object, 'present');
123+
return affected;
124+
} catch (error) {
125+
const present = await this.resolveUpdatedAtColumnPresence(object);
126+
if (present !== false) throw error;
127+
settleAbsent();
128+
return issue(unstamped(), options);
129+
}
130+
}

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

Lines changed: 24 additions & 58 deletions
Original file line numberDiff line numberDiff line change
@@ -195,6 +195,9 @@ import { applyEmptyOperator, applyJsonMembership, applyLike, applyLikePattern, a
195195
// [#25521 cut 20] Date bucketing (`buildDateBucketExpr`); the method of the same name below hands the body what
196196
// it reads (`DateBucketHost`).
197197
import { buildDateBucketExpr } from './sql-driver-date-bucket.js';
198+
// [#25521 cut 21] The presumed-timestamp update; the two methods of the same names below hand the bodies what
199+
// they read (`PresumedTimestampHost`).
200+
import { resolveUpdatedAtColumnPresence, updateWithPresumedTimestamp } from './sql-driver-presumed-timestamp.js';
198201
import { makeDatabaseDirectory, probeAbsentSqliteDatabaseFile, SqliteDatabaseFileError } from './sqlite-database-file.js';
199202
import { jsonMembershipPredicate } from '@objectstack/core';
200203
import knex, { Knex } from 'knex';
@@ -7510,26 +7513,20 @@ export class SqlDriver implements IDataDriver {
75107513
* snapshot — and, on Postgres, so it runs on a transaction that is still
75117514
* usable (see {@link updateWithPresumedTimestamp}).
75127515
*/
7513-
protected async resolveUpdatedAtColumnPresence(
7516+
protected resolveUpdatedAtColumnPresence(
75147517
object: string,
75157518
trx?: Knex.Transaction,
75167519
): Promise<boolean | null> {
7517-
const physical = this.physicalTableByObject[object] ?? object;
7518-
const runner = trx ?? this.knex;
7519-
let builder = runner(physical);
7520-
const remoteSchema = this.physicalSchemaByObject[object];
7521-
if (remoteSchema) builder = builder.withSchema(remoteSchema);
7522-
let info: Record<string, unknown>;
7523-
try {
7524-
info = (await builder.columnInfo()) as Record<string, unknown>;
7525-
} catch {
7526-
// The probe itself failed — we learned nothing, so we may not claim the
7527-
// column is absent. The caller rethrows the write's own error.
7528-
return null;
7529-
}
7530-
const columns = Object.keys(info ?? {});
7531-
if (columns.length === 0) return null;
7532-
return columns.includes('updated_at');
7520+
// [#25521 cut 21] The body moved to `sql-driver-presumed-timestamp.ts` (see `PresumedTimestampHost`).
7521+
const readKnex = () => this.knex;
7522+
const readPhysicalSchemaByObject = () => this.physicalSchemaByObject;
7523+
const readPhysicalTableByObject = () => this.physicalTableByObject;
7524+
const host: ThisParameterType<typeof resolveUpdatedAtColumnPresence> = {
7525+
get knex() { return readKnex(); },
7526+
get physicalSchemaByObject() { return readPhysicalSchemaByObject(); },
7527+
get physicalTableByObject() { return readPhysicalTableByObject(); },
7528+
};
7529+
return resolveUpdatedAtColumnPresence.call(host, object, trx);
75337530
}
75347531

75357532
/**
@@ -7584,53 +7581,22 @@ export class SqlDriver implements IDataDriver {
75847581
* caller owns the WHERE and the tenant scope, so this method never rebuilds
75857582
* them and cannot get them wrong.
75867583
*/
7587-
protected async updateWithPresumedTimestamp(
7584+
protected updateWithPresumedTimestamp(
75887585
object: string,
75897586
formatted: Record<string, any>,
75907587
options: DriverOptions | undefined,
75917588
issue: (payload: Record<string, any>, options?: DriverOptions) => Promise<number>,
75927589
): Promise<number> {
7593-
const unstamped = (): Record<string, any> => {
7594-
const { updated_at: _dropped, ...rest } = formatted;
7595-
return rest;
7596-
};
7597-
const settleAbsent = (): void => {
7598-
this.updatedAtColumnState.set(object, 'absent');
7599-
this.logger.warn(
7600-
`[sql-driver] '${object}' has no physical 'updated_at' column, so this driver will not ` +
7601-
'stamp one on update. The object is registered as managed, whose schema this ' +
7602-
"driver's own DDL would give `created_at`/`updated_at` — a table migrated out-of-band " +
7603-
'without them will keep a stale "last modified" for every consumer that reads it ' +
7604-
'(list-view sorts, delta sync, cache invalidation, audit). Add the column, or accept ' +
7605-
'that it is not tracked here.',
7606-
);
7590+
// [#25521 cut 21] The body moved to `sql-driver-presumed-timestamp.ts` (see `PresumedTimestampHost`).
7591+
const readLogger = () => this.logger;
7592+
const readUpdatedAtColumnState = () => this.updatedAtColumnState;
7593+
const host: ThisParameterType<typeof updateWithPresumedTimestamp> = {
7594+
attemptWithoutPoisoning: (...a) => this.attemptWithoutPoisoning(...a),
7595+
get logger() { return readLogger(); },
7596+
resolveUpdatedAtColumnPresence: (...a) => this.resolveUpdatedAtColumnPresence(...a),
7597+
get updatedAtColumnState() { return readUpdatedAtColumnState(); },
76077598
};
7608-
7609-
const parentTrx = options?.transaction as Knex.Transaction | undefined;
7610-
if (parentTrx) {
7611-
const attempt = await this.attemptWithoutPoisoning(parentTrx, (scoped) =>
7612-
issue(formatted, { ...options, transaction: scoped }),
7613-
);
7614-
if (attempt.ok) {
7615-
this.updatedAtColumnState.set(object, 'present');
7616-
return attempt.value;
7617-
}
7618-
const present = await this.resolveUpdatedAtColumnPresence(object, parentTrx);
7619-
if (present !== false) throw attempt.error;
7620-
settleAbsent();
7621-
return issue(unstamped(), options);
7622-
}
7623-
7624-
try {
7625-
const affected = await issue(formatted, options);
7626-
this.updatedAtColumnState.set(object, 'present');
7627-
return affected;
7628-
} catch (error) {
7629-
const present = await this.resolveUpdatedAtColumnPresence(object);
7630-
if (present !== false) throw error;
7631-
settleAbsent();
7632-
return issue(unstamped(), options);
7633-
}
7599+
return updateWithPresumedTimestamp.call(host, object, formatted, options, issue);
76347600
}
76357601

76367602
/**

0 commit comments

Comments
 (0)