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' ;
6983import { 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 - z A - Z 0 - 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+ }
0 commit comments