|
| 1 | +// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +import { describe, it, expect, afterEach, vi } from 'vitest'; |
| 4 | +import { SqlDriver, diffManagedIndexes, type PhysicalIndex } from '../src/index.js'; |
| 5 | + |
| 6 | +/** |
| 7 | + * A failed index read is not an empty index list (#7332). |
| 8 | + * |
| 9 | + * `introspectIndexes` used to wrap its whole dialect dispatch — SQLite, |
| 10 | + * Postgres and MySQL alike — in one bare `catch {}` and return `byName` in |
| 11 | + * whatever half-built state it had reached. The caller could not tell "this |
| 12 | + * table genuinely has no such index" from "the read failed and I am guessing", |
| 13 | + * so a transient SQLITE_BUSY / WAL hiccup was laundered into a confident, |
| 14 | + * specific, FALSE report that the database is missing declared indexes. |
| 15 | + * |
| 16 | + * The swallow's own justification — *"let creation handle conflicts"* — is |
| 17 | + * sound where it was written, {@link SqlDriver.getExistingIndexNames}: a |
| 18 | + * wrong-but-optimistic reading there costs one redundant `CREATE INDEX`, which |
| 19 | + * `syncDeclaredIndexes` absorbs as "already exists". Drift DETECTION has no |
| 20 | + * such backstop, and it inherited the swallow only because it was wired onto |
| 21 | + * the same function later (#3728). So the split is by call site, not by |
| 22 | + * removal: the creation seam opts into `{ onFailure: 'partial' }`, everything |
| 23 | + * else — detection included — sees the error. |
| 24 | + * |
| 25 | + * Note the asymmetry this closes: the sibling read in the very same detect |
| 26 | + * path, `introspectColumns`, has never swallowed. `reconcileAndWarnDrift` |
| 27 | + * already carries the handler for a throwing `detectTableDrift` |
| 28 | + * ("could not introspect '<table>' for drift detection"), and both CLI |
| 29 | + * consumers already `catch → printError → exit(1)`. The index dimension was |
| 30 | + * the one that could not reach any of them. |
| 31 | + */ |
| 32 | +describe('index introspection failure is not "no indexes" (#7332)', () => { |
| 33 | + let knexInstance: any; |
| 34 | + |
| 35 | + const makeDriver = (opts: any = {}) => { |
| 36 | + const d = new SqlDriver({ |
| 37 | + client: 'better-sqlite3', |
| 38 | + connection: { filename: ':memory:' }, |
| 39 | + useNullAsDefault: true, |
| 40 | + ...opts, |
| 41 | + }); |
| 42 | + knexInstance = (d as any).knex; |
| 43 | + (d as any).logger = { warn: vi.fn(), info: vi.fn(), error: vi.fn() }; |
| 44 | + return d; |
| 45 | + }; |
| 46 | + |
| 47 | + afterEach(async () => { |
| 48 | + await knexInstance?.destroy(); |
| 49 | + knexInstance = undefined; |
| 50 | + }); |
| 51 | + |
| 52 | + const productMeta = [ |
| 53 | + { |
| 54 | + name: 'product', |
| 55 | + fields: { |
| 56 | + id: { type: 'string' }, |
| 57 | + organization_id: { type: 'string' }, |
| 58 | + code: { type: 'string' }, |
| 59 | + }, |
| 60 | + indexes: [{ name: 'idx_product_code', fields: ['code'] }], |
| 61 | + }, |
| 62 | + ]; |
| 63 | + |
| 64 | + /** |
| 65 | + * Fail the index read the way a busy database does — mid-dispatch, on one |
| 66 | + * statement — rather than by stubbing the method under test. `PRAGMA |
| 67 | + * index_list` is the SQLite branch's second round-trip; `introspectColumns` |
| 68 | + * goes through `knex(table).columnInfo()` and is deliberately untouched, so |
| 69 | + * the column dimension still reads clean and only the index dimension breaks. |
| 70 | + */ |
| 71 | + const breakIndexRead = (driver: SqlDriver, message = 'SQLITE_BUSY: database is locked') => { |
| 72 | + const knex: any = (driver as any).knex; |
| 73 | + const real = knex.raw.bind(knex); |
| 74 | + // knex defines `raw` as non-writable (but configurable), so a plain |
| 75 | + // assignment throws — the swap has to go through `defineProperty`. |
| 76 | + const swap = (fn: any) => Object.defineProperty(knex, 'raw', { value: fn, configurable: true }); |
| 77 | + swap((sql: any, ...rest: any[]) => { |
| 78 | + if (typeof sql === 'string' && /PRAGMA\s+index_list/i.test(sql)) throw new Error(message); |
| 79 | + return real(sql, ...rest); |
| 80 | + }); |
| 81 | + return () => swap(real); |
| 82 | + }; |
| 83 | + |
| 84 | + // ── Detection sees the failure ──────────────────────────────────────────── |
| 85 | + |
| 86 | + it('detectManagedDrift propagates the read failure instead of reporting "(absent)"', async () => { |
| 87 | + const driver = makeDriver(); |
| 88 | + await driver.initObjects(productMeta); |
| 89 | + const restore = breakIndexRead(driver); |
| 90 | + try { |
| 91 | + await expect(driver.detectManagedDrift(productMeta as any)).rejects.toThrow(/SQLITE_BUSY/); |
| 92 | + } finally { |
| 93 | + restore(); |
| 94 | + } |
| 95 | + }); |
| 96 | + |
| 97 | + it('does not invent a create_index remedy for an index that is actually there', async () => { |
| 98 | + const driver = makeDriver(); |
| 99 | + await driver.initObjects(productMeta); |
| 100 | + |
| 101 | + // Ground truth first: the index the read is about to miss really exists. |
| 102 | + const physical: PhysicalIndex[] = await (driver as any).introspectIndexes('product'); |
| 103 | + expect(physical.map((p) => p.name)).toContain('idx_product_code'); |
| 104 | + |
| 105 | + const restore = breakIndexRead(driver); |
| 106 | + try { |
| 107 | + const drift = await driver.detectManagedDrift(productMeta as any).catch((e) => e); |
| 108 | + expect(drift).toBeInstanceOf(Error); |
| 109 | + } finally { |
| 110 | + restore(); |
| 111 | + } |
| 112 | + }); |
| 113 | + |
| 114 | + it('the boot path reports the failure as a failure, not as drift', async () => { |
| 115 | + const driver = makeDriver(); |
| 116 | + await driver.initObjects(productMeta); |
| 117 | + (driver as any).logger.warn.mockClear(); |
| 118 | + |
| 119 | + const restore = breakIndexRead(driver); |
| 120 | + try { |
| 121 | + await (driver as any).reconcileAndWarnDrift('product', productMeta[0].fields, productMeta[0].indexes); |
| 122 | + } finally { |
| 123 | + restore(); |
| 124 | + } |
| 125 | + |
| 126 | + const warnings = (driver as any).logger.warn.mock.calls.map((c: any[]) => String(c[0])); |
| 127 | + expect(warnings.some((w: string) => /could not introspect 'product' for drift detection/.test(w))).toBe(true); |
| 128 | + // The false report the swallow used to produce, verbatim from the differ. |
| 129 | + expect(warnings.some((w: string) => /has no such index/.test(w))).toBe(false); |
| 130 | + }); |
| 131 | + |
| 132 | + it('introspectIndexes throws by default — the honest contract for a read', async () => { |
| 133 | + const driver = makeDriver(); |
| 134 | + await driver.initObjects(productMeta); |
| 135 | + const restore = breakIndexRead(driver); |
| 136 | + try { |
| 137 | + await expect((driver as any).introspectIndexes('product')).rejects.toThrow(/SQLITE_BUSY/); |
| 138 | + } finally { |
| 139 | + restore(); |
| 140 | + } |
| 141 | + }); |
| 142 | + |
| 143 | + // ── Creation keeps the swallow, because it keeps the backstop ───────────── |
| 144 | + |
| 145 | + it('getExistingIndexNames still degrades to a partial read rather than throwing', async () => { |
| 146 | + const driver = makeDriver(); |
| 147 | + await driver.initObjects(productMeta); |
| 148 | + const restore = breakIndexRead(driver); |
| 149 | + try { |
| 150 | + await expect((driver as any).getExistingIndexNames('product')).resolves.toBeInstanceOf(Set); |
| 151 | + } finally { |
| 152 | + restore(); |
| 153 | + } |
| 154 | + }); |
| 155 | + |
| 156 | + it('a boot whose index read fails throughout still creates the declared index', async () => { |
| 157 | + // The whole justification for keeping the swallow on the creation path: an |
| 158 | + // optimistic wrong reading is corrected by the database rejecting the |
| 159 | + // duplicate, so the boot completes and the schema converges anyway. |
| 160 | + const driver = makeDriver(); |
| 161 | + const restore = breakIndexRead(driver); |
| 162 | + try { |
| 163 | + await driver.initObjects(productMeta); |
| 164 | + } finally { |
| 165 | + restore(); |
| 166 | + } |
| 167 | + |
| 168 | + const physical: PhysicalIndex[] = await (driver as any).introspectIndexes('product'); |
| 169 | + expect(physical.map((p) => p.name)).toContain('idx_product_code'); |
| 170 | + }); |
| 171 | + |
| 172 | + it('an index read that fails on the SECOND boot does not take the boot down', async () => { |
| 173 | + const driver = makeDriver(); |
| 174 | + await driver.initObjects(productMeta); |
| 175 | + const restore = breakIndexRead(driver); |
| 176 | + try { |
| 177 | + // Everything already exists; the read that would prove it is broken. |
| 178 | + await expect(driver.initObjects(productMeta)).resolves.not.toThrow(); |
| 179 | + } finally { |
| 180 | + restore(); |
| 181 | + } |
| 182 | + }); |
| 183 | + |
| 184 | + // ── A truncated read can never ARM a destructive remedy ─────────────────── |
| 185 | + |
| 186 | + it('losing physical indexes only ever removes drop remedies, never adds one', () => { |
| 187 | + // The differ's three sections all key off PRESENCE in the physical list: |
| 188 | + // `replace_unique_index` needs the legacy index present, `drop_index` needs |
| 189 | + // the orphan present, `recreate_index` needs the declared name present. |
| 190 | + // Dropping entries is therefore monotone — this pins that direction, which |
| 191 | + // is why a false read is loud-and-wrong rather than destructive. |
| 192 | + const full: PhysicalIndex[] = [ |
| 193 | + { name: 'product_code_unique', columns: ['code'], unique: true, primary: false }, |
| 194 | + { name: 'idx_product_stale', columns: ['legacy_col'], unique: false, primary: false }, |
| 195 | + ]; |
| 196 | + const args = { |
| 197 | + table: 'product', |
| 198 | + expected: [{ name: 'idx_product_code', columns: ['code'], unique: false }], |
| 199 | + legacy: [ |
| 200 | + { |
| 201 | + column: 'code', |
| 202 | + legacyNames: ['product_code_unique'], |
| 203 | + replacement: { name: 'uniq_product_organization_id_code', columns: ['organization_id', 'code'], unique: true as const }, |
| 204 | + }, |
| 205 | + ], |
| 206 | + tenantField: 'organization_id', |
| 207 | + }; |
| 208 | + |
| 209 | + const complete = diffManagedIndexes({ ...args, physical: full } as any); |
| 210 | + expect(complete.some((d) => d.op.type === 'replace_unique_index')).toBe(true); |
| 211 | + expect(complete.some((d) => d.op.type === 'drop_index')).toBe(true); |
| 212 | + |
| 213 | + const truncated = diffManagedIndexes({ ...args, physical: [] } as any); |
| 214 | + expect(truncated.some((d) => d.category === 'destructive')).toBe(false); |
| 215 | + expect(truncated.map((d) => d.op.type)).toEqual(['create_index']); |
| 216 | + }); |
| 217 | +}); |
0 commit comments