Skip to content

Commit 3917686

Browse files
committed
refactor(driver-sql): generated split of sql-driver.ts by scripts/codemod-split-sql-driver.mjs
Output of `node scripts/codemod-split-sql-driver.mjs --write` on sql-driver.ts at dbca3ef, unedited: 20 method bodies in 10 sections move to section modules, the class keeps host stubs. Byte-identity proved by the script (undoing the split rebuilds the base file byte-for-byte). Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017ihL2gLghEqeDKTbDTC7Zd
1 parent 939ace0 commit 3917686

11 files changed

Lines changed: 762 additions & 228 deletions
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [#29520 codemod] The "Aggregation" section of `SqlDriver`: the bodies of
5+
* `foldEmptyAggregateAnswers` moved out of `sql-driver.ts` whole by
6+
* `scripts/codemod-split-sql-driver.mjs`.
7+
*
8+
* A MOVE, not a redesign. Each function below is the body of the `SqlDriver`
9+
* method of the same name exactly as it stood: not re-indented, not
10+
* formatted, not edited. The method stays on the class with its docblock and
11+
* signature, so the published `dist/*.d.ts`, an instance spy and a subclass
12+
* override are what they were; the docblock there is the contract.
13+
*
14+
* No body reads a `SqlDriver` member, so each method calls its function
15+
* directly. `index.ts` re-exports nothing from this module.
16+
*/
17+
18+
19+
/** The body of `SqlDriver#foldEmptyAggregateAnswers`; the method's docblock there is its contract. */
20+
export function foldEmptyAggregateAnswers(rows: any, identities: Map<string, number>): any {
21+
if (identities.size === 0 || !Array.isArray(rows)) return rows;
22+
for (const row of rows) {
23+
if (!row || typeof row !== 'object') continue;
24+
for (const [column, identity] of identities) {
25+
if (row[column] === null) row[column] = identity;
26+
}
27+
}
28+
return rows;
29+
}
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [#29520 codemod] The "Bulk & Batch Operations" section of `SqlDriver`: the
5+
* bodies of `bulkUpdate` moved out of `sql-driver.ts` whole by
6+
* `scripts/codemod-split-sql-driver.mjs`.
7+
*
8+
* A MOVE, not a redesign. Each function below is the body of the `SqlDriver`
9+
* method of the same name exactly as it stood: not re-indented, not
10+
* formatted, not edited. The method stays on the class with its docblock and
11+
* signature, so the published `dist/*.d.ts`, an instance spy and a subclass
12+
* override are what they were; the docblock there is the contract.
13+
*
14+
* The bodies reach the class through {@link BulkOperationsHost}: exactly the
15+
* `SqlDriver` members they read. Each method hands its body one literal of the
16+
* members that body reads, plus a `.call`: methods go as closures that call
17+
* them on the driver at call time, so a subclass override or an instance spy
18+
* is still the one reached; fields and accessors go as GETTERS, read when the
19+
* body reads them, as they were on the class.
20+
*
21+
* The module imports `sql-driver.ts` for types only, so the two modules form
22+
* no evaluation cycle. `index.ts` re-exports nothing from this module.
23+
*/
24+
25+
import type { DriverOptions } from '@objectstack/spec/data';
26+
import type { Knex } from 'knex';
27+
import type { SqlDriver } from './sql-driver.js';
28+
29+
/**
30+
* The `SqlDriver` members the functions below read — every one of them, and
31+
* no other. Each is typed AS the class member (an indexed access on the
32+
* class), so a change to a member's signature on the class is a change here
33+
* too. `readonly` members are the getters.
34+
*/
35+
export interface BulkOperationsHost {
36+
readonly knex: SqlDriver['knex'];
37+
update: SqlDriver['update'];
38+
}
39+
40+
/** The body of `SqlDriver#bulkUpdate`; the method's docblock there is its contract. */
41+
export async function bulkUpdate(this: Pick<BulkOperationsHost, 'knex' | 'update'>, object: string, updates: Array<{ id: string | number; data: Record<string, any> }>, options?: DriverOptions): Promise<Record<string, unknown>[]> {
42+
// An empty batch issues no statement, exactly as before: a BEGIN/COMMIT
43+
// pair — and the pool checkout behind it — buys nothing for zero rows.
44+
if (updates.length === 0) return [];
45+
46+
const applyAll = async (scoped: DriverOptions): Promise<Record<string, any>[]> => {
47+
const results: Record<string, any>[] = [];
48+
for (const { id, data } of updates) {
49+
const updated = await this.update(object, id, data, scoped);
50+
if (updated) results.push(updated);
51+
}
52+
return results;
53+
};
54+
55+
// The `(caller's transaction) ?? this.knex` runner idiom this file already
56+
// uses (see {@link collidingAutoNumberReservations}); here the choice of
57+
// runner is also the choice between a transaction and a savepoint.
58+
const runner: Knex | Knex.Transaction = (options?.transaction as Knex.Transaction | undefined) ?? this.knex;
59+
return runner.transaction(async (trx) => applyAll({ ...options, transaction: trx }));
60+
}
Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [#29520 codemod] The "Column creation helper" section of `SqlDriver`: the
5+
* bodies of `decorateHashShadowDuplicate`, `schemaBytesPerChar`,
6+
* `rethrowWithRowSizeExplanation` moved out of `sql-driver.ts` whole by
7+
* `scripts/codemod-split-sql-driver.mjs`.
8+
*
9+
* A MOVE, not a redesign. Each function below is the body of the `SqlDriver`
10+
* method of the same name exactly as it stood: not re-indented, not
11+
* formatted, not edited. The method stays on the class with its docblock and
12+
* signature, so the published `dist/*.d.ts`, an instance spy and a subclass
13+
* override are what they were; the docblock there is the contract.
14+
*
15+
* The bodies reach the class through {@link ColumnCreationHost}: exactly the
16+
* `SqlDriver` members they read. Each method hands its body one literal of the
17+
* members that body reads, plus a `.call`: methods go as closures that call
18+
* them on the driver at call time, so a subclass override or an instance spy
19+
* is still the one reached; fields and accessors go as GETTERS, read when the
20+
* body reads them, as they were on the class.
21+
*
22+
* The module imports `sql-driver.ts` for types only, so the two modules form
23+
* no evaluation cycle. `index.ts` re-exports nothing from this module.
24+
*/
25+
26+
import type { SqlDriver } from './sql-driver.js';
27+
28+
/**
29+
* The `SqlDriver` members the functions below read — every one of them, and
30+
* no other. Each is typed AS the class member (an indexed access on the
31+
* class), so a change to a member's signature on the class is a change here
32+
* too. `readonly` members are the getters.
33+
*/
34+
export interface ColumnCreationHost {
35+
explainHashShadowDuplicate: SqlDriver['explainHashShadowDuplicate'];
36+
explainRowSizeOverflow: SqlDriver['explainRowSizeOverflow'];
37+
readonly knex: SqlDriver['knex'];
38+
logDurabilityFailure: SqlDriver['logDurabilityFailure'];
39+
}
40+
41+
/** The body of `SqlDriver#decorateHashShadowDuplicate`; the method's docblock there is its contract. */
42+
export async function decorateHashShadowDuplicate(this: Pick<ColumnCreationHost, 'explainHashShadowDuplicate' | 'logDurabilityFailure'>, tableName: string, values: Record<string, unknown>, error: unknown): Promise<unknown> {
43+
let explanation: string | null = null;
44+
try {
45+
explanation = await this.explainHashShadowDuplicate(tableName, values, error);
46+
} catch {
47+
// The disambiguation is a diagnostic. If it cannot be made, the original
48+
// failure is still the failure — never mask it with this one.
49+
return error;
50+
}
51+
if (!explanation) return error;
52+
this.logDurabilityFailure(explanation);
53+
return Object.assign(new Error(`${explanation} (server said: ${String((error as { message?: string })?.message ?? error)})`), {
54+
code: (error as { code?: string })?.code,
55+
cause: error,
56+
});
57+
}
58+
59+
/** The body of `SqlDriver#schemaBytesPerChar`; the method's docblock there is its contract. */
60+
export async function schemaBytesPerChar(this: Pick<ColumnCreationHost, 'knex'>): Promise<{ bytesPerChar: number; charset: string } | null> {
61+
try {
62+
const res: any = await this.knex.raw(
63+
'select cs.CHARACTER_SET_NAME as charset, cs.MAXLEN as maxlen ' +
64+
'from information_schema.CHARACTER_SETS cs ' +
65+
'where cs.CHARACTER_SET_NAME = @@character_set_database',
66+
);
67+
const row = (Array.isArray(res) ? res[0]?.[0] : (res?.rows?.[0] ?? res?.[0])) ?? null;
68+
const maxlen = Number(row?.maxlen ?? row?.MAXLEN);
69+
const charset = String(row?.charset ?? row?.CHARSET ?? '');
70+
if (!Number.isInteger(maxlen) || maxlen <= 0 || !charset) return null;
71+
return { bytesPerChar: maxlen, charset };
72+
} catch {
73+
// Introspection is a nicety here; the advice below holds without it.
74+
return null;
75+
}
76+
}
77+
78+
/** The body of `SqlDriver#rethrowWithRowSizeExplanation`; the method's docblock there is its contract. */
79+
export async function rethrowWithRowSizeExplanation(this: Pick<ColumnCreationHost, 'explainRowSizeOverflow' | 'logDurabilityFailure'>, tableName: string, fields: Record<string, any> | undefined, keyedColumns: ReadonlyMap<string, { unique: boolean }>, addedColumns: string[] | null, e: any): Promise<never> {
80+
const overflow = await this.explainRowSizeOverflow(tableName, fields, keyedColumns, addedColumns, e);
81+
if (!overflow) throw e;
82+
const said = String(e?.sqlMessage ?? e?.message ?? e);
83+
this.logDurabilityFailure(overflow, said);
84+
throw Object.assign(new Error(`${overflow} (server said: ${said})`), {
85+
code: (e as { code?: string }).code,
86+
cause: e,
87+
});
88+
}
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [#29520 codemod] The "CRUD — IDataDriver core" section of `SqlDriver`: the
5+
* bodies of `sequenceKeyHash` moved out of `sql-driver.ts` whole by
6+
* `scripts/codemod-split-sql-driver.mjs`.
7+
*
8+
* A MOVE, not a redesign. Each function below is the body of the `SqlDriver`
9+
* method of the same name exactly as it stood: not re-indented, not
10+
* formatted, not edited. The method stays on the class with its docblock and
11+
* signature, so the published `dist/*.d.ts`, an instance spy and a subclass
12+
* override are what they were; the docblock there is the contract.
13+
*
14+
* No body reads a `SqlDriver` member, so each method calls its function
15+
* directly. `index.ts` re-exports nothing from this module.
16+
*/
17+
18+
import { createHash } from 'node:crypto';
19+
20+
/** The body of `SqlDriver#sequenceKeyHash`; the method's docblock there is its contract. */
21+
export function sequenceKeyHash(object: string, tenantId: string, field: string, scope: string): string {
22+
return createHash('sha256')
23+
.update(`${object}\u001f${tenantId}\u001f${field}\u001f${scope}`)
24+
.digest('hex');
25+
}
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [#29520 codemod] The "Database helpers" section of `SqlDriver`: the bodies of
5+
* `sqliteFilename` moved out of `sql-driver.ts` whole by
6+
* `scripts/codemod-split-sql-driver.mjs`.
7+
*
8+
* A MOVE, not a redesign. Each function below is the body of the `SqlDriver`
9+
* method of the same name exactly as it stood: not re-indented, not
10+
* formatted, not edited. The method stays on the class with its docblock and
11+
* signature, so the published `dist/*.d.ts`, an instance spy and a subclass
12+
* override are what they were; the docblock there is the contract.
13+
*
14+
* The bodies reach the class through {@link DatabaseHelpersHost}: exactly the
15+
* `SqlDriver` members they read. Each method hands its body one literal of the
16+
* members that body reads, plus a `.call`: methods go as closures that call
17+
* them on the driver at call time, so a subclass override or an instance spy
18+
* is still the one reached; fields and accessors go as GETTERS, read when the
19+
* body reads them, as they were on the class.
20+
*
21+
* The module imports `sql-driver.ts` for types only, so the two modules form
22+
* no evaluation cycle. `index.ts` re-exports nothing from this module.
23+
*/
24+
25+
import type { SqlDriver } from './sql-driver.js';
26+
27+
/**
28+
* The `SqlDriver` members the functions below read — every one of them, and
29+
* no other. Each is typed AS the class member (an indexed access on the
30+
* class), so a change to a member's signature on the class is a change here
31+
* too. `readonly` members are the getters.
32+
*/
33+
export interface DatabaseHelpersHost {
34+
readonly config: SqlDriver['config'];
35+
readonly isSqlite: SqlDriver['isSqlite'];
36+
readonly openedEmptyInMemory: SqlDriver['openedEmptyInMemory'];
37+
}
38+
39+
/** The body of `SqlDriver#sqliteFilename`; the method's docblock there is its contract. */
40+
export function sqliteFilename(this: Pick<DatabaseHelpersHost, 'config' | 'isSqlite' | 'openedEmptyInMemory'>): string | null {
41+
if (!this.isSqlite) return null;
42+
// Redirected to `:memory:` because the declared file did not exist and the
43+
// host asked not to create one (#6743). `this.config` still names the
44+
// declared target — on purpose, so the CLI can print it — but NO on-disk
45+
// file backs this connection, which is precisely what this method reports.
46+
// Both callers depend on that reading: `ensureDatabaseExists` would
47+
// otherwise `mkdir` the state directory this mode exists to avoid, and
48+
// `applySqliteJournalMode` would try to put an in-memory database in WAL.
49+
if (this.openedEmptyInMemory) return null;
50+
const conn = (this.config as any).connection;
51+
const filename = typeof conn === 'string' ? conn : conn?.filename;
52+
if (typeof filename !== 'string' || filename === '') return null;
53+
return filename.startsWith(':') ? null : filename;
54+
}
Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [#29520 codemod] The "Field mapping" section of `SqlDriver`: the bodies of
5+
* `mapSortField`, `orderKeysFor` moved out of `sql-driver.ts` whole by
6+
* `scripts/codemod-split-sql-driver.mjs`.
7+
*
8+
* A MOVE, not a redesign. Each function below is the body of the `SqlDriver`
9+
* method of the same name exactly as it stood: not re-indented, not
10+
* formatted, not edited. The method stays on the class with its docblock and
11+
* signature, so the published `dist/*.d.ts`, an instance spy and a subclass
12+
* override are what they were; the docblock there is the contract.
13+
*
14+
* The bodies reach the class through {@link FieldMappingHost}: exactly the
15+
* `SqlDriver` members they read. Each method hands its body one literal of the
16+
* members that body reads, plus a `.call`: methods go as closures that call
17+
* them on the driver at call time, so a subclass override or an instance spy
18+
* is still the one reached; fields and accessors go as GETTERS, read when the
19+
* body reads them, as they were on the class.
20+
*
21+
* The module imports `sql-driver.ts` for types only, so the two modules form
22+
* no evaluation cycle. `index.ts` re-exports nothing from this module.
23+
*/
24+
25+
import type { DriverQuery } from '@objectstack/spec/contracts';
26+
import type { SqlDriver } from './sql-driver.js';
27+
28+
/**
29+
* The `SqlDriver` members the functions below read — every one of them, and
30+
* no other. Each is typed AS the class member (an indexed access on the
31+
* class), so a change to a member's signature on the class is a change here
32+
* too. `readonly` members are the getters.
33+
*/
34+
export interface FieldMappingHost {
35+
readonly logger: SqlDriver['logger'];
36+
readonly nondeterministicPagingWarned: SqlDriver['nondeterministicPagingWarned'];
37+
paginationTieBreaker: SqlDriver['paginationTieBreaker'];
38+
}
39+
40+
/** The body of `SqlDriver#mapSortField`; the method's docblock there is its contract. */
41+
export function mapSortField(field: string): string {
42+
if (field === 'createdAt') return 'created_at';
43+
if (field === 'updatedAt') return 'updated_at';
44+
return field;
45+
}
46+
47+
/** The body of `SqlDriver#orderKeysFor`; the method's docblock there is its contract. */
48+
export function orderKeysFor(this: Pick<FieldMappingHost, 'logger' | 'nondeterministicPagingWarned' | 'paginationTieBreaker'>, object: string, query: DriverQuery, opts?: { singleRowLookup?: boolean }): Array<{ field: string; direction: 'asc' | 'desc' }> {
49+
const keys: Array<{ field: string; direction: 'asc' | 'desc' }> = [];
50+
if (Array.isArray(query.orderBy)) {
51+
for (const item of query.orderBy) {
52+
if (item.field) {
53+
keys.push({ field: item.field, direction: item.order === 'desc' ? 'desc' : 'asc' });
54+
}
55+
}
56+
}
57+
58+
const paged =
59+
!opts?.singleRowLookup && (query.limit !== undefined || query.offset !== undefined);
60+
if (keys.length === 0 && !paged) return keys;
61+
62+
const tieBreaker = this.paginationTieBreaker(object);
63+
if (tieBreaker && !keys.some((k) => k.field === tieBreaker)) {
64+
keys.push({ field: tieBreaker, direction: keys[keys.length - 1]?.direction ?? 'asc' });
65+
} else if (!tieBreaker && keys.length === 0) {
66+
// Paged, unsorted, and no column this driver can trust to order by: the
67+
// read goes out exactly as before, and its pages are not a partition.
68+
// Say so once per object rather than leave it to be discovered by a user
69+
// counting records — a guarantee the contract states as MUST, quietly
70+
// unavailable, is the same invisible failure it was written against.
71+
// (Sorted reads on such a table keep the caller's own ORDER BY, so only
72+
// the ties within it reshuffle; this case has nothing at all.)
73+
if (!this.nondeterministicPagingWarned.has(object)) {
74+
this.nondeterministicPagingWarned.add(object);
75+
this.logger.warn(
76+
`Paged read of '${object}' is NOT deterministic: this driver did not create the table, `
77+
+ 'so it cannot name a unique column to order by, and the query asked for no sort of '
78+
+ 'its own. Walking the pages may serve one row twice and never serve another. '
79+
+ 'Give the query an `orderBy` on a unique column, or declare the '
80+
+ 'object so this driver manages its table.',
81+
);
82+
}
83+
}
84+
return keys;
85+
}

0 commit comments

Comments
 (0)