|
| 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 | +} |
0 commit comments