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): ignore schema name differences in DDL comparison

lxk955f2ff1e20c1db
diff --git a/apps/desktop/src/components/diff/SchemaDiffDdlPanel.vue b/apps/desktop/src/components/diff/SchemaDiffDdlPanel.vue
index f8f7e42981..b11de7f3f9 100644
--- a/apps/desktop/src/components/diff/SchemaDiffDdlPanel.vue
+++ b/apps/desktop/src/components/diff/SchemaDiffDdlPanel.vue
@@ -2,6 +2,7 @@
import { ref, computed, watch, nextTick } from "vue";
import { useI18n } from "vue-i18n";
import { Button } from "@/components/ui/button";
+import { Switch } from "@/components/ui/switch";
import { copyToClipboard } from "@/lib/common/clipboard";
import { useToast } from "@/composables/useToast";
import { useSettingsStore } from "@/stores/settingsStore";
@@ -9,12 +10,15 @@ import { DEFAULT_CUSTOM_THEME_DDL_COLORS } from "@/stores/settingsStore";
import { useDiffScrollSync } from "@/composables/useDiffScrollSync";
import { buildHunks, type DiffLine } from "@/components/diff/DiffHunkBuilder";
import { buildSchemaDiffHighlightSegments, type SchemaDiffHighlightSegment } from "@/lib/schema/schemaDiffHighlight";
+import { stripSchemaFromSql } from "@/lib/schema/schemaDiffDdlNormalize";
import { findFirstSchemaDiffChangedLineNumber, findSchemaDiffDdlLineNumber } from "@/lib/schema/schemaDiffDdlLocate";
import DiffSvgConnector from "@/components/diff/DiffSvgConnector.vue";
import { FileCode, ScrollText, Copy, Play, FileDiff } from "@lucide/vue";
import { Splitpanes, Pane } from "splitpanes";
import "splitpanes/dist/splitpanes.css";
+import { schemaDiffEffectiveSchema } from "@/lib/schema/schemaDiff";
import type { SchemaDiffObject, CompatibilityWarning, DependencyGraph, PermissionDiff, MissingRollbackObject, RollbackCompleteness } from "@/lib/schema/schemaDiff";
+import type { DatabaseType } from "@/types/database";
const { t } = useI18n();
const { toast } = useToast();
@@ -37,6 +41,12 @@ function toRgba(hex: string, alpha: number): string {
const props = defineProps<{
selectedObject: SchemaDiffObject | null;
focusedObject?: SchemaDiffObject | null;
+ sourceSchema?: string;
+ targetSchema?: string;
+ sourceDatabase?: string;
+ targetDatabase?: string;
+ sourceDbType?: string;
+ targetDbType?: string;
deploySql: string;
deploySqlAll: string;
rollbackForwardSql?: string;
@@ -70,6 +80,29 @@ const rollbackRightPaneRef = ref<HTMLDivElement>();
const rollbackContainerSize = ref({ width: 0, height: 0 });
const rollbackConnectorKey = ref(0);
+// Off by default: raw DDL is what the comparison actually found, so hiding
+// schema qualifiers has to be an explicit per-dialog choice, not a sticky one.
+const ignoreSchemaName = ref(false);
+
+function toggleIgnoreSchemaName(val: boolean) {
+ ignoreSchemaName.value = val;
+}
+
+const effectiveSourceSchema = computed(() => schemaDiffEffectiveSchema(props.sourceDbType as DatabaseType | undefined, props.sourceDatabase ?? "", props.sourceSchema));
+const effectiveTargetSchema = computed(() => schemaDiffEffectiveSchema(props.targetDbType as DatabaseType | undefined, props.targetDatabase ?? "", props.targetSchema));
+
+const effectiveSourceDdl = computed(() => {
+ const ddl = props.selectedObject?.sourceDdl || "";
+ if (!ddl || !ignoreSchemaName.value) return ddl;
+ return stripSchemaFromSql(ddl, effectiveSourceSchema.value);
+});
+
+const effectiveTargetDdl = computed(() => {
+ const ddl = props.selectedObject?.targetDdl || "";
+ if (!ddl || !ignoreSchemaName.value) return ddl;
+ return stripSchemaFromSql(ddl, effectiveTargetSchema.value);
+});
+
const rollbackHunks = computed(() => {
if (!props.rollbackSql) return [];
return buildHunks(props.rollbackForwardSql ?? props.deploySql, props.rollbackSql);
@@ -77,7 +110,7 @@ const rollbackHunks = computed(() => {
const hunks = computed(() => {
if (!props.selectedObject?.sourceDdl && !props.selectedObject?.targetDdl) return [];
- return buildHunks(props.selectedObject?.sourceDdl || "", props.selectedObject?.targetDdl || "");
+ return buildHunks(effectiveSourceDdl.value, effectiveTargetDdl.value);
});
const { syncScroll, measureHunks } = useDiffScrollSync({
@@ -216,8 +249,8 @@ function locateFocusedObject() {
focusedSourceLineNumber.value = focusedObject.operationType === "modify" ? findFirstSchemaDiffChangedLineNumber(hunks.value, "source") : null;
focusedTargetLineNumber.value = focusedObject.operationType === "modify" ? findFirstSchemaDiffChangedLineNumber(hunks.value, "target") : null;
} else {
- focusedSourceLineNumber.value = findSchemaDiffDdlLineNumber(selectedObject.sourceDdl ?? "", focusedObject, "source");
- focusedTargetLineNumber.value = findSchemaDiffDdlLineNumber(selectedObject.targetDdl ?? "", focusedObject, "target");
+ focusedSourceLineNumber.value = findSchemaDiffDdlLineNumber(effectiveSourceDdl.value, focusedObject, "source");
+ focusedTargetLineNumber.value = findSchemaDiffDdlLineNumber(effectiveTargetDdl.value, focusedObject, "target");
}
scrollPaneToLine(leftPaneRef.value, focusedSourceLineNumber.value);
scrollPaneToLine(rightPaneRef.value, focusedTargetLineNumber.value);
@@ -282,6 +315,16 @@ function copyDeploySqlAll() {
copyToClipboard(props.deploySqlAll);
toast(t("diff.copied"), 2000);
}
+
+function copySourceDdl() {
+ copyToClipboard(effectiveSourceDdl.value);
+ toast(t("diff.copied"), 2000);
+}
+
+function copyTargetDdl() {
+ copyToClipboard(effectiveTargetDdl.value);
+ toast(t("diff.copied"), 2000);
+}
</script>
<template>
@@ -336,6 +379,12 @@ function copyDeploySqlAll() {
{{ t("diff.operation") }}
<span class="ml-1 px-1.5 py-0.5 rounded-full text-[10px] bg-purple-500 text-white font-bold">{{ permissionDiffs.length }}</span>
</button>
+ <div v-if="activeTab === 'ddl'" class="ml-auto flex items-center pr-3">
+ <label class="flex items-center gap-1.5 text-xs cursor-pointer select-none text-muted-foreground hover:text-foreground">
+ <Switch size="sm" :model-value="ignoreSchemaName" :aria-label="t('diff.ignoreSchemaName')" @update:model-value="toggleIgnoreSchemaName(Boolean($event))" />
+ <span>{{ t("diff.ignoreSchemaName") }}</span>
+ </label>
+ </div>
</div>
<!-- DDL Compare -->
@@ -354,8 +403,12 @@ function copyDeploySqlAll() {
<!-- Source DDL -->
<Pane min-size="20">
<div ref="leftPaneRef" class="h-full overflow-y-auto border-r" @scroll="handleScroll('left')">
- <div class="sticky top-0 bg-background px-3 py-1.5 text-xs font-medium border-b z-10">
- {{ t("diff.sourceDdl") }}
+ <div class="sticky top-0 bg-background px-3 py-1.5 text-xs font-medium border-b z-10 flex items-center justify-between">
+ <span>{{ t("diff.sourceDdl") }}{{ props.sourceSchema ? ` (${props.sourceSchema})` : "" }}</span>
+ <Button v-if="props.selectedObject?.sourceDdl" variant="ghost" size="sm" class="h-5 px-1.5 text-[11px] gap-1 text-muted-foreground hover:text-foreground" :title="t('diff.copy')" @click="copySourceDdl">
+ <Copy class="w-3 h-3" />
+ {{ t("diff.copy") }}
+ </Button>
</div>
<div v-for="hunk in hunks" :key="`left-${hunk.id}`" :data-hunk-id="hunk.id">
<div v-for="(line, idx) in hunk.leftLines" :key="`l-${hunk.id}-${idx}`" class="flex min-h-[1.5em]" :class="focusedLineClass(line, 'source')" :data-ddl-line-number="line.lineNumber ?? undefined" :style="{ backgroundColor: lineBackground(line) }">
@@ -378,8 +431,12 @@ function copyDeploySqlAll() {
<!-- Target DDL -->
<Pane min-size="20">
<div ref="rightPaneRef" class="h-full overflow-y-auto" @scroll="handleScroll('right')">
- <div class="sticky top-0 bg-background px-3 py-1.5 text-xs font-medium border-b z-10">
- {{ t("diff.targetDdl") }}
+ <div class="sticky top-0 bg-background px-3 py-1.5 text-xs font-medium border-b z-10 flex items-center justify-between">
+ <span>{{ t("diff.targetDdl") }}{{ props.targetSchema ? ` (${props.targetSchema})` : "" }}</span>
+ <Button v-if="props.selectedObject?.targetDdl" variant="ghost" size="sm" class="h-5 px-1.5 text-[11px] gap-1 text-muted-foreground hover:text-foreground" :title="t('diff.copy')" @click="copyTargetDdl">
+ <Copy class="w-3 h-3" />
+ {{ t("diff.copy") }}
+ </Button>
</div>
<div v-for="hunk in hunks" :key="`right-${hunk.id}`" :data-hunk-id="hunk.id">
<div v-for="(line, idx) in hunk.rightLines" :key="`r-${hunk.id}-${idx}`" class="flex min-h-[1.5em]" :class="focusedLineClass(line, 'target')" :data-ddl-line-number="line.lineNumber ?? undefined" :style="{ backgroundColor: lineBackground(line) }">
diff --git a/apps/desktop/src/components/diff/SchemaDiffDialog.vue b/apps/desktop/src/components/diff/SchemaDiffDialog.vue
index a3ef3e5e5b..0394e802df 100644
--- a/apps/desktop/src/components/diff/SchemaDiffDialog.vue
+++ b/apps/desktop/src/components/diff/SchemaDiffDialog.vue
@@ -1836,6 +1836,12 @@ const targetConnectionInfo = computed(() => {
<SchemaDiffDdlPanel
:selected-object="displayedSelectedObject"
:focused-object="selectedTreeObject"
+ :source-schema="sourceSchema"
+ :target-schema="targetSchema"
+ :source-database="sourceDatabase"
+ :target-database="targetDatabase"
+ :source-db-type="sourceDbType"
+ :target-db-type="targetDbType"
:deploy-sql="focusedDeploySql"
:deploy-sql-all="selectedDeploySql"
:rollback-forward-sql="selectedForwardDeploySql"
diff --git a/apps/desktop/src/components/diff/__tests__/SchemaDiffDdlPanel.spec.ts b/apps/desktop/src/components/diff/__tests__/SchemaDiffDdlPanel.spec.ts
new file mode 100644
index 0000000000..561162eff1
--- /dev/null
+++ b/apps/desktop/src/components/diff/__tests__/SchemaDiffDdlPanel.spec.ts
@@ -0,0 +1,231 @@
+// @vitest-environment happy-dom
+
+import { createApp, defineComponent, h, nextTick, type App } from "vue";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import type { SchemaDiffObject } from "@/lib/schema/schemaDiff";
+
+vi.mock("vue-i18n", () => ({
+ useI18n: () => ({ t: (key: string) => key }),
+}));
+
+vi.mock("@/composables/useToast", () => ({
+ useToast: () => ({ toast: vi.fn() }),
+}));
+
+vi.mock("@/lib/common/clipboard", () => ({
+ copyToClipboard: vi.fn(),
+}));
+
+vi.mock("@/stores/settingsStore", () => ({
+ useSettingsStore: () => ({
+ editorSettings: {
+ customThemes: [],
+ activeCustomThemeId: "",
+ },
+ }),
+ DEFAULT_CUSTOM_THEME_DDL_COLORS: {
+ addedRowBg: "#00ff00",
+ addedRowBgAlpha: 20,
+ removedRowBg: "#ff0000",
+ removedRowBgAlpha: 20,
+ modifiedRowBg: "#ffaa00",
+ modifiedRowBgAlpha: 20,
+ modifiedCharBg: "#ffaa00",
+ modifiedCharBgAlpha: 40,
+ },
+}));
+
+vi.mock("@/components/diff/DiffSvgConnector.vue", () => ({
+ default: defineComponent({
+ setup() {
+ return () => h("div", { class: "diff-svg-connector" });
+ },
+ }),
+}));
+
+vi.mock("splitpanes", () => ({
+ Splitpanes: defineComponent({
+ setup(_props, { slots }) {
+ return () => h("div", { class: "splitpanes" }, slots.default?.());
+ },
+ }),
+ Pane: defineComponent({
+ setup(_props, { slots }) {
+ return () => h("div", { class: "pane" }, slots.default?.());
+ },
+ }),
+}));
+
+vi.mock("@/components/ui/switch", async () => {
+ const { defineComponent, h } = await import("vue");
+ return {
+ Switch: defineComponent({
+ props: { modelValue: Boolean },
+ emits: ["update:modelValue"],
+ setup(props, { emit }) {
+ return () =>
+ h("button", {
+ class: "switch-stub",
+ "data-model-value": String(props.modelValue),
+ onClick: () => emit("update:modelValue", !props.modelValue),
+ });
+ },
+ }),
+ };
+});
+
+import SchemaDiffDdlPanel from "@/components/diff/SchemaDiffDdlPanel.vue";
+
+const mountedApps: App[] = [];
+
+beforeEach(() => {
+ localStorage.clear();
+});
+
+afterEach(() => {
+ for (const app of mountedApps.splice(0)) app.unmount();
+ document.body.innerHTML = "";
+});
+
+describe("SchemaDiffDdlPanel", () => {
+ const sampleObject: SchemaDiffObject = {
+ id: "table-users",
+ operationType: "modify",
+ objectKind: "table",
+ name: "users",
+ selected: true,
+ sourceDdl: `CREATE TABLE "public"."users" (
+ "id" integer NOT NULL,
+ "name" text NOT NULL,
+ CONSTRAINT "users_pkey" PRIMARY KEY ("id")
+);`,
+ targetDdl: `CREATE TABLE "other_schema"."users" (
+ "id" integer NOT NULL,
+ "name" text NOT NULL,
+ CONSTRAINT "users_pkey" PRIMARY KEY ("id")
+);`,
+ };
+
+ it("shows raw DDL by default and keeps the schema-name switch off", async () => {
+ const host = document.createElement("div");
+ document.body.append(host);
+
+ const app = createApp(
+ defineComponent({
+ setup() {
+ return () =>
+ h(SchemaDiffDdlPanel, {
+ selectedObject: sampleObject,
+ sourceSchema: "public",
+ targetSchema: "other_schema",
+ deploySql: "",
+ deploySqlAll: "",
+ });
+ },
+ }),
+ );
+ mountedApps.push(app);
+ app.mount(host);
+ await nextTick();
+
+ // Check header displays schema names
+ expect(host.textContent).toContain("diff.sourceDdl (public)");
+ expect(host.textContent).toContain("diff.targetDdl (other_schema)");
+
+ // Check switch exists and starts off
+ const switchLabel = host.querySelector("label");
+ expect(switchLabel?.textContent).toContain("diff.ignoreSchemaName");
+ const switchBtn = host.querySelector(".switch-stub") as HTMLButtonElement | null;
+ expect(switchBtn?.getAttribute("data-model-value")).toBe("false");
+
+ // Raw DDL, including schema qualifiers, is shown by default
+ expect(host.textContent).toContain('CREATE TABLE "public"."users"');
+ expect(host.textContent).toContain('CREATE TABLE "other_schema"."users"');
+
+ // The toggle is per dialog and never persisted
+ expect(localStorage.getItem("dbx-schema-diff-ignore-schema-name")).toBeNull();
+ });
+
+ it("strips schema names when the switch is toggled on without persisting it", async () => {
+ const host = document.createElement("div");
+ document.body.append(host);
+
+ const app = createApp(
+ defineComponent({
+ setup() {
+ return () =>
+ h(SchemaDiffDdlPanel, {
+ selectedObject: sampleObject,
+ sourceSchema: "public",
+ targetSchema: "other_schema",
+ deploySql: "",
+ deploySqlAll: "",
+ });
+ },
+ }),
+ );
+ mountedApps.push(app);
+ app.mount(host);
+ await nextTick();
+
+ // Find the switch button and click it to turn it on
+ const switchBtn = host.querySelector(".switch-stub") as HTMLButtonElement | null;
+ expect(switchBtn).not.toBeNull();
+ switchBtn?.click();
+ await nextTick();
+
+ // Now the schema qualifiers should be stripped on both sides
+ expect(host.textContent).toContain('CREATE TABLE "users"');
+ expect(host.textContent).not.toContain('CREATE TABLE "public"."users"');
+ expect(host.textContent).not.toContain('CREATE TABLE "other_schema"."users"');
+
+ // Toggling is not persisted across dialogs
+ expect(localStorage.getItem("dbx-schema-diff-ignore-schema-name")).toBeNull();
+ });
+
+ it("uses the selected database as schema for MySQL views without an explicit schema", async () => {
+ const mysqlViewObject: SchemaDiffObject = {
+ id: "view-active-users",
+ operationType: "modify",
+ objectKind: "view",
+ name: "active_users",
+ selected: true,
+ sourceDdl: "CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `mydb`.`active_users` AS SELECT * FROM `mydb`.`users`;",
+ targetDdl: "CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `otherdb`.`active_users` AS SELECT * FROM `otherdb`.`users`;",
+ };
+
+ const host = document.createElement("div");
+ document.body.append(host);
+
+ const app = createApp(
+ defineComponent({
+ setup() {
+ return () =>
+ h(SchemaDiffDdlPanel, {
+ selectedObject: mysqlViewObject,
+ sourceDatabase: "mydb",
+ targetDatabase: "otherdb",
+ sourceDbType: "mysql",
+ targetDbType: "mysql",
+ deploySql: "",
+ deploySqlAll: "",
+ });
+ },
+ }),
+ );
+ mountedApps.push(app);
+ app.mount(host);
+ await nextTick();
+
+ const switchBtn = host.querySelector(".switch-stub") as HTMLButtonElement | null;
+ expect(switchBtn).not.toBeNull();
+ switchBtn?.click();
+ await nextTick();
+
+ // The database is the schema for MySQL, so the qualifier is stripped even
+ // though the schema picker left sourceSchema/targetSchema empty.
+ expect(host.textContent).toContain("VIEW `active_users` AS SELECT * FROM `users`");
+ expect(host.textContent).not.toContain("VIEW `mydb`.");
+ expect(host.textContent).not.toContain("VIEW `otherdb`.");
+ });
+});
diff --git a/apps/desktop/src/i18n/locales/az.ts b/apps/desktop/src/i18n/locales/az.ts
index 9126ffd21e..f0bcc74722 100644
--- a/apps/desktop/src/i18n/locales/az.ts
+++ b/apps/desktop/src/i18n/locales/az.ts
@@ -7029,6 +7029,7 @@ export default withEnglishFallback({
recentConfigs: "Son konfiqurasiyalar",
selectRecentConfig: "Son konfiqurasiyanı seç",
ignoreComments: "Şərh fərqlərini nəzərə alma",
+ ignoreSchemaName: "Sxem adı fərqlərini nəzərə alma",
ignoreForeignKeyChecks: "Xarici açar yoxlamalarını nəzərə alma",
ignoreForeignKeyChecksHint: "Cədvəllərin istənilən sıra ilə silinib yenidən yaradılması üçün skripti SET FOREIGN_KEY_CHECKS = 0 / = 1 ilə əhatə edir",
compare: "Müqayisə et",
diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.ts
index 7d0c20c932..4f5af0476e 100644
--- a/apps/desktop/src/i18n/locales/en.ts
+++ b/apps/desktop/src/i18n/locales/en.ts
@@ -9109,6 +9109,7 @@ export default {
recentConfigs: "Recent Configs",
selectRecentConfig: "Select recent config",
ignoreComments: "Ignore comment differences",
+ ignoreSchemaName: "Ignore schema name 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",
diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.ts
index ed653a2b2f..5240f83a15 100644
--- a/apps/desktop/src/i18n/locales/es.ts
+++ b/apps/desktop/src/i18n/locales/es.ts
@@ -7975,6 +7975,7 @@ export default withEnglishFallback({
recentConfigs: "Configs recientes",
selectRecentConfig: "Seleccionar config reciente",
ignoreComments: "Ignorar diferencias de comentarios",
+ ignoreSchemaName: "Ignorar diferencias de nombres de esquema",
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",
diff --git a/apps/desktop/src/i18n/locales/id.ts b/apps/desktop/src/i18n/locales/id.ts
index a04ea1c68b..7d4417a3fa 100644
--- a/apps/desktop/src/i18n/locales/id.ts
+++ b/apps/desktop/src/i18n/locales/id.ts
@@ -7728,6 +7728,7 @@ export default withEnglishFallback({
recentConfigs: "Konfigurasi Terbaru",
selectRecentConfig: "Pilih konfigurasi terbaru",
ignoreComments: "Abaikan perbedaan komentar",
+ ignoreSchemaName: "Abaikan perbedaan nama skema",
ignoreForeignKeyChecks: "Abaikan pemeriksaan kunci asing",
ignoreForeignKeyChecksHint: "Membungkus skrip dengan SET FOREIGN_KEY_CHECKS = 0 / = 1 agar tabel dapat dihapus dan dibuat ulang dalam urutan apa pun",
compare: "Bandingkan",
diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.ts
index 314ea9254a..7e2f504f52 100644
--- a/apps/desktop/src/i18n/locales/it.ts
+++ b/apps/desktop/src/i18n/locales/it.ts
@@ -7759,6 +7759,7 @@ export default withEnglishFallback({
recentConfigs: "Configurazioni Recenti",
selectRecentConfig: "Seleziona configurazione recente",
ignoreComments: "Ignora differenze nei commenti",
+ ignoreSchemaName: "Ignora differenze nei nomi degli schemi",
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",
diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.ts
index 6d25f0b87d..21dd9475dd 100644
--- a/apps/desktop/src/i18n/locales/ja.ts
+++ b/apps/desktop/src/i18n/locales/ja.ts
@@ -7779,6 +7779,7 @@ export default withEnglishFallback({
recentConfigs: "最近の設定",
selectRecentConfig: "最近の設定を選択",
ignoreComments: "コメントの差分を無視",
+ ignoreSchemaName: "スキーマ名の差分を無視",
ignoreForeignKeyChecks: "外部キー検査を無視",
ignoreForeignKeyChecksHint: "スクリプトの前後に SET FOREIGN_KEY_CHECKS = 0 / = 1 を付け、テーブルを任意の順序で削除・再作成できるようにします",
continueOnError: "エラー時も続行",
diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.ts
index 3f489dc09d..89dff29c53 100644
--- a/apps/desktop/src/i18n/locales/ko.ts
+++ b/apps/desktop/src/i18n/locales/ko.ts
@@ -7883,6 +7883,7 @@ export default withEnglishFallback({
recentConfigs: "최근 설정",
selectRecentConfig: "최근 설정 선택",
ignoreComments: "주석 차이 무시",
+ ignoreSchemaName: "스키마 이름 차이 무시",
ignoreForeignKeyChecks: "외래 키 검사 무시",
ignoreForeignKeyChecksHint: "스크립트 앞뒤에 SET FOREIGN_KEY_CHECKS = 0 / = 1을 추가해 테이블을 임의 순서로 삭제하고 다시 만들 수 있게 합니다",
continueOnError: "오류 발생 시 계속",
diff --git a/apps/desktop/src/i18n/locales/pl.ts b/apps/desktop/src/i18n/locales/pl.ts
index 172321ff5a..584acbe57d 100644
--- a/apps/desktop/src/i18n/locales/pl.ts
+++ b/apps/desktop/src/i18n/locales/pl.ts
@@ -7791,6 +7791,7 @@ export default withEnglishFallback({
recentConfigs: "Ostatnie konfiguracje",
selectRecentConfig: "Wybierz ostatnią konfigurację",
ignoreComments: "Ignoruj różnice w komentarzach",
+ ignoreSchemaName: "Ignoruj różnice w nazwach schematów",
ignoreForeignKeyChecks: "Pomiń sprawdzanie kluczy obcych",
ignoreForeignKeyChecksHint: "Otacza skrypt poleceniami SET FOREIGN_KEY_CHECKS = 0 i SET FOREIGN_KEY_CHECKS = 1, aby można było usuwać i ponownie tworzyć tabele w dowolnej kolejności",
compare: "Porównaj",
diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.ts
index 882ba2fd0b..f6d066b8eb 100644
--- a/apps/desktop/src/i18n/locales/pt-BR.ts
+++ b/apps/desktop/src/i18n/locales/pt-BR.ts
@@ -7753,6 +7753,7 @@ export default withEnglishFallback({
selectDatabase: "Selecionar banco de dados",
selectSchema: "Selecionar schema",
ignoreComments: "Ignorar diferenças de comentários",
+ ignoreSchemaName: "Ignorar diferenças de nome de esquema",
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",
diff --git a/apps/desktop/src/i18n/locales/ru.ts b/apps/desktop/src/i18n/locales/ru.ts
index 90dd0a80d1..23ce578b5c 100644
--- a/apps/desktop/src/i18n/locales/ru.ts
+++ b/apps/desktop/src/i18n/locales/ru.ts
@@ -9333,6 +9333,7 @@ export default withEnglishFallback({
recentConfigs: "Недавние конфигурации",
selectRecentConfig: "Выбрать недавнюю конфигурацию",
ignoreComments: "Игнорировать различия комментариев",
+ ignoreSchemaName: "Игнорировать различия имён схем",
ignoreForeignKeyChecks: "Игнорировать проверку внешних ключей",
ignoreForeignKeyChecksHint: "Оборачивает скрипт в SET FOREIGN_KEY_CHECKS = 0 / = 1, позволяя удалять и создавать таблицы в любом порядке",
continueOnError: "Продолжать при ошибке",
diff --git a/apps/desktop/src/i18n/locales/th.ts b/apps/desktop/src/i18n/locales/th.ts
index ee2c9f2f3a..2d70c8b65f 100644
--- a/apps/desktop/src/i18n/locales/th.ts
+++ b/apps/desktop/src/i18n/locales/th.ts
@@ -9714,6 +9714,7 @@ export default withEnglishFallback({
recentConfigs: "การตั้งค่าล่าสุด",
selectRecentConfig: "เลือกการตั้งค่าล่าสุด",
ignoreComments: "ละเว้นความแตกต่างของคอมเมนต์",
+ ignoreSchemaName: "ละเว้นความแตกต่างของชื่อสกีมา",
ignoreForeignKeyChecks: "ละเว้นการตรวจสอบ foreign key",
ignoreForeignKeyChecksHint: "ครอบ script ด้วย SET FOREIGN_KEY_CHECKS = 0 / = 1 เพื่อให้ลบและสร้างตารางใหม่ได้ทุกลำดับ",
continueOnError: "ดำเนินการต่อเมื่อเกิดข้อผิดพลาด",
diff --git a/apps/desktop/src/i18n/locales/tr.ts b/apps/desktop/src/i18n/locales/tr.ts
index c78354ff58..04cc1c6840 100644
--- a/apps/desktop/src/i18n/locales/tr.ts
+++ b/apps/desktop/src/i18n/locales/tr.ts
@@ -6909,6 +6909,7 @@ export default withEnglishFallback({
recentConfigs: "Son Yapılandırmalar",
selectRecentConfig: "Son yapılandırmayı seç",
ignoreComments: "Açıklama farklarını yoksay",
+ ignoreSchemaName: "Şema adı farklarını yoksay",
ignoreForeignKeyChecks: "Yabancı anahtar denetimlerini yoksay",
ignoreForeignKeyChecksHint: "Tabloların herhangi bir sırayla silinip yeniden oluşturulabilmesi için betiği SET FOREIGN_KEY_CHECKS = 0 / = 1 ile sarar",
compare: "Karşılaştır",
diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.ts
index ee04699804..ad77937270 100644
--- a/apps/desktop/src/i18n/locales/zh-CN.ts
+++ b/apps/desktop/src/i18n/locales/zh-CN.ts
@@ -9076,6 +9076,7 @@ export default withEnglishFallback({
recentConfigs: "最近配置",
selectRecentConfig: "选择最近配置",
ignoreComments: "忽略注释差异",
+ ignoreSchemaName: "忽略模式名差异",
ignoreForeignKeyChecks: "忽略外键检查",
ignoreForeignKeyChecksHint: "在脚本首尾加上 SET FOREIGN_KEY_CHECKS = 0 / = 1,允许以任意顺序删除和重建表",
continueOnError: "遇错继续",
diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.ts
index 28ecb318db..ea712895e1 100644
--- a/apps/desktop/src/i18n/locales/zh-TW.ts
+++ b/apps/desktop/src/i18n/locales/zh-TW.ts
@@ -6899,6 +6899,7 @@ export default withEnglishFallback({
selectDatabase: "選擇資料庫",
selectSchema: "選擇 Schema",
ignoreComments: "忽略註解差異",
+ ignoreSchemaName: "忽略模式名差異",
ignoreForeignKeyChecks: "忽略外鍵檢查",
ignoreForeignKeyChecksHint: "在指令碼開頭與結尾加上 SET FOREIGN_KEY_CHECKS = 0 / = 1,允許以任意順序刪除與重建資料表",
continueOnError: "遇錯繼續",
diff --git a/apps/desktop/src/lib/__tests__/schema/schemaDiffDdlNormalize.spec.ts b/apps/desktop/src/lib/__tests__/schema/schemaDiffDdlNormalize.spec.ts
new file mode 100644
index 0000000000..043efb5626
--- /dev/null
+++ b/apps/desktop/src/lib/__tests__/schema/schemaDiffDdlNormalize.spec.ts
@@ -0,0 +1,177 @@
+import { describe, expect, it } from "vitest";
+import { inferSchemaFromSql, stripSchemaFromSql } from "@/lib/schema/schemaDiffDdlNormalize";
+import { buildHunks } from "@/components/diff/DiffHunkBuilder";
+
+describe("schemaDiffDdlNormalize", () => {
+ describe("inferSchemaFromSql", () => {
+ it("infers quoted double-quote schema from CREATE TABLE", () => {
+ expect(inferSchemaFromSql('CREATE TABLE "public"."users" ("id" int);')).toBe("public");
+ });
+
+ it("infers bracketed schema from CREATE TABLE", () => {
+ expect(inferSchemaFromSql("CREATE TABLE [dbo].[users] ([id] int);")).toBe("dbo");
+ });
+
+ it("infers backtick schema from CREATE TABLE", () => {
+ expect(inferSchemaFromSql("CREATE TABLE `mydb`.`users` (`id` int);")).toBe("mydb");
+ });
+
+ it("infers unquoted schema from CREATE TABLE", () => {
+ expect(inferSchemaFromSql("CREATE TABLE public.users (id int);")).toBe("public");
+ });
+
+ it("infers schema from ALTER TABLE", () => {
+ expect(inferSchemaFromSql('ALTER TABLE ONLY "my_schema"."orders" ADD CONSTRAINT "fk" ...;')).toBe("my_schema");
+ });
+
+ it("infers schema from CREATE VIEW", () => {
+ expect(inferSchemaFromSql('CREATE OR REPLACE VIEW "analytics"."sales" AS SELECT 1;')).toBe("analytics");
+ });
+
+ it("infers schema from MySQL CREATE ALGORITHM/DEFINER VIEW", () => {
+ expect(inferSchemaFromSql("CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `mydb`.`v` AS SELECT 1;")).toBe("mydb");
+ });
+
+ it("infers schema from MySQL ALTER VIEW", () => {
+ expect(inferSchemaFromSql("ALTER ALGORITHM=UNDEFINED DEFINER=`root`@`%` SQL SECURITY DEFINER VIEW `mydb`.`v` AS SELECT 1;")).toBe("mydb");
+ });
+
+ it("returns null when table has no schema prefix", () => {
+ expect(inferSchemaFromSql('CREATE TABLE "users" ("id" int);')).toBeNull();
+ });
+ });
+
+ describe("stripSchemaFromSql", () => {
+ it("strips double-quoted PostgreSQL schema from table, index, comments and foreign keys", () => {
+ const sql = `CREATE TABLE "public"."users" (
+ "id" integer NOT NULL,
+ "name" text NOT NULL,
+ CONSTRAINT "users_pkey" PRIMARY KEY ("id")
+);
+COMMENT ON TABLE "public"."users" IS 'user accounts in public.schema';
+COMMENT ON COLUMN "public"."users"."name" IS 'user display name';
+CREATE INDEX "users_name_idx" ON "public"."users" USING btree ("name");
+ALTER TABLE ONLY "public"."orders" ADD CONSTRAINT "fk_user" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id");
+`;
+
+ const result = stripSchemaFromSql(sql, "public");
+
+ expect(result).toBe(`CREATE TABLE "users" (
+ "id" integer NOT NULL,
+ "name" text NOT NULL,
+ CONSTRAINT "users_pkey" PRIMARY KEY ("id")
+);
+COMMENT ON TABLE "users" IS 'user accounts in public.schema';
+COMMENT ON COLUMN "users"."name" IS 'user display name';
+CREATE INDEX "users_name_idx" ON "users" USING btree ("name");
+ALTER TABLE ONLY "orders" ADD CONSTRAINT "fk_user" FOREIGN KEY ("user_id") REFERENCES "users"("id");
+`);
+ });
+
+ it("strips bracketed SQL Server schema prefix", () => {
+ const sql = "CREATE TABLE [dbo].[users] ([id] int NOT NULL);";
+ expect(stripSchemaFromSql(sql, "dbo")).toBe("CREATE TABLE [users] ([id] int NOT NULL);");
+ });
+
+ it("strips backtick MySQL database/schema prefix", () => {
+ const sql = "CREATE TABLE `db_name`.`users` (`id` int NOT NULL);";
+ expect(stripSchemaFromSql(sql, "db_name")).toBe("CREATE TABLE `users` (`id` int NOT NULL);");
+ });
+
+ it("strips inferred schema from a MySQL ALGORITHM/DEFINER view", () => {
+ const sql = "CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `mydb`.`active_users` AS SELECT * FROM `mydb`.`users`;";
+ expect(stripSchemaFromSql(sql)).toBe("CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `active_users` AS SELECT * FROM `users`;");
+ });
+
+ it("keeps backslash-escaped quotes in MySQL string literals when stripping", () => {
+ const sql = "CREATE TABLE `db`.`t` (`id` int COMMENT 'user\\'s db.notes');";
+ expect(stripSchemaFromSql(sql, "db")).toBe("CREATE TABLE `t` (`id` int COMMENT 'user\\'s db.notes');");
+ });
+
+ it("keeps escaped-quote literals distinct so unequal comments still differ", () => {
+ const source = "CREATE TABLE `db`.`t` (`id` int COMMENT 'user\\'s db.notes');";
+ const target = "CREATE TABLE `db`.`t` (`id` int COMMENT 'user\\'s db.other');";
+ expect(stripSchemaFromSql(source, "db")).not.toBe(stripSchemaFromSql(target, "db"));
+ });
+
+ it("does not start a string literal at an apostrophe inside a quoted identifier", () => {
+ const sql = `CREATE TABLE "public"."it's" ("id" int);`;
+ expect(stripSchemaFromSql(sql, "public")).toBe(`CREATE TABLE "it's" ("id" int);`);
+ });
+
+ it("protects string literals inside array literals", () => {
+ const sql = "CREATE TABLE public.users (tags text[] DEFAULT ARRAY['public.a','public.b']);";
+ expect(stripSchemaFromSql(sql, "public")).toBe("CREATE TABLE users (tags text[] DEFAULT ARRAY['public.a','public.b']);");
+ });
+
+ it("strips unquoted schema prefix without touching string literals", () => {
+ const sql = `CREATE TABLE public.users (
+ id integer NOT NULL,
+ status text DEFAULT 'public.active'
+);`;
+ const result = stripSchemaFromSql(sql, "public");
+ expect(result).toBe(`CREATE TABLE users (
+ id integer NOT NULL,
+ status text DEFAULT 'public.active'
+);`);
+ });
+
+ it("strips unquoted schema prefix without lookbehind syntax", () => {
+ // Regression: the unquoted strip must not use lookbehind syntax (old
+ // WebKit cannot parse it); a `.` before the name blocks the strip, so
+ // dot-qualified second segments are preserved.
+ expect(stripSchemaFromSql("CREATE TABLE public.users (id int);", "public")).toBe("CREATE TABLE users (id int);");
+ expect(stripSchemaFromSql("CREATE TABLE public.public.users (id int);", "public")).toBe("CREATE TABLE public.users (id int);");
+ expect(stripSchemaFromSql("SELECT * FROM x.public.users;", "public")).toBe("SELECT * FROM x.public.users;");
+ });
+
+ it("preserves comments and dollar-quoted functions", () => {
+ const sql = `-- comment with public.users
+/* block comment with public.users */
+CREATE FUNCTION public.calc() RETURNS void AS $func$
+ SELECT * FROM public.users;
+$func$ LANGUAGE plpgsql;`;
+ const result = stripSchemaFromSql(sql, "public");
+ expect(result).toContain("-- comment with public.users");
+ expect(result).toContain("/* block comment with public.users */");
+ expect(result).toContain("CREATE FUNCTION calc()");
+ expect(result).toContain("SELECT * FROM public.users;");
+ });
+
+ it("infers schema automatically when schema argument is omitted", () => {
+ const sql = 'CREATE TABLE "my_app"."accounts" ("id" int);';
+ expect(stripSchemaFromSql(sql)).toBe('CREATE TABLE "accounts" ("id" int);');
+ });
+
+ it("preserves cross-schema references when stripping primary schema", () => {
+ const sql = 'CREATE TABLE "public"."users" ("org_id" int REFERENCES "auth"."org"("id"));';
+ expect(stripSchemaFromSql(sql, "public")).toBe('CREATE TABLE "users" ("org_id" int REFERENCES "auth"."org"("id"));');
+ });
+
+ it("results in equal diff hunks when two tables only differ by schema name", () => {
+ const sourceDdl = `CREATE TABLE "public"."users" (
+ "id" integer NOT NULL,
+ "name" text NOT NULL,
+ CONSTRAINT "users_pkey" PRIMARY KEY ("id")
+);
+CREATE INDEX "users_name_idx" ON "public"."users" ("name");`;
+
+ const targetDdl = `CREATE TABLE "test_schema"."users" (
+ "id" integer NOT NULL,
+ "name" text NOT NULL,
+ CONSTRAINT "users_pkey" PRIMARY KEY ("id")
+);
+CREATE INDEX "users_name_idx" ON "test_schema"."users" ("name");`;
+
+ const rawHunks = buildHunks(sourceDdl, targetDdl);
+ const hasChangesRaw = rawHunks.some((h) => h.type !== "equal");
+ expect(hasChangesRaw).toBe(true);
+
+ const cleanSource = stripSchemaFromSql(sourceDdl, "public");
+ const cleanTarget = stripSchemaFromSql(targetDdl, "test_schema");
+ const normalizedHunks = buildHunks(cleanSource, cleanTarget);
+
+ expect(normalizedHunks.every((h) => h.type === "equal")).toBe(true);
+ });
+ });
+});
diff --git a/apps/desktop/src/lib/schema/schemaDiff.ts b/apps/desktop/src/lib/schema/schemaDiff.ts
index 35fc91bd0b..7d92530c6e 100644
--- a/apps/desktop/src/lib/schema/schemaDiff.ts
+++ b/apps/desktop/src/lib/schema/schemaDiff.ts
@@ -397,18 +397,24 @@ export interface GenerateSchemaSyncPlanOptions {
const MYSQL_LIKE_SCHEMA_DIFF_TARGET_TYPES = new Set<DatabaseType>(["mysql", "doris", "starrocks", "goldendb", "sundb", "databend", "gbase"]);
-export function schemaDiffDeployTargetSchema(databaseType: DatabaseType | undefined, targetDatabase: string, targetSchema?: string): string | undefined {
- const schema = targetSchema?.trim();
- if (schema) return schema;
-
- const database = targetDatabase.trim();
- if (databaseType && MYSQL_LIKE_SCHEMA_DIFF_TARGET_TYPES.has(databaseType) && database) {
- return database;
+/** Resolve the schema that qualifies an object: an explicit schema wins; engines without a
+ * separate schema namespace use the selected database as the schema. */
+export function schemaDiffEffectiveSchema(databaseType: DatabaseType | undefined, database: string, schema?: string): string | undefined {
+ const trimmedSchema = schema?.trim();
+ if (trimmedSchema) return trimmedSchema;
+
+ const trimmedDatabase = database.trim();
+ if (databaseType && MYSQL_LIKE_SCHEMA_DIFF_TARGET_TYPES.has(databaseType) && trimmedDatabase) {
+ return trimmedDatabase;
}
return undefined;
}
+export function schemaDiffDeployTargetSchema(databaseType: DatabaseType | undefined, targetDatabase: string, targetSchema?: string): string | undefined {
+ return schemaDiffEffectiveSchema(databaseType, targetDatabase, targetSchema);
+}
+
// Unified object type for UI display
export type DiffOperationType = "modify" | "create" | "delete" | "none";
export type DiffObjectKind = "table" | "view" | "function" | "sequence" | "rule" | "owner" | "column" | "index" | "trigger" | "foreignKey" | "tableOption";
diff --git a/apps/desktop/src/lib/schema/schemaDiffDdlNormalize.ts b/apps/desktop/src/lib/schema/schemaDiffDdlNormalize.ts
new file mode 100644
index 0000000000..b78c35e8a3
--- /dev/null
+++ b/apps/desktop/src/lib/schema/schemaDiffDdlNormalize.ts
@@ -0,0 +1,170 @@
+function escapeRegExp(value: string): string {
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+}
+
+// Object keywords may be preceded by CREATE/ALTER modifiers. MySQL view DDL
+// puts ALGORITHM=…/DEFINER=…/SQL SECURITY … between the verb and VIEW, so the
+// schema qualifier is not directly after the object keyword without them.
+export function inferSchemaFromSql(sql: string): string | null {
+ if (!sql) return null;
+ const match = sql.match(
+ /\b(?:CREATE\s+(?:OR\s+REPLACE\s+)?(?:(?:TEMPORARY|UNLOGGED|ALGORITHM\s*=\s*\w+|DEFINER\s*=\s*\S+|SQL\s+SECURITY\s+(?:DEFINER|INVOKER))\s+)*(?:TABLE|VIEW|SEQUENCE|FUNCTION|PROCEDURE|TRIGGER)|ALTER\s+(?:(?:TEMPORARY|UNLOGGED|ALGORITHM\s*=\s*\w+|DEFINER\s*=\s*\S+|SQL\s+SECURITY\s+(?:DEFINER|INVOKER))\s+)*(?:TABLE(?:\s+ONLY)?|VIEW)|COMMENT\s+ON\s+(?:TABLE|COLUMN|INDEX|CONSTRAINT))\s+(?:IF\s+NOT\s+EXISTS\s+)?(?:(?:"([^"]+)")|(?:`([^`]+)`)|(?:\[([^\]]+)\])|([a-zA-Z0-9_]+))\s*\./i,
+ );
+ if (!match) return null;
+ return match[1] || match[2] || match[3] || match[4] || null;
+}
+
+// Advance past a quoted span so the quote-state scanner never mistakes quotes
+// inside it for the start of another construct. Returns the index just past the
+// closing delimiter (or the end of the input when unterminated).
+function skipQuoted(sql: string, start: number, quote: string, backslashEscapes: boolean): number {
+ let i = start + 1;
+ while (i < sql.length) {
+ const ch = sql[i];
+ if (backslashEscapes && ch === "\\") {
+ i += 2;
+ continue;
+ }
+ if (ch === quote) {
+ if (sql[i + 1] === quote) {
+ i += 2;
+ continue;
+ }
+ return i + 1;
+ }
+ i += 1;
+ }
+ return sql.length;
+}
+
+function skipBracketIdentifier(sql: string, start: number): number | null {
+ const close = sql.indexOf("]", start + 1);
+ if (close === -1 || close - start > 128) return null;
+ const content = sql.slice(start + 1, close);
+ // Only SQL Server style identifiers; keep array literals such as
+ // ARRAY['a','b'] on the normal path so their literals stay protected.
+ if (!/^[\w $@#.-]+$/.test(content)) return null;
+ return close + 1;
+}
+
+export function stripSchemaFromSql(sql: string, schema?: string): string {
+ if (!sql) return "";
+
+ const targetSchemas: string[] = [];
+ if (schema && schema.trim()) {
+ targetSchemas.push(schema.trim());
+ } else {
+ const inferred = inferSchemaFromSql(sql);
+ if (inferred) targetSchemas.push(inferred);
+ }
+
+ if (targetSchemas.length === 0) return sql;
+
+ function stripInCode(text: string): string {
+ let result = text;
+ for (const s of targetSchemas) {
+ const esc = escapeRegExp(s);
+ // 1. Quoted with double quotes: "schema".
+ result = result.replace(new RegExp(`"${esc}"\\s*\\.`, "gi"), "");
+ // 2. Quoted with backticks: `schema`.
+ result = result.replace(new RegExp(`\`${esc}\`\\s*\\.`, "gi"), "");
+ // 3. Quoted with brackets: [schema].
+ result = result.replace(new RegExp(`\\[${esc}\\]\\s*\\.`, "gi"), "");
+ // 4. Unquoted: schema. (preceded by non-identifier character or start of string)
+ // No lookbehind assertion here: old WebKit (before Safari 16.4) throws
+ // while parsing the module on lookbehind syntax, which kills the whole
+ // app at startup (see legacyWebViewRegexCompat.spec.ts). Match the
+ // preceding character explicitly and re-emit it instead; a single pass
+ // keeps the exact original semantics (a `.` before the name blocks the
+ // strip, so `x.public.users` and the second half of
+ // `public.public.users` are left alone).
+ result = result.replace(new RegExp(`(^|[^\\w."\`\\[])${esc}\\s*\\.`, "gi"), "$1");
+ }
+ return result;
+ }
+
+ // Single pass that masks string literals and comments (and skips over quoted
+ // identifiers) so only real code is stripped. A single regex alternation
+ // cannot do this correctly: MySQL honours `\'` inside literals, `''` is an
+ // escaped quote everywhere, and an apostrophe inside a quoted identifier must
+ // not open a string.
+ let out = "";
+ let codeStart = 0;
+
+ function emitProtected(start: number, end: number) {
+ if (start > codeStart) out += stripInCode(sql.slice(codeStart, start));
+ out += sql.slice(start, end);
+ codeStart = end;
+ }
+
+ let i = 0;
+ while (i < sql.length) {
+ const ch = sql[i];
+
+ // Single-quoted string literal: '' and backslash escapes (MySQL, E-strings).
+ if (ch === "'") {
+ const end = skipQuoted(sql, i, "'", true);
+ emitProtected(i, end);
+ i = end;
+ continue;
+ }
+
+ // Quoted identifier: skipped (kept in code) but must not start a literal.
+ if (ch === '"') {
+ i = skipQuoted(sql, i, '"', false);
+ continue;
+ }
+
+ if (ch === "`") {
+ i = skipQuoted(sql, i, "`", false);
+ continue;
+ }
+
+ if (ch === "[") {
+ const end = skipBracketIdentifier(sql, i);
+ if (end !== null) {
+ i = end;
+ continue;
+ }
+ i += 1;
+ continue;
+ }
+
+ // -- line comment.
+ if (ch === "-" && sql[i + 1] === "-") {
+ let end = i + 2;
+ while (end < sql.length && sql[end] !== "\n" && sql[end] !== "\r") end += 1;
+ emitProtected(i, end);
+ i = end;
+ continue;
+ }
+
+ // /* block comment */
+ if (ch === "/" && sql[i + 1] === "*") {
+ const close = sql.indexOf("*/", i + 2);
+ const end = close === -1 ? sql.length : close + 2;
+ emitProtected(i, end);
+ i = end;
+ continue;
+ }
+
+ // PostgreSQL dollar-quoted string: $tag$ ... $tag$
+ if (ch === "$") {
+ const delimiter = /^\$[A-Za-z0-9_]*\$/.exec(sql.slice(i));
+ if (delimiter) {
+ const close = sql.indexOf(delimiter[0], i + delimiter[0].length);
+ if (close !== -1) {
+ const end = close + delimiter[0].length;
+ emitProtected(i, end);
+ i = end;
+ continue;
+ }
+ }
+ }
+
+ i += 1;
+ }
+
+ if (codeStart < sql.length) out += stripInCode(sql.slice(codeStart));
+ return out;
+}