Skip to content

armgit / dbx

Public Imported from GitHub
0

25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。

feat(diff): add continue on error option to schema deploy

Xsyl.waya5048531494e
diff --git a/apps/desktop/src/components/diff/SchemaDiffDeployStep.vue b/apps/desktop/src/components/diff/SchemaDiffDeployStep.vue
index 27f80300a3..ecad0be1dc 100644
--- a/apps/desktop/src/components/diff/SchemaDiffDeployStep.vue
+++ b/apps/desktop/src/components/diff/SchemaDiffDeployStep.vue
@@ -52,12 +52,15 @@ const props = defineProps<{
ignoreForeignKeyChecks?: boolean;
/** Whether the target database is MySQL, the only engine that gets the option. */
showIgnoreForeignKeyChecks?: boolean;
+ /** Skip failed statements and keep running the rest of the deploy script. */
+ continueOnError?: boolean;
}>();
const emit = defineEmits<{
"update:deploySql": [sql: string];
"update:deploySqlMode": [mode: "forward" | "rollback"];
"update:ignoreForeignKeyChecks": [enabled: boolean];
+ "update:continueOnError": [enabled: boolean];
back: [];
deploy: [];
}>();
@@ -395,6 +398,10 @@ function getObjectIconColor(kind: DiffObjectKind): string {
<input type="checkbox" class="accent-primary" :checked="ignoreForeignKeyChecks === true" :disabled="executing" @change="emit('update:ignoreForeignKeyChecks', ($event.target as HTMLInputElement).checked)" />
{{ t("diff.ignoreForeignKeyChecks") }}
</label>
+ <label class="flex items-center gap-1.5 text-xs" :class="executing ? 'cursor-not-allowed opacity-50' : 'cursor-pointer'" :title="t('diff.continueOnErrorHint')">
+ <input type="checkbox" class="accent-primary" :checked="continueOnError === true" :disabled="executing" @change="emit('update:continueOnError', ($event.target as HTMLInputElement).checked)" />
+ {{ t("diff.continueOnError") }}
+ </label>
</div>
<div class="flex items-center gap-2">
<Button variant="ghost" size="sm" class="h-7 text-xs gap-1" @click="$emit('back')">
diff --git a/apps/desktop/src/components/diff/SchemaDiffDialog.vue b/apps/desktop/src/components/diff/SchemaDiffDialog.vue
index 1d97f7a566..f273f67c87 100644
--- a/apps/desktop/src/components/diff/SchemaDiffDialog.vue
+++ b/apps/desktop/src/components/diff/SchemaDiffDialog.vue
@@ -23,7 +23,7 @@ import SideBySideTextDiff, { type TextDiffSide } from "@/components/common/SideB
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { getSchemaDiffOptionsForDbType } from "@/lib/schema/schemaDiffOptions";
-import { buildDeployTxResult } from "@/lib/schema/deployTxResult";
+import { buildContinueOnErrorDeployLog, buildDeployTxResult, type DeployTxResult } from "@/lib/schema/deployTxResult";
import { getSchemaDiffNextProgressStep, isSchemaDiffPostgresLike, shouldLoadSchemaDiffExtraObjectPhase, type SchemaDiffProgressPhase } from "@/lib/schema/schemaDiffProgress";
import { createSchemaDiffTableListLoader } from "@/lib/schema/schemaDiffTableList";
import { countSchemaDiffActionableObjects, partitionSchemaDiffObjectsByResultTab, swapSchemaDiffRoutineMappings } from "@/lib/schema/schemaDiffRoutine";
@@ -164,7 +164,7 @@ const executing = ref(false);
const lastDiffResult = ref<SchemaDiffPreparation | null>(null);
const targetDbVersion = ref<string | null>(null);
const showResultDialog = ref(false);
-const deployResult = ref<{ success: boolean; status?: string; message: string; affectedRows?: number; error?: string } | null>(null);
+const deployResult = ref<DeployTxResult | null>(null);
const partitionedDiffObjects = computed(() => partitionSchemaDiffObjectsByResultTab(diffObjects.value));
const tableDiffObjects = computed(() => partitionedDiffObjects.value.tableObjects);
@@ -205,6 +205,7 @@ const deploySqlMode = ref<"forward" | "rollback">("forward");
// the backend — for MySQL targets alone; the backend re-checks the target type and
// returns every other engine's script unchanged.
const ignoreForeignKeyChecks = ref(false);
+const continueOnError = ref(false);
const isMysqlDeployTarget = computed(() => targetEngineDbType.value === "mysql");
const effectiveIgnoreForeignKeyChecks = computed(() => ignoreForeignKeyChecks.value && isMysqlDeployTarget.value);
@@ -437,6 +438,7 @@ function resetComparisonResultState() {
dependencyGraph.value = null;
deploySqlMode.value = "forward";
ignoreForeignKeyChecks.value = false;
+ continueOnError.value = false;
showConfirmDialog.value = false;
showResultDialog.value = false;
deployResult.value = null;
@@ -1015,6 +1017,13 @@ async function executeDeploySql() {
sql: selectedDeploySql.value,
source: t("production.sourceSchemaDiff"),
execute: async () => {
+ if (continueOnError.value) {
+ const results = await api.executeMulti(targetConnectionId.value, targetDatabase.value, selectedDeploySql.value, targetSchema.value || undefined, undefined, {
+ continueOnError: true,
+ maxRows: 1,
+ });
+ return buildContinueOnErrorDeployLog(results);
+ }
const txLog = await api.executeScriptWith2pc(targetConnectionId.value, targetDatabase.value, [selectedDeploySql.value], targetSchema.value, destructiveStatements.value.length > 0);
return txLog;
},
@@ -1526,6 +1535,7 @@ const targetConnectionInfo = computed(() => {
<SchemaDiffDeployStep
v-model:deploy-sql="selectedDeploySql"
v-model:ignore-foreign-key-checks="ignoreForeignKeyChecks"
+ v-model:continue-on-error="continueOnError"
:show-ignore-foreign-key-checks="isMysqlDeployTarget"
:selected-objects="currentTabDiffObjects"
:target-connection-id="targetConnectionId"
@@ -1614,6 +1624,14 @@ const targetConnectionInfo = computed(() => {
<li v-for="(item, index) in destructiveStatements" :key="`${item.objectType}-${index}`" class="truncate" :title="item.statement">{{ item.action.toUpperCase() }} {{ item.objectType }}: {{ item.statement }}</li>
</ul>
</div>
+
+ <label class="flex items-start gap-2 rounded border border-yellow-300 bg-yellow-50 p-3 text-xs text-yellow-800 dark:border-yellow-700 dark:bg-yellow-950/30 dark:text-yellow-200" :class="executing ? 'cursor-not-allowed opacity-60' : 'cursor-pointer'">
+ <input v-model="continueOnError" type="checkbox" class="mt-0.5 accent-primary" :disabled="executing" />
+ <span>
+ <span class="font-medium">{{ t("diff.continueOnError") }}</span>
+ <span class="mt-1 block">{{ t("diff.continueOnErrorHint") }}</span>
+ </span>
+ </label>
</div>
<DialogFooter>
@@ -1633,14 +1651,24 @@ const targetConnectionInfo = computed(() => {
<DialogTitle class="flex items-center gap-2" :class="deployResult?.success ? 'text-green-500' : 'text-destructive'">
<AlertTriangle v-if="!deployResult?.success" class="h-5 w-5" />
<CircleCheck v-else class="h-5 w-5" />
- <template v-if="deployResult?.status === 'mixed'">{{ t("diff.deployMixedTitle") }}</template>
+ <template v-if="deployResult?.status === 'completed_with_errors'">{{ t("diff.deployCompletedWithErrorsTitle") }}</template>
+ <template v-else-if="deployResult?.status === 'mixed'">{{ t("diff.deployMixedTitle") }}</template>
<template v-else-if="deployResult?.status === 'rolled_back'">{{ t("diff.deployRolledBackTitle") }}</template>
<template v-else>{{ deployResult?.success ? t("diff.deploySuccess") : t("diff.deployFailed") }}</template>
</DialogTitle>
</DialogHeader>
<div class="py-2">
- <div v-if="deployResult?.status === 'mixed'" class="space-y-2">
+ <div v-if="deployResult?.status === 'completed_with_errors'" class="space-y-2">
+ <p class="text-sm text-destructive-foreground">{{ deployResult.message }}</p>
+ <div v-if="deployResult.failures?.length" class="max-h-56 space-y-2 overflow-auto rounded border border-destructive/30 bg-destructive/5 p-2 text-xs">
+ <div v-for="failure in deployResult.failures" :key="failure.index" class="space-y-1">
+ <div class="font-medium text-destructive">{{ t("diff.statementNumber", { index: failure.index + 1 }) }}</div>
+ <pre class="whitespace-pre-wrap font-mono">{{ failure.error }}</pre>
+ </div>
+ </div>
+ </div>
+ <div v-else-if="deployResult?.status === 'mixed'" class="space-y-2">
<p class="text-sm text-destructive-foreground">{{ deployResult.message }}</p>
<div class="bg-yellow-50 border border-yellow-300 p-3 rounded text-xs text-yellow-800">
{{ t("diff.deployMixedWarning") }}
diff --git a/apps/desktop/src/components/diff/__tests__/SchemaDiffDeployStep.spec.ts b/apps/desktop/src/components/diff/__tests__/SchemaDiffDeployStep.spec.ts
index ee96d08720..fef4a7c4d1 100644
--- a/apps/desktop/src/components/diff/__tests__/SchemaDiffDeployStep.spec.ts
+++ b/apps/desktop/src/components/diff/__tests__/SchemaDiffDeployStep.spec.ts
@@ -54,8 +54,8 @@ vi.mock("codemirror", () => ({ basicSetup: [] }));
const mountedApps: App[] = [];
-async function mountDeployStep(extraProps: Record<string, unknown> = {}, onIgnoreForeignKeyChecks?: (value: boolean) => void) {
- const state = reactive({ ignoreForeignKeyChecks: false });
+async function mountDeployStep(extraProps: Record<string, unknown> = {}, onIgnoreForeignKeyChecks?: (value: boolean) => void, onContinueOnError?: (value: boolean) => void) {
+ const state = reactive({ ignoreForeignKeyChecks: false, continueOnError: false });
const container = document.createElement("div");
document.body.append(container);
const app = createApp(
@@ -70,10 +70,15 @@ async function mountDeployStep(extraProps: Record<string, unknown> = {}, onIgnor
executing: false,
...extraProps,
ignoreForeignKeyChecks: state.ignoreForeignKeyChecks,
+ continueOnError: state.continueOnError,
"onUpdate:ignoreForeignKeyChecks": (value: boolean) => {
state.ignoreForeignKeyChecks = value;
onIgnoreForeignKeyChecks?.(value);
},
+ "onUpdate:continueOnError": (value: boolean) => {
+ state.continueOnError = value;
+ onContinueOnError?.(value);
+ },
}),
}),
);
@@ -89,6 +94,39 @@ function foreignKeyCheckbox(container: HTMLElement): HTMLInputElement | null {
return label?.querySelector<HTMLInputElement>('input[type="checkbox"]') ?? null;
}
+function continueOnErrorCheckbox(container: HTMLElement): HTMLInputElement | null {
+ const label = [...container.querySelectorAll<HTMLLabelElement>("label")].find((candidate) => candidate.textContent?.includes("diff.continueOnError"));
+ return label?.querySelector<HTMLInputElement>('input[type="checkbox"]') ?? null;
+}
+
+describe("SchemaDiffDeployStep continue-on-error option", () => {
+ it("is offered unchecked by default and reports both states to the dialog", async () => {
+ const updates: boolean[] = [];
+ const { container, state } = await mountDeployStep({}, undefined, (value) => updates.push(value));
+
+ const checkbox = continueOnErrorCheckbox(container);
+ expect(checkbox).not.toBeNull();
+ expect(checkbox?.checked).toBe(false);
+ expect(checkbox?.closest("label")?.getAttribute("title")).toBe("diff.continueOnErrorHint");
+
+ checkbox!.checked = true;
+ checkbox!.dispatchEvent(new Event("change"));
+ await nextTick();
+ checkbox!.checked = false;
+ checkbox!.dispatchEvent(new Event("change"));
+ await nextTick();
+
+ expect(updates).toEqual([true, false]);
+ expect(state.continueOnError).toBe(false);
+ });
+
+ it("is disabled while the deploy is running", async () => {
+ const { container } = await mountDeployStep({ executing: true });
+
+ expect(continueOnErrorCheckbox(container)?.disabled).toBe(true);
+ });
+});
+
afterEach(() => {
for (const app of mountedApps.splice(0)) app.unmount();
document.body.innerHTML = "";
diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.ts
index 17a2523a81..00e9a20f07 100644
--- a/apps/desktop/src/i18n/locales/en.ts
+++ b/apps/desktop/src/i18n/locales/en.ts
@@ -8298,6 +8298,11 @@ export default {
ignoreComments: "Ignore comment differences",
ignoreForeignKeyChecks: "Ignore foreign key checks",
ignoreForeignKeyChecksHint: "Wraps the script in SET FOREIGN_KEY_CHECKS = 0 / = 1 so tables can be dropped and recreated in any order",
+ continueOnError: "Continue on error",
+ continueOnErrorHint: "Runs the script statement by statement: failed statements are skipped so later statements still run; already executed statements are not rolled back.",
+ deployCompletedWithErrorsTitle: "Deploy finished with failed statements",
+ deployCompletedWithErrors: "Executed {executedCount} statements; {failedCount} failed. Failed statements were skipped and later statements still ran.",
+ statementNumber: "Statement {index}",
compare: "Compare",
comparing: "Comparing schemas...",
noDifferences: "No differences found",
diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.ts
index b4a58af7ea..e4dcd1457c 100644
--- a/apps/desktop/src/i18n/locales/es.ts
+++ b/apps/desktop/src/i18n/locales/es.ts
@@ -7419,6 +7419,11 @@ export default withEnglishFallback({
ignoreComments: "Ignorar diferencias de comentarios",
ignoreForeignKeyChecks: "Ignorar la comprobación de claves foráneas",
ignoreForeignKeyChecksHint: "Envuelve el script con SET FOREIGN_KEY_CHECKS = 0 / = 1 para poder eliminar y recrear tablas en cualquier orden",
+ continueOnError: "Continuar en caso de error",
+ continueOnErrorHint: "Ejecuta el script instrucción por instrucción: las instrucciones con error se omiten y las siguientes continúan ejecutándose; las instrucciones ya ejecutadas no se revierten.",
+ deployCompletedWithErrorsTitle: "Implementación finalizada con instrucciones fallidas",
+ deployCompletedWithErrors: "Se ejecutaron {executedCount} instrucciones; {failedCount} fallaron. Las instrucciones fallidas se omitieron y las siguientes continuaron ejecutándose.",
+ statementNumber: "Instrucción {index}",
compare: "Comparar",
comparing: "Comparando esquemas...",
noDifferences: "No se encontraron diferencias",
diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.ts
index dc23bce408..11615c18f9 100644
--- a/apps/desktop/src/i18n/locales/it.ts
+++ b/apps/desktop/src/i18n/locales/it.ts
@@ -7203,6 +7203,11 @@ export default withEnglishFallback({
ignoreComments: "Ignora differenze nei commenti",
ignoreForeignKeyChecks: "Ignora i controlli delle chiavi esterne",
ignoreForeignKeyChecksHint: "Racchiude lo script tra SET FOREIGN_KEY_CHECKS = 0 / = 1 per eliminare e ricreare le tabelle in qualsiasi ordine",
+ continueOnError: "Continua in caso di errore",
+ continueOnErrorHint: "Esegue lo script istruzione per istruzione: le istruzioni non riuscite vengono saltate e quelle successive continuano a essere eseguite; le istruzioni già eseguite non vengono annullate.",
+ deployCompletedWithErrorsTitle: "Distribuzione completata con istruzioni non riuscite",
+ deployCompletedWithErrors: "Eseguite {executedCount} istruzioni; {failedCount} non riuscite. Le istruzioni non riuscite sono state saltate e quelle successive sono state comunque eseguite.",
+ statementNumber: "Istruzione {index}",
compare: "Confronta",
comparing: "Confronto degli schemi...",
noDifferences: "Nessuna differenza trovata",
diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.ts
index 27e8809661..a81fc940a4 100644
--- a/apps/desktop/src/i18n/locales/ja.ts
+++ b/apps/desktop/src/i18n/locales/ja.ts
@@ -7231,6 +7231,11 @@ export default withEnglishFallback({
ignoreComments: "コメントの差分を無視",
ignoreForeignKeyChecks: "外部キー検査を無視",
ignoreForeignKeyChecksHint: "スクリプトの前後に SET FOREIGN_KEY_CHECKS = 0 / = 1 を付け、テーブルを任意の順序で削除・再作成できるようにします",
+ continueOnError: "エラー時も続行",
+ continueOnErrorHint: "スクリプトを1文ずつ実行します。失敗した文はスキップし、後続の文は実行を続けます。実行済みの文はロールバックされません。",
+ deployCompletedWithErrorsTitle: "デプロイ完了(失敗した文あり)",
+ deployCompletedWithErrors: "{executedCount} 件の文を実行し、{failedCount} 件が失敗しました。失敗した文はスキップされ、後続の文は実行されました。",
+ statementNumber: "{index} 番目の文",
compare: "比較",
comparing: "スキーマを比較中...",
noDifferences: "差分が見つかりません",
diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.ts
index 2c68e9c1ef..70762f2cec 100644
--- a/apps/desktop/src/i18n/locales/ko.ts
+++ b/apps/desktop/src/i18n/locales/ko.ts
@@ -7070,6 +7070,11 @@ export default withEnglishFallback({
ignoreComments: "주석 차이 무시",
ignoreForeignKeyChecks: "외래 키 검사 무시",
ignoreForeignKeyChecksHint: "스크립트 앞뒤에 SET FOREIGN_KEY_CHECKS = 0 / = 1을 추가해 테이블을 임의 순서로 삭제하고 다시 만들 수 있게 합니다",
+ continueOnError: "오류 발생 시 계속",
+ continueOnErrorHint: "스크립트를 문장 단위로 실행합니다. 실패한 문장은 건너뛰고 이후 문장은 계속 실행되며, 이미 실행된 문장은 롤백되지 않습니다.",
+ deployCompletedWithErrorsTitle: "배포 완료(실패한 문장 있음)",
+ deployCompletedWithErrors: "{executedCount}개 문장을 실행했으며 {failedCount}개가 실패했습니다. 실패한 문장은 건너뛰고 이후 문장은 계속 실행되었습니다.",
+ statementNumber: "{index}번째 문장",
compare: "비교",
comparing: "스키마를 비교하는 중...",
noDifferences: "차이점이 없습니다",
diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.ts
index 700ccecb9b..e38b2596f7 100644
--- a/apps/desktop/src/i18n/locales/pt-BR.ts
+++ b/apps/desktop/src/i18n/locales/pt-BR.ts
@@ -7197,6 +7197,11 @@ export default withEnglishFallback({
ignoreComments: "Ignorar diferenças de comentários",
ignoreForeignKeyChecks: "Ignorar verificações de chave estrangeira",
ignoreForeignKeyChecksHint: "Envolve o script com SET FOREIGN_KEY_CHECKS = 0 / = 1 para permitir remover e recriar tabelas em qualquer ordem",
+ continueOnError: "Continuar em caso de erro",
+ continueOnErrorHint: "Executa o script instrução por instrução: instruções com erro são ignoradas e as seguintes continuam a ser executadas; instruções já executadas não são revertidas.",
+ deployCompletedWithErrorsTitle: "Implantação concluída com instruções com falha",
+ deployCompletedWithErrors: "Foram executadas {executedCount} instruções; {failedCount} falharam. As instruções com falha foram ignoradas e as seguintes continuaram a ser executadas.",
+ statementNumber: "Instrução {index}",
compare: "Comparar",
comparing: "Comparando schemas...",
noDifferences: "Nenhuma diferença encontrada",
diff --git a/apps/desktop/src/i18n/locales/ru.ts b/apps/desktop/src/i18n/locales/ru.ts
index 6740bbe1c5..58710a45d7 100644
--- a/apps/desktop/src/i18n/locales/ru.ts
+++ b/apps/desktop/src/i18n/locales/ru.ts
@@ -8516,6 +8516,11 @@ export default withEnglishFallback({
ignoreComments: "Игнорировать различия комментариев",
ignoreForeignKeyChecks: "Игнорировать проверку внешних ключей",
ignoreForeignKeyChecksHint: "Оборачивает скрипт в SET FOREIGN_KEY_CHECKS = 0 / = 1, позволяя удалять и создавать таблицы в любом порядке",
+ continueOnError: "Продолжать при ошибке",
+ continueOnErrorHint: "Выполняет скрипт по одной инструкции: неудачные инструкции пропускаются, а последующие продолжают выполняться; уже выполненные инструкции не откатываются.",
+ deployCompletedWithErrorsTitle: "Развёртывание завершено с ошибками в инструкциях",
+ deployCompletedWithErrors: "Выполнено инструкций: {executedCount}; с ошибкой: {failedCount}. Неудачные инструкции пропущены, последующие выполнены.",
+ statementNumber: "Инструкция {index}",
compare: "Сравнить",
comparing: "Сравнение схем...",
noDifferences: "Различия не найдены",
diff --git a/apps/desktop/src/i18n/locales/th.ts b/apps/desktop/src/i18n/locales/th.ts
index 387ea3b62a..b3876eb07b 100644
--- a/apps/desktop/src/i18n/locales/th.ts
+++ b/apps/desktop/src/i18n/locales/th.ts
@@ -8954,6 +8954,11 @@ export default withEnglishFallback({
ignoreComments: "ละเว้นความแตกต่างของคอมเมนต์",
ignoreForeignKeyChecks: "ละเว้นการตรวจสอบ foreign key",
ignoreForeignKeyChecksHint: "ครอบ script ด้วย SET FOREIGN_KEY_CHECKS = 0 / = 1 เพื่อให้ลบและสร้างตารางใหม่ได้ทุกลำดับ",
+ continueOnError: "ดำเนินการต่อเมื่อเกิดข้อผิดพลาด",
+ continueOnErrorHint: "รันสคริปต์ทีละคำสั่ง: คำสั่งที่ล้มเหลวจะถูกข้ามและคำสั่งถัดไปจะยังคงทำงานต่อ; คำสั่งที่รันไปแล้วจะไม่ถูกย้อนกลับทั้งหมด",
+ deployCompletedWithErrorsTitle: "ปรับใช้เสร็จสิ้นแต่มีคำสั่งที่ล้มเหลว",
+ deployCompletedWithErrors: "รันแล้ว {executedCount} คำสั่ง ล้มเหลว {failedCount} คำสั่ง คำสั่งที่ล้มเหลวถูกข้ามและคำสั่งถัดไปยังคงทำงานต่อ",
+ statementNumber: "คำสั่งที่ {index}",
compare: "เปรียบเทียบ",
comparing: "กำลังเปรียบเทียบ Schema…",
noDifferences: "ไม่พบความแตกต่าง",
diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.ts
index 953a282461..48b4e345e4 100644
--- a/apps/desktop/src/i18n/locales/zh-CN.ts
+++ b/apps/desktop/src/i18n/locales/zh-CN.ts
@@ -8280,6 +8280,11 @@ export default withEnglishFallback({
ignoreComments: "忽略注释差异",
ignoreForeignKeyChecks: "忽略外键检查",
ignoreForeignKeyChecksHint: "在脚本首尾加上 SET FOREIGN_KEY_CHECKS = 0 / = 1,允许以任意顺序删除和重建表",
+ continueOnError: "遇错继续",
+ continueOnErrorHint: "逐条提交:出错的语句会被跳过,后续语句继续执行;已执行的语句不会整体回滚。",
+ deployCompletedWithErrorsTitle: "部署完成(部分语句失败)",
+ deployCompletedWithErrors: "已执行 {executedCount} 条语句,其中 {failedCount} 条失败;失败语句已跳过,后续语句已继续执行。",
+ statementNumber: "第 {index} 条语句",
compare: "开始比较",
comparing: "正在比较结构...",
noDifferences: "两个数据库结构完全一致",
diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.ts
index 834303c0ea..ac5263666a 100644
--- a/apps/desktop/src/i18n/locales/zh-TW.ts
+++ b/apps/desktop/src/i18n/locales/zh-TW.ts
@@ -6546,6 +6546,11 @@ export default withEnglishFallback({
ignoreComments: "忽略註解差異",
ignoreForeignKeyChecks: "忽略外鍵檢查",
ignoreForeignKeyChecksHint: "在指令碼開頭與結尾加上 SET FOREIGN_KEY_CHECKS = 0 / = 1,允許以任意順序刪除與重建資料表",
+ continueOnError: "遇錯繼續",
+ continueOnErrorHint: "逐條提交:出錯的語句會被跳過,後續語句繼續執行;已執行的語句不會整體回滾。",
+ deployCompletedWithErrorsTitle: "部署完成(部分語句失敗)",
+ deployCompletedWithErrors: "已執行 {executedCount} 條語句,其中 {failedCount} 條失敗;失敗語句已跳過,後續語句已繼續執行。",
+ statementNumber: "第 {index} 條語句",
compare: "開始比較",
comparing: "正在比較結構……",
noDifferences: "兩個資料庫結構完全一致",
diff --git a/apps/desktop/src/lib/__tests__/schema/deployTxResult.spec.ts b/apps/desktop/src/lib/__tests__/schema/deployTxResult.spec.ts
new file mode 100644
index 0000000000..03f1e248ba
--- /dev/null
+++ b/apps/desktop/src/lib/__tests__/schema/deployTxResult.spec.ts
@@ -0,0 +1,83 @@
+import { describe, expect, it } from "vitest";
+import type { BackendError } from "@/lib/backend/errorUtils";
+import { buildContinueOnErrorDeployLog, buildDeployTxResult } from "@/lib/schema/deployTxResult";
+import type { QueryResult } from "@/types/database";
+
+function statementResult(overrides: Partial<QueryResult> = {}): QueryResult {
+ return {
+ columns: [],
+ rows: [],
+ affected_rows: 0,
+ execution_time_ms: 1,
+ ...overrides,
+ };
+}
+
+function backendError(detail: string): BackendError {
+ return {
+ version: 1,
+ code: "DBX-SQL-0001",
+ messageKey: "errors.sqlExecution",
+ messageParams: {},
+ source: "test",
+ operationOutcome: "not_started",
+ detail,
+ };
+}
+
+const t = (key: string, params?: Record<string, unknown>) => (params ? `${key}:${JSON.stringify(params)}` : key);
+
+describe("buildContinueOnErrorDeployLog", () => {
+ it("reports a clean commit when every statement succeeded", () => {
+ const log = buildContinueOnErrorDeployLog([statementResult({ statement_index: 0 }), statementResult({ statement_index: 1, execution_time_ms: 2 })]);
+
+ expect(log.status).toBe("committed");
+ expect(log.executed_count).toBe(2);
+ expect(log.statement_count).toBe(2);
+ expect(log.metadata.failures).toEqual([]);
+ expect(log.error).toBeNull();
+ });
+
+ it("keeps going past a failure and records the failed statement index and error", () => {
+ const log = buildContinueOnErrorDeployLog([statementResult({ statement_index: 0 }), statementResult({ statement_index: 1, execution_error: true, error: backendError("Duplicate column name 'nickname'") }), statementResult({ statement_index: 2 })]);
+
+ expect(log.status).toBe("completed_with_errors");
+ expect(log.executed_count).toBe(3);
+ expect(log.statement_count).toBe(3);
+ expect(log.metadata.failures).toEqual([{ index: 1, error: "Duplicate column name 'nickname'" }]);
+ expect(log.error).toContain("#2: Duplicate column name 'nickname'");
+ });
+
+ it("falls back to the result position when the backend did not tag the statement index", () => {
+ const log = buildContinueOnErrorDeployLog([statementResult(), statementResult({ execution_error: true, error: backendError("syntax error") })]);
+
+ expect(log.metadata.failures).toEqual([{ index: 1, error: "syntax error" }]);
+ });
+});
+
+describe("buildDeployTxResult continue-on-error", () => {
+ it("surfaces the executed/failed counts and every failed statement", () => {
+ const log = buildContinueOnErrorDeployLog([statementResult({ statement_index: 0 }), statementResult({ statement_index: 1, execution_error: true, error: backendError("boom") }), statementResult({ statement_index: 2, execution_error: true, error: backendError("bang") })]);
+
+ const result = buildDeployTxResult(log, t);
+
+ expect(result.success).toBe(false);
+ expect(result.status).toBe("completed_with_errors");
+ expect(result.message).toContain("diff.deployCompletedWithErrors");
+ expect(result.message).toContain('"executedCount":3');
+ expect(result.message).toContain('"failedCount":2');
+ expect(result.failedCount).toBe(2);
+ expect(result.failures).toEqual([
+ { index: 1, error: "boom" },
+ { index: 2, error: "bang" },
+ ]);
+ });
+
+ it("treats an all-success continue-on-error run as a normal commit", () => {
+ const result = buildDeployTxResult(buildContinueOnErrorDeployLog([statementResult({ statement_index: 0 })]), t);
+
+ expect(result.success).toBe(true);
+ expect(result.status).toBe("committed");
+ expect(result.failedCount).toBeUndefined();
+ });
+});
diff --git a/apps/desktop/src/lib/schema/deployTxResult.ts b/apps/desktop/src/lib/schema/deployTxResult.ts
index b17cbed53d..aa02a301c2 100644
--- a/apps/desktop/src/lib/schema/deployTxResult.ts
+++ b/apps/desktop/src/lib/schema/deployTxResult.ts
@@ -1,3 +1,12 @@
+import { formatError } from "@/lib/backend/errorUtils";
+import type { QueryResult } from "@/types/database";
+
+export interface DeployFailure {
+ /** Zero-based index of the statement that failed. */
+ index: number;
+ error: string;
+}
+
export interface DeployTxResult {
success: boolean;
status?: string;
@@ -6,6 +15,44 @@ export interface DeployTxResult {
error?: string;
executedCount?: number;
statementCount?: number;
+ failedCount?: number;
+ failures?: DeployFailure[];
+}
+
+/**
+ * Builds a deploy log for the schema-diff "continue on error" mode.
+ *
+ * Unlike the transactional deploy path, `executeMulti(..., { continueOnError: true })`
+ * commits every statement on its own and keeps running after a failure. The result is
+ * shaped like a transaction log so the existing deploy result dialog can render it,
+ * with the failed statements carried in `metadata.failures`.
+ */
+export function buildContinueOnErrorDeployLog(results: QueryResult[]): Record<string, any> {
+ const failures: DeployFailure[] = [];
+ results.forEach((result, position) => {
+ if (result.execution_error !== true && !result.error) return;
+ failures.push({
+ index: result.statement_index ?? position,
+ error: result.error ? formatError(result.error) : "Statement failed",
+ });
+ });
+ const now = new Date().toISOString();
+ const suffix = globalThis.crypto?.randomUUID?.() ?? `${Date.now()}-${Math.random().toString(16).slice(2)}`;
+ return {
+ transaction_id: `deploy_continue_${suffix}`,
+ status: failures.length ? "completed_with_errors" : "committed",
+ participants: [{ id: "connection", name: "schema-diff", role: "database" }],
+ created_at: now,
+ updated_at: now,
+ executed_count: results.length,
+ statement_count: results.length,
+ error: failures.length ? failures.map((failure) => `#${failure.index + 1}: ${failure.error}`).join("\n") : null,
+ metadata: {
+ source: "schema_diff_deploy",
+ mode: "continue_on_error",
+ failures,
+ },
+ };
}
export function buildDeployTxResult(txLog: any, t: (key: string, params?: Record<string, any>) => string): DeployTxResult {
@@ -14,6 +61,8 @@ export function buildDeployTxResult(txLog: any, t: (key: string, params?: Record
const executedCount = txLog?.executedCount ?? txLog?.executed_count;
const statementCount = txLog?.statementCount ?? txLog?.statement_count;
const affectedRows = txLog?.metadata?.affected_rows ?? txLog?.affectedRows;
+ const failures: DeployFailure[] = Array.isArray(txLog?.metadata?.failures) ? txLog.metadata.failures : [];
+ const failedCount = failures.length;
if (status === "committed") {
return {
@@ -25,6 +74,18 @@ export function buildDeployTxResult(txLog: any, t: (key: string, params?: Record
statementCount,
};
}
+ if (status === "completed_with_errors") {
+ return {
+ success: false,
+ status,
+ message: t("diff.deployCompletedWithErrors", { executedCount: executedCount ?? 0, failedCount }),
+ error,
+ executedCount,
+ statementCount,
+ failedCount,
+ failures,
+ };
+ }
if (status === "mixed") {
return {
success: false,
@@ -37,6 +98,8 @@ export function buildDeployTxResult(txLog: any, t: (key: string, params?: Record
error,
executedCount,
statementCount,
+ failedCount: failedCount || undefined,
+ failures: failures.length ? failures : undefined,
};
}
if (status === "rolled_back") {
@@ -48,6 +111,8 @@ export function buildDeployTxResult(txLog: any, t: (key: string, params?: Record
error,
executedCount: executedCount ?? 0,
statementCount,
+ failedCount: failedCount || undefined,
+ failures: failures.length ? failures : undefined,
};
}
return {