Skip to content

Commit bd1670f

Browse files
committed
refactor(driver-sql): move introspectIndexes into sql-driver-introspection.ts
Move-only: the body of SqlDriver#introspectIndexes moves unedited into the module the other catalog reads live in, and the class method hands it its host (the dialect getters and knex as getters, resolveHashShadowKeys as a late-bound closure so a subclass override or an instance spy still dispatches). The method keeps its docblock and signature, less async, so the published declarations do not move. sql-driver.ts no longer reads parseIndexDdl or applyIndexKeyParts and drops them from its import; the module imports them from schema-drift.ts. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_013Wyp3j7s8XDQmCUaKPbmXH
1 parent f00e8d5 commit bd1670f

2 files changed

Lines changed: 143 additions & 99 deletions

File tree

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

Lines changed: 127 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,20 @@
1414
* shorter than the host literal a stub would need, so moving it would make
1515
* `sql-driver.ts` longer, not shorter.
1616
*
17+
* [#25521 cut 5] `introspectIndexes`, the per-table index read schema sync
18+
* and index drift detection are built on, moved here too: it is the fifth
19+
* catalog read of the same shape, with the same `onFailure` contract as the
20+
* foreign-key and primary-key reads above. `resolveHashShadowKeys`, the MySQL
21+
* hash-shadow enrichment it calls, stayed in the class with the rest of the
22+
* hash-shadow family; the body reaches it through a closure that calls it on
23+
* the driver at call time, so a subclass override or a test spy on the
24+
* instance is still the one it reaches. `TursoDriver` overrides
25+
* `introspectIndexes` and calls `super` on its local arm, which reaches the
26+
* class method, which hands this body its host. `parseIndexDdl`,
27+
* `applyIndexKeyParts` and the type `PhysicalIndex` are imported from
28+
* `schema-drift.ts`, where they live; `sql-driver.ts` no longer reads the two
29+
* functions and dropped them from its import.
30+
*
1731
* A MOVE, not a redesign. Each function below is the body of the `SqlDriver`
1832
* method of the same name as it stood, re-indented one level and otherwise
1933
* unedited: the same catalog statements, the same dialect arms, the same
@@ -67,6 +81,7 @@ import type {
6781
UniqueConstraintMember,
6882
} from './sql-driver.js';
6983
import { postgresTableNameCollisionError, singleColumnUniqueColumns } from './sql-driver.js';
84+
import { applyIndexKeyParts, parseIndexDdl, type PhysicalIndex } from './schema-drift.js';
7085

7186
/**
7287
* The `SqlDriver` members the functions below read — every one of them, and
@@ -87,6 +102,7 @@ export interface IntrospectionHost {
87102
readonly isPostgres: SqlDriver['isPostgres'];
88103
readonly isSqlite: SqlDriver['isSqlite'];
89104
readonly knex: SqlDriver['knex'];
105+
resolveHashShadowKeys: SqlDriver['resolveHashShadowKeys'];
90106
}
91107

92108
/** The body of `SqlDriver#introspectColumnOrder`; the method's docblock there is its contract. */
@@ -798,3 +814,114 @@ export async function introspectSchema(this: Pick<IntrospectionHost, 'dialectNam
798814
// this repairs, wearing a fix's clothes.
799815
return { tables, dialect: this.dialectName, introspectedAt };
800816
}
817+
818+
/** The body of `SqlDriver#introspectIndexes`; the method's docblock there is its contract. */
819+
export async function introspectIndexes(
820+
this: Pick<IntrospectionHost, 'isMysql' | 'isPostgres' | 'isSqlite' | 'knex' | 'resolveHashShadowKeys'>,
821+
tableName: string,
822+
opts: {
823+
/**
824+
* What a failed read means to THIS caller (#7332). `'throw'` (the
825+
* default) surfaces it; `'partial'` returns whatever was read before the
826+
* failure — correct only where a short read is self-correcting.
827+
*/
828+
onFailure?: 'throw' | 'partial';
829+
} = {},
830+
): Promise<PhysicalIndex[]> {
831+
const byName = new Map<string, PhysicalIndex>();
832+
const upsert = (name: string, unique: boolean, primary: boolean): PhysicalIndex => {
833+
let e = byName.get(name);
834+
if (!e) byName.set(name, (e = { name, columns: [], unique, primary }));
835+
return e;
836+
};
837+
try {
838+
if (this.isSqlite) {
839+
const safe = tableName.replace(/[^a-zA-Z0-9_]/g, '');
840+
// `sqlite_master.sql` is the only place an expression key or a WHERE
841+
// predicate survives; it is NULL for the indexes SQLite auto-creates
842+
// for a UNIQUE/PK constraint, which are plain by construction.
843+
const ddlByName = new Map<string, string>();
844+
const master: any = await this.knex.raw(
845+
`SELECT name, sql FROM sqlite_master WHERE type = 'index' AND tbl_name = ?`,
846+
[tableName],
847+
);
848+
for (const r of Array.isArray(master) ? master : (master?.rows ?? [])) {
849+
if (typeof r?.sql === 'string' && r.sql) ddlByName.set(r.name, r.sql);
850+
}
851+
const list: any = await this.knex.raw(`PRAGMA index_list(${safe})`);
852+
for (const r of list) {
853+
const entry = upsert(r.name, r.unique === 1 || r.unique === true, r.origin === 'pk');
854+
const parsed = parseIndexDdl(ddlByName.get(r.name) ?? '');
855+
if (parsed) {
856+
applyIndexKeyParts(entry, parsed.keyParts);
857+
if (parsed.partial) entry.partial = true;
858+
} else {
859+
const info: any = await this.knex.raw(`PRAGMA index_info(${JSON.stringify(r.name)})`);
860+
for (const c of info) if (c.name != null) entry.columns.push(c.name);
861+
}
862+
// `PRAGMA index_list` reports partiality directly (SQLite ≥ 3.8.9);
863+
// belt-and-braces with the parsed predicate above.
864+
if (r.partial === 1 || r.partial === true) entry.partial = true;
865+
}
866+
} else if (this.isPostgres) {
867+
// `to_regclass` resolves the name the way every other statement in the
868+
// session does — first match along `search_path` — instead of pinning
869+
// one schema literally. The literal was `n.nspname = 'public'`, which is
870+
// the same answer for a default deployment (`current_schema()` IS
871+
// `public` there) and NO answer at all for a session pointed anywhere
872+
// else: measured on a live Postgres 16 under a non-public search_path,
873+
// this returned `[]` for a table carrying a primary key AND a declared
874+
// unique index. Empty here does not read as "I could not see"; it reads
875+
// as "there are no indexes", which is what `assertConflictTargetHonoured`
876+
// turns into a refusal — a silent fail-open on the identity check.
877+
// Resolving by OID also removes the ambiguity a schema list would add:
878+
// two schemas on the path can hold the same table name, and only one of
879+
// them is the one a query would hit.
880+
const res: any = await this.knex.raw(
881+
`SELECT i.relname AS index_name, ix.indisunique AS is_unique, ix.indisprimary AS is_primary,
882+
(ix.indpred IS NOT NULL) AS is_partial,
883+
pg_get_indexdef(ix.indexrelid) AS indexdef
884+
FROM pg_index ix
885+
JOIN pg_class i ON i.oid = ix.indexrelid
886+
WHERE ix.indrelid = to_regclass(?)
887+
ORDER BY i.relname`,
888+
[tableName],
889+
);
890+
for (const r of res.rows) {
891+
const entry = upsert(r.index_name, r.is_unique === true, r.is_primary === true);
892+
if (r.is_partial === true) entry.partial = true;
893+
const parsed = parseIndexDdl(r.indexdef);
894+
if (parsed) applyIndexKeyParts(entry, parsed.keyParts);
895+
}
896+
} else if (this.isMysql) {
897+
// `EXPRESSION` only exists from MySQL 8.0.13 (functional indexes); on an
898+
// older server or MariaDB the column is unknown and the query errors, so
899+
// fall back rather than lose index introspection wholesale.
900+
const columns = 'INDEX_NAME, NON_UNIQUE, COLUMN_NAME, EXPRESSION';
901+
const statisticsQuery = (select: string) =>
902+
this.knex.raw(
903+
`SELECT ${select}
904+
FROM information_schema.STATISTICS
905+
WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ?
906+
ORDER BY INDEX_NAME, SEQ_IN_INDEX`,
907+
[tableName],
908+
);
909+
let res: any;
910+
try {
911+
res = await statisticsQuery(columns);
912+
} catch {
913+
res = await statisticsQuery('INDEX_NAME, NON_UNIQUE, COLUMN_NAME');
914+
}
915+
for (const r of res[0]) {
916+
const entry = upsert(r.INDEX_NAME, Number(r.NON_UNIQUE) === 0, r.INDEX_NAME === 'PRIMARY');
917+
if (r.COLUMN_NAME != null) entry.columns.push(r.COLUMN_NAME);
918+
else if (r.EXPRESSION != null) applyIndexKeyParts(entry, [String(r.EXPRESSION)]);
919+
}
920+
await this.resolveHashShadowKeys(tableName, [...byName.values()]);
921+
}
922+
} catch (e) {
923+
// Only a caller that can CORRECT a short read may ask for one (#7332).
924+
if (opts.onFailure !== 'partial') throw e;
925+
}
926+
return [...byName.values()];
927+
}

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

Lines changed: 16 additions & 99 deletions
Original file line numberDiff line numberDiff line change
@@ -109,7 +109,6 @@ import {
109109
import { postureEnforcesWall } from '@objectstack/spec/security';
110110
import { temporalStorageForm } from '@objectstack/core';
111111
import {
112-
applyIndexKeyParts,
113112
buildIndexName,
114113
describeMissingIndexColumns,
115114
diffManagedIndexes,
@@ -132,7 +131,6 @@ import {
132131
legacyUniqueReplacements,
133132
normalizeDeclaredIndex,
134133
organizationKeyPartSql,
135-
parseIndexDdl,
136134
uniqueIndexesFromFields,
137135
type DeclaredIndexInput,
138136
type HashShadowKeyPart,
@@ -161,12 +159,14 @@ import {
161159
import { recoverUnencodedJsonText } from './unencoded-json-text.js';
162160
// [#25521 cut 1] The catalog-introspection helpers (`introspectColumnOrder`,
163161
// `introspectColumns` and the foreign-key, primary-key and unique-constraint reads),
164-
// and [cut 4] `introspectSchema`, the whole-schema read built on them; the methods
162+
// [cut 4] `introspectSchema`, the whole-schema read built on them, and [cut 5]
163+
// `introspectIndexes`, the per-table index read schema sync is built on; the methods
165164
// of the same names below hand each body the members it reads (`IntrospectionHost`).
166165
import {
167166
introspectColumnOrder,
168167
introspectColumns,
169168
introspectForeignKeys,
169+
introspectIndexes,
170170
introspectPrimaryKeys,
171171
introspectSchema,
172172
introspectUniqueConstraints,
@@ -15140,7 +15140,7 @@ export class SqlDriver implements IDataDriver {
1514015140
* what tells the differ this index is none of its business
1514115141
* (`isSyncReproducibleIndex`).
1514215142
*/
15143-
protected async introspectIndexes(
15143+
protected introspectIndexes(
1514415144
tableName: string,
1514515145
opts: {
1514615146
/**
@@ -15151,102 +15151,19 @@ export class SqlDriver implements IDataDriver {
1515115151
onFailure?: 'throw' | 'partial';
1515215152
} = {},
1515315153
): Promise<PhysicalIndex[]> {
15154-
const byName = new Map<string, PhysicalIndex>();
15155-
const upsert = (name: string, unique: boolean, primary: boolean): PhysicalIndex => {
15156-
let e = byName.get(name);
15157-
if (!e) byName.set(name, (e = { name, columns: [], unique, primary }));
15158-
return e;
15154+
// [#25521 cut 5] The body moved to `sql-driver-introspection.ts` (see `IntrospectionHost`).
15155+
const readIsMysql = () => this.isMysql;
15156+
const readIsPostgres = () => this.isPostgres;
15157+
const readIsSqlite = () => this.isSqlite;
15158+
const readKnex = () => this.knex;
15159+
const host: ThisParameterType<typeof introspectIndexes> = {
15160+
get isMysql() { return readIsMysql(); },
15161+
get isPostgres() { return readIsPostgres(); },
15162+
get isSqlite() { return readIsSqlite(); },
15163+
get knex() { return readKnex(); },
15164+
resolveHashShadowKeys: (...a) => this.resolveHashShadowKeys(...a),
1515915165
};
15160-
try {
15161-
if (this.isSqlite) {
15162-
const safe = tableName.replace(/[^a-zA-Z0-9_]/g, '');
15163-
// `sqlite_master.sql` is the only place an expression key or a WHERE
15164-
// predicate survives; it is NULL for the indexes SQLite auto-creates
15165-
// for a UNIQUE/PK constraint, which are plain by construction.
15166-
const ddlByName = new Map<string, string>();
15167-
const master: any = await this.knex.raw(
15168-
`SELECT name, sql FROM sqlite_master WHERE type = 'index' AND tbl_name = ?`,
15169-
[tableName],
15170-
);
15171-
for (const r of Array.isArray(master) ? master : (master?.rows ?? [])) {
15172-
if (typeof r?.sql === 'string' && r.sql) ddlByName.set(r.name, r.sql);
15173-
}
15174-
const list: any = await this.knex.raw(`PRAGMA index_list(${safe})`);
15175-
for (const r of list) {
15176-
const entry = upsert(r.name, r.unique === 1 || r.unique === true, r.origin === 'pk');
15177-
const parsed = parseIndexDdl(ddlByName.get(r.name) ?? '');
15178-
if (parsed) {
15179-
applyIndexKeyParts(entry, parsed.keyParts);
15180-
if (parsed.partial) entry.partial = true;
15181-
} else {
15182-
const info: any = await this.knex.raw(`PRAGMA index_info(${JSON.stringify(r.name)})`);
15183-
for (const c of info) if (c.name != null) entry.columns.push(c.name);
15184-
}
15185-
// `PRAGMA index_list` reports partiality directly (SQLite ≥ 3.8.9);
15186-
// belt-and-braces with the parsed predicate above.
15187-
if (r.partial === 1 || r.partial === true) entry.partial = true;
15188-
}
15189-
} else if (this.isPostgres) {
15190-
// `to_regclass` resolves the name the way every other statement in the
15191-
// session does — first match along `search_path` — instead of pinning
15192-
// one schema literally. The literal was `n.nspname = 'public'`, which is
15193-
// the same answer for a default deployment (`current_schema()` IS
15194-
// `public` there) and NO answer at all for a session pointed anywhere
15195-
// else: measured on a live Postgres 16 under a non-public search_path,
15196-
// this returned `[]` for a table carrying a primary key AND a declared
15197-
// unique index. Empty here does not read as "I could not see"; it reads
15198-
// as "there are no indexes", which is what `assertConflictTargetHonoured`
15199-
// turns into a refusal — a silent fail-open on the identity check.
15200-
// Resolving by OID also removes the ambiguity a schema list would add:
15201-
// two schemas on the path can hold the same table name, and only one of
15202-
// them is the one a query would hit.
15203-
const res: any = await this.knex.raw(
15204-
`SELECT i.relname AS index_name, ix.indisunique AS is_unique, ix.indisprimary AS is_primary,
15205-
(ix.indpred IS NOT NULL) AS is_partial,
15206-
pg_get_indexdef(ix.indexrelid) AS indexdef
15207-
FROM pg_index ix
15208-
JOIN pg_class i ON i.oid = ix.indexrelid
15209-
WHERE ix.indrelid = to_regclass(?)
15210-
ORDER BY i.relname`,
15211-
[tableName],
15212-
);
15213-
for (const r of res.rows) {
15214-
const entry = upsert(r.index_name, r.is_unique === true, r.is_primary === true);
15215-
if (r.is_partial === true) entry.partial = true;
15216-
const parsed = parseIndexDdl(r.indexdef);
15217-
if (parsed) applyIndexKeyParts(entry, parsed.keyParts);
15218-
}
15219-
} else if (this.isMysql) {
15220-
// `EXPRESSION` only exists from MySQL 8.0.13 (functional indexes); on an
15221-
// older server or MariaDB the column is unknown and the query errors, so
15222-
// fall back rather than lose index introspection wholesale.
15223-
const columns = 'INDEX_NAME, NON_UNIQUE, COLUMN_NAME, EXPRESSION';
15224-
const statisticsQuery = (select: string) =>
15225-
this.knex.raw(
15226-
`SELECT ${select}
15227-
FROM information_schema.STATISTICS
15228-
WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ?
15229-
ORDER BY INDEX_NAME, SEQ_IN_INDEX`,
15230-
[tableName],
15231-
);
15232-
let res: any;
15233-
try {
15234-
res = await statisticsQuery(columns);
15235-
} catch {
15236-
res = await statisticsQuery('INDEX_NAME, NON_UNIQUE, COLUMN_NAME');
15237-
}
15238-
for (const r of res[0]) {
15239-
const entry = upsert(r.INDEX_NAME, Number(r.NON_UNIQUE) === 0, r.INDEX_NAME === 'PRIMARY');
15240-
if (r.COLUMN_NAME != null) entry.columns.push(r.COLUMN_NAME);
15241-
else if (r.EXPRESSION != null) applyIndexKeyParts(entry, [String(r.EXPRESSION)]);
15242-
}
15243-
await this.resolveHashShadowKeys(tableName, [...byName.values()]);
15244-
}
15245-
} catch (e) {
15246-
// Only a caller that can CORRECT a short read may ask for one (#7332).
15247-
if (opts.onFailure !== 'partial') throw e;
15248-
}
15249-
return [...byName.values()];
15166+
return introspectIndexes.call(host, tableName, opts);
1525015167
}
1525115168

1525215169
/**

0 commit comments

Comments
 (0)