From c9d4a10f15b1c0a4b57c3a1c597041a108956d05 Mon Sep 17 00:00:00 2001 From: ciat-777 Date: Sun, 15 Mar 2026 13:16:50 +0800 Subject: [PATCH] fix(db): make external bootstrap idempotent --- src/server/db/runtimeSchemaBootstrap.test.ts | 75 ++++++++++++++++++++ src/server/db/runtimeSchemaBootstrap.ts | 34 ++++++++- 2 files changed, 108 insertions(+), 1 deletion(-) diff --git a/src/server/db/runtimeSchemaBootstrap.test.ts b/src/server/db/runtimeSchemaBootstrap.test.ts index fc378b6..9d4f460 100644 --- a/src/server/db/runtimeSchemaBootstrap.test.ts +++ b/src/server/db/runtimeSchemaBootstrap.test.ts @@ -38,4 +38,79 @@ describe('runtime schema bootstrap', () => { expect(executedSql.slice(0, expectedBootstrapSql.length)).toEqual(expectedBootstrapSql); }); + + it('ignores duplicate mysql index errors when replaying bootstrap statements', async () => { + const executedSql: string[] = []; + const targetSql = 'CREATE UNIQUE INDEX `model_availability_account_model_unique` ON `model_availability` (`account_id`, `model_name`(191))'; + + await ensureRuntimeDatabaseSchema({ + ...createStubClient('mysql', executedSql), + execute: async (sqlText: string) => { + executedSql.push(sqlText); + if (sqlText === targetSql) { + const error = new Error("Duplicate key name 'model_availability_account_model_unique'") as Error & { code?: string }; + error.code = 'ER_DUP_KEYNAME'; + throw error; + } + return []; + }, + }); + + expect(executedSql).toContain(targetSql); + }); + + it('replays the mysql bootstrap against an already-initialized schema', async () => { + const executedSql: string[] = []; + const createdStatements = new Set(); + + const mysqlClient = createStubClient('mysql', executedSql); + mysqlClient.execute = async (sqlText: string) => { + executedSql.push(sqlText); + const normalized = sqlText.trim().toLowerCase(); + const createsSchemaObject = normalized.startsWith('create table if not exists') + || normalized.startsWith('create index') + || normalized.startsWith('create unique index'); + + if (createsSchemaObject) { + if (createdStatements.has(sqlText)) { + const error = new Error( + normalized.startsWith('create table') + ? 'Table already exists' + : 'Duplicate key name during bootstrap replay', + ) as Error & { code?: string }; + error.code = normalized.startsWith('create table') ? 'ER_TABLE_EXISTS_ERROR' : 'ER_DUP_KEYNAME'; + throw error; + } + createdStatements.add(sqlText); + } + + return []; + }; + + await ensureRuntimeDatabaseSchema(mysqlClient); + await ensureRuntimeDatabaseSchema(mysqlClient); + + expect(executedSql.length).toBeGreaterThan(createdStatements.size); + expect(createdStatements.size).toBeGreaterThan(0); + }); + + it('ignores postgres relation-already-exists errors when replaying bootstrap statements', async () => { + const executedSql: string[] = []; + const targetSql = 'CREATE UNIQUE INDEX "model_availability_account_model_unique" ON "model_availability" ("account_id", "model_name")'; + + await ensureRuntimeDatabaseSchema({ + ...createStubClient('postgres', executedSql), + execute: async (sqlText: string) => { + executedSql.push(sqlText); + if (sqlText === targetSql) { + const error = new Error('relation "model_availability_account_model_unique" already exists') as Error & { code?: string }; + error.code = '42P07'; + throw error; + } + return []; + }, + }); + + expect(executedSql).toContain(targetSql); + }); }); diff --git a/src/server/db/runtimeSchemaBootstrap.ts b/src/server/db/runtimeSchemaBootstrap.ts index 1ee2ef1..3121489 100644 --- a/src/server/db/runtimeSchemaBootstrap.ts +++ b/src/server/db/runtimeSchemaBootstrap.ts @@ -28,6 +28,38 @@ export interface RuntimeSchemaConnectionInput { ssl?: boolean; } +function normalizeSchemaErrorMessage(error: unknown): string { + if (typeof error === 'object' && error && 'message' in error) { + return String((error as { message?: unknown }).message || ''); + } + return String(error || ''); +} + +function isExistingSchemaObjectError(error: unknown): boolean { + const lowered = normalizeSchemaErrorMessage(error).toLowerCase(); + const code = typeof error === 'object' && error && 'code' in error + ? String((error as { code?: unknown }).code || '') + : ''; + + return code === 'ER_DUP_KEYNAME' + || code === 'ER_TABLE_EXISTS_ERROR' + || code === '42P07' + || code === '42710' + || lowered.includes('already exists') + || lowered.includes('duplicate key name') + || lowered.includes('relation') && lowered.includes('already exists'); +} + +async function executeBootstrapStatement(client: RuntimeSchemaClient, sqlText: string): Promise { + try { + await client.execute(sqlText); + } catch (error) { + if (!isExistingSchemaObjectError(error)) { + throw error; + } + } +} + function validateIdentifier(identifier: string): string { if (!/^[a-z_][a-z0-9_]*$/i.test(identifier)) { throw new Error(`Invalid SQL identifier: ${identifier}`); @@ -212,7 +244,7 @@ export async function ensureRuntimeDatabaseSchema(client: RuntimeSchemaClient): : readGeneratedBootstrapStatements(client.dialect); for (const sqlText of statements) { - await client.execute(sqlText); + await executeBootstrapStatement(client, sqlText); } await ensureLegacySchemaCompatibility(createLegacySchemaInspector(client));