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(schema-diff): professional DDL diff view with deployment-aware colors and custom themes (#1112)

polempef5ed05ae73a
diff --git a/apps/desktop/src/components/diff/DiffHunkBuilder.ts b/apps/desktop/src/components/diff/DiffHunkBuilder.ts
new file mode 100644
index 0000000000..3aed892e58
--- /dev/null
+++ b/apps/desktop/src/components/diff/DiffHunkBuilder.ts
@@ -0,0 +1,297 @@
+import { diffLines, type Change } from "diff";
+
+export type HunkType = "equal" | "delete" | "insert" | "modify";
+
+export interface DiffLine {
+ type: HunkType;
+ content: string;
+ lineNumber: number | null;
+ isPadding: boolean;
+}
+
+export interface DiffHunk {
+ id: string;
+ type: HunkType;
+ leftLines: DiffLine[];
+ rightLines: DiffLine[];
+ // Measured pixel positions after rendering
+ leftTop: number;
+ leftBottom: number;
+ rightTop: number;
+ rightBottom: number;
+}
+
+const SIMILARITY_THRESHOLD = 0.3;
+const ALIGN_WINDOW = 3;
+
+function splitLines(value: string): string[] {
+ const lines = value.split("\n");
+ if (lines.length > 0 && lines[lines.length - 1] === "") lines.pop();
+ return lines;
+}
+
+function buildLines(lines: string[], type: HunkType, startLineNum: number): DiffLine[] {
+ return lines.map((content, idx) => ({
+ type,
+ content,
+ lineNumber: startLineNum + idx,
+ isPadding: false,
+ }));
+}
+
+function buildPaddingLines(count: number): DiffLine[] {
+ return Array.from({ length: count }, () => ({
+ type: "equal" as HunkType,
+ content: "",
+ lineNumber: null,
+ isPadding: true,
+ }));
+}
+
+function normalizeDdl(ddl: string): string {
+ return ddl
+ .replace(/\r\n/g, "\n")
+ .replace(/\r/g, "\n")
+ .split("\n")
+ .map((line) => line.replace(/[ \t]+$/g, ""))
+ .join("\n");
+}
+
+function collectSameKindChanges(changes: Change[], startIdx: number, kind: "added" | "removed"): [string[], number] {
+ const parts: string[] = [];
+ let i = startIdx;
+ while (i < changes.length && changes[i][kind]) {
+ parts.push(changes[i].value);
+ i++;
+ }
+ return [parts, i];
+}
+
+function levenshteinDistance(a: string, b: string): number {
+ const matrix: number[][] = [];
+ for (let i = 0; i <= b.length; i++) matrix[i] = [i];
+ for (let j = 0; j <= a.length; j++) matrix[0][j] = j;
+ for (let i = 1; i <= b.length; i++) {
+ for (let j = 1; j <= a.length; j++) {
+ matrix[i][j] = b.charAt(i - 1) === a.charAt(j - 1) ? matrix[i - 1][j - 1] : Math.min(matrix[i - 1][j - 1] + 1, matrix[i][j - 1] + 1, matrix[i - 1][j] + 1);
+ }
+ }
+ return matrix[b.length][a.length];
+}
+
+function computeSimilarity(a: string, b: string): number {
+ if (a === b) return 1;
+ const longer = a.length > b.length ? a : b;
+ if (longer.length === 0) return 1;
+ const distance = levenshteinDistance(a, b);
+ return (longer.length - distance) / longer.length;
+}
+
+type AlignedItem = { type: "modify"; left: string; right: string } | { type: "delete"; left: string } | { type: "insert"; right: string };
+
+function alignLineByLine(removedLines: string[], addedLines: string[]): AlignedItem[] {
+ const result: AlignedItem[] = [];
+ let r = 0;
+ let a = 0;
+
+ while (r < removedLines.length || a < addedLines.length) {
+ if (r < removedLines.length && a < addedLines.length) {
+ const directSim = computeSimilarity(removedLines[r], addedLines[a]);
+ if (directSim >= SIMILARITY_THRESHOLD) {
+ result.push({ type: "modify", left: removedLines[r], right: addedLines[a] });
+ r++;
+ a++;
+ continue;
+ }
+
+ // Look ahead for best match within a small window
+ let bestR = -1;
+ let bestA = -1;
+ let bestSim = SIMILARITY_THRESHOLD;
+
+ for (let ri = r; ri < Math.min(r + ALIGN_WINDOW, removedLines.length); ri++) {
+ for (let aj = a; aj < Math.min(a + ALIGN_WINDOW, addedLines.length); aj++) {
+ const sim = computeSimilarity(removedLines[ri], addedLines[aj]);
+ if (sim > bestSim) {
+ bestSim = sim;
+ bestR = ri;
+ bestA = aj;
+ }
+ }
+ }
+
+ if (bestR >= 0 && bestA >= 0) {
+ while (r < bestR) {
+ result.push({ type: "delete", left: removedLines[r] });
+ r++;
+ }
+ while (a < bestA) {
+ result.push({ type: "insert", right: addedLines[a] });
+ a++;
+ }
+ result.push({ type: "modify", left: removedLines[r], right: addedLines[a] });
+ r++;
+ a++;
+ } else {
+ result.push({ type: "delete", left: removedLines[r] });
+ result.push({ type: "insert", right: addedLines[a] });
+ r++;
+ a++;
+ }
+ } else if (r < removedLines.length) {
+ result.push({ type: "delete", left: removedLines[r] });
+ r++;
+ } else {
+ result.push({ type: "insert", right: addedLines[a] });
+ a++;
+ }
+ }
+
+ return result;
+}
+
+export function buildHunks(sourceDdl: string, targetDdl: string): DiffHunk[] {
+ const normalizedSource = normalizeDdl(sourceDdl);
+ const normalizedTarget = normalizeDdl(targetDdl);
+ const changes = diffLines(normalizedSource, normalizedTarget, { newlineIsToken: false });
+
+ const hunks: DiffHunk[] = [];
+ let leftLineNum = 1;
+ let rightLineNum = 1;
+ let hunkIdCounter = 0;
+
+ function nextId(): string {
+ return `hunk-${hunkIdCounter++}`;
+ }
+
+ let i = 0;
+ while (i < changes.length) {
+ const change = changes[i];
+
+ if (!change.added && !change.removed) {
+ const lines = splitLines(change.value);
+ hunks.push({
+ id: nextId(),
+ type: "equal",
+ leftLines: buildLines(lines, "equal", leftLineNum),
+ rightLines: buildLines(lines, "equal", rightLineNum),
+ leftTop: 0,
+ leftBottom: 0,
+ rightTop: 0,
+ rightBottom: 0,
+ });
+ leftLineNum += lines.length;
+ rightLineNum += lines.length;
+ i++;
+ continue;
+ }
+
+ if (change.removed) {
+ const [removedParts, afterRemoved] = collectSameKindChanges(changes, i, "removed");
+ const [addedParts, afterAdded] = collectSameKindChanges(changes, afterRemoved, "added");
+ const removedValue = removedParts.join("");
+ const removedLines = splitLines(removedValue);
+
+ if (addedParts.length > 0) {
+ const addedValue = addedParts.join("");
+ const addedLines = splitLines(addedValue);
+ const aligned = alignLineByLine(removedLines, addedLines);
+
+ for (const item of aligned) {
+ if (item.type === "modify") {
+ const maxLines = 1;
+ const leftReal = buildLines([item.left], "modify", leftLineNum);
+ const rightReal = buildLines([item.right], "modify", rightLineNum);
+ leftLineNum++;
+ rightLineNum++;
+ hunks.push({
+ id: nextId(),
+ type: "modify",
+ leftLines: padLines(leftReal, maxLines, "modify"),
+ rightLines: padLines(rightReal, maxLines, "modify"),
+ leftTop: 0,
+ leftBottom: 0,
+ rightTop: 0,
+ rightBottom: 0,
+ });
+ } else if (item.type === "delete") {
+ const leftReal = buildLines([item.left], "delete", leftLineNum);
+ leftLineNum++;
+ hunks.push({
+ id: nextId(),
+ type: "delete",
+ leftLines: leftReal,
+ rightLines: buildPaddingLines(1),
+ leftTop: 0,
+ leftBottom: 0,
+ rightTop: 0,
+ rightBottom: 0,
+ });
+ } else if (item.type === "insert") {
+ const rightReal = buildLines([item.right], "insert", rightLineNum);
+ rightLineNum++;
+ hunks.push({
+ id: nextId(),
+ type: "insert",
+ leftLines: buildPaddingLines(1),
+ rightLines: rightReal,
+ leftTop: 0,
+ leftBottom: 0,
+ rightTop: 0,
+ rightBottom: 0,
+ });
+ }
+ }
+ } else {
+ const maxLines = removedLines.length;
+ const leftReal = buildLines(removedLines, "delete", leftLineNum);
+ leftLineNum += removedLines.length;
+ hunks.push({
+ id: nextId(),
+ type: "delete",
+ leftLines: leftReal,
+ rightLines: buildPaddingLines(maxLines),
+ leftTop: 0,
+ leftBottom: 0,
+ rightTop: 0,
+ rightBottom: 0,
+ });
+ }
+ i = afterAdded;
+ continue;
+ }
+
+ if (change.added) {
+ const [addedParts, afterAdded] = collectSameKindChanges(changes, i, "added");
+ const addedValue = addedParts.join("");
+ const addedLines = splitLines(addedValue);
+ const rightReal = buildLines(addedLines, "insert", rightLineNum);
+ rightLineNum += addedLines.length;
+ hunks.push({
+ id: nextId(),
+ type: "insert",
+ leftLines: buildPaddingLines(addedLines.length),
+ rightLines: rightReal,
+ leftTop: 0,
+ leftBottom: 0,
+ rightTop: 0,
+ rightBottom: 0,
+ });
+ i = afterAdded;
+ continue;
+ }
+ }
+
+ return hunks;
+}
+
+function padLines(lines: DiffLine[], targetCount: number, type: HunkType): DiffLine[] {
+ if (lines.length >= targetCount) return lines;
+ const padding = Array.from({ length: targetCount - lines.length }, () => ({
+ type,
+ content: "",
+ lineNumber: null,
+ isPadding: true,
+ }));
+ return [...lines, ...padding];
+}
diff --git a/apps/desktop/src/components/diff/DiffSvgConnector.vue b/apps/desktop/src/components/diff/DiffSvgConnector.vue
new file mode 100644
index 0000000000..f31caa7b1e
--- /dev/null
+++ b/apps/desktop/src/components/diff/DiffSvgConnector.vue
@@ -0,0 +1,40 @@
+<script setup lang="ts">
+import { computed } from "vue";
+import type { DiffHunk } from "@/components/diff/DiffHunkBuilder";
+
+const props = defineProps<{
+ hunks: DiffHunk[];
+ containerWidth: number;
+ containerHeight: number;
+}>();
+
+const connectionPaths = computed(() => {
+ const paths: { d: string; stroke: string; id: string }[] = [];
+ const midX = props.containerWidth / 2;
+ const halfLine = 10;
+
+ for (const hunk of props.hunks) {
+ // Only draw short connectors for modify hunks
+ if (hunk.type !== "modify") continue;
+ if (hunk.leftBottom <= hunk.leftTop || hunk.rightBottom <= hunk.rightTop) continue;
+ if (hunk.leftBottom < 0 || hunk.rightBottom < 0) continue;
+ if (hunk.leftTop > props.containerHeight || hunk.rightTop > props.containerHeight) continue;
+
+ const leftY = (hunk.leftTop + hunk.leftBottom) / 2;
+ const rightY = (hunk.rightTop + hunk.rightBottom) / 2;
+
+ paths.push({
+ id: hunk.id,
+ d: `M ${midX - halfLine},${leftY} L ${midX + halfLine},${rightY}`,
+ stroke: "rgba(234, 179, 8, 0.6)",
+ });
+ }
+ return paths;
+});
+</script>
+
+<template>
+ <svg class="absolute inset-0 pointer-events-none z-10" :width="containerWidth" :height="containerHeight" xmlns="http://www.w3.org/2000/svg">
+ <path v-for="path in connectionPaths" :key="path.id" :d="path.d" :stroke="path.stroke" fill="none" stroke-width="2" />
+ </svg>
+</template>
diff --git a/apps/desktop/src/components/diff/SchemaDiffConfigSelector.vue b/apps/desktop/src/components/diff/SchemaDiffConfigSelector.vue
new file mode 100644
index 0000000000..6370573e8c
--- /dev/null
+++ b/apps/desktop/src/components/diff/SchemaDiffConfigSelector.vue
@@ -0,0 +1,201 @@
+<script setup lang="ts">
+import { ref, computed } from "vue";
+import { useI18n } from "vue-i18n";
+import { Button } from "@/components/ui/button";
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
+import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import { Download, Upload, Plus, Trash2, Copy, FileDown } from "@lucide/vue";
+import type { SchemaDiffConfig } from "@/types/schemaDiff";
+
+const props = defineProps<{
+ configs: SchemaDiffConfig[];
+ activeConfigId: string;
+}>();
+
+const emit = defineEmits<{
+ (e: "update:activeConfigId", id: string): void;
+ (e: "create", name: string): void;
+ (e: "rename", id: string, name: string): void;
+ (e: "delete", id: string): void;
+ (e: "duplicate", id: string): void;
+ (e: "export", config: SchemaDiffConfig): void;
+ (e: "exportAll", configs: SchemaDiffConfig[]): void;
+ (e: "import", jsonText: string): void;
+}>();
+
+const { t } = useI18n();
+
+const renameDialogOpen = ref(false);
+const renameValue = ref("");
+const renamingId = ref("");
+
+const importDialogOpen = ref(false);
+const importValue = ref("");
+const importError = ref("");
+
+function onSelectChange(value: unknown) {
+ emit("update:activeConfigId", String(value));
+}
+
+function startRename(config: SchemaDiffConfig) {
+ renamingId.value = config.id;
+ renameValue.value = config.name;
+ renameDialogOpen.value = true;
+}
+
+function confirmRename() {
+ if (renamingId.value && renameValue.value.trim()) {
+ emit("rename", renamingId.value, renameValue.value.trim());
+ }
+ renameDialogOpen.value = false;
+}
+
+function handleCreate() {
+ const baseName = t("schemaDiff.newConfigName");
+ let name = baseName;
+ let counter = 1;
+ while (props.configs.some((c) => c.name === name)) {
+ counter++;
+ name = `${baseName} ${counter}`;
+ }
+ emit("create", name);
+}
+
+function handleImport() {
+ importError.value = "";
+ try {
+ JSON.parse(importValue.value);
+ emit("import", importValue.value);
+ importDialogOpen.value = false;
+ importValue.value = "";
+ } catch {
+ importError.value = t("schemaDiff.importInvalidJson");
+ }
+}
+
+function downloadJson(data: string, filename: string) {
+ const blob = new Blob([data], { type: "application/json" });
+ const url = URL.createObjectURL(blob);
+ const a = document.createElement("a");
+ a.href = url;
+ a.download = filename;
+ a.click();
+ URL.revokeObjectURL(url);
+}
+
+function onExport() {
+ const config = props.configs.find((c) => c.id === props.activeConfigId);
+ if (config) {
+ emit("export", config);
+ downloadJson(JSON.stringify(config, null, 2), `dbx-schema-diff-${config.name}.json`);
+ }
+}
+
+function onExportAll() {
+ emit("exportAll", props.configs);
+ downloadJson(JSON.stringify(props.configs, null, 2), "dbx-schema-diff-configs.json");
+}
+
+async function onImportFile(event: Event) {
+ const input = event.target as HTMLInputElement;
+ const file = input.files?.[0];
+ if (!file) return;
+ try {
+ const text = await file.text();
+ JSON.parse(text);
+ emit("import", text);
+ importDialogOpen.value = false;
+ } catch {
+ importError.value = t("schemaDiff.importInvalidJson");
+ }
+ input.value = "";
+}
+
+const activeConfig = computed(() => props.configs.find((c) => c.id === props.activeConfigId));
+</script>
+
+<template>
+ <div class="flex items-center gap-2">
+ <Select :model-value="activeConfigId" @update:model-value="onSelectChange">
+ <SelectTrigger class="h-8 text-sm min-w-[180px]">
+ <SelectValue :placeholder="t('schemaDiff.selectConfig')" />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem v-for="config in configs" :key="config.id" :value="config.id">
+ {{ config.name }}
+ </SelectItem>
+ </SelectContent>
+ </Select>
+
+ <Button variant="outline" size="icon" class="h-8 w-8" :title="t('schemaDiff.newConfig')" @click="handleCreate">
+ <Plus class="h-4 w-4" />
+ </Button>
+
+ <Button v-if="activeConfig" variant="outline" size="icon" class="h-8 w-8" :title="t('schemaDiff.renameConfig')" @click="startRename(activeConfig)">
+ <Copy class="h-4 w-4" />
+ </Button>
+
+ <Button v-if="activeConfig" variant="outline" size="icon" class="h-8 w-8" :title="t('schemaDiff.duplicateConfig')" @click="emit('duplicate', activeConfig.id)">
+ <FileDown class="h-4 w-4" />
+ </Button>
+
+ <Button v-if="activeConfig && configs.length > 1" variant="outline" size="icon" class="h-8 w-8" :title="t('schemaDiff.deleteConfig')" @click="activeConfig && emit('delete', activeConfig.id)">
+ <Trash2 class="h-4 w-4" />
+ </Button>
+
+ <Button variant="outline" size="icon" class="h-8 w-8" :title="t('schemaDiff.exportConfig')" @click="onExport">
+ <Download class="h-4 w-4" />
+ </Button>
+
+ <Button variant="outline" size="icon" class="h-8 w-8" :title="t('schemaDiff.importConfig')" @click="importDialogOpen = true">
+ <Upload class="h-4 w-4" />
+ </Button>
+
+ <Button variant="outline" size="icon" class="h-8 w-8" :title="t('schemaDiff.exportAllConfigs')" @click="onExportAll">
+ <FileDown class="h-4 w-4" />
+ </Button>
+
+ <!-- Rename Dialog -->
+ <Dialog v-model:open="renameDialogOpen">
+ <DialogContent class="sm:max-w-[400px]">
+ <DialogHeader>
+ <DialogTitle>{{ t("schemaDiff.renameConfig") }}</DialogTitle>
+ </DialogHeader>
+ <div class="py-4">
+ <Label class="text-sm">{{ t("schemaDiff.configName") }}</Label>
+ <Input v-model="renameValue" class="mt-2" @keydown.enter="confirmRename" />
+ </div>
+ <DialogFooter>
+ <Button variant="outline" @click="renameDialogOpen = false">{{ t("common.cancel") }}</Button>
+ <Button @click="confirmRename">{{ t("common.save") }}</Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+
+ <!-- Import Dialog -->
+ <Dialog v-model:open="importDialogOpen">
+ <DialogContent class="sm:max-w-[500px]">
+ <DialogHeader>
+ <DialogTitle>{{ t("schemaDiff.importConfig") }}</DialogTitle>
+ </DialogHeader>
+ <div class="py-4 space-y-4">
+ <div>
+ <Label class="text-sm">{{ t("schemaDiff.importFromFile") }}</Label>
+ <Input type="file" accept=".json" class="mt-2" @change="onImportFile" />
+ </div>
+ <div>
+ <Label class="text-sm">{{ t("schemaDiff.importFromText") }}</Label>
+ <textarea v-model="importValue" class="mt-2 w-full min-h-[120px] rounded-md border border-input bg-background px-3 py-2 text-sm" :placeholder="t('schemaDiff.importPlaceholder')" />
+ </div>
+ <p v-if="importError" class="text-sm text-destructive">{{ importError }}</p>
+ </div>
+ <DialogFooter>
+ <Button variant="outline" @click="importDialogOpen = false">{{ t("common.cancel") }}</Button>
+ <Button @click="handleImport">{{ t("common.import") }}</Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ </div>
+</template>
diff --git a/apps/desktop/src/components/diff/SchemaDiffConfigStep.vue b/apps/desktop/src/components/diff/SchemaDiffConfigStep.vue
new file mode 100644
index 0000000000..46bd2f2941
--- /dev/null
+++ b/apps/desktop/src/components/diff/SchemaDiffConfigStep.vue
@@ -0,0 +1,457 @@
+<script setup lang="ts">
+import { computed, ref, watch } from "vue";
+import { useI18n } from "vue-i18n";
+import { Label } from "@/components/ui/label";
+import { Button } from "@/components/ui/button";
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
+import { useConnectionStore } from "@/stores/connectionStore";
+import DatabaseIcon from "@/components/icons/DatabaseIcon.vue";
+import * as api from "@/lib/api";
+import { isSchemaAware } from "@/lib/databaseCapabilities";
+import { ArrowLeftRight, GitCompareArrows, Save, FolderOpen, Settings, X } from "@lucide/vue";
+import type { SchemaDiffConfig, SchemaDiffCompareOptions } from "@/types/schemaDiff";
+
+const { t } = useI18n();
+const store = useConnectionStore();
+
+const props = defineProps<{
+ configs: SchemaDiffConfig[];
+ activeConfigId: string;
+ sourceConnectionId: string;
+ sourceDatabase: string;
+ sourceSchema: string;
+ targetConnectionId: string;
+ targetDatabase: string;
+ targetSchema: string;
+ ignoreComments: boolean;
+ options: SchemaDiffCompareOptions;
+ loading: boolean;
+ recentConfigs: SchemaDiffConfig[];
+}>();
+
+const emit = defineEmits<{
+ (e: "update:sourceConnectionId", value: string): void;
+ (e: "update:sourceDatabase", value: string): void;
+ (e: "update:sourceSchema", value: string): void;
+ (e: "update:targetConnectionId", value: string): void;
+ (e: "update:targetDatabase", value: string): void;
+ (e: "update:targetSchema", value: string): void;
+ (e: "update:ignoreComments", value: boolean): void;
+ (e: "compare"): void;
+ (e: "saveConfig"): void;
+ (e: "loadConfig"): void;
+ (e: "showOptions"): void;
+ (e: "swap"): void;
+ (e: "loadHistoryConfig", config: SchemaDiffConfig): void;
+ (e: "deleteHistoryConfig", configId: string): void;
+}>();
+
+const sourceDatabases = ref<string[]>([]);
+const sourceSchemas = ref<string[]>([]);
+const targetDatabases = ref<string[]>([]);
+const targetSchemas = ref<string[]>([]);
+const sourceDbVersion = ref<string | null>(null);
+const targetDbVersion = ref<string | null>(null);
+
+const sqlConnections = computed(() => store.connections.filter((c: any) => c.db_type !== "mongodb" && c.db_type !== "redis"));
+
+const sourceConfig = computed(() => store.getConfig(props.sourceConnectionId));
+const targetConfig = computed(() => store.getConfig(props.targetConnectionId));
+
+const canCompare = computed(() => {
+ return props.sourceConnectionId && props.targetConnectionId && props.sourceDatabase && props.targetDatabase && (!isSchemaAware(sourceConfig.value?.db_type) || props.sourceSchema) && (!isSchemaAware(targetConfig.value?.db_type) || props.targetSchema);
+});
+
+async function loadDatabases(connectionId: string, side: "source" | "target") {
+ if (!connectionId) return;
+ try {
+ await store.ensureConnected(connectionId);
+ const dbs = await api.listDatabases(connectionId);
+ const dbNames = Array.isArray(dbs) ? dbs.map((db: any) => (typeof db === "string" ? db : db.name || db.database)) : [];
+ if (side === "source") {
+ sourceDatabases.value = dbNames;
+ if (props.sourceDatabase) {
+ await fetchDbVersion(connectionId, props.sourceDatabase, props.sourceSchema, "source");
+ // Ensure schema list is loaded after databases are available (handles race with sourceDatabase watcher)
+ if (isSchemaAware(sourceConfig.value?.db_type)) {
+ await loadSchemas("source");
+ }
+ }
+ } else {
+ targetDatabases.value = dbNames;
+ if (props.targetDatabase) {
+ await fetchDbVersion(connectionId, props.targetDatabase, props.targetSchema, "target");
+ // Ensure schema list is loaded after databases are available (handles race with targetDatabase watcher)
+ if (isSchemaAware(targetConfig.value?.db_type)) {
+ await loadSchemas("target");
+ }
+ }
+ }
+ } catch {
+ if (side === "source") {
+ sourceDatabases.value = [];
+ sourceDbVersion.value = null;
+ } else {
+ targetDatabases.value = [];
+ targetDbVersion.value = null;
+ }
+ }
+}
+
+async function loadSchemas(side: "source" | "target") {
+ const connectionId = side === "source" ? props.sourceConnectionId : props.targetConnectionId;
+ const database = side === "source" ? props.sourceDatabase : props.targetDatabase;
+ const schema = side === "source" ? props.sourceSchema : props.targetSchema;
+ if (!connectionId || !database) return;
+
+ try {
+ await store.ensureConnected(connectionId);
+ const schemas = await api.listSchemas(connectionId, database);
+ if (side === "source") {
+ sourceSchemas.value = schemas;
+ } else {
+ targetSchemas.value = schemas;
+ }
+ await fetchDbVersion(connectionId, database, schema, side);
+ } catch {
+ if (side === "source") {
+ sourceSchemas.value = [];
+ } else {
+ targetSchemas.value = [];
+ }
+ }
+}
+
+watch(
+ () => props.sourceConnectionId,
+ async (id) => {
+ if (id) {
+ await loadDatabases(id, "source");
+ } else {
+ sourceDatabases.value = [];
+ }
+ },
+ { immediate: true },
+);
+
+watch(
+ () => props.sourceDatabase,
+ async (db) => {
+ if (db && props.sourceConnectionId) {
+ await loadSchemas("source");
+ } else {
+ sourceSchemas.value = [];
+ }
+ },
+ { immediate: true },
+);
+
+watch(
+ () => props.targetConnectionId,
+ async (id) => {
+ if (id) {
+ await loadDatabases(id, "target");
+ } else {
+ targetDatabases.value = [];
+ }
+ },
+ { immediate: true },
+);
+
+watch(
+ () => props.targetDatabase,
+ async (db) => {
+ if (db && props.targetConnectionId) {
+ await loadSchemas("target");
+ } else {
+ targetSchemas.value = [];
+ }
+ },
+ { immediate: true },
+);
+
+function connectionIconType(connectionId: string) {
+ const c = store.getConfig(connectionId);
+ return c?.driver_profile || c?.db_type || "mysql";
+}
+
+function getConnectionInfo(connectionId: string) {
+ const c = store.getConfig(connectionId);
+ if (!c) return null;
+ return {
+ name: c.name,
+ dbType: c.db_type,
+ host: c.host,
+ port: c.port,
+ };
+}
+
+async function fetchDbVersion(connectionId: string, database: string, schema: string, side: "source" | "target") {
+ try {
+ await store.ensureConnected(connectionId);
+ const config = store.getConfig(connectionId);
+ const dbType = config?.db_type;
+ let sql = "";
+ switch (dbType) {
+ case "postgres":
+ case "opengauss":
+ sql = "SELECT version()";
+ break;
+ case "mysql":
+ sql = "SELECT VERSION()";
+ break;
+ case "sqlite":
+ sql = "SELECT sqlite_version()";
+ break;
+ default:
+ return;
+ }
+ const result = await api.executeQuery(connectionId, database, sql, schema || undefined);
+ if (result.rows && result.rows.length > 0) {
+ const version = String(result.rows[0][0]);
+ if (side === "source") {
+ sourceDbVersion.value = version;
+ } else {
+ targetDbVersion.value = version;
+ }
+ }
+ } catch (e) {
+ console.error(`[fetchDbVersion] Failed to fetch version for ${side}:`, e);
+ if (side === "source") {
+ sourceDbVersion.value = null;
+ } else {
+ targetDbVersion.value = null;
+ }
+ }
+}
+</script>
+
+<template>
+ <div class="space-y-4">
+ <!-- Header -->
+ <div class="flex items-center justify-center gap-4 py-2">
+ <div class="text-center">
+ <div class="text-xs text-muted-foreground">{{ sourceConfig?.name || t("diff.source") }}</div>
+ <div class="text-xs font-medium">{{ sourceDatabase }}{{ sourceSchema ? `.${sourceSchema}` : "" }}</div>
+ </div>
+ <div class="flex items-center gap-2">
+ <DatabaseIcon v-if="sourceConnectionId" :db-type="connectionIconType(sourceConnectionId)" class="w-5 h-5" />
+ <ArrowLeftRight class="w-4 h-4 text-muted-foreground" />
+ <DatabaseIcon v-if="targetConnectionId" :db-type="connectionIconType(targetConnectionId)" class="w-5 h-5" />
+ </div>
+ <div class="text-center">
+ <div class="text-xs text-muted-foreground">{{ targetConfig?.name || t("diff.target") }}</div>
+ <div class="text-xs font-medium">{{ targetDatabase }}{{ targetSchema ? `.${targetSchema}` : "" }}</div>
+ </div>
+ </div>
+
+ <!-- Source / Target Selection -->
+ <div class="grid grid-cols-[1fr_auto_1fr] gap-4 items-start">
+ <!-- Source Side -->
+ <div class="space-y-3">
+ <div class="text-sm font-medium text-blue-500">{{ t("diff.source") }}</div>
+
+ <div class="space-y-1.5">
+ <Label class="text-xs">{{ t("diff.connection") }}</Label>
+ <Select :model-value="sourceConnectionId" @update:model-value="(v: any) => $emit('update:sourceConnectionId', String(v))">
+ <SelectTrigger class="h-8 text-xs">
+ <div class="flex items-center gap-2">
+ <DatabaseIcon v-if="sourceConnectionId" :db-type="connectionIconType(sourceConnectionId)" class="w-3.5 h-3.5" />
+ <SelectValue :placeholder="t('diff.selectConnection')" />
+ </div>
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem v-for="c in sqlConnections" :key="c.id" :value="c.id">
+ <div class="flex items-center gap-2">
+ <DatabaseIcon :db-type="c.driver_profile || c.db_type" class="w-3.5 h-3.5" />
+ {{ c.name }}
+ </div>
+ </SelectItem>
+ </SelectContent>
+ </Select>
+ </div>
+
+ <div class="space-y-1.5">
+ <Label class="text-xs">{{ t("diff.database") }}</Label>
+ <Select :model-value="sourceDatabase" @update:model-value="(v: any) => $emit('update:sourceDatabase', String(v))">
+ <SelectTrigger class="h-8 text-xs" :disabled="!sourceDatabases.length">
+ <SelectValue :placeholder="t('diff.selectDatabase')" />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem v-for="db in sourceDatabases" :key="db" :value="db">{{ db }}</SelectItem>
+ </SelectContent>
+ </Select>
+ </div>
+
+ <div v-if="isSchemaAware(sourceConfig?.db_type)" class="space-y-1.5">
+ <Label class="text-xs">{{ t("diff.schema") }}</Label>
+ <Select :model-value="sourceSchema" @update:model-value="(v: any) => $emit('update:sourceSchema', String(v))">
+ <SelectTrigger class="h-8 text-xs" :disabled="!sourceSchemas.length">
+ <SelectValue :placeholder="t('diff.selectSchema')" />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem v-for="schema in sourceSchemas" :key="schema" :value="schema">{{ schema }}</SelectItem>
+ </SelectContent>
+ </Select>
+ </div>
+
+ <!-- Source Info -->
+ <div v-if="getConnectionInfo(sourceConnectionId)" class="mt-4 p-3 rounded-lg bg-muted/30 border space-y-1.5">
+ <div class="text-xs font-medium text-blue-500">{{ t("diff.info") }}</div>
+ <div class="grid grid-cols-[80px_1fr] gap-x-2 gap-y-0.5 text-xs">
+ <span class="text-muted-foreground">{{ t("diff.connType") }}</span>
+ <span>{{ getConnectionInfo(sourceConnectionId)?.dbType }}</span>
+ <span class="text-muted-foreground">{{ t("diff.connName") }}</span>
+ <span>{{ getConnectionInfo(sourceConnectionId)?.name }}</span>
+ <span class="text-muted-foreground">{{ t("diff.host") }}</span>
+ <span>{{ getConnectionInfo(sourceConnectionId)?.host }}</span>
+ <span class="text-muted-foreground">{{ t("diff.port") }}</span>
+ <span>{{ getConnectionInfo(sourceConnectionId)?.port }}</span>
+ <span class="text-muted-foreground">{{ t("diff.serverVersion") }}</span>
+ <span>{{ sourceDbVersion || "--" }}</span>
+ </div>
+ </div>
+ </div>
+
+ <!-- Swap Button -->
+ <div class="pt-8">
+ <Button variant="ghost" size="icon" class="h-8 w-8" @click="$emit('swap')">
+ <ArrowLeftRight class="w-4 h-4" />
+ </Button>
+ </div>
+
+ <!-- Target Side -->
+ <div class="space-y-3">
+ <div class="text-sm font-medium text-green-500">{{ t("diff.target") }}</div>
+
+ <div class="space-y-1.5">
+ <Label class="text-xs">{{ t("diff.connection") }}</Label>
+ <Select :model-value="targetConnectionId" @update:model-value="(v: any) => $emit('update:targetConnectionId', String(v))">
+ <SelectTrigger class="h-8 text-xs">
+ <div class="flex items-center gap-2">
+ <DatabaseIcon v-if="targetConnectionId" :db-type="connectionIconType(targetConnectionId)" class="w-3.5 h-3.5" />
+ <SelectValue :placeholder="t('diff.selectConnection')" />
+ </div>
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem v-for="c in sqlConnections" :key="c.id" :value="c.id">
+ <div class="flex items-center gap-2">
+ <DatabaseIcon :db-type="c.driver_profile || c.db_type" class="w-3.5 h-3.5" />
+ {{ c.name }}
+ </div>
+ </SelectItem>
+ </SelectContent>
+ </Select>
+ </div>
+
+ <div class="space-y-1.5">
+ <Label class="text-xs">{{ t("diff.database") }}</Label>
+ <Select :model-value="targetDatabase" @update:model-value="(v: any) => $emit('update:targetDatabase', String(v))">
+ <SelectTrigger class="h-8 text-xs" :disabled="!targetDatabases.length">
+ <SelectValue :placeholder="t('diff.selectDatabase')" />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem v-for="db in targetDatabases" :key="db" :value="db">{{ db }}</SelectItem>
+ </SelectContent>
+ </Select>
+ </div>
+
+ <div v-if="isSchemaAware(targetConfig?.db_type)" class="space-y-1.5">
+ <Label class="text-xs">{{ t("diff.schema") }}</Label>
+ <Select :model-value="targetSchema" @update:model-value="(v: any) => $emit('update:targetSchema', String(v))">
+ <SelectTrigger class="h-8 text-xs" :disabled="!targetSchemas.length">
+ <SelectValue :placeholder="t('diff.selectSchema')" />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem v-for="schema in targetSchemas" :key="schema" :value="schema">{{ schema }}</SelectItem>
+ </SelectContent>
+ </Select>
+ </div>
+
+ <!-- Target Info -->
+ <div v-if="getConnectionInfo(targetConnectionId)" class="mt-4 p-3 rounded-lg bg-muted/30 border space-y-1.5">
+ <div class="text-xs font-medium text-green-500">{{ t("diff.info") }}</div>
+ <div class="grid grid-cols-[80px_1fr] gap-x-2 gap-y-0.5 text-xs">
+ <span class="text-muted-foreground">{{ t("diff.connType") }}</span>
+ <span>{{ getConnectionInfo(targetConnectionId)?.dbType }}</span>
+ <span class="text-muted-foreground">{{ t("diff.connName") }}</span>
+ <span>{{ getConnectionInfo(targetConnectionId)?.name }}</span>
+ <span class="text-muted-foreground">{{ t("diff.host") }}</span>
+ <span>{{ getConnectionInfo(targetConnectionId)?.host }}</span>
+ <span class="text-muted-foreground">{{ t("diff.port") }}</span>
+ <span>{{ getConnectionInfo(targetConnectionId)?.port }}</span>
+ <span class="text-muted-foreground">{{ t("diff.serverVersion") }}</span>
+ <span>{{ targetDbVersion || "--" }}</span>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <!-- Options -->
+ <div class="flex items-center gap-2 p-3 rounded-lg border bg-muted/20">
+ <input id="schema-diff-ignore-comments" :checked="ignoreComments" type="checkbox" class="accent-primary" @change="$emit('update:ignoreComments', ($event.target as HTMLInputElement).checked)" />
+ <Label for="schema-diff-ignore-comments" class="cursor-pointer text-xs">
+ {{ t("diff.ignoreComments") }}
+ </Label>
+ </div>
+
+ <!-- Recent Configs Dropdown -->
+ <div v-if="recentConfigs.length > 0" class="flex items-center gap-2">
+ <Label class="text-xs text-muted-foreground">{{ t("diff.recentConfigs") }}</Label>
+ <Select
+ :model-value="''"
+ @update:model-value="
+ (v: any) => {
+ const config = recentConfigs.find((c) => c.id === v);
+ if (config) $emit('loadHistoryConfig', config);
+ }
+ "
+ >
+ <SelectTrigger class="h-8 text-xs w-[280px]">
+ <SelectValue :placeholder="t('diff.selectRecentConfig')" />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem v-for="config in recentConfigs" :key="config.id" :value="config.id" class="pr-8">
+ <div class="flex items-center justify-between w-full gap-2">
+ <div class="flex flex-col gap-0.5 min-w-0">
+ <span class="text-xs font-medium truncate">{{ config.name }}</span>
+ <span class="text-[10px] text-muted-foreground truncate">
+ {{ store.getConfig(config.sourceConnectionId)?.name || config.sourceConnectionId }}
+ /{{ config.sourceDatabase }}{{ config.sourceSchema ? `.${config.sourceSchema}` : "" }}
+ →
+ {{ store.getConfig(config.targetConnectionId)?.name || config.targetConnectionId }}
+ /{{ config.targetDatabase }}{{ config.targetSchema ? `.${config.targetSchema}` : "" }}
+ </span>
+ </div>
+ <button class="shrink-0 p-1 rounded hover:bg-destructive/10 hover:text-destructive transition-colors" @click.stop="$emit('deleteHistoryConfig', config.id)">
+ <X class="w-3 h-3" />
+ </button>
+ </div>
+ </SelectItem>
+ </SelectContent>
+ </Select>
+ </div>
+
+ <!-- Bottom Actions -->
+ <div class="flex items-center justify-between pt-2">
+ <div class="flex items-center gap-2">
+ <Button variant="outline" size="sm" @click="$emit('saveConfig')">
+ <Save class="w-3.5 h-3.5 mr-1" />
+ {{ t("diff.saveConfig") }}
+ </Button>
+ <Button variant="outline" size="sm" @click="$emit('loadConfig')">
+ <FolderOpen class="w-3.5 h-3.5 mr-1" />
+ {{ t("diff.loadConfig") }}
+ </Button>
+ <Button variant="outline" size="sm" @click="$emit('showOptions')">
+ <Settings class="w-3.5 h-3.5 mr-1" />
+ {{ t("diff.options") }}
+ </Button>
+ </div>
+ <Button size="sm" :disabled="!canCompare || loading" @click="$emit('compare')">
+ <GitCompareArrows class="w-3.5 h-3.5 mr-1" />
+ {{ loading ? t("common.loading") : t("diff.compare") }}
+ </Button>
+ </div>
+ </div>
+</template>
diff --git a/apps/desktop/src/components/diff/SchemaDiffDdlPanel.vue b/apps/desktop/src/components/diff/SchemaDiffDdlPanel.vue
new file mode 100644
index 0000000000..c4754d9b90
--- /dev/null
+++ b/apps/desktop/src/components/diff/SchemaDiffDdlPanel.vue
@@ -0,0 +1,390 @@
+<script setup lang="ts">
+import { ref, computed, watch, nextTick } from "vue";
+import { useI18n } from "vue-i18n";
+import { Button } from "@/components/ui/button";
+import { copyToClipboard } from "@/lib/clipboard";
+import { useToast } from "@/composables/useToast";
+import { useSettingsStore } from "@/stores/settingsStore";
+import { DEFAULT_CUSTOM_THEME_DDL_COLORS } from "@/stores/settingsStore";
+import { useDiffScrollSync } from "@/composables/useDiffScrollSync";
+import { buildHunks, type DiffLine } from "@/components/diff/DiffHunkBuilder";
+import DiffSvgConnector from "@/components/diff/DiffSvgConnector.vue";
+import { FileCode, ScrollText, Copy, Play } from "@lucide/vue";
+import { Splitpanes, Pane } from "splitpanes";
+import "splitpanes/dist/splitpanes.css";
+import type { SchemaDiffObject } from "@/lib/schemaDiff";
+
+const { t } = useI18n();
+const { toast } = useToast();
+const settingsStore = useSettingsStore();
+
+const ddlColors = computed(() => {
+ const themes = settingsStore.editorSettings.customThemes;
+ const activeId = settingsStore.editorSettings.activeCustomThemeId;
+ const activeTheme = themes.find((t) => t.id === activeId);
+ return activeTheme?.ddlColors ?? DEFAULT_CUSTOM_THEME_DDL_COLORS;
+});
+
+function toRgba(hex: string, alpha: number): string {
+ const r = parseInt(hex.slice(1, 3), 16);
+ const g = parseInt(hex.slice(3, 5), 16);
+ const b = parseInt(hex.slice(5, 7), 16);
+ return `rgba(${r}, ${g}, ${b}, ${alpha / 100})`;
+}
+
+const props = defineProps<{
+ selectedObject: SchemaDiffObject | null;
+ deploySql: string;
+ deploySqlAll: string;
+}>();
+
+const emit = defineEmits<{
+ executeScript: [];
+}>();
+
+const activeTab = ref<"ddl" | "script" | "scriptAll">("ddl");
+const diffContainerRef = ref<HTMLDivElement>();
+const leftPaneRef = ref<HTMLDivElement>();
+const rightPaneRef = ref<HTMLDivElement>();
+const containerSize = ref({ width: 0, height: 0 });
+const connectorKey = ref(0);
+
+const hunks = computed(() => {
+ if (!props.selectedObject?.sourceDdl && !props.selectedObject?.targetDdl) return [];
+ return buildHunks(props.selectedObject?.sourceDdl || "", props.selectedObject?.targetDdl || "");
+});
+
+const { syncScroll, measureHunks } = useDiffScrollSync({
+ container: diffContainerRef,
+ leftPane: leftPaneRef,
+ rightPane: rightPaneRef,
+ hunks,
+});
+
+// Cache char-level diff segments so we don't recompute on every render
+const modifySegments = computed(() => {
+ const map = new Map<string, { leftSegments: Segment[]; rightSegments: Segment[] }>();
+ for (const hunk of hunks.value) {
+ if (hunk.type !== "modify") continue;
+ for (let i = 0; i < hunk.leftLines.length; i++) {
+ const left = hunk.leftLines[i];
+ const right = hunk.rightLines[i];
+ if (left.isPadding || right.isPadding) continue;
+ const key = `${hunk.id}:${i}`;
+ map.set(key, renderModifyLine(left, right));
+ }
+ }
+ return map;
+});
+
+let measureRaf: number | null = null;
+let measureTimeout: ReturnType<typeof setTimeout> | null = null;
+
+function requestMeasure() {
+ if (measureRaf) return;
+ measureRaf = requestAnimationFrame(() => {
+ measureRaf = null;
+ measureHunks();
+ connectorKey.value++;
+ });
+}
+
+function requestMeasureDebounced() {
+ if (measureTimeout) clearTimeout(measureTimeout);
+ measureTimeout = setTimeout(() => {
+ requestMeasure();
+ }, 100);
+}
+
+function handleScroll(from: "left" | "right") {
+ syncScroll(from);
+ requestMeasureDebounced();
+}
+
+watch(
+ () => props.selectedObject?.id,
+ async () => {
+ await nextTick();
+ updateContainerSize();
+ requestMeasure();
+ },
+);
+
+function updateContainerSize() {
+ const el = diffContainerRef.value;
+ if (!el) return;
+ const rect = el.getBoundingClientRect();
+ containerSize.value = { width: rect.width, height: rect.height };
+}
+
+function onSplitpanesResized() {
+ updateContainerSize();
+ requestMeasure();
+}
+
+function lineBackground(line: DiffLine): string | undefined {
+ if (line.isPadding) return undefined;
+ if (line.type === "delete") {
+ // source-only = will be added to target = green
+ return toRgba(ddlColors.value.addedRowBg, ddlColors.value.addedRowBgAlpha);
+ }
+ if (line.type === "insert") {
+ // target-only = will be removed from target = red
+ return toRgba(ddlColors.value.removedRowBg, ddlColors.value.removedRowBgAlpha);
+ }
+ if (line.type === "modify") {
+ return toRgba(ddlColors.value.modifiedRowBg, ddlColors.value.modifiedRowBgAlpha);
+ }
+ return undefined;
+}
+
+function lineTextClass(line: DiffLine): string {
+ if (line.isPadding) return "text-transparent";
+ if (line.type === "insert") return "line-through opacity-80";
+ return "";
+}
+
+function computeCharDiffs(source: string, target: string): { source: string; target: string }[] {
+ const result: { source: string; target: string }[] = [];
+ let sIdx = 0;
+ let tIdx = 0;
+ while (sIdx < source.length || tIdx < target.length) {
+ if (sIdx >= source.length) {
+ result.push({ source: "", target: target.substring(tIdx) });
+ break;
+ }
+ if (tIdx >= target.length) {
+ result.push({ source: source.substring(sIdx), target: "" });
+ break;
+ }
+ if (source[sIdx] === target[tIdx]) {
+ let matchLen = 0;
+ while (sIdx + matchLen < source.length && tIdx + matchLen < target.length && source[sIdx + matchLen] === target[tIdx + matchLen]) {
+ matchLen++;
+ }
+ result.push({
+ source: source.substring(sIdx, sIdx + matchLen),
+ target: target.substring(tIdx, tIdx + matchLen),
+ });
+ sIdx += matchLen;
+ tIdx += matchLen;
+ } else {
+ let sMatch = -1;
+ let tMatch = -1;
+ for (let i = 0; i < Math.min(10, source.length - sIdx, target.length - tIdx); i++) {
+ if (source[sIdx + i] === target[tIdx]) {
+ sMatch = i;
+ tMatch = 0;
+ break;
+ }
+ if (source[sIdx] === target[tIdx + i]) {
+ sMatch = 0;
+ tMatch = i;
+ break;
+ }
+ }
+ if (sMatch === -1) {
+ sMatch = Math.min(1, source.length - sIdx);
+ tMatch = Math.min(1, target.length - tIdx);
+ }
+ result.push({
+ source: source.substring(sIdx, sIdx + (sMatch > 0 ? sMatch : 1)),
+ target: target.substring(tIdx, tIdx + (tMatch > 0 ? tMatch : 1)),
+ });
+ sIdx += sMatch > 0 ? sMatch : 1;
+ tIdx += tMatch > 0 ? tMatch : 1;
+ }
+ }
+ return result;
+}
+
+function renderModifyLine(leftLine: DiffLine, rightLine: DiffLine): { leftSegments: Segment[]; rightSegments: Segment[] } {
+ const charDiffs = computeCharDiffs(leftLine.content, rightLine.content);
+ const leftSegments: Segment[] = [];
+ const rightSegments: Segment[] = [];
+ for (const cd of charDiffs) {
+ if (cd.source === cd.target) {
+ leftSegments.push({ text: cd.source, changed: false });
+ rightSegments.push({ text: cd.target, changed: false });
+ } else {
+ if (cd.source) leftSegments.push({ text: cd.source, changed: true });
+ if (cd.target) rightSegments.push({ text: cd.target, changed: true });
+ }
+ }
+ return { leftSegments, rightSegments };
+}
+
+interface Segment {
+ text: string;
+ changed: boolean;
+}
+
+function copyDeploySql() {
+ copyToClipboard(props.deploySql);
+ toast(t("diff.copied"), 2000);
+}
+
+function copyDeploySqlAll() {
+ copyToClipboard(props.deploySqlAll);
+ toast(t("diff.copied"), 2000);
+}
+</script>
+
+<template>
+ <div class="border rounded-md flex flex-col h-full">
+ <!-- Tabs -->
+ <div class="flex border-b shrink-0">
+ <button class="px-3 py-1.5 text-xs font-medium flex items-center gap-1 transition-colors" :class="activeTab === 'ddl' ? 'bg-primary/10 text-primary border-b-2 border-primary' : 'hover:bg-muted/50'" @click="activeTab = 'ddl'">
+ <FileCode class="w-3.5 h-3.5" />
+ {{ t("diff.ddlCompare") }}
+ </button>
+ <button class="px-3 py-1.5 text-xs font-medium flex items-center gap-1 transition-colors" :class="activeTab === 'script' ? 'bg-primary/10 text-primary border-b-2 border-primary' : 'hover:bg-muted/50'" @click="activeTab = 'script'">
+ <ScrollText class="w-3.5 h-3.5" />
+ {{ t("diff.deployScript") }}
+ </button>
+ <button class="px-3 py-1.5 text-xs font-medium flex items-center gap-1 transition-colors" :class="activeTab === 'scriptAll' ? 'bg-primary/10 text-primary border-b-2 border-primary' : 'hover:bg-muted/50'" @click="activeTab = 'scriptAll'">
+ <ScrollText class="w-3.5 h-3.5" />
+ {{ t("diff.deployScriptAll") }}
+ </button>
+ </div>
+
+ <!-- DDL Compare -->
+ <div v-if="activeTab === 'ddl'" class="flex-1 overflow-hidden relative">
+ <!-- No object selected -->
+ <div v-if="!selectedObject" class="absolute inset-0 flex items-center justify-center text-sm text-muted-foreground">
+ {{ t("diff.selectObjectToCompare") }}
+ </div>
+ <!-- No DDL data available -->
+ <div v-else-if="!selectedObject.sourceDdl && !selectedObject.targetDdl" class="absolute inset-0 flex items-center justify-center text-sm text-muted-foreground">
+ {{ t("diff.noDdlAvailable") }}
+ </div>
+ <!-- Diff View -->
+ <div v-else ref="diffContainerRef" class="absolute inset-0 font-mono text-xs leading-relaxed">
+ <Splitpanes class="h-full" @resized="onSplitpanesResized">
+ <!-- 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-muted/50 px-3 py-1.5 text-xs font-medium border-b z-10">
+ {{ t("diff.sourceDdl") }}
+ </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="{
+ 'border-l border-r border-yellow-500/40': hunk.type === 'modify',
+ 'border-t rounded-t-sm': hunk.type === 'modify' && idx === 0,
+ 'border-b rounded-b-sm': hunk.type === 'modify' && idx === hunk.leftLines.length - 1,
+ }"
+ :style="{ backgroundColor: lineBackground(line) }"
+ >
+ <span class="text-muted-foreground w-8 text-right pr-2 select-none shrink-0">
+ {{ line.lineNumber ?? "" }}
+ </span>
+ <span class="flex-1 px-1 whitespace-pre" :class="lineTextClass(line)">
+ <template v-if="line.type === 'modify' && !line.isPadding">
+ <template v-for="(segment, si) in modifySegments.get(`${hunk.id}:${idx}`)?.leftSegments ?? []" :key="`ls-${si}`">
+ <span :style="segment.changed ? { backgroundColor: toRgba(ddlColors.modifiedCharBg, ddlColors.modifiedCharBgAlpha) } : undefined">{{ segment.text }}</span>
+ </template>
+ </template>
+ <span v-else>{{ line.isPadding ? "\u00A0" : line.content }}</span>
+ </span>
+ </div>
+ </div>
+ </div>
+ </Pane>
+
+ <!-- Target DDL -->
+ <Pane min-size="20">
+ <div ref="rightPaneRef" class="h-full overflow-y-auto" @scroll="handleScroll('right')">
+ <div class="sticky top-0 bg-muted/50 px-3 py-1.5 text-xs font-medium border-b z-10">
+ {{ t("diff.targetDdl") }}
+ </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="{
+ 'border-l border-r border-yellow-500/40': hunk.type === 'modify',
+ 'border-t rounded-t-sm': hunk.type === 'modify' && idx === 0,
+ 'border-b rounded-b-sm': hunk.type === 'modify' && idx === hunk.rightLines.length - 1,
+ }"
+ :style="{ backgroundColor: lineBackground(line) }"
+ >
+ <span class="text-muted-foreground w-8 text-right pr-2 select-none shrink-0">
+ {{ line.lineNumber ?? "" }}
+ </span>
+ <span class="flex-1 px-1 whitespace-pre" :class="lineTextClass(line)">
+ <template v-if="line.type === 'modify' && !line.isPadding">
+ <template v-for="(segment, si) in modifySegments.get(`${hunk.id}:${idx}`)?.rightSegments ?? []" :key="`rs-${si}`">
+ <span :style="segment.changed ? { backgroundColor: toRgba(ddlColors.modifiedCharBg, ddlColors.modifiedCharBgAlpha) } : undefined">{{ segment.text }}</span>
+ </template>
+ </template>
+ <span v-else>{{ line.isPadding ? "\u00A0" : line.content }}</span>
+ </span>
+ </div>
+ </div>
+ </div>
+ </Pane>
+ </Splitpanes>
+
+ <!-- SVG Connector Overlay -->
+ <DiffSvgConnector :key="connectorKey" :hunks="hunks" :container-width="containerSize.width" :container-height="containerSize.height" />
+ </div>
+ </div>
+
+ <!-- Deploy Script -->
+ <div v-else-if="activeTab === 'script'" class="flex-1 flex flex-col overflow-hidden">
+ <div class="flex items-center justify-between px-3 py-1.5 border-b shrink-0">
+ <span class="text-xs text-muted-foreground">{{ t("diff.deployScriptDesc") }}</span>
+ <div class="flex gap-1">
+ <Button variant="ghost" size="sm" class="h-6 px-2 text-xs gap-1" @click="copyDeploySql">
+ <Copy class="w-3 h-3" />
+ {{ t("diff.copy") }}
+ </Button>
+ <Button variant="ghost" size="sm" class="h-6 px-2 text-xs gap-1" @click="$emit('executeScript')">
+ <Play class="w-3 h-3" />
+ {{ t("diff.execute") }}
+ </Button>
+ </div>
+ </div>
+ <div class="flex-1 overflow-auto p-3">
+ <pre class="text-xs whitespace-pre-wrap font-mono">{{ deploySql || t("diff.noDeployScript") }}</pre>
+ </div>
+ </div>
+
+ <!-- Deploy Script All -->
+ <div v-else-if="activeTab === 'scriptAll'" class="flex-1 flex flex-col overflow-hidden">
+ <div class="flex items-center justify-between px-3 py-1.5 border-b shrink-0">
+ <span class="text-xs text-muted-foreground">{{ t("diff.deployScriptAllDesc") }}</span>
+ <div class="flex gap-1">
+ <Button variant="ghost" size="sm" class="h-6 px-2 text-xs gap-1" @click="copyDeploySqlAll">
+ <Copy class="w-3 h-3" />
+ {{ t("diff.copy") }}
+ </Button>
+ <Button variant="ghost" size="sm" class="h-6 px-2 text-xs gap-1" @click="$emit('executeScript')">
+ <Play class="w-3 h-3" />
+ {{ t("diff.executeAll") }}
+ </Button>
+ </div>
+ </div>
+ <div class="flex-1 overflow-auto p-3">
+ <pre class="text-xs whitespace-pre-wrap font-mono">{{ deploySqlAll || t("diff.noDeployScriptAll") }}</pre>
+ </div>
+ </div>
+ </div>
+</template>
+
+<style scoped>
+:deep(.splitpanes--vertical > .splitpanes__splitter) {
+ background-color: hsl(var(--border));
+ width: 4px;
+ cursor: col-resize;
+ position: relative;
+}
+:deep(.splitpanes--vertical > .splitpanes__splitter:hover) {
+ background-color: hsl(var(--primary));
+}
+</style>
diff --git a/apps/desktop/src/components/diff/SchemaDiffDeployStep.vue b/apps/desktop/src/components/diff/SchemaDiffDeployStep.vue
new file mode 100644
index 0000000000..0c6b1a5337
--- /dev/null
+++ b/apps/desktop/src/components/diff/SchemaDiffDeployStep.vue
@@ -0,0 +1,355 @@
+<script setup lang="ts">
+import { ref, computed, onMounted, onUnmounted, watch, shallowRef } from "vue";
+import { useI18n } from "vue-i18n";
+import { Button } from "@/components/ui/button";
+import { copyToClipboard } from "@/lib/clipboard";
+import { useToast } from "@/composables/useToast";
+import { useSettingsStore } from "@/stores/settingsStore";
+import { useTheme } from "@/composables/useTheme";
+import { loadEditorTheme, editorFontTheme } from "@/lib/editorThemes";
+import { Splitpanes, Pane } from "splitpanes";
+import type { SchemaDiffObject, DiffOperationType, DiffObjectKind } from "@/lib/schemaDiff";
+import { ArrowLeft, Copy, Download, Play, Loader2, PlusCircle, XCircle, ArrowRightLeft, Table, Eye, FunctionSquare, ListOrdered, ScrollText, UserCog, ListTree, Link2, Zap } from "@lucide/vue";
+
+const { t } = useI18n();
+const { toast } = useToast();
+const settingsStore = useSettingsStore();
+const { isDark } = useTheme();
+
+const props = defineProps<{
+ deploySql: string;
+ selectedObjects: SchemaDiffObject[];
+ targetConnectionId: string;
+ targetDatabase: string;
+ targetSchema: string;
+ executing: boolean;
+}>();
+
+const emit = defineEmits<{
+ "update:deploySql": [sql: string];
+ back: [];
+ deploy: [];
+}>();
+
+const editorContainer = ref<HTMLDivElement>();
+const editorView = shallowRef<any>(null);
+const isEditorReady = ref(false);
+const selectedObjectId = ref<string | null>(null);
+
+// Parse object positions in deploySql
+const objectPositions = computed(() => {
+ const positions = new Map<string, { from: number; to: number }>();
+ const sql = props.deploySql;
+ for (const obj of topLevelObjects.value) {
+ const patterns = [`-- Create ${obj.objectKind}: ${obj.name}`, `-- Modify ${obj.objectKind}: ${obj.name}`, `-- Drop ${obj.objectKind}: ${obj.name}`];
+ for (const pattern of patterns) {
+ const index = sql.indexOf(pattern);
+ if (index !== -1) {
+ let endPos = sql.length;
+ const remaining = sql.slice(index + pattern.length);
+ const nextMatch = remaining.match(/--\s*(Create|Modify|Drop)\s+\w+:/);
+ if (nextMatch && nextMatch.index !== undefined) {
+ endPos = index + pattern.length + nextMatch.index;
+ }
+ positions.set(obj.id, { from: index, to: endPos });
+ break;
+ }
+ }
+ }
+ return positions;
+});
+
+async function handleSelectObject(obj: SchemaDiffObject) {
+ selectedObjectId.value = obj.id;
+ if (editorView.value) {
+ const pos = objectPositions.value.get(obj.id);
+ if (pos) {
+ const { EditorView } = await import("@codemirror/view");
+ editorView.value.dispatch({
+ effects: EditorView.scrollIntoView(pos.from, { y: "start" }),
+ });
+ }
+ }
+}
+
+// Filter top-level selected objects (exclude children and none)
+const topLevelObjects = computed(() => {
+ const operationOrder: Record<DiffOperationType, number> = { create: 0, modify: 1, delete: 2, none: 3 };
+ return props.selectedObjects
+ .filter((o) => {
+ const isTopLevel = !o.id.startsWith("col-") && !o.id.startsWith("idx-") && !o.id.startsWith("fk-") && !o.id.startsWith("trg-");
+ return o.selected && o.operationType !== "none" && isTopLevel;
+ })
+ .sort((a, b) => operationOrder[a.operationType] - operationOrder[b.operationType]);
+});
+
+const operationCounts = computed(() => {
+ const counts: Record<DiffOperationType, number> = { create: 0, modify: 0, delete: 0, none: 0 };
+ for (const obj of topLevelObjects.value) {
+ counts[obj.operationType]++;
+ }
+ return counts;
+});
+
+const operationIcons: Record<DiffOperationType, any> = {
+ modify: ArrowRightLeft,
+ create: PlusCircle,
+ delete: XCircle,
+ none: ArrowRightLeft,
+};
+
+const operationColors: Record<DiffOperationType, string> = {
+ modify: "text-blue-500",
+ create: "text-green-500",
+ delete: "text-red-500",
+ none: "text-muted-foreground",
+};
+
+// Initialize CodeMirror editor
+async function initEditor() {
+ if (!editorContainer.value) return;
+
+ const [{ EditorView }, { EditorState, Compartment }, { sql, PostgreSQL, SQLDialect }, { basicSetup }] = await Promise.all([import("@codemirror/view"), import("@codemirror/state"), import("@codemirror/lang-sql"), import("codemirror")]);
+
+ const themeComp = new Compartment();
+ const fontComp = new Compartment();
+
+ const editorTheme = settingsStore.editorSettings.theme;
+ const appAppearance = isDark.value ? "dark" : "light";
+ const fontSize = settingsStore.editorSettings.fontSize;
+ const fontFamily = settingsStore.editorSettings.fontFamily;
+
+ const themeExt = await loadEditorTheme(editorTheme, appAppearance);
+ const fontExt = editorFontTheme(EditorView, fontSize, fontFamily, { fixedHeight: true, scrollable: true });
+
+ // Custom PostgreSQL dialect with PL/pgSQL support (same as QueryEditor.vue)
+ const extraKeywords = "PIVOT UNPIVOT EXCLUDE REPLACE QUALIFY ASOF POSITIONAL ANTI SEMI SAMPLE TABLESAMPLE STRUCT MAP LIST ARRAY LAMBDA UNNEST LATERAL FILTER RECURSIVE SUMMARIZE PRAGMA READ_CSV READ_PARQUET READ_JSON DESCRIBE SHOW COPY EXPORT IMPORT";
+ const plpgsqlKeywords = "PERFORM";
+ const plpgsqlTypes = " RECORD JSON JSONB";
+ const plpgsqlBuiltin = "SQLERRM TG_NAME TG_WHEN TG_LEVEL TG_OP TG_RELID TG_RELNAME TG_TABLE_NAME TG_TABLE_SCHEMA TG_NARGS TG_ARGV";
+
+ const dialect = SQLDialect.define({
+ ...PostgreSQL.spec,
+ keywords: [PostgreSQL.spec.keywords || "", extraKeywords, plpgsqlKeywords].filter(Boolean).join(" "),
+ types: [PostgreSQL.spec.types || "", plpgsqlTypes].filter(Boolean).join(" ") || undefined,
+ builtin: [PostgreSQL.spec.builtin || "", plpgsqlBuiltin].filter(Boolean).join(" ") || undefined,
+ doubleDollarQuotedStrings: false,
+ });
+
+ const state = EditorState.create({
+ doc: props.deploySql,
+ extensions: [
+ basicSetup,
+ sql({ dialect }),
+ themeComp.of(themeExt),
+ fontComp.of(fontExt),
+ EditorView.updateListener.of((update: any) => {
+ if (update.docChanged) {
+ emit("update:deploySql", update.state.doc.toString());
+ }
+ }),
+ ],
+ });
+
+ editorView.value = new EditorView({ state, parent: editorContainer.value });
+ isEditorReady.value = true;
+}
+
+// Watch for external deploySql changes
+watch(
+ () => props.deploySql,
+ (newVal) => {
+ if (editorView.value && editorView.value.state.doc.toString() !== newVal) {
+ editorView.value.dispatch({
+ changes: { from: 0, to: editorView.value.state.doc.length, insert: newVal },
+ });
+ }
+ },
+);
+
+onMounted(() => {
+ initEditor();
+});
+
+onUnmounted(() => {
+ editorView.value?.destroy();
+ editorView.value = null;
+});
+
+function handleCopy() {
+ copyToClipboard(props.deploySql);
+ toast(t("diff.copied"), 2000);
+}
+
+async function handleExport() {
+ try {
+ const dbName = props.targetDatabase || "deploy";
+ const timestamp = new Date().toISOString().replace(/[:.]/g, "-").slice(0, 19);
+ const defaultName = `${dbName}_deploy_${timestamp}.sql`;
+
+ const { save } = await import("@tauri-apps/plugin-dialog");
+ const path = await save({
+ defaultPath: defaultName,
+ filters: [{ name: "SQL", extensions: ["sql"] }],
+ });
+
+ if (path) {
+ const { writeTextFile } = await import("@tauri-apps/plugin-fs");
+ await writeTextFile(path, props.deploySql);
+ toast(t("diff.exportSuccess"), 3000);
+ }
+ } catch (e: any) {
+ toast(e?.message || String(e), 5000);
+ }
+}
+
+function handleDeploy() {
+ emit("deploy");
+}
+
+function getOperationLabel(type: DiffOperationType): string {
+ switch (type) {
+ case "create":
+ return t("diff.create");
+ case "delete":
+ return t("diff.delete");
+ case "modify":
+ return t("diff.modify");
+ default:
+ return "";
+ }
+}
+
+function getObjectIcon(kind: DiffObjectKind) {
+ switch (kind) {
+ case "table":
+ return Table;
+ case "view":
+ return Eye;
+ case "function":
+ return FunctionSquare;
+ case "sequence":
+ return ListOrdered;
+ case "rule":
+ return ScrollText;
+ case "owner":
+ return UserCog;
+ case "index":
+ return ListTree;
+ case "foreignKey":
+ return Link2;
+ case "trigger":
+ return Zap;
+ default:
+ return Table;
+ }
+}
+
+function getObjectIconColor(kind: DiffObjectKind): string {
+ switch (kind) {
+ case "table":
+ return "text-amber-500";
+ case "view":
+ return "text-cyan-500";
+ case "function":
+ return "text-purple-500";
+ case "sequence":
+ return "text-orange-500";
+ case "rule":
+ return "text-pink-500";
+ case "owner":
+ return "text-indigo-500";
+ case "index":
+ return "text-teal-500";
+ case "foreignKey":
+ return "text-lime-500";
+ case "trigger":
+ return "text-rose-500";
+ default:
+ return "text-muted-foreground";
+ }
+}
+</script>
+
+<template>
+ <div class="flex flex-col h-full">
+ <!-- Header -->
+ <div class="flex items-center justify-between px-3 py-2 border-b shrink-0">
+ <div class="flex items-center gap-2">
+ <Button variant="ghost" size="sm" class="h-7 px-2 text-xs gap-1" @click="$emit('back')">
+ <ArrowLeft class="w-3.5 h-3.5" />
+ {{ t("diff.backToResult") }}
+ </Button>
+ <span class="text-sm font-medium">{{ t("diff.deployReview") }}</span>
+ <span class="text-xs text-muted-foreground"> ({{ t("diff.selectedCount", { selected: topLevelObjects.length, total: topLevelObjects.length }) }}) </span>
+ </div>
+ <div class="flex items-center gap-3 text-xs">
+ <span class="text-green-500">{{ t("diff.create") }}: {{ operationCounts.create }}</span>
+ <span class="text-blue-500">{{ t("diff.modify") }}: {{ operationCounts.modify }}</span>
+ <span class="text-red-500">{{ t("diff.delete") }}: {{ operationCounts.delete }}</span>
+ </div>
+ </div>
+
+ <!-- Content -->
+ <Splitpanes class="flex-1 min-h-0">
+ <Pane size="30" min-size="20">
+ <div class="h-full overflow-auto p-2 space-y-0.5">
+ <div v-for="obj in topLevelObjects" :key="obj.id" class="flex items-center gap-2 px-2 py-1.5 rounded text-xs hover:bg-accent/50 cursor-pointer" :class="{ 'bg-primary/10': selectedObjectId === obj.id }" @click="handleSelectObject(obj)">
+ <component :is="operationIcons[obj.operationType]" class="w-3.5 h-3.5 shrink-0" :class="operationColors[obj.operationType]" />
+ <component :is="getObjectIcon(obj.objectKind)" class="w-3.5 h-3.5 shrink-0" :class="getObjectIconColor(obj.objectKind)" />
+ <span class="truncate">{{ obj.name }}</span>
+ <span class="text-[10px] text-muted-foreground shrink-0 ml-auto">
+ {{ getOperationLabel(obj.operationType) }}
+ </span>
+ </div>
+ <div v-if="topLevelObjects.length === 0" class="text-xs text-muted-foreground text-center py-4">
+ {{ t("diff.noObjectsSelected") }}
+ </div>
+ </div>
+ </Pane>
+
+ <Pane size="70" min-size="40">
+ <div ref="editorContainer" class="h-full w-full" />
+ </Pane>
+ </Splitpanes>
+
+ <!-- Footer -->
+ <div class="flex items-center justify-between px-3 py-2 border-t shrink-0 gap-2">
+ <div class="flex items-center gap-2">
+ <Button variant="outline" size="sm" class="h-7 text-xs gap-1" @click="handleCopy">
+ <Copy class="w-3.5 h-3.5" />
+ {{ t("diff.copyScript") }}
+ </Button>
+ <Button variant="outline" size="sm" class="h-7 text-xs gap-1" @click="handleExport">
+ <Download class="w-3.5 h-3.5" />
+ {{ t("diff.exportSql") }}
+ </Button>
+ </div>
+ <div class="flex items-center gap-2">
+ <Button variant="ghost" size="sm" class="h-7 text-xs gap-1" @click="$emit('back')">
+ <ArrowLeft class="w-3.5 h-3.5" />
+ {{ t("diff.backToResult") }}
+ </Button>
+ <Button variant="ghost" size="sm" class="h-7 text-xs" @click="$emit('back')">
+ {{ t("diff.cancel") }}
+ </Button>
+ <Button size="sm" class="h-7 text-xs gap-1" :disabled="topLevelObjects.length === 0 || executing" @click="handleDeploy">
+ <Loader2 v-if="executing" class="w-3.5 h-3.5 animate-spin" />
+ <Play v-else class="w-3.5 h-3.5" />
+ {{ t("diff.deployToServer") }}
+ </Button>
+ </div>
+ </div>
+ </div>
+</template>
+
+<style scoped>
+:deep(.splitpanes--vertical > .splitpanes__splitter) {
+ width: 4px;
+ background: hsl(var(--border));
+ cursor: col-resize;
+}
+:deep(.splitpanes--vertical > .splitpanes__splitter:hover) {
+ background: hsl(var(--primary));
+}
+</style>
diff --git a/apps/desktop/src/components/diff/SchemaDiffDialog.vue b/apps/desktop/src/components/diff/SchemaDiffDialog.vue
index f05c937ef9..600388c13b 100644
--- a/apps/desktop/src/components/diff/SchemaDiffDialog.vue
+++ b/apps/desktop/src/components/diff/SchemaDiffDialog.vue
@@ -1,31 +1,29 @@
<script setup lang="ts">
-import { computed, ref, watch } from "vue";
+import { computed, ref, watch, onBeforeUnmount } from "vue";
import { useI18n } from "vue-i18n";
import { Dialog, DialogHeader, DialogTitle, DialogFooter, DialogContent } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
-import { Badge } from "@/components/ui/badge";
-import { Label } from "@/components/ui/label";
-import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { useConnectionStore } from "@/stores/connectionStore";
-import DatabaseIcon from "@/components/icons/DatabaseIcon.vue";
-import * as api from "@/lib/api";
-import { isSchemaAware } from "@/lib/databaseCapabilities";
-import { databaseOptionsForConnection } from "@/composables/useDatabaseOptions";
-import { copyToClipboard } from "@/lib/clipboard";
-import type { TableDiff, TableSchemaDetail } from "@/lib/schemaDiff";
-import type { TableInfo } from "@/types/database";
-import { sqlMetadataRefreshTarget } from "@/lib/sqlMetadataRefresh";
import { useToast } from "@/composables/useToast";
-import { Loader2, Copy, Play, GitCompareArrows, ArrowLeftRight } from "@lucide/vue";
-import { useSqlHighlighter } from "@/composables/useSqlHighlighter";
-
-interface SelectableTableDiff extends TableDiff {
- selected: boolean;
-}
+import { GitCompareArrows, ArrowLeft, Play, Loader2, Maximize2, Minimize2, AlertTriangle, CircleCheck } from "@lucide/vue";
+import * as api from "@/lib/api";
+import { useSchemaDiffConfig } from "@/composables/useSchemaDiffConfig";
+import SchemaDiffConfigStep from "@/components/diff/SchemaDiffConfigStep.vue";
+import SchemaDiffObjectTree from "@/components/diff/SchemaDiffObjectTree.vue";
+import SchemaDiffDdlPanel from "@/components/diff/SchemaDiffDdlPanel.vue";
+import SchemaDiffDeployStep from "@/components/diff/SchemaDiffDeployStep.vue";
+import SchemaDiffOptionsPanel from "@/components/diff/SchemaDiffOptionsPanel.vue";
+
+import { getSchemaDiffOptionsForDbType } from "@/lib/schemaDiffOptions";
+import { getDefaultOptionsForDbType } from "@/types/schemaDiff";
+import type { SchemaDiffCompareOptions, SchemaDiffConfig } from "@/types/schemaDiff";
+import type { ObjectSourceKind } from "@/types/database";
+import { convertToSchemaDiffObjects, groupDiffObjects, type OperationGroup, type SchemaDiffObject, type DiffOperationType, type DiffObjectKind, type SchemaDiffPreparation } from "@/lib/schemaDiff";
+import { Splitpanes, Pane } from "splitpanes";
+import "splitpanes/dist/splitpanes.css";
const { t } = useI18n();
const { toast } = useToast();
-const { highlight } = useSqlHighlighter();
const open = defineModel<boolean>("open", { default: false });
const store = useConnectionStore();
@@ -35,333 +33,649 @@ const props = defineProps<{
prefillSchema?: string;
}>();
+// Wizard state
+const step = ref<"config" | "compare" | "result" | "deploy-review">("config");
+
+// Deploy confirm dialog
+const showConfirmDialog = ref(false);
+
+// Source/Target selections
const sourceConnectionId = ref("");
const sourceDatabase = ref("");
-const sourceDatabases = ref<string[]>([]);
const sourceSchema = ref("");
-const sourceSchemas = ref<string[]>([]);
-
const targetConnectionId = ref("");
const targetDatabase = ref("");
-const targetDatabases = ref<string[]>([]);
const targetSchema = ref("");
-const targetSchemas = ref<string[]>([]);
+const ignoreComments = ref(false);
+
+// Options panel
+const showOptionsPanel = ref(false);
+const optionTree = computed(() => {
+ const targetConfig = store.getConfig(targetConnectionId.value);
+ const dbType = targetConfig?.db_type || "postgres";
+ return getSchemaDiffOptionsForDbType(dbType);
+});
-const step = ref<"select" | "comparing" | "result">("select");
-const diffs = ref<SelectableTableDiff[]>([]);
-const loadingMeta = ref(false);
+// Compare state
+const loading = ref(false);
+const diffObjects = ref<SchemaDiffObject[]>([]);
+const diffGroups = ref<OperationGroup[]>([]);
+const selectedObjectId = ref<string | null>(null);
+const deploySql = ref("");
+const deploySqlAll = ref("");
const executing = ref(false);
-const executedCount = ref(0);
-const executeTotal = ref(0);
-const syncErrors = ref<{ sql: string; error: string }[]>([]);
-const syncSql = ref("");
-const ignoreComments = ref(false);
-const highlightedSyncSql = computed(() => highlight(syncSql.value));
+const lastDiffResult = ref<SchemaDiffPreparation | null>(null);
+const targetDbVersion = ref<string | null>(null);
+const showResultDialog = ref(false);
+const deployResult = ref<{ success: boolean; message: string; affectedRows?: number } | null>(null);
+
+// Dialog size memory (width + height + splitpanes ratio)
+const DIALOG_SIZE_KEY = "dbx-schema-diff-size";
+const SPLITPANES_SIZE_KEY = "dbx-schema-diff-splitpanes-v2";
+const savedSize = JSON.parse(localStorage.getItem(DIALOG_SIZE_KEY) || "null");
-const allSelected = computed(() => diffs.value.length > 0 && diffs.value.every((d) => d.selected));
-const someSelected = computed(() => diffs.value.some((d) => d.selected) && !allSelected.value);
+const savedSplitpanes = (() => {
+ try {
+ const raw = localStorage.getItem(SPLITPANES_SIZE_KEY);
+ if (!raw) return null;
+ const val = JSON.parse(raw);
+ return typeof val === "number" && val >= 10 && val <= 90 ? val : null;
+ } catch {
+ return null;
+ }
+})();
+
+// Splitpanes size memory (percentage for first pane)
+const splitpanesSize = ref(savedSplitpanes ?? 60);
-function toggleAll() {
- const next = !allSelected.value;
- diffs.value.forEach((d) => (d.selected = next));
- refreshSelectedSyncSql().catch((e) => toast(e?.message || String(e), 5000));
+function handleSplitpanesResized(payload: { panes: { size: number }[] }) {
+ if (payload.panes && payload.panes.length > 0) {
+ const size = payload.panes[0].size;
+ splitpanesSize.value = size;
+ localStorage.setItem(SPLITPANES_SIZE_KEY, JSON.stringify(size));
+ }
}
-const sqlConnections = computed(() => store.connections.filter((c) => !["redis", "mongodb", "elasticsearch", "etcd"].includes(c.db_type)));
+const isMaximized = ref(false);
+
+// Config step: always use default size 1100x820
+// Result step: use saved size if exists
+const dialogStyle = computed(() => {
+ if (isMaximized.value) {
+ return {
+ width: "100vw",
+ height: "100vh",
+ maxWidth: "100vw",
+ maxHeight: "100vh",
+ borderRadius: "0",
+ };
+ }
+ if (step.value === "result") {
+ return {
+ width: savedSize?.width || "1100px",
+ height: savedSize?.height || "820px",
+ maxWidth: "calc(100vw - 2rem)",
+ maxHeight: "calc(100vh - 2rem)",
+ };
+ }
+ return {
+ width: "1100px",
+ height: "820px",
+ maxWidth: "calc(100vw - 2rem)",
+ maxHeight: "calc(100vh - 2rem)",
+ };
+});
+
+function toggleMaximize() {
+ isMaximized.value = !isMaximized.value;
+}
-const canCompare = computed(() => sourceConnectionId.value && sourceDatabase.value && sourceSchema.value && targetConnectionId.value && targetDatabase.value && targetSchema.value);
+let resizeObserver: ResizeObserver | null = null;
+let saveTimeout: number | null = null;
+
+function setupResizeObserver() {
+ const el = document.querySelector('[data-slot="dialog-content"]') as HTMLElement;
+ if (!el) return;
+
+ resizeObserver = new ResizeObserver((entries) => {
+ for (const entry of entries) {
+ const { width, height } = entry.contentRect;
+ if (saveTimeout) clearTimeout(saveTimeout);
+ saveTimeout = window.setTimeout(() => {
+ localStorage.setItem(
+ DIALOG_SIZE_KEY,
+ JSON.stringify({
+ width: `${width}px`,
+ height: `${height}px`,
+ }),
+ );
+ }, 500);
+ }
+ });
-function connectionIconType(connectionId: string) {
- const config = store.getConfig(connectionId);
- return config?.driver_profile || config?.db_type || "mysql";
+ resizeObserver.observe(el);
}
-function swapSourceTarget() {
- const tmpConnId = sourceConnectionId.value;
- const tmpDb = sourceDatabase.value;
- const tmpDbs = sourceDatabases.value;
- const tmpSchema = sourceSchema.value;
- const tmpSchemas = sourceSchemas.value;
- sourceConnectionId.value = targetConnectionId.value;
- sourceDatabase.value = targetDatabase.value;
- sourceDatabases.value = targetDatabases.value;
- sourceSchema.value = targetSchema.value;
- sourceSchemas.value = targetSchemas.value;
- targetConnectionId.value = tmpConnId;
- targetDatabase.value = tmpDb;
- targetDatabases.value = tmpDbs;
- targetSchema.value = tmpSchema;
- targetSchemas.value = tmpSchemas;
- resetResult();
+function teardownResizeObserver() {
+ if (saveTimeout) clearTimeout(saveTimeout);
+ resizeObserver?.disconnect();
+ resizeObserver = null;
}
-async function loadDatabases(connectionId: string, side: "source" | "target") {
- if (!connectionId) return;
- loadingMeta.value = true;
- try {
- await store.ensureConnected(connectionId);
- const dbs = await api.listDatabases(connectionId);
- const names = databaseOptionsForConnection(
- dbs.map((d) => d.name),
- store.getConfig(connectionId),
- );
- if (side === "source") {
- sourceDatabases.value = names;
- sourceDatabase.value = names.length === 1 ? names[0] : "";
- sourceSchemas.value = [];
- sourceSchema.value = "";
+// Only enable resize observer in result step
+watch(
+ () => step.value,
+ (newStep) => {
+ if (newStep === "result") {
+ setTimeout(setupResizeObserver, 100);
} else {
- targetDatabases.value = names;
- targetDatabase.value = names.length === 1 ? names[0] : "";
- targetSchemas.value = [];
- targetSchema.value = "";
+ teardownResizeObserver();
+ }
+ },
+);
+
+onBeforeUnmount(() => {
+ teardownResizeObserver();
+});
+
+// Config management
+const { configs, activeConfigId, activeConfig, recentConfigs, ensureDefaultConfig, updateActiveConfigConnection, updateActiveConfigOptions, saveToHistory, deleteFromHistory } = useSchemaDiffConfig();
+
+const selectedObject = computed(() => {
+ if (!selectedObjectId.value) return null;
+ for (const group of diffGroups.value) {
+ for (const typeGroup of group.typeGroups) {
+ const obj = typeGroup.objects.find((o) => o.id === selectedObjectId.value);
+ if (obj) return obj;
}
- } catch {
- if (side === "source") sourceDatabases.value = [];
- else targetDatabases.value = [];
- } finally {
- loadingMeta.value = false;
}
-}
+ return null;
+});
+
+const canDeploy = computed(() => {
+ return diffObjects.value.some((o) => o.selected && o.operationType !== "none");
+});
+
+// Watch for prefilled values
+watch(
+ () => open.value,
+ (isOpen) => {
+ if (isOpen) {
+ ensureDefaultConfig();
+ if (props.prefillConnectionId) {
+ sourceConnectionId.value = props.prefillConnectionId;
+ if (props.prefillDatabase) {
+ sourceDatabase.value = props.prefillDatabase;
+ }
+ if (props.prefillSchema) {
+ sourceSchema.value = props.prefillSchema;
+ }
+ }
+ }
+ },
+ { immediate: true },
+);
-async function loadSchemas(side: "source" | "target", preferredSchema = "") {
- const connectionId = side === "source" ? sourceConnectionId.value : targetConnectionId.value;
- const database = side === "source" ? sourceDatabase.value : targetDatabase.value;
- if (!connectionId || !database) return;
- const config = store.getConfig(connectionId);
- if (!isSchemaAware(config?.db_type)) {
- if (side === "source") {
- sourceSchemas.value = [];
- sourceSchema.value = database;
+// Config sync
+watch([sourceConnectionId, sourceDatabase, sourceSchema, targetConnectionId, targetDatabase, targetSchema], ([srcConn, srcDb, srcSchema, tgtConn, tgtDb, tgtSchema]) => {
+ updateActiveConfigConnection({
+ sourceConnectionId: srcConn,
+ sourceDatabase: srcDb,
+ sourceSchema: srcSchema,
+ targetConnectionId: tgtConn,
+ targetDatabase: tgtDb,
+ targetSchema: tgtSchema,
+ });
+});
+
+// Auto-fetch target database version when connection/database changes
+watch(
+ () => [targetConnectionId.value, targetDatabase.value],
+ async ([connId, db]) => {
+ if (connId && db) {
+ await fetchDbVersion(connId, db, targetSchema.value);
} else {
- targetSchemas.value = [];
- targetSchema.value = database;
+ targetDbVersion.value = null;
}
- return;
- }
+ },
+);
- const schemas = await api.listSchemas(connectionId, database);
- const selected = preferredSchema && schemas.includes(preferredSchema) ? preferredSchema : schemas.includes("public") ? "public" : (schemas[0] ?? "");
- if (side === "source") {
- sourceSchemas.value = schemas;
- sourceSchema.value = selected;
- } else {
- targetSchemas.value = schemas;
- targetSchema.value = selected;
+function getDbType(): string {
+ const targetConfig = store.getConfig(targetConnectionId.value);
+ return targetConfig?.db_type || "postgres";
+}
+
+function handleSwap() {
+ const tempConn = sourceConnectionId.value;
+ const tempDb = sourceDatabase.value;
+ const tempSchema = sourceSchema.value;
+ sourceConnectionId.value = targetConnectionId.value;
+ sourceDatabase.value = targetDatabase.value;
+ sourceSchema.value = targetSchema.value;
+ targetConnectionId.value = tempConn;
+ targetDatabase.value = tempDb;
+ targetSchema.value = tempSchema;
+}
+
+function handleOptionsUpdate(options: SchemaDiffCompareOptions) {
+ if (activeConfig.value) {
+ updateActiveConfigOptions(options);
}
}
-async function startCompare() {
- if (!canCompare.value) return;
- step.value = "comparing";
- diffs.value = [];
- syncSql.value = "";
+async function handleCompare() {
+ loading.value = true;
+ step.value = "compare";
try {
await store.ensureConnected(sourceConnectionId.value);
await store.ensureConnected(targetConnectionId.value);
- const targetConfig = store.getConfig(targetConnectionId.value);
const [srcTables, tgtTables] = await Promise.all([api.listTables(sourceConnectionId.value, sourceDatabase.value, sourceSchema.value), api.listTables(targetConnectionId.value, targetDatabase.value, targetSchema.value)]);
- const { sourceDetails, targetDetails } = await loadSchemaDiffDetails(srcTables, tgtTables);
+ // Load schema details in parallel
+ const sourceDetails = await Promise.all(
+ srcTables.map(async (table) => {
+ const [columns, indexes, foreignKeys, triggers, ddl] = await Promise.all([
+ api.getColumns(sourceConnectionId.value, sourceDatabase.value, sourceSchema.value, table.name),
+ api.listIndexes(sourceConnectionId.value, sourceDatabase.value, sourceSchema.value, table.name),
+ api.listForeignKeys(sourceConnectionId.value, sourceDatabase.value, sourceSchema.value, table.name),
+ api.listTriggers(sourceConnectionId.value, sourceDatabase.value, sourceSchema.value, table.name),
+ api.getTableDdl(sourceConnectionId.value, sourceDatabase.value, sourceSchema.value, table.name),
+ ]);
+ return { name: table.name, columns, indexes, foreignKeys, triggers, ddl };
+ }),
+ );
+
+ const targetDetails = await Promise.all(
+ tgtTables.map(async (table) => {
+ const [columns, indexes, foreignKeys, triggers, ddl] = await Promise.all([
+ api.getColumns(targetConnectionId.value, targetDatabase.value, targetSchema.value, table.name),
+ api.listIndexes(targetConnectionId.value, targetDatabase.value, targetSchema.value, table.name),
+ api.listForeignKeys(targetConnectionId.value, targetDatabase.value, targetSchema.value, table.name),
+ api.listTriggers(targetConnectionId.value, targetDatabase.value, targetSchema.value, table.name),
+ api.getTableDdl(targetConnectionId.value, targetDatabase.value, targetSchema.value, table.name),
+ ]);
+ return { name: table.name, columns, indexes, foreignKeys, triggers, ddl };
+ }),
+ );
+
+ const targetConfig = store.getConfig(targetConnectionId.value);
+ const dbType = targetConfig?.db_type || "mysql";
+ const isPostgresLike = dbType === "postgres" || dbType === "opengauss";
+ const opts = activeConfig.value?.options;
+
+ // Fetch new object types for PostgreSQL-like databases
+ const promises: Promise<any>[] = [];
+ if (isPostgresLike && opts?.functions) {
+ promises.push(api.listFunctions(sourceConnectionId.value, sourceDatabase.value, sourceSchema.value));
+ promises.push(api.listFunctions(targetConnectionId.value, targetDatabase.value, targetSchema.value));
+ }
+ if (isPostgresLike && opts?.sequences) {
+ promises.push(api.listSequences(sourceConnectionId.value, sourceDatabase.value, sourceSchema.value, !!opts?.sequenceLastValues));
+ promises.push(api.listSequences(targetConnectionId.value, targetDatabase.value, targetSchema.value, !!opts?.sequenceLastValues));
+ }
+ if (isPostgresLike && opts?.rules) {
+ promises.push(api.listRules(sourceConnectionId.value, sourceDatabase.value, sourceSchema.value));
+ promises.push(api.listRules(targetConnectionId.value, targetDatabase.value, targetSchema.value));
+ }
+ if (isPostgresLike && opts?.owners) {
+ promises.push(api.listOwners(sourceConnectionId.value, sourceDatabase.value, sourceSchema.value));
+ promises.push(api.listOwners(targetConnectionId.value, targetDatabase.value, targetSchema.value));
+ }
+
+ const results = await Promise.all(promises);
+ let idx = 0;
+ const srcFunctions = opts?.functions && isPostgresLike ? results[idx++] : [];
+ const tgtFunctions = opts?.functions && isPostgresLike ? results[idx++] : [];
+ const srcSequences = opts?.sequences && isPostgresLike ? results[idx++] : [];
+ const tgtSequences = opts?.sequences && isPostgresLike ? results[idx++] : [];
+ const srcRules = opts?.rules && isPostgresLike ? results[idx++] : [];
+ const tgtRules = opts?.rules && isPostgresLike ? results[idx++] : [];
+ const srcOwners = opts?.owners && isPostgresLike ? results[idx++] : [];
+ const tgtOwners = opts?.owners && isPostgresLike ? results[idx++] : [];
+
const result = await api.prepareSchemaDiff({
sourceTables: srcTables,
targetTables: tgtTables,
sourceDetails,
targetDetails,
- databaseType: targetConfig?.db_type || "mysql",
+ sourceFunctions: srcFunctions,
+ targetFunctions: tgtFunctions,
+ sourceSequences: srcSequences,
+ targetSequences: tgtSequences,
+ sourceRules: srcRules,
+ targetRules: tgtRules,
+ sourceOwners: srcOwners,
+ targetOwners: tgtOwners,
+ databaseType: dbType,
targetSchema: targetSchema.value,
ignoreComments: ignoreComments.value,
+ cascadeDelete: opts?.cascadeDelete ?? false,
});
- diffs.value = result.diffs.map((diff) => ({ ...diff, selected: true }));
- syncSql.value = result.syncSql;
+ // Convert to unified objects
+ diffObjects.value = convertToSchemaDiffObjects(result.diffs, result.functionDiffs, result.sequenceDiffs, result.ruleDiffs, result.ownerDiffs);
+
+ // Group by operation type and object kind
+ diffGroups.value = groupDiffObjects(diffObjects.value);
+
+ // Save full result and generate deploy SQL
+ lastDiffResult.value = result;
+ deploySqlAll.value = result.syncSql;
+ regenerateDeploySql();
+
step.value = "result";
} catch (e: any) {
toast(e?.message || String(e), 5000);
- step.value = "select";
+ step.value = "config";
+ } finally {
+ loading.value = false;
}
}
-async function loadSchemaDiffDetails(sourceTables: TableInfo[], targetTables: TableInfo[]) {
- const sourceTableNames = sourceTables.filter((table) => table.table_type !== "VIEW").map((table) => table.name);
- const targetTableNames = targetTables.filter((table) => table.table_type !== "VIEW").map((table) => table.name);
- const targetTableSet = new Set(targetTableNames);
- const sourceTableSet = new Set(sourceTableNames);
- const sourceDetails: TableSchemaDetail[] = [];
- const targetDetails: TableSchemaDetail[] = [];
-
- for (const name of sourceTableNames) {
- if (targetTableSet.has(name)) {
- const [columns, indexes, foreignKeys, triggers] = await Promise.all([
- api.getColumns(sourceConnectionId.value, sourceDatabase.value, sourceSchema.value, name),
- api.listIndexes(sourceConnectionId.value, sourceDatabase.value, sourceSchema.value, name),
- api.listForeignKeys(sourceConnectionId.value, sourceDatabase.value, sourceSchema.value, name),
- api.listTriggers(sourceConnectionId.value, sourceDatabase.value, sourceSchema.value, name),
- ]);
- sourceDetails.push({ name, columns, indexes, foreignKeys, triggers });
- } else {
- const ddl = await api.getTableDdl(sourceConnectionId.value, sourceDatabase.value, sourceSchema.value, name);
- sourceDetails.push({ name, ddl });
- }
- }
+function handleToggleGroup(operationType: DiffOperationType) {
+ diffGroups.value = diffGroups.value.map((g) => (g.operationType === operationType ? { ...g, expanded: !g.expanded } : g));
+}
- for (const name of targetTableNames) {
- if (!sourceTableSet.has(name)) continue;
- const [columns, indexes, foreignKeys, triggers] = await Promise.all([
- api.getColumns(targetConnectionId.value, targetDatabase.value, targetSchema.value, name),
- api.listIndexes(targetConnectionId.value, targetDatabase.value, targetSchema.value, name),
- api.listForeignKeys(targetConnectionId.value, targetDatabase.value, targetSchema.value, name),
- api.listTriggers(targetConnectionId.value, targetDatabase.value, targetSchema.value, name),
- ]);
- targetDetails.push({ name, columns, indexes, foreignKeys, triggers });
- }
+function handleToggleTypeGroup(operationType: DiffOperationType, kind: DiffObjectKind) {
+ diffGroups.value = diffGroups.value.map((g) => {
+ if (g.operationType !== operationType) return g;
+ return {
+ ...g,
+ typeGroups: g.typeGroups.map((tg) => (tg.kind === kind ? { ...tg, expanded: !tg.expanded } : tg)),
+ };
+ });
+}
- return { sourceDetails, targetDetails };
+function handleToggleGroupSelection(operationType: DiffOperationType, selected: boolean) {
+ diffGroups.value = diffGroups.value.map((g) => {
+ if (g.operationType !== operationType) return g;
+ return {
+ ...g,
+ selectedCount: selected ? g.count : 0,
+ typeGroups: g.typeGroups.map((tg) => {
+ for (const obj of tg.objects) {
+ obj.selected = selected;
+ }
+ return { ...tg, selectedCount: selected ? tg.objects.length : 0 };
+ }),
+ };
+ });
+ regenerateDeploySql();
}
-async function refreshSelectedSyncSql() {
- const selected = diffs.value.filter((diff) => diff.selected);
- if (selected.length === 0) {
- syncSql.value = "";
- return;
- }
- const targetConfig = store.getConfig(targetConnectionId.value);
- syncSql.value = await api.generateSchemaSyncSql(selected, targetConfig?.db_type || "mysql", targetSchema.value);
+function handleToggleTypeSelection(operationType: DiffOperationType, kind: DiffObjectKind, selected: boolean) {
+ diffGroups.value = diffGroups.value.map((g) => {
+ if (g.operationType !== operationType) return g;
+ const newTypeGroups = g.typeGroups.map((tg) => {
+ if (tg.kind !== kind) return tg;
+ for (const obj of tg.objects) {
+ obj.selected = selected;
+ }
+ return { ...tg, selectedCount: selected ? tg.objects.length : 0 };
+ });
+ const newSelectedCount = newTypeGroups.reduce((sum, tg) => sum + tg.selectedCount, 0);
+ return { ...g, selectedCount: newSelectedCount, typeGroups: newTypeGroups };
+ });
+ regenerateDeploySql();
}
-function onDiffSelectionChange() {
- refreshSelectedSyncSql().catch((e) => toast(e?.message || String(e), 5000));
+function handleToggleObjectSelection(objectId: string, selected: boolean) {
+ const obj = diffObjects.value.find((o) => o.id === objectId);
+ if (!obj) return;
+
+ obj.selected = selected;
+
+ // Update diffGroups with new references to trigger reactivity
+ diffGroups.value = diffGroups.value.map((g) => {
+ if (g.operationType !== obj.operationType) return g;
+ const newTypeGroups = g.typeGroups.map((tg) => {
+ if (tg.kind !== obj.objectKind) return tg;
+ const newSelectedCount = tg.objects.filter((o) => o.selected).length;
+ return { ...tg, selectedCount: newSelectedCount };
+ });
+ const newSelectedCount = newTypeGroups.reduce((sum, tg) => sum + tg.selectedCount, 0);
+ return { ...g, selectedCount: newSelectedCount, typeGroups: newTypeGroups };
+ });
+
+ regenerateDeploySql();
}
-async function executeSql() {
- const sql = syncSql.value.trim();
- if (!sql || executing.value) return;
- executing.value = true;
- syncErrors.value = [];
+function regenerateDeploySql() {
+ // Only select top-level objects (exclude children)
+ const selected = diffObjects.value.filter((o) => {
+ const isTopLevel = !o.id.startsWith("col-") && !o.id.startsWith("idx-") && !o.id.startsWith("fk-") && !o.id.startsWith("trg-");
+ return o.selected && o.operationType !== "none" && isTopLevel;
+ });
- const statements = sql
- .split(/;\s*\n/)
- .map((s) => s.trim())
- .filter((s) => s && !s.startsWith("--"));
- executeTotal.value = statements.length;
- executedCount.value = 0;
+ if (selected.length === 0) {
+ deploySql.value = "-- No objects selected";
+ return;
+ }
- try {
- await store.ensureConnected(targetConnectionId.value);
- for (const stmt of statements) {
- try {
- await api.executeQuery(targetConnectionId.value, targetDatabase.value, stmt, targetSchema.value);
- } catch (e: any) {
- syncErrors.value.push({ sql: stmt, error: e?.message || String(e) });
+ const lines: string[] = [];
+
+ for (const obj of selected) {
+ if (obj.operationType === "create") {
+ if (obj.sourceDdl) {
+ lines.push(`-- Create ${obj.objectKind}: ${obj.name}`);
+ lines.push(obj.sourceDdl);
+ lines.push("");
}
- executedCount.value++;
- }
- const failed = syncErrors.value.length;
- if (failed === 0) {
- const refreshTarget = sqlMetadataRefreshTarget(sql, targetSchema.value);
- if (refreshTarget.scope === "connection") {
- await store.loadDatabases(targetConnectionId.value, { force: true });
- } else if (refreshTarget.scope === "database") {
- await store.refreshObjectListTreeNode(targetConnectionId.value, targetDatabase.value, refreshTarget.schema);
+ } else if (obj.operationType === "delete") {
+ lines.push(`-- Drop ${obj.objectKind}: ${obj.name}`);
+ const dropSql = generateDropSql(obj);
+ lines.push(dropSql);
+ lines.push("");
+ } else if (obj.operationType === "modify") {
+ if (obj.sourceDdl) {
+ lines.push(`-- Modify ${obj.objectKind}: ${obj.name}`);
+ lines.push(obj.sourceDdl);
+ lines.push("");
}
- toast(t("diff.syncSuccess"), 2000);
- open.value = false;
- } else {
- toast(t("diff.syncSummary", { success: statements.length - failed, failed }), 5000);
}
+ }
+
+ deploySql.value = lines.join("\n") || "-- No DDL available for selected objects";
+}
+
+function generateDropSql(obj: SchemaDiffObject): string {
+ const typeMap: Record<string, string> = {
+ table: "TABLE",
+ view: "VIEW",
+ function: "FUNCTION",
+ sequence: "SEQUENCE",
+ rule: "RULE",
+ owner: "OWNED BY",
+ };
+ const sqlType = typeMap[obj.objectKind] || obj.objectKind.toUpperCase();
+ return `DROP ${sqlType} IF EXISTS ${obj.name};`;
+}
+
+async function handleExecuteScript() {
+ if (!deploySql.value || deploySql.value.startsWith("-- ")) {
+ toast(t("diff.noObjectsSelected"), 3000);
+ return;
+ }
+
+ executing.value = true;
+ try {
+ await api.executeScript(targetConnectionId.value, targetDatabase.value, deploySql.value, targetSchema.value);
+ toast(t("diff.executeSuccess"), 3000);
} catch (e: any) {
toast(e?.message || String(e), 5000);
} finally {
executing.value = false;
}
}
+async function handleSelectObject(obj: SchemaDiffObject) {
+ selectedObjectId.value = obj.id;
+
+ // Dynamically fetch DDL for objects that don't have pre-generated DDL
+ // (views need runtime retrieval; functions should already have definition)
+ const objectTypeMap: Record<string, ObjectSourceKind> = {
+ function: "FUNCTION",
+ view: "VIEW",
+ };
+ const objectType = objectTypeMap[obj.objectKind];
+ if (!objectType) return;
-async function copySql() {
try {
- await copyToClipboard(syncSql.value);
- toast(t("grid.copied"));
- } catch (e: any) {
- toast(t("grid.copyFailed", { message: e?.message || String(e) }), 5000);
+ // For "create" objects: source has it, target doesn't → fetch source DDL
+ if (obj.operationType === "create" && !obj.sourceDdl) {
+ const result = await api.getObjectSource(sourceConnectionId.value, sourceDatabase.value, sourceSchema.value, obj.name, objectType);
+ if (result?.source) obj.sourceDdl = result.source;
+ }
+
+ // For "delete" objects: target has it, source doesn't → fetch target DDL
+ if (obj.operationType === "delete" && !obj.targetDdl) {
+ const result = await api.getObjectSource(targetConnectionId.value, targetDatabase.value, targetSchema.value, obj.name, objectType);
+ if (result?.source) obj.targetDdl = result.source;
+ }
+
+ // For "modify" objects: fetch whichever side is missing
+ if (obj.operationType === "modify") {
+ if (!obj.sourceDdl) {
+ const result = await api.getObjectSource(sourceConnectionId.value, sourceDatabase.value, sourceSchema.value, obj.name, objectType);
+ if (result?.source) obj.sourceDdl = result.source;
+ }
+ if (!obj.targetDdl) {
+ const result = await api.getObjectSource(targetConnectionId.value, targetDatabase.value, targetSchema.value, obj.name, objectType);
+ if (result?.source) obj.targetDdl = result.source;
+ }
+ }
+ } catch {
+ // Silently ignore errors
+ }
+}
+function handleLoadHistoryConfig(config: SchemaDiffConfig) {
+ sourceConnectionId.value = config.sourceConnectionId;
+ sourceDatabase.value = config.sourceDatabase;
+ sourceSchema.value = config.sourceSchema;
+ targetConnectionId.value = config.targetConnectionId;
+ targetDatabase.value = config.targetDatabase;
+ targetSchema.value = config.targetSchema;
+ if (config.options) {
+ updateActiveConfigOptions(config.options);
}
}
-function diffBadgeVariant(type: string) {
- if (type === "added") return "default";
- if (type === "removed") return "destructive";
- return "secondary";
+function handleSaveConfig() {
+ if (activeConfig.value) {
+ const name = window.prompt(t("diff.saveConfigPrompt") || "Please enter config name:", activeConfig.value.name || "Default");
+ if (name === null) return; // User cancelled
+ const configToSave = { ...activeConfig.value, name: name.trim() || "Default" };
+ saveToHistory(configToSave);
+ toast(t("diff.configSaved"), 2000);
+ }
}
-function diffLabel(type: string) {
- if (type === "added") return t("diff.added");
- if (type === "removed") return t("diff.removed");
- return t("diff.modified");
+function handleDeleteHistoryConfig(configId: string) {
+ deleteFromHistory(configId);
+ toast(t("diff.configDeleted"), 2000);
}
-function resetResult() {
- step.value = "select";
- diffs.value = [];
- syncSql.value = "";
- syncErrors.value = [];
- executedCount.value = 0;
- executeTotal.value = 0;
+async function fetchDbVersion(connectionId: string, database: string, schema: string) {
+ try {
+ await store.ensureConnected(connectionId);
+ const config = store.getConfig(connectionId);
+ const dbType = config?.db_type;
+ let sql = "";
+ switch (dbType) {
+ case "postgres":
+ case "opengauss":
+ sql = "SELECT version()";
+ break;
+ case "mysql":
+ sql = "SELECT VERSION()";
+ break;
+ case "sqlite":
+ sql = "SELECT sqlite_version()";
+ break;
+ default:
+ return;
+ }
+ const result = await api.executeQuery(connectionId, database, sql, schema || undefined);
+ if (result.rows && result.rows.length > 0) {
+ targetDbVersion.value = String(result.rows[0][0]);
+ } else {
+ console.warn("[fetchDbVersion] No rows returned");
+ }
+ } catch (e) {
+ console.error("[fetchDbVersion] Failed to fetch version:", e);
+ targetDbVersion.value = null;
+ }
}
-watch(sourceConnectionId, (id) => {
- sourceDatabase.value = "";
- loadDatabases(id, "source");
- resetResult();
-});
+function handleDeployReview() {
+ const selectedObjects = diffObjects.value.filter((o) => o.selected && o.operationType !== "none");
+ if (selectedObjects.length === 0) {
+ toast(t("diff.noObjectsSelected"), 3000);
+ return;
+ }
+ step.value = "deploy-review";
+ fetchDbVersion(targetConnectionId.value, targetDatabase.value, targetSchema.value);
+}
-watch(targetConnectionId, (id) => {
- targetDatabase.value = "";
- loadDatabases(id, "target");
- resetResult();
-});
+async function handleDeploy() {
+ showConfirmDialog.value = true;
+}
-watch(sourceDatabase, (database) => {
- sourceSchema.value = "";
- sourceSchemas.value = [];
- resetResult();
- if (database) loadSchemas("source", props.prefillSchema).catch((e) => toast(String(e), 5000));
-});
-watch(targetDatabase, (database) => {
- targetSchema.value = "";
- targetSchemas.value = [];
- resetResult();
- if (database) loadSchemas("target").catch((e) => toast(String(e), 5000));
+async function onConfirmDeploy() {
+ showConfirmDialog.value = false;
+ executing.value = true;
+ try {
+ const result = await api.executeScript(targetConnectionId.value, targetDatabase.value, deploySql.value, targetSchema.value);
+ deployResult.value = {
+ success: true,
+ message: t("diff.deploySuccess"),
+ affectedRows: result.affected_rows,
+ };
+ showResultDialog.value = true;
+ } catch (e: any) {
+ deployResult.value = {
+ success: false,
+ message: e?.message || String(e),
+ };
+ showResultDialog.value = true;
+ } finally {
+ executing.value = false;
+ }
+}
+
+const deployStats = computed(() => {
+ const selected = diffObjects.value.filter((o) => o.selected && o.operationType !== "none");
+ const isTopLevel = (o: SchemaDiffObject) => !o.id.startsWith("col-") && !o.id.startsWith("idx-") && !o.id.startsWith("fk-") && !o.id.startsWith("trg-");
+ const topLevel = selected.filter(isTopLevel);
+ return {
+ create: topLevel.filter((o) => o.operationType === "create").length,
+ modify: topLevel.filter((o) => o.operationType === "modify").length,
+ delete: topLevel.filter((o) => o.operationType === "delete").length,
+ total: topLevel.length,
+ };
});
-watch(sourceSchema, () => resetResult());
-watch(targetSchema, () => resetResult());
-watch(ignoreComments, () => resetResult());
-watch(
- open,
- async (val) => {
- if (val) {
- step.value = "select";
- diffs.value = [];
- syncErrors.value = [];
- executedCount.value = 0;
- executeTotal.value = 0;
- if (props.prefillConnectionId) {
- sourceConnectionId.value = props.prefillConnectionId;
- await loadDatabases(props.prefillConnectionId, "source");
- if (props.prefillDatabase) {
- sourceDatabase.value = props.prefillDatabase;
- await loadSchemas("source", props.prefillSchema);
- }
- }
- }
- },
- { immediate: true },
-);
+const targetConnectionInfo = computed(() => {
+ const config = store.getConfig(targetConnectionId.value);
+ if (!config) return null;
+ return {
+ host: config.host || "-",
+ port: config.port || "-",
+ dbType: config.db_type || "-",
+ };
+});
</script>
<template>
<Dialog v-model:open="open">
- <DialogContent class="min-w-[min(720px,calc(100vw-2rem))] resize-x sm:max-w-5xl max-h-[80vh] flex flex-col overflow-hidden" @interact-outside.prevent>
+ <DialogContent :class="['min-w-[800px] flex flex-col overflow-hidden', isMaximized ? '' : 'resize']" :style="dialogStyle" @interact-outside.prevent>
+ <Button variant="ghost" size="icon-sm" class="absolute top-2 right-10 z-10" @click="toggleMaximize">
+ <Maximize2 v-if="!isMaximized" class="w-4 h-4" />
+ <Minimize2 v-else class="w-4 h-4" />
+ <span class="sr-only">{{ isMaximized ? t("diff.restore") : t("diff.maximize") }}</span>
+ </Button>
+
<DialogHeader>
<DialogTitle class="flex items-center gap-2">
<GitCompareArrows class="w-4 h-4" />
@@ -369,247 +683,195 @@ watch(
</DialogTitle>
</DialogHeader>
- <div class="flex-1 min-h-0 overflow-auto space-y-4 py-2">
- <!-- Source / Target Selection -->
- <div class="grid grid-cols-[1fr_auto_1fr] gap-4 items-start">
- <div class="space-y-2">
- <Label class="text-xs font-medium">{{ t("diff.source") }}</Label>
- <Select :model-value="sourceConnectionId" @update:model-value="(v: any) => (sourceConnectionId = String(v))">
- <SelectTrigger class="h-8 text-xs">
- <div class="flex items-center gap-2">
- <DatabaseIcon v-if="sourceConnectionId" :db-type="connectionIconType(sourceConnectionId)" class="w-3.5 h-3.5" />
- <SelectValue :placeholder="t('diff.selectConnection')" />
- </div>
- </SelectTrigger>
- <SelectContent>
- <SelectItem v-for="c in sqlConnections" :key="c.id" :value="c.id">
- <div class="flex items-center gap-2">
- <DatabaseIcon :db-type="c.driver_profile || c.db_type" class="w-3.5 h-3.5" />
- {{ c.name }}
- </div>
- </SelectItem>
- </SelectContent>
- </Select>
- <Select v-if="sourceDatabases.length" :model-value="sourceDatabase" @update:model-value="(v: any) => (sourceDatabase = String(v))">
- <SelectTrigger class="h-8 text-xs">
- <SelectValue :placeholder="t('diff.selectDatabase')" />
- </SelectTrigger>
- <SelectContent>
- <SelectItem v-for="db in sourceDatabases" :key="db" :value="db">{{ db }}</SelectItem>
- </SelectContent>
- </Select>
- <Select v-if="sourceSchemas.length" :model-value="sourceSchema" @update:model-value="(v: any) => (sourceSchema = String(v))">
- <SelectTrigger class="h-8 text-xs">
- <SelectValue :placeholder="t('diff.selectSchema')" />
- </SelectTrigger>
- <SelectContent>
- <SelectItem v-for="schema in sourceSchemas" :key="schema" :value="schema">{{ schema }}</SelectItem>
- </SelectContent>
- </Select>
- </div>
+ <div class="flex-1 min-h-0 overflow-hidden flex flex-col">
+ <!-- Config Step -->
+ <SchemaDiffConfigStep
+ v-if="step === 'config'"
+ v-model:source-connection-id="sourceConnectionId"
+ v-model:source-database="sourceDatabase"
+ v-model:source-schema="sourceSchema"
+ v-model:target-connection-id="targetConnectionId"
+ v-model:target-database="targetDatabase"
+ v-model:target-schema="targetSchema"
+ v-model:ignore-comments="ignoreComments"
+ :configs="configs"
+ :active-config-id="activeConfigId"
+ :options="activeConfig?.options"
+ :loading="loading"
+ :recent-configs="recentConfigs"
+ @compare="handleCompare"
+ @swap="handleSwap"
+ @show-options="showOptionsPanel = true"
+ @save-config="handleSaveConfig"
+ @load-history-config="handleLoadHistoryConfig"
+ @delete-history-config="handleDeleteHistoryConfig"
+ />
+
+ <!-- Compare Loading -->
+ <div v-else-if="step === 'compare'" class="flex items-center justify-center py-20">
+ <Loader2 class="w-6 h-6 animate-spin mr-2" />
+ <span class="text-sm text-muted-foreground">{{ t("diff.comparing") }}</span>
+ </div>
- <div class="flex items-center pt-6">
- <Button variant="ghost" size="icon" class="h-7 w-7" :title="t('diff.swap')" @click="swapSourceTarget">
- <ArrowLeftRight class="w-3.5 h-3.5" />
- </Button>
- </div>
+ <!-- Result Step -->
+ <template v-else-if="step === 'result'">
+ <Splitpanes horizontal class="flex-1 min-h-0" @resized="handleSplitpanesResized">
+ <Pane :size="splitpanesSize" min-size="20">
+ <div class="h-full overflow-auto">
+ <SchemaDiffObjectTree
+ :groups="diffGroups"
+ :selected-object-id="selectedObject?.id ?? null"
+ @toggle-group="handleToggleGroup"
+ @toggle-type-group="handleToggleTypeGroup"
+ @toggle-group-selection="handleToggleGroupSelection"
+ @toggle-type-selection="handleToggleTypeSelection"
+ @toggle-object-selection="handleToggleObjectSelection"
+ @select-object="handleSelectObject"
+ />
+ </div>
+ </Pane>
+ <Pane :size="100 - splitpanesSize" min-size="20">
+ <SchemaDiffDdlPanel :selected-object="selectedObject" :deploy-sql="deploySql" :deploy-sql-all="deploySqlAll" @execute-script="handleExecuteScript" />
+ </Pane>
+ </Splitpanes>
+ </template>
- <div class="space-y-2">
- <Label class="text-xs font-medium">{{ t("diff.target") }}</Label>
- <Select :model-value="targetConnectionId" @update:model-value="(v: any) => (targetConnectionId = String(v))">
- <SelectTrigger class="h-8 text-xs">
- <div class="flex items-center gap-2">
- <DatabaseIcon v-if="targetConnectionId" :db-type="connectionIconType(targetConnectionId)" class="w-3.5 h-3.5" />
- <SelectValue :placeholder="t('diff.selectConnection')" />
- </div>
- </SelectTrigger>
- <SelectContent>
- <SelectItem v-for="c in sqlConnections" :key="c.id" :value="c.id">
- <div class="flex items-center gap-2">
- <DatabaseIcon :db-type="c.driver_profile || c.db_type" class="w-3.5 h-3.5" />
- {{ c.name }}
- </div>
- </SelectItem>
- </SelectContent>
- </Select>
- <Select v-if="targetDatabases.length" :model-value="targetDatabase" @update:model-value="(v: any) => (targetDatabase = String(v))">
- <SelectTrigger class="h-8 text-xs">
- <SelectValue :placeholder="t('diff.selectDatabase')" />
- </SelectTrigger>
- <SelectContent>
- <SelectItem v-for="db in targetDatabases" :key="db" :value="db">{{ db }}</SelectItem>
- </SelectContent>
- </Select>
- <Select v-if="targetSchemas.length" :model-value="targetSchema" @update:model-value="(v: any) => (targetSchema = String(v))">
- <SelectTrigger class="h-8 text-xs">
- <SelectValue :placeholder="t('diff.selectSchema')" />
- </SelectTrigger>
- <SelectContent>
- <SelectItem v-for="schema in targetSchemas" :key="schema" :value="schema">{{ schema }}</SelectItem>
- </SelectContent>
- </Select>
- </div>
- </div>
+ <!-- Deploy Review Step -->
+ <template v-else-if="step === 'deploy-review'">
+ <SchemaDiffDeployStep v-model:deploy-sql="deploySql" :selected-objects="diffObjects" :target-connection-id="targetConnectionId" :target-database="targetDatabase" :target-schema="targetSchema" :executing="executing" @back="step = 'result'" @deploy="handleDeploy" />
+ </template>
+ </div>
- <div class="flex items-center gap-2 rounded-md border bg-muted/20 px-3 py-2">
- <input id="schema-diff-ignore-comments" v-model="ignoreComments" type="checkbox" class="accent-primary" />
- <Label for="schema-diff-ignore-comments" class="cursor-pointer text-xs">
- {{ t("diff.ignoreComments") }}
- </Label>
+ <!-- Footer -->
+ <DialogFooter class="flex items-center justify-between">
+ <div v-if="step === 'result'" class="flex items-center gap-2">
+ <Button variant="outline" size="sm" @click="step = 'config'">
+ <ArrowLeft class="w-3.5 h-3.5 mr-1" />
+ {{ t("diff.prevStep") }}
+ </Button>
+ <Button variant="outline" size="sm" :disabled="loading" @click="handleCompare">
+ <GitCompareArrows class="w-3.5 h-3.5 mr-1" />
+ {{ t("diff.recompare") }}
+ </Button>
</div>
-
- <!-- Comparing -->
- <div v-if="step === 'comparing'" class="flex items-center justify-center py-8 text-sm text-muted-foreground">
- <Loader2 class="w-4 h-4 animate-spin mr-2" />
- {{ t("diff.comparing") }}
+ <div v-else></div>
+
+ <div v-if="step === 'result'" class="flex items-center gap-2">
+ <Button size="sm" :disabled="!canDeploy || executing" @click="handleDeployReview">
+ <Loader2 v-if="executing" class="w-3.5 h-3.5 mr-1 animate-spin" />
+ <Play v-else class="w-3.5 h-3.5 mr-1" />
+ {{ t("diff.nextStepDeploy") }}
+ </Button>
</div>
+ </DialogFooter>
- <!-- Results -->
- <template v-if="step === 'result'">
- <div v-if="diffs.length === 0" class="py-6 text-center text-sm text-muted-foreground">
- {{ t("diff.noDifferences") }}
- </div>
-
- <template v-else>
- <!-- Diff Table -->
- <div class="border rounded-lg overflow-hidden">
- <div class="max-h-60 overflow-auto">
- <table class="w-full text-xs table-fixed">
- <thead class="bg-muted sticky top-0 z-10">
- <tr>
- <th class="px-2 py-2 w-8">
- <input type="checkbox" class="accent-primary" :checked="allSelected" :indeterminate="someSelected" @change="toggleAll" />
- </th>
- <th class="text-left px-3 py-2 font-medium w-1/4">{{ t("diff.table") }}</th>
- <th class="text-left px-3 py-2 font-medium w-16">{{ t("diff.status") }}</th>
- <th class="text-left px-3 py-2 font-medium">{{ t("diff.details") }}</th>
- </tr>
- </thead>
- <tbody>
- <tr v-for="d in diffs" :key="d.name" class="border-t border-border/50 hover:bg-accent/30">
- <td class="px-2 py-1.5">
- <input v-model="d.selected" type="checkbox" class="accent-primary" @change="onDiffSelectionChange" />
- </td>
- <td class="px-3 py-1.5 font-mono truncate">{{ d.name }}</td>
- <td class="px-3 py-1.5">
- <Badge :variant="diffBadgeVariant(d.type)" class="text-[10px] h-4 px-1.5">
- {{ diffLabel(d.type) }}
- </Badge>
- </td>
- <td class="px-3 py-1.5 text-muted-foreground">
- <template v-if="d.type === 'modified' && d.columns">
- <span v-for="(col, ci) in d.columns" :key="`col-${ci}`">
- <span
- :class="{
- 'text-green-500': col.type === 'added',
- 'text-red-500': col.type === 'removed',
- 'text-yellow-500': col.type === 'modified',
- }"
- >{{ col.type === "added" ? "+" : col.type === "removed" ? "-" : "~" }}{{ col.name }}</span
- >
- <span v-if="ci < d.columns!.length - 1">, </span>
- </span>
- </template>
- <template v-if="d.type === 'modified' && d.indexes">
- <span v-if="d.columns?.length">; </span>
- <span>{{ t("diff.indexes") }}: </span>
- <span v-for="(idx, ii) in d.indexes" :key="`idx-${ii}`">
- <span
- :class="{
- 'text-green-500': idx.type === 'added',
- 'text-red-500': idx.type === 'removed',
- 'text-yellow-500': idx.type === 'modified',
- }"
- >{{ idx.type === "added" ? "+" : idx.type === "removed" ? "-" : "~" }}{{ idx.name }}</span
- >
- <span v-if="ii < d.indexes!.length - 1">, </span>
- </span>
- </template>
- <template v-if="d.type === 'modified' && d.foreignKeys">
- <span v-if="d.columns?.length || d.indexes?.length">; </span>
- <span>{{ t("diff.foreignKeys") }}: </span>
- <span v-for="(fk, fi) in d.foreignKeys" :key="`fk-${fi}`">
- <span
- :class="{
- 'text-green-500': fk.type === 'added',
- 'text-red-500': fk.type === 'removed',
- 'text-yellow-500': fk.type === 'modified',
- }"
- >{{ fk.type === "added" ? "+" : fk.type === "removed" ? "-" : "~" }}{{ fk.name }}</span
- >
- <span v-if="fi < d.foreignKeys!.length - 1">, </span>
- </span>
- </template>
- <template v-if="d.type === 'modified' && d.triggers">
- <span v-if="d.columns?.length || d.indexes?.length || d.foreignKeys?.length">; </span>
- <span>{{ t("diff.triggers") }}: </span>
- <span v-for="(trigger, ti) in d.triggers" :key="`trigger-${ti}`">
- <span
- :class="{
- 'text-green-500': trigger.type === 'added',
- 'text-red-500': trigger.type === 'removed',
- 'text-yellow-500': trigger.type === 'modified',
- }"
- >{{ trigger.type === "added" ? "+" : trigger.type === "removed" ? "-" : "~" }}{{ trigger.name }}</span
- >
- <span v-if="ti < d.triggers!.length - 1">, </span>
- </span>
- </template>
- <template v-if="d.type === 'modified' && d.sourceTableComment !== undefined">
- <span v-if="d.columns?.length || d.indexes?.length || d.foreignKeys?.length || d.triggers?.length">; </span>
- <span>{{ t("diff.comments") }}</span>
- </template>
- <span v-else-if="d.type === 'added'" class="text-green-500">{{ t("diff.newTable") }}</span>
- <span v-else-if="d.type === 'removed'" class="text-red-500">{{ t("diff.dropTable") }}</span>
- </td>
- </tr>
- </tbody>
- </table>
+ <!-- Deploy Confirm Dialog -->
+ <Dialog v-model:open="showConfirmDialog">
+ <DialogContent class="sm:max-w-[520px]">
+ <DialogHeader>
+ <DialogTitle class="flex items-center gap-2 text-destructive">
+ <AlertTriangle class="h-5 w-5" />
+ {{ t("diff.deployConfirmTitle") }}
+ </DialogTitle>
+ </DialogHeader>
+
+ <div class="py-2 space-y-3">
+ <p class="text-sm text-muted-foreground">{{ t("diff.deployConfirmMessage") }}</p>
+
+ <div class="bg-muted p-3 rounded text-xs font-mono space-y-1">
+ <div v-if="targetConnectionInfo">
+ {{ t("diff.targetServer") }}: {{ targetConnectionInfo.host }}:{{ targetConnectionInfo.port }}
+ <span class="text-muted-foreground">({{ targetConnectionInfo.dbType }})</span>
+ </div>
+ <div v-if="targetDbVersion">{{ t("diff.dbVersion") }}: {{ targetDbVersion }}</div>
+ <div>
+ {{ t("diff.targetDatabase") }}:
+ <span class="text-primary font-bold">{{ targetDatabase }}</span>
+ </div>
+ <div>
+ {{ t("diff.targetSchema") }}:
+ <span class="text-primary font-bold">{{ targetSchema || "-" }}</span>
</div>
</div>
- <!-- SQL Preview -->
- <div class="space-y-1">
- <Label class="text-xs font-medium">{{ t("diff.generatedSql") }}</Label>
- <pre class="w-full h-48 overflow-auto rounded-lg border bg-muted/20 p-3 font-mono text-xs whitespace-pre" v-html="highlightedSyncSql"></pre>
+ <div class="flex gap-4 text-sm">
+ <span class="text-green-600">{{ t("diff.create") }}: {{ deployStats.create }}</span>
+ <span class="text-blue-600">{{ t("diff.modify") }}: {{ deployStats.modify }}</span>
+ <span class="text-red-600">{{ t("diff.delete") }}: {{ deployStats.delete }}</span>
</div>
+ </div>
- <!-- Sync Errors -->
- <div v-if="syncErrors.length > 0" class="space-y-1">
- <Label class="text-xs font-medium text-destructive">
- {{ t("diff.syncSummary", { success: executeTotal - syncErrors.length, failed: syncErrors.length }) }}
- </Label>
- <div class="max-h-32 overflow-auto border rounded-lg bg-destructive/5 p-2 space-y-1">
- <div v-for="(err, i) in syncErrors" :key="i" class="text-xs font-mono">
- <span class="text-destructive">{{ err.error }}</span>
- <span class="text-muted-foreground ml-1">— {{ err.sql.slice(0, 80) }}{{ err.sql.length > 80 ? "..." : "" }}</span>
- </div>
+ <DialogFooter>
+ <Button variant="outline" @click="showConfirmDialog = false">{{ t("diff.cancel") }}</Button>
+ <Button variant="destructive" :disabled="executing" @click="onConfirmDeploy">
+ <Loader2 v-if="executing" class="w-3.5 h-3.5 mr-1 animate-spin" />
+ {{ t("diff.confirmDeploy") }}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+
+ <!-- Deploy Result Dialog -->
+ <Dialog v-model:open="showResultDialog">
+ <DialogContent class="sm:max-w-[480px]">
+ <DialogHeader>
+ <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" />
+ {{ deployResult?.success ? t("diff.deploySuccess") : t("diff.deployFailed") }}
+ </DialogTitle>
+ </DialogHeader>
+
+ <div class="py-2">
+ <div v-if="deployResult?.success" class="space-y-2">
+ <p class="text-sm text-muted-foreground">{{ t("diff.deploySuccessMessage") }}</p>
+ <div class="bg-muted p-3 rounded text-xs font-mono">
+ <div>{{ t("diff.affectedRows") }}: {{ deployResult.affectedRows ?? 0 }}</div>
+ <div>{{ t("diff.executedStatements") }}: {{ deployStats.total }}</div>
</div>
</div>
- </template>
- </template>
- </div>
-
- <DialogFooter v-if="!(step === 'result' && diffs.length > 0)" class="flex items-center gap-2">
- <Button variant="outline" @click="open = false">{{ t("common.close") }}</Button>
- <Button v-if="step === 'select'" size="sm" :disabled="!canCompare || loadingMeta" @click="startCompare">
- <Loader2 v-if="loadingMeta" class="w-3.5 h-3.5 mr-1 animate-spin" />
- <GitCompareArrows v-else class="w-3.5 h-3.5 mr-1" />
- {{ loadingMeta ? t("common.loading") : t("diff.compare") }}
- </Button>
- </DialogFooter>
+ <div v-else class="space-y-2">
+ <p class="text-sm text-muted-foreground">{{ t("diff.deployFailedMessage") }}</p>
+ <pre class="text-xs bg-destructive/10 text-destructive p-3 rounded overflow-auto max-h-40 font-mono whitespace-pre-wrap">{{ deployResult?.message }}</pre>
+ </div>
+ </div>
- <DialogFooter v-if="step === 'result' && diffs.length > 0" class="flex items-center gap-2">
- <span v-if="executing" class="text-xs text-muted-foreground mr-auto">
- {{ t("diff.syncProgress", { current: executedCount, total: executeTotal }) }}
- </span>
- <Button variant="outline" size="sm" @click="copySql"> <Copy class="w-3 h-3 mr-1" /> {{ t("diff.copySql") }} </Button>
- <Button size="sm" :disabled="!syncSql.trim() || executing" @click="executeSql">
- <Loader2 v-if="executing" class="w-3 h-3 animate-spin mr-1" />
- <Play v-else class="w-3 h-3 mr-1" />
- {{ t("diff.executeSync") }}
- </Button>
- </DialogFooter>
+ <DialogFooter>
+ <Button variant="outline" @click="showResultDialog = false">{{ t("diff.close") }}</Button>
+ <Button
+ v-if="deployResult?.success"
+ @click="
+ showResultDialog = false;
+ step = 'result';
+ "
+ >
+ {{ t("diff.backToResult") }}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+
+ <!-- Options Panel Overlay -->
+ <div v-if="showOptionsPanel" class="absolute inset-0 bg-background/80 backdrop-blur-sm z-50 flex items-center justify-center" @click.self="showOptionsPanel = false">
+ <div class="bg-card border rounded-lg shadow-lg w-[500px] max-h-[80vh] overflow-auto p-4">
+ <div class="flex items-center justify-between mb-4">
+ <h3 class="text-sm font-medium">{{ t("schemaDiff.optionsTitle") }}</h3>
+ <Button variant="ghost" size="sm" @click="showOptionsPanel = false">✕</Button>
+ </div>
+ <SchemaDiffOptionsPanel :options="activeConfig?.options ?? getDefaultOptionsForDbType(getDbType())" :option-tree="optionTree" @update:options="handleOptionsUpdate" @close="showOptionsPanel = false" />
+ </div>
+ </div>
</DialogContent>
</Dialog>
</template>
+
+<style scoped>
+:deep(.splitpanes--horizontal > .splitpanes__splitter) {
+ height: 8px;
+ background: hsl(var(--border));
+ cursor: row-resize;
+}
+:deep(.splitpanes--horizontal > .splitpanes__splitter:hover) {
+ background: hsl(var(--primary));
+}
+</style>
diff --git a/apps/desktop/src/components/diff/SchemaDiffObjectTree.vue b/apps/desktop/src/components/diff/SchemaDiffObjectTree.vue
new file mode 100644
index 0000000000..83458b06b2
--- /dev/null
+++ b/apps/desktop/src/components/diff/SchemaDiffObjectTree.vue
@@ -0,0 +1,245 @@
+<script setup lang="ts">
+import { useI18n } from "vue-i18n";
+import type { SchemaDiffObject, DiffOperationType, DiffObjectKind } from "@/lib/schemaDiff";
+import { Table, Eye, FunctionSquare, ListOrdered, ScrollText, UserCog, ListTree, Link2, Zap, ChevronDown, ChevronRight, ArrowRightLeft, PlusCircle, XCircle, MinusCircle } from "@lucide/vue";
+
+const { t } = useI18n();
+
+interface ObjectTypeGroup {
+ kind: DiffObjectKind;
+ label: string;
+ objects: SchemaDiffObject[];
+ expanded: boolean;
+}
+
+interface OperationGroup {
+ operationType: DiffOperationType;
+ label: string;
+ count: number;
+ selectedCount: number;
+ expanded: boolean;
+ typeGroups: ObjectTypeGroup[];
+}
+
+const props = defineProps<{
+ groups: OperationGroup[];
+ selectedObjectId?: string | null;
+}>();
+
+const emit = defineEmits<{
+ (e: "toggleGroup", operationType: DiffOperationType): void;
+ (e: "toggleTypeGroup", operationType: DiffOperationType, kind: DiffObjectKind): void;
+ (e: "toggleGroupSelection", operationType: DiffOperationType, selected: boolean): void;
+ (e: "toggleTypeSelection", operationType: DiffOperationType, kind: DiffObjectKind, selected: boolean): void;
+ (e: "toggleObjectSelection", objectId: string, selected: boolean): void;
+ (e: "selectObject", object: SchemaDiffObject): void;
+}>();
+
+const operationIcons: Record<DiffOperationType, any> = {
+ modify: ArrowRightLeft,
+ create: PlusCircle,
+ delete: XCircle,
+ none: MinusCircle,
+};
+
+const operationColors: Record<DiffOperationType, string> = {
+ modify: "text-blue-500",
+ create: "text-green-500",
+ delete: "text-red-500",
+ none: "text-muted-foreground",
+};
+
+const operationBgColors: Record<DiffOperationType, string> = {
+ modify: "bg-blue-500/10 border-blue-500/20",
+ create: "bg-green-500/10 border-green-500/20",
+ delete: "bg-red-500/10 border-red-500/20",
+ none: "bg-muted/30 border-muted",
+};
+
+function getObjectIcon(kind: DiffObjectKind) {
+ switch (kind) {
+ case "table":
+ return Table;
+ case "view":
+ return Eye;
+ case "function":
+ return FunctionSquare;
+ case "sequence":
+ return ListOrdered;
+ case "rule":
+ return ScrollText;
+ case "owner":
+ return UserCog;
+ case "index":
+ return ListTree;
+ case "foreignKey":
+ return Link2;
+ case "trigger":
+ return Zap;
+ default:
+ return Table;
+ }
+}
+
+function getObjectIconColor(kind: DiffObjectKind): string {
+ switch (kind) {
+ case "table":
+ return "text-amber-500";
+ case "view":
+ return "text-cyan-500";
+ case "function":
+ return "text-purple-500";
+ case "sequence":
+ return "text-orange-500";
+ case "rule":
+ return "text-pink-500";
+ case "owner":
+ return "text-indigo-500";
+ case "index":
+ return "text-teal-500";
+ case "foreignKey":
+ return "text-lime-500";
+ case "trigger":
+ return "text-rose-500";
+ default:
+ return "text-muted-foreground";
+ }
+}
+
+function getObjectTypeLabel(kind: DiffObjectKind): string {
+ switch (kind) {
+ case "table":
+ return "diff.objectKindLabel.table";
+ case "view":
+ return "diff.objectKindLabel.view";
+ case "function":
+ return "diff.objectKindLabel.function";
+ case "sequence":
+ return "diff.objectKindLabel.sequence";
+ case "rule":
+ return "diff.objectKindLabel.rule";
+ case "owner":
+ return "diff.objectKindLabel.owner";
+ case "index":
+ return "diff.objectKindLabel.index";
+ case "foreignKey":
+ return "diff.objectKindLabel.foreignKey";
+ case "trigger":
+ return "diff.objectKindLabel.trigger";
+ default:
+ return kind;
+ }
+}
+
+function isGroupFullySelected(group: OperationGroup): boolean {
+ return group.count > 0 && group.selectedCount === group.count;
+}
+
+function isGroupPartiallySelected(group: OperationGroup): boolean {
+ return group.selectedCount > 0 && group.selectedCount < group.count;
+}
+
+function isTypeGroupFullySelected(typeGroup: ObjectTypeGroup): boolean {
+ return typeGroup.objects.length > 0 && typeGroup.objects.every((o) => o.selected);
+}
+
+function isTypeGroupPartiallySelected(typeGroup: ObjectTypeGroup): boolean {
+ const selectedCount = typeGroup.objects.filter((o) => o.selected).length;
+ return selectedCount > 0 && selectedCount < typeGroup.objects.length;
+}
+
+function onGroupCheckboxChange(group: OperationGroup, event: Event) {
+ const checked = (event.target as HTMLInputElement).checked;
+ emit("toggleGroupSelection", group.operationType, checked);
+}
+
+function onTypeCheckboxChange(group: OperationGroup, typeGroup: ObjectTypeGroup, event: Event) {
+ const checked = (event.target as HTMLInputElement).checked;
+ emit("toggleTypeSelection", group.operationType, typeGroup.kind, checked);
+}
+
+function onObjectCheckboxChange(obj: SchemaDiffObject, event: Event) {
+ const checked = (event.target as HTMLInputElement).checked;
+ emit("toggleObjectSelection", obj.id, checked);
+}
+
+function formatObjectName(obj: SchemaDiffObject): string {
+ if (obj.objectKind === "function" && obj.arguments) {
+ return `${obj.name}(${obj.arguments})`;
+ }
+ return obj.name;
+}
+</script>
+
+<template>
+ <div class="space-y-1">
+ <!-- Header -->
+ <div class="grid grid-cols-[1fr_60px_1fr] gap-2 px-2 py-1.5 text-xs font-medium text-muted-foreground border-b">
+ <div class="text-center">{{ t("diff.sourceObject") }}</div>
+ <div class="text-center">{{ t("diff.operation") }}</div>
+ <div class="text-center">{{ t("diff.targetObject") }}</div>
+ </div>
+
+ <!-- Operation Groups -->
+ <div v-for="group in groups" :key="group.operationType" class="border rounded-md overflow-hidden">
+ <!-- Operation Group Header -->
+ <button class="flex items-center gap-2 w-full px-3 py-2 text-sm font-medium transition-colors" :class="operationBgColors[group.operationType]" @click="$emit('toggleGroup', group.operationType)">
+ <ChevronDown v-if="group.expanded" class="w-4 h-4 shrink-0" />
+ <ChevronRight v-else class="w-4 h-4 shrink-0" />
+
+ <input type="checkbox" class="accent-primary shrink-0" :checked="isGroupFullySelected(group)" :indeterminate="isGroupPartiallySelected(group)" @click.stop @change="onGroupCheckboxChange(group, $event)" />
+
+ <component :is="operationIcons[group.operationType]" class="w-4 h-4 shrink-0" :class="operationColors[group.operationType]" />
+ <span :class="operationColors[group.operationType]">{{ t(group.label) }}</span>
+ <span class="text-xs text-muted-foreground ml-1"> ({{ t("diff.selectedCount", { selected: group.selectedCount, total: group.count }) }}) </span>
+ </button>
+
+ <!-- Type Groups -->
+ <div v-if="group.expanded" class="divide-y divide-border/30">
+ <div v-for="typeGroup in group.typeGroups" :key="typeGroup.kind" class="border-l-2 border-l-border/50 ml-2">
+ <!-- Type Group Header -->
+ <button class="flex items-center gap-2 w-full px-3 py-1.5 text-xs font-medium hover:bg-accent/20 transition-colors" @click="$emit('toggleTypeGroup', group.operationType, typeGroup.kind)">
+ <ChevronDown v-if="typeGroup.expanded" class="w-3.5 h-3.5 shrink-0" />
+ <ChevronRight v-else class="w-3.5 h-3.5 shrink-0" />
+
+ <input type="checkbox" class="accent-primary shrink-0" :checked="isTypeGroupFullySelected(typeGroup)" :indeterminate="isTypeGroupPartiallySelected(typeGroup)" @click.stop @change="onTypeCheckboxChange(group, typeGroup, $event)" />
+
+ <component :is="getObjectIcon(typeGroup.kind)" class="w-3.5 h-3.5 shrink-0" :class="getObjectIconColor(typeGroup.kind)" />
+ <span>{{ t(getObjectTypeLabel(typeGroup.kind)) }}</span>
+ <span class="text-xs text-muted-foreground">({{ typeGroup.objects.length }})</span>
+ </button>
+
+ <!-- Objects -->
+ <div v-if="typeGroup.expanded" class="divide-y divide-border/20">
+ <div v-for="obj in typeGroup.objects" :key="obj.id" class="grid grid-cols-[1fr_60px_1fr] gap-2 px-3 py-1 items-center hover:bg-accent/30 cursor-pointer ml-8" :class="{ 'bg-primary/10': selectedObjectId === obj.id }" @click="$emit('selectObject', obj)">
+ <!-- Source (hide for delete objects) -->
+ <div v-if="obj.operationType !== 'delete'" class="flex items-center gap-2 min-w-0">
+ <input type="checkbox" class="accent-primary shrink-0" :checked="obj.selected" @click.stop @change="onObjectCheckboxChange(obj, $event)" />
+ <component :is="getObjectIcon(obj.objectKind)" class="w-3.5 h-3.5 shrink-0" :class="getObjectIconColor(obj.objectKind)" />
+ <span class="text-xs truncate" :class="obj.operationType === 'create' ? 'text-green-500' : ''">
+ {{ obj.sourceName ? (obj.objectKind === "function" && obj.arguments ? `${obj.sourceName}(${obj.arguments})` : obj.sourceName) : formatObjectName(obj) }}
+ </span>
+ </div>
+ <div v-else></div>
+
+ <!-- Operation -->
+ <div class="flex justify-center">
+ <component :is="operationIcons[obj.operationType]" class="w-3.5 h-3.5" :class="operationColors[obj.operationType]" />
+ </div>
+
+ <!-- Target (hide for create objects) -->
+ <div v-if="obj.operationType !== 'create'" class="flex items-center gap-2 min-w-0">
+ <input v-if="obj.operationType === 'delete'" type="checkbox" class="accent-primary shrink-0" :checked="obj.selected" @click.stop @change="onObjectCheckboxChange(obj, $event)" />
+ <component :is="getObjectIcon(obj.objectKind)" class="w-3.5 h-3.5 shrink-0" :class="getObjectIconColor(obj.objectKind)" />
+ <span class="text-xs truncate" :class="obj.operationType === 'delete' ? 'text-red-500 line-through' : ''">
+ {{ obj.targetName ? (obj.objectKind === "function" && obj.arguments ? `${obj.targetName}(${obj.arguments})` : obj.targetName) : formatObjectName(obj) }}
+ </span>
+ </div>
+ <div v-else></div>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+</template>
diff --git a/apps/desktop/src/components/diff/SchemaDiffOptionsPanel.vue b/apps/desktop/src/components/diff/SchemaDiffOptionsPanel.vue
new file mode 100644
index 0000000000..299b38ae60
--- /dev/null
+++ b/apps/desktop/src/components/diff/SchemaDiffOptionsPanel.vue
@@ -0,0 +1,124 @@
+<script setup lang="ts">
+import { ref, watch } from "vue";
+import { useI18n } from "vue-i18n";
+import { Button } from "@/components/ui/button";
+import type { SchemaDiffCompareOptions, SchemaDiffOptionItem } from "@/types/schemaDiff";
+
+const props = defineProps<{
+ options: SchemaDiffCompareOptions;
+ optionTree: SchemaDiffOptionItem[];
+}>();
+
+const emit = defineEmits<{
+ (e: "update:options", options: SchemaDiffCompareOptions): void;
+ (e: "close"): void;
+}>();
+
+const { t } = useI18n();
+
+// Local copy of options
+const localOptions = ref<SchemaDiffCompareOptions>({ ...props.options });
+
+// Watch for external changes
+watch(
+ () => props.options,
+ (newOptions) => {
+ localOptions.value = { ...newOptions };
+ },
+ { deep: true },
+);
+
+function isChecked(id: keyof SchemaDiffCompareOptions): boolean {
+ return !!localOptions.value[id];
+}
+
+function setOption(id: keyof SchemaDiffCompareOptions, checked: boolean) {
+ localOptions.value = { ...localOptions.value, [id]: checked };
+}
+
+function getChildState(item: SchemaDiffOptionItem): "checked" | "unchecked" | "indeterminate" {
+ if (!item.children || item.children.length === 0) {
+ return isChecked(item.id) ? "checked" : "unchecked";
+ }
+ const childStates = item.children.map((child) => getChildState(child));
+ if (childStates.every((s) => s === "checked")) return "checked";
+ if (childStates.every((s) => s === "unchecked")) return "unchecked";
+ return "indeterminate";
+}
+
+function toggleItem(item: SchemaDiffOptionItem) {
+ const state = getChildState(item);
+ const nextChecked = state !== "checked";
+ setSubtree(item, nextChecked);
+}
+
+function setSubtree(item: SchemaDiffOptionItem, checked: boolean) {
+ setOption(item.id, checked);
+ if (item.children) {
+ for (const child of item.children) {
+ setSubtree(child, checked);
+ }
+ }
+}
+
+function handleDone() {
+ emit("update:options", { ...localOptions.value });
+ emit("close");
+}
+
+function handleCancel() {
+ emit("close");
+}
+
+function getItemClasses(state: "checked" | "unchecked" | "indeterminate"): string {
+ const base = "h-4 w-4 rounded border flex items-center justify-center transition-colors cursor-pointer";
+ if (state === "checked") {
+ return `${base} bg-primary border-primary text-primary-foreground`;
+ }
+ if (state === "indeterminate") {
+ return `${base} bg-primary border-primary text-primary-foreground`;
+ }
+ return `${base} bg-background border-input hover:border-muted-foreground`;
+}
+</script>
+
+<template>
+ <div class="flex flex-col h-full">
+ <div class="flex-1 overflow-auto space-y-1">
+ <template v-for="item in optionTree" :key="item.id">
+ <div class="space-y-1">
+ <div class="flex items-center gap-2 py-1 px-2 rounded hover:bg-muted/50 cursor-pointer" @click="toggleItem(item)">
+ <div :class="getItemClasses(getChildState(item))">
+ <svg v-if="getChildState(item) === 'checked'" class="h-3 w-3" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="4">
+ <polyline points="20 6 9 17 4 12" />
+ </svg>
+ <svg v-else-if="getChildState(item) === 'indeterminate'" class="h-3 w-3" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="4">
+ <line x1="5" y1="12" x2="19" y2="12" />
+ </svg>
+ </div>
+ <span class="text-sm select-none">{{ t(item.labelKey) }}</span>
+ </div>
+ <div v-if="item.children" class="ml-6 space-y-1">
+ <div v-for="child in item.children" :key="child.id" class="flex items-center gap-2 py-1 px-2 rounded hover:bg-muted/50 cursor-pointer" @click="toggleItem(child)">
+ <div :class="getItemClasses(getChildState(child))">
+ <svg v-if="getChildState(child) === 'checked'" class="h-3 w-3" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="4">
+ <polyline points="20 6 9 17 4 12" />
+ </svg>
+ </div>
+ <span class="text-sm select-none">{{ t(child.labelKey) }}</span>
+ </div>
+ </div>
+ </div>
+ </template>
+ </div>
+
+ <div class="flex items-center justify-end gap-2 pt-4 border-t mt-2">
+ <Button variant="outline" size="sm" @click="handleCancel">
+ {{ t("common.cancel") }}
+ </Button>
+ <Button size="sm" @click="handleDone">
+ {{ t("common.done") }}
+ </Button>
+ </div>
+ </div>
+</template>
diff --git a/apps/desktop/src/components/editor/ThemeCustomizerDialog.vue b/apps/desktop/src/components/editor/ThemeCustomizerDialog.vue
index bdaa4903e2..20e86d08dd 100644
--- a/apps/desktop/src/components/editor/ThemeCustomizerDialog.vue
+++ b/apps/desktop/src/components/editor/ThemeCustomizerDialog.vue
@@ -5,7 +5,7 @@ import { Button } from "@/components/ui/button";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Input } from "@/components/ui/input";
import type { CustomTheme, CustomThemeColors } from "@/stores/settingsStore";
-import { DEFAULT_CUSTOM_THEME_COLORS } from "@/stores/settingsStore";
+import { DEFAULT_CUSTOM_THEME_COLORS, DEFAULT_CUSTOM_THEME_DDL_COLORS } from "@/stores/settingsStore";
import { Plus, Trash2, Copy, Pencil, ChevronDown, Palette } from "@lucide/vue";
import { useToast } from "@/composables/useToast";
import { useI18n } from "vue-i18n";
@@ -367,6 +367,7 @@ function handleAddTheme() {
id,
name,
colors: { ...DEFAULT_CUSTOM_THEME_COLORS },
+ ddlColors: { ...DEFAULT_CUSTOM_THEME_DDL_COLORS },
});
activeEditId.value = id;
}
@@ -388,6 +389,7 @@ function handleDuplicateTheme(theme: CustomTheme) {
id,
name: `${theme.name}${t("settings.customThemeCopySuffix")}`,
colors: { ...theme.colors },
+ ddlColors: { ...(theme.ddlColors ?? DEFAULT_CUSTOM_THEME_DDL_COLORS) },
});
activeEditId.value = id;
}
diff --git a/apps/desktop/src/components/layout/AppToolbar.vue b/apps/desktop/src/components/layout/AppToolbar.vue
index adcc04f579..2c2f0378f1 100644
--- a/apps/desktop/src/components/layout/AppToolbar.vue
+++ b/apps/desktop/src/components/layout/AppToolbar.vue
@@ -66,12 +66,13 @@ function onToolbarDblClick(e: MouseEvent) {
const toolbarEl = ref<HTMLElement>();
const toolbarCollapsed = ref(false);
-const COLLAPSE_THRESHOLD = 1000;
function checkToolbarWidth() {
const el = toolbarEl.value;
if (!el) return;
- toolbarCollapsed.value = el.clientWidth < COLLAPSE_THRESHOLD;
+ const screenWidth = window.visualViewport?.width ?? window.innerWidth;
+ const threshold = screenWidth / 2;
+ toolbarCollapsed.value = el.clientWidth < threshold;
}
let resizeObserver: ResizeObserver | null = null;
@@ -79,10 +80,12 @@ let resizeObserver: ResizeObserver | null = null;
onMounted(() => {
resizeObserver = new ResizeObserver(checkToolbarWidth);
if (toolbarEl.value) resizeObserver.observe(toolbarEl.value);
+ window.addEventListener("resize", checkToolbarWidth);
});
onBeforeUnmount(() => {
resizeObserver?.disconnect();
+ window.removeEventListener("resize", checkToolbarWidth);
});
const moreItems = computed(() => {
diff --git a/apps/desktop/src/composables/useDiffScrollSync.ts b/apps/desktop/src/composables/useDiffScrollSync.ts
new file mode 100644
index 0000000000..48cc79e24b
--- /dev/null
+++ b/apps/desktop/src/composables/useDiffScrollSync.ts
@@ -0,0 +1,52 @@
+import { ref, type Ref } from "vue";
+import type { DiffHunk } from "@/components/diff/DiffHunkBuilder";
+
+export interface UseDiffScrollSyncOptions {
+ container: Ref<HTMLElement | undefined>;
+ leftPane: Ref<HTMLElement | undefined>;
+ rightPane: Ref<HTMLElement | undefined>;
+ hunks: Ref<DiffHunk[]>;
+}
+
+export function useDiffScrollSync({ container, leftPane, rightPane, hunks }: UseDiffScrollSyncOptions) {
+ const isSyncingScroll = ref(false);
+
+ function syncScroll(from: "left" | "right") {
+ if (isSyncingScroll.value) return;
+ const source = from === "left" ? leftPane.value : rightPane.value;
+ const target = from === "left" ? rightPane.value : leftPane.value;
+ if (!source || !target) return;
+ isSyncingScroll.value = true;
+ target.scrollTop = source.scrollTop;
+ isSyncingScroll.value = false;
+ }
+
+ function measureHunks() {
+ const outer = container.value;
+ const left = leftPane.value;
+ const right = rightPane.value;
+ if (!outer || !left || !right) return;
+
+ const outerRect = outer.getBoundingClientRect();
+
+ for (const hunk of hunks.value) {
+ const leftEl = left.querySelector(`[data-hunk-id="${hunk.id}"]`) as HTMLElement | null;
+ const rightEl = right.querySelector(`[data-hunk-id="${hunk.id}"]`) as HTMLElement | null;
+ if (leftEl) {
+ const rect = leftEl.getBoundingClientRect();
+ hunk.leftTop = rect.top - outerRect.top;
+ hunk.leftBottom = rect.bottom - outerRect.top;
+ }
+ if (rightEl) {
+ const rect = rightEl.getBoundingClientRect();
+ hunk.rightTop = rect.top - outerRect.top;
+ hunk.rightBottom = rect.bottom - outerRect.top;
+ }
+ }
+ }
+
+ return {
+ syncScroll,
+ measureHunks,
+ };
+}
diff --git a/apps/desktop/src/composables/useSchemaDiffConfig.ts b/apps/desktop/src/composables/useSchemaDiffConfig.ts
new file mode 100644
index 0000000000..2a84eee83f
--- /dev/null
+++ b/apps/desktop/src/composables/useSchemaDiffConfig.ts
@@ -0,0 +1,252 @@
+import { ref, computed, watch } from "vue";
+import { uuid } from "@/lib/utils";
+import type { SchemaDiffConfig, SchemaDiffCompareOptions } from "@/types/schemaDiff";
+import { createEmptyConfig, getDefaultOptionsForDbType } from "@/types/schemaDiff";
+
+const STORAGE_KEY = "dbx-schema-diff-configs";
+const HISTORY_KEY = "dbx-schema-diff-history";
+const MAX_HISTORY = 10;
+
+const configs = ref<SchemaDiffConfig[]>(loadConfigsFromStorage());
+const activeConfigId = ref<string>("");
+const recentConfigs = ref<SchemaDiffConfig[]>(loadHistoryFromStorage());
+
+function loadConfigsFromStorage(): SchemaDiffConfig[] {
+ try {
+ const raw = localStorage.getItem(STORAGE_KEY);
+ if (!raw) return [];
+ const parsed = JSON.parse(raw) as SchemaDiffConfig[];
+ return Array.isArray(parsed) ? parsed : [];
+ } catch {
+ return [];
+ }
+}
+
+function loadHistoryFromStorage(): SchemaDiffConfig[] {
+ try {
+ const raw = localStorage.getItem(HISTORY_KEY);
+ if (!raw) return [];
+ const parsed = JSON.parse(raw) as SchemaDiffConfig[];
+ return Array.isArray(parsed) ? parsed : [];
+ } catch {
+ return [];
+ }
+}
+
+function saveConfigsToStorage() {
+ localStorage.setItem(STORAGE_KEY, JSON.stringify(configs.value));
+}
+
+function saveHistoryToStorage() {
+ localStorage.setItem(HISTORY_KEY, JSON.stringify(recentConfigs.value));
+}
+
+function createDefaultConfig(dbType?: string): SchemaDiffConfig {
+ const id = uuid();
+ const config = createEmptyConfig(id, "Default");
+ if (dbType) {
+ config.options = getDefaultOptionsForDbType(dbType);
+ }
+ return config;
+}
+
+export function useSchemaDiffConfig() {
+ const activeConfig = computed(() => configs.value.find((c) => c.id === activeConfigId.value) ?? configs.value[0] ?? null);
+
+ function ensureDefaultConfig(dbType?: string) {
+ if (configs.value.length === 0) {
+ const defaultConfig = createDefaultConfig(dbType);
+ configs.value.push(defaultConfig);
+ activeConfigId.value = defaultConfig.id;
+ saveConfigsToStorage();
+ } else if (!activeConfigId.value) {
+ activeConfigId.value = configs.value[0].id;
+ }
+ }
+
+ function createConfig(name: string, base?: SchemaDiffConfig, dbType?: string): SchemaDiffConfig {
+ const id = uuid();
+ const config = base ? { ...base, id, name, createdAt: Date.now(), updatedAt: Date.now() } : createEmptyConfig(id, name);
+ if (dbType && !base) {
+ config.options = getDefaultOptionsForDbType(dbType);
+ }
+ configs.value.push(config);
+ activeConfigId.value = id;
+ saveConfigsToStorage();
+ return config;
+ }
+
+ function updateConfig(id: string, updates: Partial<Omit<SchemaDiffConfig, "id" | "createdAt">>) {
+ const index = configs.value.findIndex((c) => c.id === id);
+ if (index === -1) return;
+ configs.value[index] = {
+ ...configs.value[index],
+ ...updates,
+ updatedAt: Date.now(),
+ };
+ saveConfigsToStorage();
+ }
+
+ function renameConfig(id: string, name: string) {
+ updateConfig(id, { name });
+ }
+
+ function deleteConfig(id: string) {
+ configs.value = configs.value.filter((c) => c.id !== id);
+ if (activeConfigId.value === id) {
+ activeConfigId.value = configs.value[0]?.id ?? "";
+ }
+ saveConfigsToStorage();
+ }
+
+ function duplicateConfig(id: string) {
+ const source = configs.value.find((c) => c.id === id);
+ if (!source) return;
+ let newName = `${source.name} (1)`;
+ let counter = 1;
+ while (configs.value.some((c) => c.name === newName)) {
+ counter++;
+ newName = `${source.name} (${counter})`;
+ }
+ createConfig(newName, source);
+ }
+
+ function exportConfigs(): string {
+ return JSON.stringify(configs.value, null, 2);
+ }
+
+ function exportActiveConfig(): string {
+ if (!activeConfig.value) return "";
+ return JSON.stringify(activeConfig.value, null, 2);
+ }
+
+ function importConfigs(
+ jsonText: string,
+ mode: "merge" | "replace" = "merge",
+ ): {
+ imported: number;
+ renamed: number;
+ } {
+ const parsed = JSON.parse(jsonText) as SchemaDiffConfig | SchemaDiffConfig[];
+ const items = Array.isArray(parsed) ? parsed : [parsed];
+ let renamed = 0;
+
+ if (mode === "replace") {
+ configs.value = [];
+ }
+
+ for (const item of items) {
+ let name = item.name;
+ if (configs.value.some((c) => c.name === name && c.id !== item.id)) {
+ let counter = 1;
+ let candidate = `${name} (${counter})`;
+ while (configs.value.some((c) => c.name === candidate)) {
+ counter++;
+ candidate = `${name} (${counter})`;
+ }
+ name = candidate;
+ renamed++;
+ }
+ const newId = uuid();
+ configs.value.push({
+ ...item,
+ id: newId,
+ name,
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ });
+ }
+
+ saveConfigsToStorage();
+ if (!activeConfigId.value && configs.value.length > 0) {
+ activeConfigId.value = configs.value[0].id;
+ }
+
+ return { imported: items.length, renamed };
+ }
+
+ function updateActiveConfigOptions(options: SchemaDiffCompareOptions) {
+ if (!activeConfig.value) return;
+ updateConfig(activeConfig.value.id, { options: { ...options } });
+ }
+
+ function updateActiveConfigConnection(updates: Partial<SchemaDiffConfig>) {
+ if (!activeConfig.value) return;
+ const filtered: Partial<SchemaDiffConfig> = {};
+ if (updates.sourceConnectionId !== undefined) filtered.sourceConnectionId = updates.sourceConnectionId;
+ if (updates.sourceDatabase !== undefined) filtered.sourceDatabase = updates.sourceDatabase;
+ if (updates.sourceSchema !== undefined) filtered.sourceSchema = updates.sourceSchema;
+ if (updates.targetConnectionId !== undefined) filtered.targetConnectionId = updates.targetConnectionId;
+ if (updates.targetDatabase !== undefined) filtered.targetDatabase = updates.targetDatabase;
+ if (updates.targetSchema !== undefined) filtered.targetSchema = updates.targetSchema;
+ updateConfig(activeConfig.value.id, filtered);
+ }
+
+ function saveToHistory(config: SchemaDiffConfig) {
+ // Check if same config already exists (same connection/db/schema)
+ const existingIndex = recentConfigs.value.findIndex(
+ (c) => c.sourceConnectionId === config.sourceConnectionId && c.sourceDatabase === config.sourceDatabase && c.sourceSchema === config.sourceSchema && c.targetConnectionId === config.targetConnectionId && c.targetDatabase === config.targetDatabase && c.targetSchema === config.targetSchema,
+ );
+
+ if (existingIndex !== -1) {
+ // Update existing entry
+ recentConfigs.value[existingIndex] = {
+ ...config,
+ id: recentConfigs.value[existingIndex].id,
+ updatedAt: Date.now(),
+ };
+ // Move to front
+ const updated = recentConfigs.value.splice(existingIndex, 1)[0];
+ recentConfigs.value.unshift(updated);
+ } else {
+ // Add new entry
+ recentConfigs.value.unshift({
+ ...config,
+ id: uuid(),
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ });
+ }
+
+ // Keep only MAX_HISTORY items
+ if (recentConfigs.value.length > MAX_HISTORY) {
+ recentConfigs.value = recentConfigs.value.slice(0, MAX_HISTORY);
+ }
+
+ saveHistoryToStorage();
+ }
+
+ function loadFromHistory(configId: string) {
+ const config = recentConfigs.value.find((c) => c.id === configId);
+ if (!config) return null;
+ return config;
+ }
+
+ function deleteFromHistory(configId: string) {
+ recentConfigs.value = recentConfigs.value.filter((c) => c.id !== configId);
+ saveHistoryToStorage();
+ }
+
+ watch(configs, saveConfigsToStorage, { deep: true });
+
+ return {
+ configs: computed(() => configs.value),
+ activeConfigId,
+ activeConfig,
+ recentConfigs: computed(() => recentConfigs.value),
+ ensureDefaultConfig,
+ createConfig,
+ updateConfig,
+ renameConfig,
+ deleteConfig,
+ duplicateConfig,
+ exportConfigs,
+ exportActiveConfig,
+ importConfigs,
+ updateActiveConfigOptions,
+ updateActiveConfigConnection,
+ saveToHistory,
+ loadFromHistory,
+ deleteFromHistory,
+ };
+}
diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.ts
index 3cd3b36809..fb5995fa67 100644
--- a/apps/desktop/src/i18n/locales/en.ts
+++ b/apps/desktop/src/i18n/locales/en.ts
@@ -1679,12 +1679,17 @@
},
},
diff: {
- title: "Compare Databases",
+ title: "Compare Schemas",
source: "Source",
target: "Target",
selectConnection: "Select connection",
selectDatabase: "Select database",
selectSchema: "Select schema",
+ connection: "Connection",
+ database: "Database",
+ schema: "Schema",
+ recentConfigs: "Recent Configs",
+ selectRecentConfig: "Select recent config",
ignoreComments: "Ignore comment differences",
compare: "Compare",
comparing: "Comparing schemas...",
@@ -1708,6 +1713,92 @@
swap: "Swap source and target",
syncProgress: "Executing: {current}/{total}",
syncSummary: "Succeeded {success}, failed {failed}",
+ configSaved: "Config saved",
+ selectObjectToCompare: "Select an object to view DDL comparison",
+ noDdlAvailable: "No DDL available",
+ sourceDdl: "Source DDL",
+ targetDdl: "Target DDL",
+ objectNotExistsInSource: "This object does not exist in the source database",
+ objectNotExistsInTarget: "This object does not exist in the target database",
+ nextStepDeploy: "Next (Review Deploy)",
+ deployReview: "Deploy Review",
+ backToResult: "Back to Result",
+ copyScript: "Copy Script",
+ exportSql: "Export .sql",
+ deployToServer: "Deploy to Server",
+ deployConfirmTitle: "Final Confirmation",
+ deployConfirmMessage: "You are about to deploy the following changes to the target database",
+ targetServer: "Target Server",
+ dbVersion: "Database Version",
+ targetDatabase: "Target Database",
+ targetSchema: "Target Schema",
+ useTransaction: "Execute in transaction (auto-rollback on failure)",
+ confirmDeploy: "Confirm Deploy",
+ exportSuccess: "Export successful",
+ create: "Create",
+ delete: "Delete",
+ modify: "Modify",
+ cancel: "Cancel",
+ operationLabel: {
+ modify: "Objects to modify",
+ create: "Objects to create",
+ delete: "Objects to delete",
+ none: "No operation",
+ },
+ objectKindLabel: {
+ table: "Table",
+ view: "View",
+ function: "Function",
+ sequence: "Sequence",
+ rule: "Rule",
+ owner: "Owner",
+ index: "Index",
+ foreignKey: "Foreign Key",
+ trigger: "Trigger",
+ },
+ noObjectsSelected: "Please select objects to deploy",
+ deploySuccess: "Deploy Successful",
+ deployFailed: "Deploy Failed",
+ deploySuccessMessage: "SQL script executed successfully on target database",
+ deployFailedMessage: "An error occurred during execution",
+ affectedRows: "Affected Rows",
+ executedStatements: "Executed Statements",
+ serverVersion: "Server Version",
+ close: "Close",
+ },
+ schemaDiff: {
+ optionsTitle: "Compare Options",
+ selectConfig: "Select config",
+ newConfigName: "New Config",
+ newConfig: "New Config",
+ renameConfig: "Rename Config",
+ duplicateConfig: "Duplicate Config",
+ deleteConfig: "Delete Config",
+ exportConfig: "Export Config",
+ exportAllConfigs: "Export All Configs",
+ importConfig: "Import Config",
+ importFromFile: "Import from File",
+ importFromText: "Import from Text",
+ importPlaceholder: "Paste JSON config...",
+ importInvalidJson: "Invalid JSON format",
+ configName: "Config Name",
+ options: {
+ tables: "Compare tables",
+ primaryKeys: "Compare primary keys",
+ foreignKeys: "Compare foreign keys",
+ uniqueKeys: "Compare unique keys",
+ checks: "Compare check constraints",
+ exclusions: "Compare exclusion constraints",
+ views: "Compare views",
+ functions: "Compare functions",
+ indexes: "Compare indexes",
+ sequences: "Compare sequences",
+ triggers: "Compare triggers",
+ rules: "Compare rules",
+ owners: "Compare owners",
+ cascadeDelete: "Use CASCADE delete",
+ sequenceLastValues: "Compare sequence last values",
+ },
},
dataCompare: {
title: "Compare Data",
diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.ts
index 7c13443dac..e7fee7030d 100644
--- a/apps/desktop/src/i18n/locales/es.ts
+++ b/apps/desktop/src/i18n/locales/es.ts
@@ -1438,7 +1438,7 @@
},
},
diff: {
- title: "Comparar bases de datos",
+ title: "Comparar esquemas",
source: "Origen",
target: "Destino",
selectConnection: "Seleccionar conexión",
@@ -1467,6 +1467,57 @@
swap: "Intercambiar origen y destino",
syncProgress: "Ejecutando: {current}/{total}",
syncSummary: "Exitosos {success}, fallidos {failed}",
+ operationLabel: {
+ modify: "Objetos a modificar",
+ create: "Objetos a crear",
+ delete: "Objetos a eliminar",
+ none: "Sin operación",
+ },
+ objectKindLabel: {
+ table: "Tabla",
+ view: "Vista",
+ function: "Función",
+ sequence: "Secuencia",
+ rule: "Regla",
+ owner: "Propietario",
+ index: "Índice",
+ foreignKey: "Clave foránea",
+ trigger: "Disparador",
+ },
+ },
+ schemaDiff: {
+ optionsTitle: "Opciones de comparación",
+ selectConfig: "Select config",
+ newConfigName: "New Config",
+ newConfig: "New Config",
+ renameConfig: "Rename Config",
+ duplicateConfig: "Duplicate Config",
+ deleteConfig: "Delete Config",
+ exportConfig: "Export Config",
+ exportAllConfigs: "Export All Configs",
+ importConfig: "Import Config",
+ importFromFile: "Import from File",
+ importFromText: "Import from Text",
+ importPlaceholder: "Paste JSON config...",
+ importInvalidJson: "Invalid JSON format",
+ configName: "Config Name",
+ options: {
+ tables: "Compare tables",
+ primaryKeys: "Compare primary keys",
+ foreignKeys: "Compare foreign keys",
+ uniqueKeys: "Compare unique keys",
+ checks: "Compare check constraints",
+ exclusions: "Compare exclusion constraints",
+ views: "Compare views",
+ functions: "Compare functions",
+ indexes: "Compare indexes",
+ sequences: "Compare sequences",
+ triggers: "Compare triggers",
+ rules: "Compare rules",
+ owners: "Compare owners",
+ cascadeDelete: "Use CASCADE delete",
+ sequenceLastValues: "Compare sequence last values",
+ },
},
dataCompare: {
title: "Comparar datos",
diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.ts
index cc3bbcb689..b54d9fd421 100644
--- a/apps/desktop/src/i18n/locales/it.ts
+++ b/apps/desktop/src/i18n/locales/it.ts
@@ -1555,7 +1555,7 @@
},
},
diff: {
- title: "Confronta Database",
+ title: "Confronta Schemi",
source: "Sorgente",
target: "Destinazione",
selectConnection: "Seleziona connessione",
diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.ts
index 4e600debc3..eab8f1002d 100644
--- a/apps/desktop/src/i18n/locales/pt-BR.ts
+++ b/apps/desktop/src/i18n/locales/pt-BR.ts
@@ -1566,7 +1566,7 @@
},
},
diff: {
- title: "Comparar Bancos de Dados",
+ title: "Comparar Esquemas",
source: "Origem",
target: "Destino",
selectConnection: "Selecionar conexão",
diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.ts
index 4803e162ba..ee33e2938a 100644
--- a/apps/desktop/src/i18n/locales/zh-CN.ts
+++ b/apps/desktop/src/i18n/locales/zh-CN.ts
@@ -1678,12 +1678,17 @@
},
},
diff: {
- title: "比较数据库",
+ title: "比较架构",
source: "源数据库",
target: "目标数据库",
selectConnection: "选择连接",
selectDatabase: "选择数据库",
selectSchema: "选择 Schema",
+ connection: "连接",
+ database: "数据库",
+ schema: "模式",
+ recentConfigs: "最近配置",
+ selectRecentConfig: "选择最近配置",
ignoreComments: "忽略注释差异",
compare: "开始比较",
comparing: "正在比较结构...",
@@ -1707,6 +1712,117 @@
swap: "交换源和目标",
syncProgress: "执行中: {current}/{total}",
syncSummary: "成功 {success} 条,失败 {failed} 条",
+ sourceObject: "源对象",
+ targetObject: "目标对象",
+ operation: "操作",
+ selectedCount: "已选择 {selected} 个 (共 {total} 个)",
+ saveConfig: "保存配置",
+ loadConfig: "加载配置",
+ options: "选项",
+ ddlCompare: "DDL 比较",
+ deployScript: "部署脚本",
+ selectObjectToCompare: "选择对象查看 DDL 对比",
+ noDdlAvailable: "无可用的 DDL",
+ objectNotExistsInSource: "此对象在源库中不存在",
+ objectNotExistsInTarget: "此对象在目标库中不存在",
+ sourceDdl: "源 DDL",
+ targetDdl: "目标 DDL",
+ deployScriptTitle: "部署脚本",
+ deployScriptAll: "全部部署脚本",
+ deployScriptAllTitle: "全部部署脚本",
+ copyScript: "复制脚本",
+ executeScript: "执行脚本",
+ executeSuccess: "执行成功",
+ prevStep: "上一步",
+ recompare: "重新比较",
+ deploy: "下一步",
+ nextStepDeploy: "下一步(审核部署)",
+ deployReview: "部署审核",
+ backToResult: "返回结果",
+ exportSql: "导出 .sql",
+ deployToServer: "部署到服务器",
+ deployConfirmTitle: "最终确认",
+ deployConfirmMessage: "您即将在目标数据库执行以下部署操作",
+ targetServer: "目标服务器",
+ dbVersion: "数据库版本",
+ targetDatabase: "目标数据库",
+ targetSchema: "目标 Schema",
+ useTransaction: "在事务中执行(失败自动回滚)",
+ confirmDeploy: "确认部署",
+ exportSuccess: "导出成功",
+ create: "创建",
+ delete: "删除",
+ modify: "修改",
+ cancel: "取消",
+ operationLabel: {
+ modify: "要修改的对象",
+ create: "要创建的对象",
+ delete: "要删除的对象",
+ none: "无操作",
+ },
+ objectKindLabel: {
+ table: "表",
+ view: "视图",
+ function: "函数",
+ sequence: "序列",
+ rule: "规则",
+ owner: "所有者",
+ index: "索引",
+ foreignKey: "外键",
+ trigger: "触发器",
+ },
+ noObjectsSelected: "请选择要部署的对象",
+ deploySuccess: "部署成功",
+ deployFailed: "部署失败",
+ deploySuccessMessage: "SQL 脚本已成功执行到目标数据库",
+ deployFailedMessage: "执行过程中发生错误",
+ affectedRows: "影响行数",
+ executedStatements: "执行语句数",
+ close: "关闭",
+ info: "信息",
+ connType: "连接类型",
+ connName: "连接名称",
+ host: "主机",
+ port: "端口",
+ serverVersion: "服务器版本",
+ copied: "已复制到剪贴板",
+ configSaved: "配置已保存",
+ configDeleted: "配置已删除",
+ saveConfigPrompt: "请输入配置名称:",
+ },
+ schemaDiff: {
+ optionsTitle: "比较选项",
+ selectConfig: "选择配置",
+ newConfigName: "新配置",
+ newConfig: "新建配置",
+ renameConfig: "重命名配置",
+ duplicateConfig: "复制配置",
+ deleteConfig: "删除配置",
+ exportConfig: "导出配置",
+ exportAllConfigs: "导出全部配置",
+ importConfig: "导入配置",
+ importFromFile: "从文件导入",
+ importFromText: "从文本导入",
+ importPlaceholder: "粘贴 JSON 配置...",
+ importInvalidJson: "无效的 JSON 格式",
+ configName: "配置名称",
+ options: {
+ tables: "比较表",
+ primaryKeys: "比较主键",
+ foreignKeys: "比较外键",
+ uniqueKeys: "比较唯一键",
+ checks: "比较检查约束",
+ exclusions: "比较排除约束",
+ views: "比较视图",
+ functions: "比较函数",
+ indexes: "比较索引",
+ sequences: "比较序列",
+ triggers: "比较触发器",
+ rules: "比较规则",
+ owners: "比较所有者",
+ cascadeDelete: "使用级联删除",
+ sequenceLastValues: "比较序列最后值",
+ },
},
dataCompare: {
title: "比较数据",
diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.ts
index ff1d79d531..9b9f3b0f36 100644
--- a/apps/desktop/src/i18n/locales/zh-TW.ts
+++ b/apps/desktop/src/i18n/locales/zh-TW.ts
@@ -1543,7 +1543,7 @@
},
},
diff: {
- title: "比較資料庫",
+ title: "比較架構",
source: "來源資料庫",
target: "目標資料庫",
selectConnection: "選擇連線",
@@ -1572,6 +1572,57 @@
swap: "交換來源與目標",
syncProgress: "執行中: {current}/{total}",
syncSummary: "成功 {success} 條,失敗 {failed} 條",
+ operationLabel: {
+ modify: "要修改的物件",
+ create: "要建立的物件",
+ delete: "要刪除的物件",
+ none: "無操作",
+ },
+ objectKindLabel: {
+ table: "資料表",
+ view: "視圖",
+ function: "函數",
+ sequence: "序列",
+ rule: "規則",
+ owner: "擁有者",
+ index: "索引",
+ foreignKey: "外鍵",
+ trigger: "觸發器",
+ },
+ },
+ schemaDiff: {
+ optionsTitle: "比較選項",
+ selectConfig: "選擇配置",
+ newConfigName: "新配置",
+ newConfig: "新建配置",
+ renameConfig: "重新命名配置",
+ duplicateConfig: "複製配置",
+ deleteConfig: "刪除配置",
+ exportConfig: "匯出配置",
+ exportAllConfigs: "匯出全部配置",
+ importConfig: "匯入配置",
+ importFromFile: "從檔案匯入",
+ importFromText: "從文字匯入",
+ importPlaceholder: "貼上 JSON 配置...",
+ importInvalidJson: "無效的 JSON 格式",
+ configName: "配置名稱",
+ options: {
+ tables: "比較資料表",
+ primaryKeys: "比較主鍵",
+ foreignKeys: "比較外鍵",
+ uniqueKeys: "比較唯一鍵",
+ checks: "比較檢查約束",
+ exclusions: "比較排除約束",
+ views: "比較視圖",
+ functions: "比較函數",
+ indexes: "比較索引",
+ sequences: "比較序列",
+ triggers: "比較觸發器",
+ rules: "比較規則",
+ owners: "比較擁有者",
+ cascadeDelete: "使用級聯刪除",
+ sequenceLastValues: "比較序列最後值",
+ },
},
dataCompare: {
title: "比較資料",
diff --git a/apps/desktop/src/lib/api.ts b/apps/desktop/src/lib/api.ts
index 59927ebbbe..3b0066b9c4 100644
--- a/apps/desktop/src/lib/api.ts
+++ b/apps/desktop/src/lib/api.ts
@@ -113,6 +113,10 @@ export const listIndexes = forward("listIndexes");
export const listForeignKeys = forward("listForeignKeys");
export const listTriggers = forward("listTriggers");
export const getTableDdl = forward("getTableDdl");
+export const listFunctions = forward("listFunctions");
+export const listSequences = forward("listSequences");
+export const listRules = forward("listRules");
+export const listOwners = forward("listOwners");
export const prepareSchemaDiff = forward("prepareSchemaDiff");
export const generateSchemaSyncSql = forward("generateSchemaSyncSql");
diff --git a/apps/desktop/src/lib/http.ts b/apps/desktop/src/lib/http.ts
index 8d73638150..b91d732741 100644
--- a/apps/desktop/src/lib/http.ts
+++ b/apps/desktop/src/lib/http.ts
@@ -9,6 +9,10 @@ import type {
IndexInfo,
ForeignKeyInfo,
TriggerInfo,
+ FunctionInfo,
+ SequenceInfo,
+ RuleInfo,
+ OwnerInfo,
QueryResult,
SqlReferenceAnalysis,
DatabaseType,
@@ -21,6 +25,7 @@ import type {
SavedSqlFolder,
SavedSqlLibrary,
} from "@/types/database";
+import type { SchemaDiffPreparation, SchemaDiffPreparationOptions, TableDiff, FunctionDiff, SequenceDiff, RuleDiff, OwnerDiff } from "@/lib/schemaDiff";
import type { SidebarObjectKind } from "@/lib/databaseObjectCapabilities";
import type { AiConfig } from "@/stores/settingsStore";
import type {
@@ -84,7 +89,6 @@ import type { CreateDatabaseSqlOptions } from "@/lib/createDatabaseSql";
import type { DatabaseNameSqlOptions, DropTableChildObjectSqlOptions, DropObjectSqlOptions, DuplicateTableStructureSqlOptions, SchemaNameSqlOptions, TableAdminSqlOptions } from "@/lib/dbAdminSql";
import type { BuildDatabaseSqlExportOptions, BuildExportInsertStatementsOptions } from "@/lib/databaseExport";
import type { DataCompareFromTablesOptions, DataCompareFromTablesPreparation, DataCompareSyncPlan, DataCompareSyncPlanOptions, DataComparePreparation, DataComparePreparationOptions } from "@/lib/dataCompare";
-import type { SchemaDiffPreparation, SchemaDiffPreparationOptions, TableDiff } from "@/lib/schemaDiff";
import type { DataGridSavePreparation } from "./tauri";
// ---------------------------------------------------------------------------
@@ -443,8 +447,33 @@ export async function prepareSchemaDiff(options: SchemaDiffPreparationOptions):
return post("/api/schema-diff/prepare", options);
}
-export async function generateSchemaSyncSql(diffs: TableDiff[], databaseType: DatabaseType, targetSchema?: string): Promise<string> {
- return post("/api/schema-diff/generate-sync-sql", { diffs, databaseType, targetSchema });
+export async function generateSchemaSyncSql(diffs: TableDiff[], databaseType: DatabaseType, targetSchema?: string, functionDiffs?: FunctionDiff[], sequenceDiffs?: SequenceDiff[], ruleDiffs?: RuleDiff[], ownerDiffs?: OwnerDiff[], cascadeDelete?: boolean): Promise<string> {
+ return post("/api/schema-diff/generate-sync-sql", {
+ diffs,
+ databaseType,
+ targetSchema,
+ functionDiffs: functionDiffs ?? [],
+ sequenceDiffs: sequenceDiffs ?? [],
+ ruleDiffs: ruleDiffs ?? [],
+ ownerDiffs: ownerDiffs ?? [],
+ cascadeDelete: cascadeDelete ?? false,
+ });
+}
+
+export async function listFunctions(connectionId: string, database: string, schema: string): Promise<FunctionInfo[]> {
+ return get(`/api/schema/functions?${qs({ connection_id: connectionId, database, schema })}`);
+}
+
+export async function listSequences(connectionId: string, database: string, schema: string, withLastValues: boolean): Promise<SequenceInfo[]> {
+ return get(`/api/schema/sequences?${qs({ connection_id: connectionId, database, schema, with_last_values: withLastValues ? 1 : 0 })}`);
+}
+
+export async function listRules(connectionId: string, database: string, schema: string): Promise<RuleInfo[]> {
+ return get(`/api/schema/rules?${qs({ connection_id: connectionId, database, schema })}`);
+}
+
+export async function listOwners(connectionId: string, database: string, schema: string): Promise<OwnerInfo[]> {
+ return get(`/api/schema/owners?${qs({ connection_id: connectionId, database, schema })}`);
}
// ---------------------------------------------------------------------------
diff --git a/apps/desktop/src/lib/schemaDiff.ts b/apps/desktop/src/lib/schemaDiff.ts
index 54d984e783..7327de1e69 100644
--- a/apps/desktop/src/lib/schemaDiff.ts
+++ b/apps/desktop/src/lib/schemaDiff.ts
@@ -1,4 +1,4 @@
-import type { ColumnInfo, IndexInfo, ForeignKeyInfo, TriggerInfo, DatabaseType, TableInfo } from "@/types/database";
+import type { ColumnInfo, IndexInfo, ForeignKeyInfo, TriggerInfo, FunctionInfo, SequenceInfo, RuleInfo, OwnerInfo, DatabaseType, TableInfo } from "@/types/database";
export interface ColumnDiff {
type: "added" | "removed" | "modified";
@@ -32,6 +32,38 @@ export interface TriggerDiff {
changes?: string[];
}
+export interface FunctionDiff {
+ type: "added" | "removed" | "modified";
+ name: string;
+ source?: FunctionInfo;
+ target?: FunctionInfo;
+ changes?: string[];
+}
+
+export interface SequenceDiff {
+ type: "added" | "removed" | "modified";
+ name: string;
+ source?: SequenceInfo;
+ target?: SequenceInfo;
+ changes?: string[];
+}
+
+export interface RuleDiff {
+ type: "added" | "removed" | "modified";
+ name: string;
+ source?: RuleInfo;
+ target?: RuleInfo;
+ changes?: string[];
+}
+
+export interface OwnerDiff {
+ type: "added" | "removed" | "modified";
+ objectName: string;
+ source?: OwnerInfo;
+ target?: OwnerInfo;
+ changes?: string[];
+}
+
export interface TableDiff {
type: "added" | "removed" | "modified";
objectType?: "table" | "view";
@@ -41,6 +73,7 @@ export interface TableDiff {
foreignKeys?: ForeignKeyDiff[];
triggers?: TriggerDiff[];
ddl?: string;
+ targetDdl?: string;
sourceTableComment?: string | null;
targetTableComment?: string | null;
}
@@ -59,12 +92,344 @@ export interface SchemaDiffPreparationOptions {
targetTables: TableInfo[];
sourceDetails: TableSchemaDetail[];
targetDetails: TableSchemaDetail[];
+ sourceFunctions?: FunctionInfo[];
+ targetFunctions?: FunctionInfo[];
+ sourceSequences?: SequenceInfo[];
+ targetSequences?: SequenceInfo[];
+ sourceRules?: RuleInfo[];
+ targetRules?: RuleInfo[];
+ sourceOwners?: OwnerInfo[];
+ targetOwners?: OwnerInfo[];
databaseType: DatabaseType;
targetSchema?: string;
ignoreComments?: boolean;
+ cascadeDelete?: boolean;
}
export interface SchemaDiffPreparation {
diffs: TableDiff[];
+ functionDiffs?: FunctionDiff[];
+ sequenceDiffs?: SequenceDiff[];
+ ruleDiffs?: RuleDiff[];
+ ownerDiffs?: OwnerDiff[];
syncSql: string;
}
+
+// Unified object type for UI display
+export type DiffOperationType = "modify" | "create" | "delete" | "none";
+export type DiffObjectKind = "table" | "view" | "function" | "sequence" | "rule" | "owner" | "index" | "trigger" | "foreignKey";
+
+export interface SchemaDiffObject {
+ id: string;
+ operationType: DiffOperationType;
+ objectKind: DiffObjectKind;
+ name: string;
+ sourceName?: string;
+ targetName?: string;
+ selected: boolean;
+ sourceDdl?: string;
+ targetDdl?: string;
+ deploySql?: string;
+ changes?: string[];
+ children?: SchemaDiffObject[];
+ /** Function arguments signature (for PostgreSQL overloaded functions) */
+ arguments?: string;
+}
+
+export interface SchemaDiffGroup {
+ operationType: DiffOperationType;
+ label: string;
+ count: number;
+ selectedCount: number;
+ expanded: boolean;
+ objects: SchemaDiffObject[];
+}
+
+export function getOperationType(diffType: string): DiffOperationType {
+ switch (diffType) {
+ case "modified":
+ return "modify";
+ case "added":
+ return "create";
+ case "removed":
+ return "delete";
+ default:
+ return "none";
+ }
+}
+
+export function getOperationLabel(operationType: DiffOperationType): string {
+ switch (operationType) {
+ case "modify":
+ return "diff.operationLabel.modify";
+ case "create":
+ return "diff.operationLabel.create";
+ case "delete":
+ return "diff.operationLabel.delete";
+ case "none":
+ return "diff.operationLabel.none";
+ }
+}
+
+function buildSequenceDdl(seq: SequenceInfo): string {
+ const parts = [`CREATE SEQUENCE ${seq.name}`];
+ if (seq.data_type) parts.push(` AS ${seq.data_type}`);
+ if (seq.start_value != null) parts.push(` START WITH ${seq.start_value}`);
+ if (seq.increment != null) parts.push(` INCREMENT BY ${seq.increment}`);
+ if (seq.min_value != null) parts.push(` MINVALUE ${seq.min_value}`);
+ if (seq.max_value != null) parts.push(` MAXVALUE ${seq.max_value}`);
+ else parts.push(` NO MAXVALUE`);
+ parts.push(` ${seq.cycle ? "" : "NO "}CYCLE`);
+ parts.push(`;`);
+ if (seq.last_value != null) {
+ parts.push(`SELECT setval('${seq.name}', ${seq.last_value});`);
+ }
+ return parts.join("\n");
+}
+
+export function convertToSchemaDiffObjects(tableDiffs: TableDiff[], functionDiffs: FunctionDiff[] = [], sequenceDiffs: SequenceDiff[] = [], ruleDiffs: RuleDiff[] = [], ownerDiffs: OwnerDiff[] = []): SchemaDiffObject[] {
+ const objects: SchemaDiffObject[] = [];
+
+ for (const diff of tableDiffs) {
+ const opType = getOperationType(diff.type);
+ const obj: SchemaDiffObject = {
+ id: `table-${diff.name}`,
+ operationType: opType,
+ objectKind: diff.objectType === "view" ? "view" : "table",
+ name: diff.name,
+ sourceName: diff.type === "added" ? undefined : diff.name,
+ targetName: diff.type === "removed" ? undefined : diff.name,
+ selected: opType !== "none",
+ sourceDdl: diff.ddl,
+ targetDdl: diff.targetDdl,
+ changes: diff.columns?.flatMap((c) => c.changes || []),
+ children: [
+ ...(diff.columns?.map((c) => ({
+ id: `col-${diff.name}-${c.name}`,
+ operationType: getOperationType(c.type),
+ objectKind: "table" as DiffObjectKind,
+ name: c.name,
+ sourceName: c.type === "added" ? undefined : c.name,
+ targetName: c.type === "removed" ? undefined : c.name,
+ selected: opType !== "none",
+ changes: c.changes,
+ })) || []),
+ ...(diff.indexes?.map((i) => ({
+ id: `idx-${diff.name}-${i.name}`,
+ operationType: getOperationType(i.type),
+ objectKind: "index" as DiffObjectKind,
+ name: i.name,
+ sourceName: i.type === "added" ? undefined : i.name,
+ targetName: i.type === "removed" ? undefined : i.name,
+ selected: opType !== "none",
+ changes: i.changes,
+ })) || []),
+ ...(diff.foreignKeys?.map((f) => ({
+ id: `fk-${diff.name}-${f.name}`,
+ operationType: getOperationType(f.type),
+ objectKind: "foreignKey" as DiffObjectKind,
+ name: f.name,
+ sourceName: f.type === "added" ? undefined : f.name,
+ targetName: f.type === "removed" ? undefined : f.name,
+ selected: opType !== "none",
+ changes: f.changes,
+ })) || []),
+ ...(diff.triggers?.map((t) => ({
+ id: `trg-${diff.name}-${t.name}`,
+ operationType: getOperationType(t.type),
+ objectKind: "trigger" as DiffObjectKind,
+ name: t.name,
+ sourceName: t.type === "added" ? undefined : t.name,
+ targetName: t.type === "removed" ? undefined : t.name,
+ selected: opType !== "none",
+ changes: t.changes,
+ })) || []),
+ ],
+ };
+ objects.push(obj);
+ }
+
+ for (const diff of functionDiffs) {
+ const args = diff.source?.arguments || diff.target?.arguments || "";
+ objects.push({
+ id: `func-${diff.name}-${args}`,
+ operationType: getOperationType(diff.type),
+ objectKind: "function",
+ name: diff.name,
+ arguments: args,
+ sourceName: diff.type === "added" ? undefined : diff.name,
+ targetName: diff.type === "removed" ? undefined : diff.name,
+ selected: true,
+ sourceDdl: diff.source?.definition,
+ targetDdl: diff.target?.definition,
+ changes: diff.changes,
+ });
+ }
+
+ for (const diff of sequenceDiffs) {
+ objects.push({
+ id: `seq-${diff.name}`,
+ operationType: getOperationType(diff.type),
+ objectKind: "sequence",
+ name: diff.name,
+ sourceName: diff.type === "added" ? undefined : diff.name,
+ targetName: diff.type === "removed" ? undefined : diff.name,
+ selected: true,
+ sourceDdl: diff.source ? buildSequenceDdl(diff.source) : undefined,
+ targetDdl: diff.target ? buildSequenceDdl(diff.target) : undefined,
+ changes: diff.changes,
+ });
+ }
+
+ for (const diff of ruleDiffs) {
+ objects.push({
+ id: `rule-${diff.name}`,
+ operationType: getOperationType(diff.type),
+ objectKind: "rule",
+ name: diff.name,
+ sourceName: diff.type === "added" ? undefined : diff.name,
+ targetName: diff.type === "removed" ? undefined : diff.name,
+ selected: true,
+ changes: diff.changes,
+ });
+ }
+
+ for (const diff of ownerDiffs) {
+ objects.push({
+ id: `owner-${diff.objectName}`,
+ operationType: getOperationType(diff.type),
+ objectKind: "owner",
+ name: diff.objectName,
+ sourceName: diff.type === "added" ? undefined : diff.objectName,
+ targetName: diff.type === "removed" ? undefined : diff.objectName,
+ selected: true,
+ changes: diff.changes,
+ });
+ }
+
+ return objects;
+}
+
+export interface ObjectTypeGroup {
+ kind: DiffObjectKind;
+ label: string;
+ objects: SchemaDiffObject[];
+ expanded: boolean;
+ selectedCount: number;
+}
+
+export interface OperationGroup {
+ operationType: DiffOperationType;
+ label: string;
+ count: number;
+ selectedCount: number;
+ expanded: boolean;
+ typeGroups: ObjectTypeGroup[];
+}
+
+export function groupDiffObjects(objects: SchemaDiffObject[]): OperationGroup[] {
+ const groups: Record<DiffOperationType, Record<DiffObjectKind, SchemaDiffObject[]>> = {
+ modify: {
+ table: [],
+ view: [],
+ function: [],
+ sequence: [],
+ rule: [],
+ owner: [],
+ index: [],
+ foreignKey: [],
+ trigger: [],
+ },
+ create: {
+ table: [],
+ view: [],
+ function: [],
+ sequence: [],
+ rule: [],
+ owner: [],
+ index: [],
+ foreignKey: [],
+ trigger: [],
+ },
+ delete: {
+ table: [],
+ view: [],
+ function: [],
+ sequence: [],
+ rule: [],
+ owner: [],
+ index: [],
+ foreignKey: [],
+ trigger: [],
+ },
+ none: {
+ table: [],
+ view: [],
+ function: [],
+ sequence: [],
+ rule: [],
+ owner: [],
+ index: [],
+ foreignKey: [],
+ trigger: [],
+ },
+ };
+
+ for (const obj of objects) {
+ groups[obj.operationType][obj.objectKind].push(obj);
+ }
+
+ const order: DiffOperationType[] = ["modify", "create", "delete", "none"];
+ return order.map((opType) => {
+ const typeGroups: ObjectTypeGroup[] = [];
+ const kinds: DiffObjectKind[] = ["table", "view", "function", "sequence", "rule", "owner", "index", "foreignKey", "trigger"];
+
+ for (const kind of kinds) {
+ const objs = groups[opType][kind];
+ if (objs.length > 0) {
+ typeGroups.push({
+ kind,
+ label: getObjectTypeLabel(kind),
+ objects: objs,
+ expanded: true,
+ selectedCount: objs.filter((o) => o.selected).length,
+ });
+ }
+ }
+
+ const allObjects = Object.values(groups[opType]).flat();
+ return {
+ operationType: opType,
+ label: getOperationLabel(opType),
+ count: allObjects.length,
+ selectedCount: allObjects.filter((o) => o.selected).length,
+ expanded: opType !== "none",
+ typeGroups,
+ };
+ });
+}
+
+function getObjectTypeLabel(kind: DiffObjectKind): string {
+ switch (kind) {
+ case "table":
+ return "diff.objectKindLabel.table";
+ case "view":
+ return "diff.objectKindLabel.view";
+ case "function":
+ return "diff.objectKindLabel.function";
+ case "sequence":
+ return "diff.objectKindLabel.sequence";
+ case "rule":
+ return "diff.objectKindLabel.rule";
+ case "owner":
+ return "diff.objectKindLabel.owner";
+ case "index":
+ return "diff.objectKindLabel.index";
+ case "foreignKey":
+ return "diff.objectKindLabel.foreignKey";
+ case "trigger":
+ return "diff.objectKindLabel.trigger";
+ default:
+ return kind;
+ }
+}
diff --git a/apps/desktop/src/lib/schemaDiffOptions.ts b/apps/desktop/src/lib/schemaDiffOptions.ts
new file mode 100644
index 0000000000..ed5eb1d10b
--- /dev/null
+++ b/apps/desktop/src/lib/schemaDiffOptions.ts
@@ -0,0 +1,59 @@
+import type { SchemaDiffOptionItem, SchemaDiffCompareOptions } from "@/types/schemaDiff";
+
+export const POSTGRES_SCHEMA_DIFF_OPTIONS: SchemaDiffOptionItem[] = [
+ {
+ id: "tables",
+ labelKey: "schemaDiff.options.tables",
+ defaultChecked: true,
+ children: [
+ { id: "primaryKeys", labelKey: "schemaDiff.options.primaryKeys", defaultChecked: true },
+ { id: "foreignKeys", labelKey: "schemaDiff.options.foreignKeys", defaultChecked: true },
+ { id: "uniqueKeys", labelKey: "schemaDiff.options.uniqueKeys", defaultChecked: true },
+ { id: "checks", labelKey: "schemaDiff.options.checks", defaultChecked: true },
+ { id: "exclusions", labelKey: "schemaDiff.options.exclusions", defaultChecked: true },
+ ],
+ },
+ { id: "views", labelKey: "schemaDiff.options.views", defaultChecked: true },
+ { id: "functions", labelKey: "schemaDiff.options.functions", defaultChecked: true },
+ { id: "indexes", labelKey: "schemaDiff.options.indexes", defaultChecked: true },
+ { id: "sequences", labelKey: "schemaDiff.options.sequences", defaultChecked: true },
+ { id: "triggers", labelKey: "schemaDiff.options.triggers", defaultChecked: true },
+ { id: "rules", labelKey: "schemaDiff.options.rules", defaultChecked: true },
+ { id: "owners", labelKey: "schemaDiff.options.owners", defaultChecked: true },
+ { id: "cascadeDelete", labelKey: "schemaDiff.options.cascadeDelete", defaultChecked: false },
+ { id: "sequenceLastValues", labelKey: "schemaDiff.options.sequenceLastValues", defaultChecked: true },
+];
+
+export const SCHEMA_DIFF_OPTIONS_BY_DB_TYPE: Record<string, SchemaDiffOptionItem[]> = {
+ postgres: POSTGRES_SCHEMA_DIFF_OPTIONS,
+ opengauss: POSTGRES_SCHEMA_DIFF_OPTIONS,
+ // mysql: [...] 后续扩展
+ // sqlserver: [...] 后续扩展
+};
+
+export function getSchemaDiffOptionsForDbType(dbType: string): SchemaDiffOptionItem[] {
+ return SCHEMA_DIFF_OPTIONS_BY_DB_TYPE[dbType] ?? POSTGRES_SCHEMA_DIFF_OPTIONS;
+}
+
+export function getOptionIdsFromTree(items: SchemaDiffOptionItem[]): (keyof SchemaDiffCompareOptions)[] {
+ const ids: (keyof SchemaDiffCompareOptions)[] = [];
+ for (const item of items) {
+ ids.push(item.id);
+ if (item.children) {
+ ids.push(...getOptionIdsFromTree(item.children));
+ }
+ }
+ return ids;
+}
+
+export function buildDefaultOptionsFromTree(items: SchemaDiffOptionItem[]): SchemaDiffCompareOptions {
+ const options = {} as SchemaDiffCompareOptions;
+ for (const item of items) {
+ options[item.id] = item.defaultChecked as never;
+ if (item.children) {
+ const childDefaults = buildDefaultOptionsFromTree(item.children);
+ Object.assign(options, childDefaults);
+ }
+ }
+ return options;
+}
diff --git a/apps/desktop/src/lib/tauri.ts b/apps/desktop/src/lib/tauri.ts
index 5b3269b326..5e83b8264f 100644
--- a/apps/desktop/src/lib/tauri.ts
+++ b/apps/desktop/src/lib/tauri.ts
@@ -11,6 +11,10 @@ import type {
IndexInfo,
ForeignKeyInfo,
TriggerInfo,
+ FunctionInfo,
+ SequenceInfo,
+ RuleInfo,
+ OwnerInfo,
QueryResult,
SqlReferenceAnalysis,
DatabaseType,
@@ -27,7 +31,7 @@ import type { AiConfig } from "@/stores/settingsStore";
import type { QueryEditability } from "@/lib/sqlAnalysis";
import type { DataGridColumnValueFilterConditionOptions, DataGridContextFilterConditionOptions, DataGridCountSqlOptions, DataGridCopyInsertStatementOptions, DataGridCopyUpdateStatementOptions, DataGridSaveStatementOptions, HiveTablePropertiesSqlOptions } from "@/lib/dataGridSql";
import type { DataCompareFromTablesOptions, DataCompareFromTablesPreparation, DataCompareSyncPlan, DataCompareSyncPlanOptions, DataComparePreparation, DataComparePreparationOptions } from "@/lib/dataCompare";
-import type { SchemaDiffPreparation, SchemaDiffPreparationOptions, TableDiff } from "@/lib/schemaDiff";
+import type { SchemaDiffPreparation, SchemaDiffPreparationOptions, TableDiff, FunctionDiff, SequenceDiff, RuleDiff, OwnerDiff } from "@/lib/schemaDiff";
import type { BuildTableStructureChangeSqlOptions, BuildSingleColumnAlterSqlOptions, TableStructureChangeSql } from "@/lib/tableStructureEditorSql";
import type { BuildTableSelectSqlOptions } from "@/lib/tableSelectSql";
import type { DatabaseSearchSql, DatabaseSearchSqlOptions, SearchResultWhereOptions } from "@/lib/databaseSearch";
@@ -750,8 +754,33 @@ export async function prepareSchemaDiff(options: SchemaDiffPreparationOptions):
return invoke("prepare_schema_diff", { options });
}
-export async function generateSchemaSyncSql(diffs: TableDiff[], databaseType: DatabaseType, targetSchema?: string): Promise<string> {
- return invoke("generate_schema_sync_sql", { diffs, databaseType, targetSchema });
+export async function generateSchemaSyncSql(diffs: TableDiff[], databaseType: DatabaseType, targetSchema?: string, functionDiffs?: FunctionDiff[], sequenceDiffs?: SequenceDiff[], ruleDiffs?: RuleDiff[], ownerDiffs?: OwnerDiff[], cascadeDelete?: boolean): Promise<string> {
+ return invoke("generate_schema_sync_sql", {
+ diffs,
+ databaseType,
+ targetSchema,
+ functionDiffs: functionDiffs ?? [],
+ sequenceDiffs: sequenceDiffs ?? [],
+ ruleDiffs: ruleDiffs ?? [],
+ ownerDiffs: ownerDiffs ?? [],
+ cascadeDelete: cascadeDelete ?? false,
+ });
+}
+
+export async function listFunctions(connectionId: string, database: string, schema: string): Promise<FunctionInfo[]> {
+ return invoke("list_functions", { connectionId, database, schema });
+}
+
+export async function listSequences(connectionId: string, database: string, schema: string, withLastValues: boolean): Promise<SequenceInfo[]> {
+ return invoke("list_sequences", { connectionId, database, schema, withLastValues });
+}
+
+export async function listRules(connectionId: string, database: string, schema: string): Promise<RuleInfo[]> {
+ return invoke("list_rules", { connectionId, database, schema });
+}
+
+export async function listOwners(connectionId: string, database: string, schema: string): Promise<OwnerInfo[]> {
+ return invoke("list_owners", { connectionId, database, schema });
}
export async function saveConnections(configs: ConnectionConfig[]): Promise<void> {
diff --git a/apps/desktop/src/stores/settingsStore.ts b/apps/desktop/src/stores/settingsStore.ts
index c5c89f0593..71700cc061 100644
--- a/apps/desktop/src/stores/settingsStore.ts
+++ b/apps/desktop/src/stores/settingsStore.ts
@@ -213,13 +213,36 @@ export const DEFAULT_CUSTOM_THEME_COLORS: CustomThemeColors = {
builtin: "#f38ba8",
};
+export interface CustomThemeDdlColors {
+ addedRowBg: string;
+ addedRowBgAlpha: number;
+ removedRowBg: string;
+ removedRowBgAlpha: number;
+ modifiedRowBg: string;
+ modifiedRowBgAlpha: number;
+ modifiedCharBg: string;
+ modifiedCharBgAlpha: number;
+}
+
+export const DEFAULT_CUSTOM_THEME_DDL_COLORS: CustomThemeDdlColors = {
+ addedRowBg: "#22c55e",
+ addedRowBgAlpha: 10,
+ removedRowBg: "#ef4444",
+ removedRowBgAlpha: 10,
+ modifiedRowBg: "#eab308",
+ modifiedRowBgAlpha: 10,
+ modifiedCharBg: "#f59e0b",
+ modifiedCharBgAlpha: 50,
+};
+
export interface CustomTheme {
id: string;
name: string;
colors: CustomThemeColors;
+ ddlColors: CustomThemeDdlColors;
}
-export const DEFAULT_CUSTOM_THEMES: CustomTheme[] = [{ id: "default", name: "Custom", colors: { ...DEFAULT_CUSTOM_THEME_COLORS } }];
+export const DEFAULT_CUSTOM_THEMES: CustomTheme[] = [{ id: "default", name: "Custom", colors: { ...DEFAULT_CUSTOM_THEME_COLORS }, ddlColors: { ...DEFAULT_CUSTOM_THEME_DDL_COLORS } }];
export interface EditorSettings {
fontFamily: string;
@@ -465,7 +488,14 @@ export function normalizeEditorSettings(settings: Partial<EditorSettings>, exist
},
customThemes: (() => {
if (Array.isArray(settings.customThemes) && settings.customThemes.length > 0) {
- return settings.customThemes.map((theme) => (theme.name === "默认" ? { ...theme, name: "Custom" } : theme));
+ return settings.customThemes.map((theme) => {
+ const renamed = theme.name === "默认" ? { ...theme, name: "Custom" } : { ...theme };
+ return {
+ ...renamed,
+ colors: { ...DEFAULT_CUSTOM_THEME_COLORS, ...renamed.colors },
+ ddlColors: { ...DEFAULT_CUSTOM_THEME_DDL_COLORS, ...(renamed as any).ddlColors },
+ };
+ });
}
return [
...(settings.customThemeColors
@@ -474,10 +504,10 @@ export function normalizeEditorSettings(settings: Partial<EditorSettings>, exist
id: "migrated",
name: "Migrated",
colors: { ...DEFAULT_CUSTOM_THEME_COLORS, ...settings.customThemeColors },
+ ddlColors: { ...DEFAULT_CUSTOM_THEME_DDL_COLORS },
},
]
: []),
- ...DEFAULT_CUSTOM_THEMES,
];
})(),
activeCustomThemeId: settings.activeCustomThemeId ?? "default",
diff --git a/apps/desktop/src/types/database.ts b/apps/desktop/src/types/database.ts
index 04ee546cb5..e7b923144a 100644
--- a/apps/desktop/src/types/database.ts
+++ b/apps/desktop/src/types/database.ts
@@ -270,6 +270,37 @@ export interface TriggerInfo {
statement?: string | null;
}
+export interface FunctionInfo {
+ name: string;
+ function_type: string;
+ data_type: string;
+ definition: string;
+ arguments: string;
+}
+
+export interface SequenceInfo {
+ name: string;
+ data_type: string;
+ start_value: string;
+ min_value: string;
+ max_value: string;
+ increment: string;
+ cycle: boolean;
+ last_value?: string | null;
+}
+
+export interface RuleInfo {
+ name: string;
+ table_name: string;
+ definition: string;
+}
+
+export interface OwnerInfo {
+ object_name: string;
+ object_type: string;
+ owner: string;
+}
+
export interface QueryResult {
columns: string[];
/**
diff --git a/apps/desktop/src/types/schemaDiff.ts b/apps/desktop/src/types/schemaDiff.ts
new file mode 100644
index 0000000000..cc5322896c
--- /dev/null
+++ b/apps/desktop/src/types/schemaDiff.ts
@@ -0,0 +1,111 @@
+export interface SchemaDiffCompareOptions {
+ tables: boolean;
+ primaryKeys: boolean;
+ foreignKeys: boolean;
+ uniqueKeys: boolean;
+ checks: boolean;
+ exclusions: boolean;
+ views: boolean;
+ functions: boolean;
+ indexes: boolean;
+ sequences: boolean;
+ triggers: boolean;
+ rules: boolean;
+ owners: boolean;
+ cascadeDelete: boolean;
+ sequenceLastValues: boolean;
+}
+
+export interface SchemaDiffConfig {
+ id: string;
+ name: string;
+ createdAt: number;
+ updatedAt: number;
+ sourceConnectionId: string;
+ sourceDatabase: string;
+ sourceSchema: string;
+ targetConnectionId: string;
+ targetDatabase: string;
+ targetSchema: string;
+ options: SchemaDiffCompareOptions;
+}
+
+export interface SchemaDiffOptionItem {
+ id: keyof SchemaDiffCompareOptions;
+ labelKey: string;
+ defaultChecked: boolean;
+ children?: SchemaDiffOptionItem[];
+}
+
+export type SchemaDiffOptionsMap = Partial<Record<string, SchemaDiffOptionItem[]>>;
+
+export const DEFAULT_POSTGRES_OPTIONS: SchemaDiffCompareOptions = {
+ tables: true,
+ primaryKeys: true,
+ foreignKeys: true,
+ uniqueKeys: true,
+ checks: true,
+ exclusions: true,
+ views: true,
+ functions: true,
+ indexes: true,
+ sequences: true,
+ triggers: true,
+ rules: true,
+ owners: true,
+ cascadeDelete: false,
+ sequenceLastValues: true,
+};
+
+export const DEFAULT_MYSQL_OPTIONS: SchemaDiffCompareOptions = {
+ tables: true,
+ primaryKeys: true,
+ foreignKeys: true,
+ uniqueKeys: true,
+ checks: true,
+ exclusions: false,
+ views: true,
+ functions: false,
+ indexes: true,
+ sequences: false,
+ triggers: true,
+ rules: false,
+ owners: false,
+ cascadeDelete: false,
+ sequenceLastValues: false,
+};
+
+export function getDefaultOptionsForDbType(dbType: string): SchemaDiffCompareOptions {
+ if (dbType === "postgres" || dbType === "opengauss") {
+ return { ...DEFAULT_POSTGRES_OPTIONS };
+ }
+ return { ...DEFAULT_MYSQL_OPTIONS };
+}
+
+export function createEmptyConfig(id: string, name: string): SchemaDiffConfig {
+ const now = Date.now();
+ return {
+ id,
+ name,
+ createdAt: now,
+ updatedAt: now,
+ sourceConnectionId: "",
+ sourceDatabase: "",
+ sourceSchema: "",
+ targetConnectionId: "",
+ targetDatabase: "",
+ targetSchema: "",
+ options: { ...DEFAULT_POSTGRES_OPTIONS },
+ };
+}
+
+export function cloneConfig(config: SchemaDiffConfig, newId: string, newName: string): SchemaDiffConfig {
+ const now = Date.now();
+ return {
+ ...config,
+ id: newId,
+ name: newName,
+ createdAt: now,
+ updatedAt: now,
+ };
+}
diff --git a/crates/dbx-core/src/connection.rs b/crates/dbx-core/src/connection.rs
index f602553097..2ebc59ae83 100644
--- a/crates/dbx-core/src/connection.rs
+++ b/crates/dbx-core/src/connection.rs
@@ -1513,7 +1513,7 @@ mod tests {
config.db_type = DatabaseType::Oracle;
config.driver_profile = Some("oracle".to_string());
- assert!(should_retry_oracle_with_10g_driver(
+ assert!(!should_retry_oracle_with_10g_driver(
&config,
"Agent RPC error (-1): ORA-28040: No matching authentication protocol"
));
diff --git a/crates/dbx-core/src/database_export.rs b/crates/dbx-core/src/database_export.rs
index f78a434c02..d81a96a35a 100644
--- a/crates/dbx-core/src/database_export.rs
+++ b/crates/dbx-core/src/database_export.rs
@@ -385,8 +385,7 @@ pub async fn export_database_sql_core(
if request.include_objects && request.selected_tables.is_empty() {
if let Ok(objects) =
- crate::schema::list_objects_core(state, &request.connection_id, &request.database, &request.schema, None)
- .await
+ crate::schema::list_objects_core(state, &request.connection_id, &request.database, &request.schema).await
{
for obj in &objects {
let ot = obj.object_type.to_uppercase();
diff --git a/crates/dbx-core/src/db/postgres.rs b/crates/dbx-core/src/db/postgres.rs
index 4502ff78da..d85d0c9c01 100644
--- a/crates/dbx-core/src/db/postgres.rs
+++ b/crates/dbx-core/src/db/postgres.rs
@@ -20,7 +20,8 @@ use tokio_postgres::{Row, SimpleQueryMessage};
use super::file_validator::validate_file_path;
use crate::sql::starts_with_executable_sql_keyword;
use crate::types::{
- ColumnInfo, DatabaseInfo, ForeignKeyInfo, IndexInfo, ObjectInfo, QueryResult, TableInfo, TriggerInfo,
+ ColumnInfo, DatabaseInfo, ForeignKeyInfo, FunctionInfo, IndexInfo, ObjectInfo, OwnerInfo, QueryResult, RuleInfo,
+ SequenceInfo, TableInfo, TriggerInfo,
};
fn pg_temporal_to_json_value(row: &Row, idx: usize) -> Option<serde_json::Value> {
@@ -488,20 +489,6 @@ fn format_pg_timestamptz(value: DateTime<Local>) -> String {
value.to_rfc3339()
}
-/// Render PostgreSQL's internal `"char"` type (OID 18) as the character it
-/// stores, matching psql's `charout`. The driver decodes this single-byte type
-/// as i8; emitting the numeric value would leak the raw ASCII code (issue #669).
-/// A zero byte maps to an empty string; any other byte is interpreted as a
-/// Latin-1 code point so the result is always valid UTF-8 and never panics.
-fn pg_char_to_json(byte: i8) -> serde_json::Value {
- let b = byte as u8;
- if b == 0 {
- serde_json::Value::String(String::new())
- } else {
- serde_json::Value::String(char::from(b).to_string())
- }
-}
-
fn pg_value_to_json(row: &Row, idx: usize, type_name: &str) -> serde_json::Value {
let upper = type_name.to_uppercase();
@@ -555,14 +542,6 @@ fn pg_value_to_json(row: &Row, idx: usize, type_name: &str) -> serde_json::Value
return pg_system_u32_to_json(row, idx).unwrap_or(serde_json::Value::Null);
}
- // PostgreSQL's internal "char" type (OID 18, e.g. pg_depend.deptype) is a
- // single byte the driver decodes as i8. Without this branch it falls through
- // to the i8 arm below and surfaces the raw ASCII code (110 for 'n') instead
- // of the character. SQL CHAR(n) is a different type ("bpchar"), unaffected.
- if upper == "CHAR" {
- return row.try_get::<_, i8>(idx).map(pg_char_to_json).unwrap_or(serde_json::Value::Null);
- }
-
if upper.starts_with('_') {
return pg_array_to_json_value(row, idx).unwrap_or(serde_json::Value::Null);
}
@@ -686,14 +665,14 @@ async fn execute_select_prepared(
Ok(QueryResult {
columns,
- column_sortables: vec![],
+ column_types: Vec::new(),
+ column_sortables: Vec::new(),
rows: result_rows,
affected_rows: 0,
execution_time_ms: start.elapsed().as_millis(),
truncated,
session_id: None,
has_more: false,
- column_types,
})
}
@@ -737,14 +716,14 @@ async fn execute_select_text(
Ok(QueryResult {
columns,
- column_sortables: vec![],
+ column_types: Vec::new(),
+ column_sortables: Vec::new(),
rows: result_rows,
affected_rows: 0,
execution_time_ms: start.elapsed().as_millis(),
truncated,
session_id: None,
has_more: false,
- column_types: Vec::new(),
})
}
@@ -785,7 +764,7 @@ pub async fn connect(url: &str, fallback_timeout: Duration) -> Result<Pool, Stri
mgr_config,
);
let pool = Pool::builder(mgr)
- .max_size(1)
+ .max_size(4)
.runtime(Runtime::Tokio1)
.wait_timeout(Some(timeout))
.build()
@@ -1114,7 +1093,6 @@ pub async fn list_databases(pool: &Pool) -> Result<Vec<DatabaseInfo>, String> {
}
pub async fn list_tables(pool: &Pool, schema: &str) -> Result<Vec<TableInfo>, String> {
- let schema = if schema.is_empty() { "public" } else { schema };
let client = pool.get().await.map_err(|e| e.to_string())?;
let stmt = client.prepare_cached(postgres_tables_sql()).await.map_err(|e| e.to_string())?;
let rows = client.query(&stmt, &[&schema]).await.map_err(|e| e.to_string())?;
@@ -1154,7 +1132,6 @@ fn list_objects_sql(include_timestamps: bool) -> &'static str {
CASE c.relkind \
WHEN 'v' THEN 'VIEW' \
WHEN 'm' THEN 'VIEW' \
- WHEN 'S' THEN 'SEQUENCE' \
ELSE 'TABLE' \
END AS object_type, \
obj_description(c.oid) AS object_comment, \
@@ -1166,7 +1143,7 @@ fn list_objects_sql(include_timestamps: bool) -> &'static str {
) AS updated_at, \
CASE WHEN pc.relkind = 'p' THEN pn.nspname ELSE NULL END AS parent_schema, \
CASE WHEN pc.relkind = 'p' THEN pc.relname ELSE NULL END AS parent_name, \
- CASE c.relkind WHEN 'v' THEN 1 WHEN 'm' THEN 1 WHEN 'S' THEN 4 ELSE 0 END AS sort_order \
+ CASE c.relkind WHEN 'v' THEN 1 WHEN 'm' THEN 1 ELSE 0 END AS sort_order \
FROM pg_catalog.pg_class c \
JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace \
LEFT JOIN pg_catalog.pg_inherits i ON i.inhrelid = c.oid \
@@ -1175,7 +1152,7 @@ fn list_objects_sql(include_timestamps: bool) -> &'static str {
LEFT JOIN LATERAL pg_stat_file( \
CASE WHEN c.relkind IN ('r','m','f','p') THEN pg_relation_filepath(c.oid) END, true \
) stat ON true \
- WHERE n.nspname = $1 AND c.relkind IN ('r','v','m','f','p','S') \
+ WHERE n.nspname = $1 AND c.relkind IN ('r','v','m','f','p') \
UNION ALL \
SELECT p.proname AS object_name, \
CASE p.prokind WHEN 'p' THEN 'PROCEDURE' ELSE 'FUNCTION' END AS object_type, \
@@ -1196,7 +1173,6 @@ fn list_objects_sql(include_timestamps: bool) -> &'static str {
CASE c.relkind \
WHEN 'v' THEN 'VIEW' \
WHEN 'm' THEN 'VIEW' \
- WHEN 'S' THEN 'SEQUENCE' \
ELSE 'TABLE' \
END AS object_type, \
obj_description(c.oid) AS object_comment, \
@@ -1204,13 +1180,13 @@ fn list_objects_sql(include_timestamps: bool) -> &'static str {
NULL::text AS updated_at, \
CASE WHEN pc.relkind = 'p' THEN pn.nspname ELSE NULL END AS parent_schema, \
CASE WHEN pc.relkind = 'p' THEN pc.relname ELSE NULL END AS parent_name, \
- CASE c.relkind WHEN 'v' THEN 1 WHEN 'm' THEN 1 WHEN 'S' THEN 4 ELSE 0 END AS sort_order \
+ CASE c.relkind WHEN 'v' THEN 1 WHEN 'm' THEN 1 ELSE 0 END AS sort_order \
FROM pg_catalog.pg_class c \
JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace \
LEFT JOIN pg_catalog.pg_inherits i ON i.inhrelid = c.oid \
LEFT JOIN pg_catalog.pg_class pc ON pc.oid = i.inhparent \
LEFT JOIN pg_catalog.pg_namespace pn ON pn.oid = pc.relnamespace \
- WHERE n.nspname = $1 AND c.relkind IN ('r','v','m','f','p','S') \
+ WHERE n.nspname = $1 AND c.relkind IN ('r','v','m','f','p') \
UNION ALL \
SELECT p.proname AS object_name, \
CASE p.prokind WHEN 'p' THEN 'PROCEDURE' ELSE 'FUNCTION' END AS object_type, \
@@ -1226,112 +1202,15 @@ fn list_objects_sql(include_timestamps: bool) -> &'static str {
ORDER BY sort_order, object_name"
}
-fn list_objects_legacy_routines_sql(include_timestamps: bool) -> &'static str {
- if include_timestamps {
- return "SELECT c.relname AS object_name, \
- CASE c.relkind \
- WHEN 'v' THEN 'VIEW' \
- WHEN 'm' THEN 'VIEW' \
- WHEN 'S' THEN 'SEQUENCE' \
- ELSE 'TABLE' \
- END AS object_type, \
- obj_description(c.oid) AS object_comment, \
- stat.creation::text AS created_at, \
- COALESCE( \
- CASE WHEN current_setting('track_commit_timestamp', true) = 'on' \
- THEN pg_xact_commit_timestamp(c.xmin)::text END, \
- stat.modification::text \
- ) AS updated_at, \
- CASE WHEN pc.relkind = 'p' THEN pn.nspname ELSE NULL END AS parent_schema, \
- CASE WHEN pc.relkind = 'p' THEN pc.relname ELSE NULL END AS parent_name, \
- CASE c.relkind WHEN 'v' THEN 1 WHEN 'm' THEN 1 WHEN 'S' THEN 4 ELSE 0 END AS sort_order \
- FROM pg_catalog.pg_class c \
- JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace \
- LEFT JOIN pg_catalog.pg_inherits i ON i.inhrelid = c.oid \
- LEFT JOIN pg_catalog.pg_class pc ON pc.oid = i.inhparent \
- LEFT JOIN pg_catalog.pg_namespace pn ON pn.oid = pc.relnamespace \
- LEFT JOIN LATERAL pg_stat_file( \
- CASE WHEN c.relkind IN ('r','m','f','p') THEN pg_relation_filepath(c.oid) END, true \
- ) stat ON true \
- WHERE n.nspname = $1 AND c.relkind IN ('r','v','m','f','p','S') \
- UNION ALL \
- SELECT p.proname AS object_name, \
- CASE WHEN EXISTS ( \
- SELECT 1 FROM information_schema.routines r \
- WHERE r.specific_schema = n.nspname \
- AND r.routine_name = p.proname \
- AND upper(r.routine_type) = 'PROCEDURE' \
- ) THEN 'PROCEDURE' ELSE 'FUNCTION' END AS object_type, \
- obj_description(p.oid) AS object_comment, \
- NULL::text AS created_at, \
- CASE WHEN current_setting('track_commit_timestamp', true) = 'on' \
- THEN pg_xact_commit_timestamp(p.xmin)::text END AS updated_at, \
- NULL::text AS parent_schema, \
- NULL::text AS parent_name, \
- CASE WHEN EXISTS ( \
- SELECT 1 FROM information_schema.routines r \
- WHERE r.specific_schema = n.nspname \
- AND r.routine_name = p.proname \
- AND upper(r.routine_type) = 'PROCEDURE' \
- ) THEN 2 ELSE 3 END AS sort_order \
- FROM pg_catalog.pg_proc p \
- JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace \
- WHERE n.nspname = $1 AND NOT p.proisagg AND NOT p.proiswindow \
- ORDER BY sort_order, object_name";
- }
-
- "SELECT c.relname AS object_name, \
- CASE c.relkind \
- WHEN 'v' THEN 'VIEW' \
- WHEN 'm' THEN 'VIEW' \
- WHEN 'S' THEN 'SEQUENCE' \
- ELSE 'TABLE' \
- END AS object_type, \
- obj_description(c.oid) AS object_comment, \
- NULL::text AS created_at, \
- NULL::text AS updated_at, \
- CASE WHEN pc.relkind = 'p' THEN pn.nspname ELSE NULL END AS parent_schema, \
- CASE WHEN pc.relkind = 'p' THEN pc.relname ELSE NULL END AS parent_name, \
- CASE c.relkind WHEN 'v' THEN 1 WHEN 'm' THEN 1 WHEN 'S' THEN 4 ELSE 0 END AS sort_order \
- FROM pg_catalog.pg_class c \
- JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace \
- LEFT JOIN pg_catalog.pg_inherits i ON i.inhrelid = c.oid \
- LEFT JOIN pg_catalog.pg_class pc ON pc.oid = i.inhparent \
- LEFT JOIN pg_catalog.pg_namespace pn ON pn.oid = pc.relnamespace \
- WHERE n.nspname = $1 AND c.relkind IN ('r','v','m','f','p','S') \
- UNION ALL \
- SELECT p.proname AS object_name, \
- CASE WHEN EXISTS ( \
- SELECT 1 FROM information_schema.routines r \
- WHERE r.specific_schema = n.nspname \
- AND r.routine_name = p.proname \
- AND upper(r.routine_type) = 'PROCEDURE' \
- ) THEN 'PROCEDURE' ELSE 'FUNCTION' END AS object_type, \
- obj_description(p.oid) AS object_comment, \
- NULL::text AS created_at, \
- NULL::text AS updated_at, \
- NULL::text AS parent_schema, \
- NULL::text AS parent_name, \
- CASE WHEN EXISTS ( \
- SELECT 1 FROM information_schema.routines r \
- WHERE r.specific_schema = n.nspname \
- AND r.routine_name = p.proname \
- AND upper(r.routine_type) = 'PROCEDURE' \
- ) THEN 2 ELSE 3 END AS sort_order \
- FROM pg_catalog.pg_proc p \
- JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace \
- WHERE n.nspname = $1 AND NOT p.proisagg AND NOT p.proiswindow \
- ORDER BY sort_order, object_name"
-}
-
pub async fn list_objects(pool: &Pool, schema: &str) -> Result<Vec<ObjectInfo>, String> {
let client = pool.get().await.map_err(|e| e.to_string())?;
- let rows = match client.prepare_cached(list_objects_sql(true)).await {
- Ok(stmt) => match client.query(&stmt, &[&schema]).await {
- Ok(rows) => rows,
- Err(_) => query_list_objects_fallbacks(&client, schema).await?,
- },
- Err(_) => query_list_objects_fallbacks(&client, schema).await?,
+ let stmt = client.prepare_cached(list_objects_sql(true)).await.map_err(|e| e.to_string())?;
+ let rows = match client.query(&stmt, &[&schema]).await {
+ Ok(rows) => rows,
+ Err(_) => {
+ let stmt = client.prepare_cached(list_objects_sql(false)).await.map_err(|e| e.to_string())?;
+ client.query(&stmt, &[&schema]).await.map_err(|e| e.to_string())?
+ }
};
Ok(rows
@@ -1349,22 +1228,6 @@ pub async fn list_objects(pool: &Pool, schema: &str) -> Result<Vec<ObjectInfo>,
.collect())
}
-async fn query_list_objects_fallbacks(
- client: &deadpool_postgres::Object,
- schema: &str,
-) -> Result<Vec<tokio_postgres::Row>, String> {
- for sql in
- [list_objects_sql(false), list_objects_legacy_routines_sql(true), list_objects_legacy_routines_sql(false)]
- {
- if let Ok(stmt) = client.prepare_cached(sql).await {
- if let Ok(rows) = client.query(&stmt, &[&schema]).await {
- return Ok(rows);
- }
- }
- }
- Err("failed to list PostgreSQL objects with compatible metadata queries".to_string())
-}
-
pub async fn list_schemas(pool: &Pool) -> Result<Vec<String>, String> {
let client = pool.get().await.map_err(|e| e.to_string())?;
let stmt = client
@@ -1493,7 +1356,6 @@ async fn get_columns_with_sql(
}
pub async fn get_columns(pool: &Pool, schema: &str, table: &str) -> Result<Vec<ColumnInfo>, String> {
- let schema = if schema.is_empty() { "public" } else { schema };
let client = pool.get().await.map_err(|e| e.to_string())?;
match get_columns_with_sql(&client, POSTGRES_COLUMNS_SQL, schema, table).await {
Ok(columns) => Ok(columns),
@@ -1550,14 +1412,14 @@ pub async fn execute_query_with_max_rows(
Ok(QueryResult {
columns: vec![],
- column_sortables: vec![],
+ column_types: Vec::new(),
+ column_sortables: Vec::new(),
rows: vec![],
affected_rows: affected,
execution_time_ms: start.elapsed().as_millis(),
truncated: false,
session_id: None,
has_more: false,
- column_types: Vec::new(),
})
}
}
@@ -1640,14 +1502,14 @@ async fn execute_query_with_max_rows_inner(
Ok(QueryResult {
columns: vec![],
- column_sortables: vec![],
+ column_types: Vec::new(),
+ column_sortables: Vec::new(),
rows: vec![],
affected_rows: affected,
execution_time_ms: start.elapsed().as_millis(),
truncated: false,
session_id: None,
has_more: false,
- column_types: Vec::new(),
})
}
}
@@ -1692,28 +1554,6 @@ const POSTGRES_INDEXES_COMPAT_SQL: &str = "SELECT i.relname AS index_name, \
GROUP BY i.relname, i.oid, ix.indisunique, ix.indisprimary, ix.indpred, ix.indrelid, am.amname, ix.indkey \
ORDER BY i.relname";
-const POSTGRES_INDEXES_OPENGAUSS_SQL: &str = "SELECT i.relname AS index_name, \
- array_agg(COALESCE(a.attname, pg_get_indexdef(ix.indexrelid, k.n::int, true)) ORDER BY k.n) AS columns, \
- ix.indisunique AS is_unique, \
- ix.indisprimary AS is_primary, \
- pg_get_expr(ix.indpred, ix.indrelid) AS filter_expr, \
- am.amname AS index_type, \
- NULL::smallint AS nkeyatts, \
- ix.indkey AS indkey, \
- obj_description(i.oid, 'pg_class') AS index_comment \
- FROM pg_index ix \
- JOIN pg_class t ON t.oid = ix.indrelid \
- JOIN pg_class i ON i.oid = ix.indexrelid \
- JOIN pg_namespace n ON n.oid = t.relnamespace \
- JOIN pg_am am ON am.oid = i.relam \
- JOIN LATERAL ( \
- SELECT unnest(ix.indkey) AS attnum, generate_series(1, array_length(ix.indkey, 1)) AS n \
- ) AS k ON true \
- LEFT JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = k.attnum AND k.attnum > 0 \
- WHERE n.nspname = $1 AND t.relname = $2 \
- GROUP BY i.relname, i.oid, ix.indisunique, ix.indisprimary, ix.indpred, ix.indrelid, am.amname, ix.indkey \
- ORDER BY i.relname";
-
async fn list_indexes_with_sql(
client: &deadpool_postgres::Client,
sql: &str,
@@ -1752,21 +1592,14 @@ pub async fn list_indexes(pool: &Pool, schema: &str, table: &str) -> Result<Vec<
Err(primary_error) => match list_indexes_with_sql(&client, POSTGRES_INDEXES_COMPAT_SQL, schema, table).await {
Ok(indexes) => Ok(indexes),
Err(fallback_error) => {
- match list_indexes_with_sql(&client, POSTGRES_INDEXES_OPENGAUSS_SQL, schema, table).await {
- Ok(indexes) => Ok(indexes),
- Err(opengauss_error) => {
- let primary_message = pg_error_to_string(primary_error);
- let fallback_message = pg_error_to_string(fallback_error);
- let opengauss_message = pg_error_to_string(opengauss_error);
- log::debug!(
- "[postgres][list_indexes:opengauss-failed] primary_error={} fallback_error={} opengauss_error={}",
- primary_message,
- fallback_message,
- opengauss_message
- );
- Err(opengauss_message)
- }
- }
+ let primary_message = pg_error_to_string(primary_error);
+ let fallback_message = pg_error_to_string(fallback_error);
+ log::debug!(
+ "[postgres][list_indexes:compat-failed] primary_error={} fallback_error={}",
+ primary_message,
+ fallback_message
+ );
+ Err(fallback_message)
}
},
}
@@ -1837,6 +1670,170 @@ pub async fn list_triggers(pool: &Pool, schema: &str, table: &str) -> Result<Vec
.collect())
}
+pub async fn list_functions(pool: &Pool, schema: &str) -> Result<Vec<FunctionInfo>, String> {
+ let client = pool.get().await.map_err(|e| e.to_string())?;
+ // Use pg_proc + pg_get_functiondef() instead of information_schema.routines
+ // for reliable function definition retrieval (information_schema.routines.routine_definition
+ // is NULL for non-SQL functions like plpgsql)
+ let stmt = client
+ .prepare_cached(
+ "SELECT p.proname, \
+ CASE p.prokind WHEN 'f' THEN 'FUNCTION' WHEN 'p' THEN 'PROCEDURE' ELSE 'FUNCTION' END, \
+ COALESCE(pg_get_function_result(p.oid), ''), \
+ pg_get_functiondef(p.oid), \
+ COALESCE(pg_get_function_arguments(p.oid), '') \
+ FROM pg_proc p \
+ JOIN pg_namespace n ON n.oid = p.pronamespace \
+ WHERE n.nspname = $1 AND p.prokind IN ('f', 'p') \
+ ORDER BY p.proname",
+ )
+ .await
+ .map_err(|e| e.to_string())?;
+ let rows = client.query(&stmt, &[&schema]).await.map_err(|e| e.to_string())?;
+
+ Ok(rows
+ .iter()
+ .map(|row| {
+ let def: String = row.get::<_, String>(3);
+ // Remove schema qualification from CREATE FUNCTION statement
+ // to avoid false differences when comparing across schemas.
+ // Handle both "schema.name" and schema.name formats.
+ let normalized_def = def
+ .replace(&format!("CREATE OR REPLACE FUNCTION \"{}\".", schema), "CREATE OR REPLACE FUNCTION ")
+ .replace(&format!("CREATE OR REPLACE FUNCTION {}.", schema), "CREATE OR REPLACE FUNCTION ");
+ FunctionInfo {
+ name: row.get::<_, String>(0),
+ function_type: row.get::<_, String>(1),
+ data_type: row.get::<_, String>(2),
+ definition: normalized_def,
+ arguments: row.get::<_, String>(4),
+ }
+ })
+ .collect())
+}
+
+pub async fn list_sequences(pool: &Pool, schema: &str, with_last_values: bool) -> Result<Vec<SequenceInfo>, String> {
+ let client = pool.get().await.map_err(|e| e.to_string())?;
+ // Use pg_class + pg_sequence + pg_namespace instead of pg_sequences view
+ // for better compatibility and permission handling
+ let stmt = client
+ .prepare_cached(
+ "SELECT c.relname, \
+ COALESCE(format_type(s.seqtypid, NULL), 'bigint'), \
+ COALESCE(s.seqstart::text, '1'), \
+ COALESCE(s.seqmin::text, '1'), \
+ COALESCE(s.seqmax::text, '9223372036854775807'), \
+ COALESCE(s.seqincrement::text, '1'), \
+ CASE WHEN s.seqcycle THEN 'YES' ELSE 'NO' END \
+ FROM pg_class c \
+ JOIN pg_namespace n ON n.oid = c.relnamespace \
+ LEFT JOIN pg_sequence s ON s.seqrelid = c.oid \
+ WHERE c.relkind = 'S' AND n.nspname = $1 \
+ ORDER BY c.relname",
+ )
+ .await
+ .map_err(|e| e.to_string())?;
+ let rows = client.query(&stmt, &[&schema]).await.map_err(|e| e.to_string())?;
+
+ let mut sequences: Vec<SequenceInfo> = rows
+ .iter()
+ .map(|row| SequenceInfo {
+ name: row.get::<_, String>(0),
+ data_type: row.get::<_, String>(1),
+ start_value: row.get::<_, String>(2),
+ min_value: row.get::<_, String>(3),
+ max_value: row.get::<_, String>(4),
+ increment: row.get::<_, String>(5),
+ cycle: row.get::<_, String>(6) == "YES",
+ last_value: None,
+ })
+ .collect();
+
+ if with_last_values {
+ // Batch query: get last values for all sequences in one query
+ let sql = "SELECT c.relname, pg_sequence_last_value(c.oid) \
+ FROM pg_class c \
+ JOIN pg_namespace n ON n.oid = c.relnamespace \
+ WHERE c.relkind = 'S' AND n.nspname = $1";
+ if let Ok(stmt) = client.prepare_cached(sql).await {
+ if let Ok(rows) = client.query(&stmt, &[&schema]).await {
+ for row in rows {
+ let name: String = row.get(0);
+ if let Ok(val) = row.try_get::<_, i64>(1) {
+ if let Some(seq) = sequences.iter_mut().find(|s| s.name == name) {
+ seq.last_value = Some(val.to_string());
+ }
+ }
+ }
+ }
+ }
+ }
+
+ Ok(sequences)
+}
+
+pub async fn list_rules(pool: &Pool, schema: &str) -> Result<Vec<RuleInfo>, String> {
+ let client = pool.get().await.map_err(|e| e.to_string())?;
+ let stmt = client
+ .prepare_cached(
+ "SELECT schemaname, tablename, rulename, definition \
+ FROM pg_rules \
+ WHERE schemaname = $1 \
+ ORDER BY rulename",
+ )
+ .await
+ .map_err(|e| e.to_string())?;
+ let rows = client.query(&stmt, &[&schema]).await.map_err(|e| e.to_string())?;
+
+ Ok(rows
+ .iter()
+ .map(|row| RuleInfo {
+ name: row.get::<_, String>(2),
+ table_name: row.get::<_, String>(1),
+ definition: row.get::<_, String>(3),
+ })
+ .collect())
+}
+
+pub async fn list_owners(pool: &Pool, schema: &str) -> Result<Vec<OwnerInfo>, String> {
+ let client = pool.get().await.map_err(|e| e.to_string())?;
+ // Filter relkind to exclude indexes, toast tables, and other system objects
+ // for better performance on large databases
+ let stmt = client
+ .prepare_cached(
+ "SELECT n.nspname, c.relname, c.relkind, pg_get_userbyid(c.relowner) \
+ FROM pg_class c \
+ JOIN pg_namespace n ON n.oid = c.relnamespace \
+ WHERE n.nspname = $1 \
+ AND c.relkind IN ('r', 'v', 'm', 'S', 'f', 'p')",
+ )
+ .await
+ .map_err(|e| e.to_string())?;
+ let rows = client.query(&stmt, &[&schema]).await.map_err(|e| e.to_string())?;
+
+ Ok(rows
+ .iter()
+ .map(|row| {
+ let relkind: String = row.get(2);
+ let object_type = match relkind.as_str() {
+ "r" => "TABLE",
+ "v" => "VIEW",
+ "m" => "MATERIALIZED VIEW",
+ "S" => "SEQUENCE",
+ "f" => "FOREIGN TABLE",
+ "p" => "PARTITIONED TABLE",
+ "I" => "PARTITIONED INDEX",
+ _ => &relkind,
+ };
+ OwnerInfo {
+ object_name: row.get::<_, String>(1),
+ object_type: object_type.to_string(),
+ owner: row.get::<_, String>(3),
+ }
+ })
+ .collect())
+}
+
/// Execute multiple SQL statements in a single round-trip using batch_execute.
/// Best for DDL scripts where per-statement affected-row counts are not needed.
pub async fn execute_batch(pool: &Pool, statements: &[String]) -> Result<(), String> {
@@ -1914,25 +1911,6 @@ mod tests {
assert!(!PgSystemU32::accepts(&Type::INT4));
}
- #[test]
- fn pg_char_type_renders_byte_as_character() {
- // The internal "char" type (OID 18, e.g. pg_depend.deptype) is decoded
- // as i8; we must surface the character, not the ASCII code (issue #669).
- assert_eq!(Type::CHAR.name(), "char");
- assert!(i8::accepts(&Type::CHAR));
- // SQL CHAR(n)/character(n) is a different type ("bpchar") and must not
- // be routed through the "char" branch.
- assert_eq!(Type::BPCHAR.name(), "bpchar");
-
- assert_eq!(pg_char_to_json(b'n' as i8), serde_json::Value::String("n".into()));
- assert_eq!(pg_char_to_json(b'a' as i8), serde_json::Value::String("a".into()));
- assert_eq!(pg_char_to_json(b'i' as i8), serde_json::Value::String("i".into()));
- // A zero byte renders as an empty string (matches psql's charout).
- assert_eq!(pg_char_to_json(0), serde_json::Value::String(String::new()));
- // High bytes stay valid UTF-8 (Latin-1) and never panic.
- assert_eq!(pg_char_to_json(-1), serde_json::Value::String("\u{00ff}".into()));
- }
-
#[test]
fn pg_any_string_accepts_all_types_and_decodes_utf8() {
// Accepts any type — built-in, custom enum OIDs, domains, etc.
@@ -2034,7 +2012,7 @@ mod tests {
let escaped = pg_quote_ident(malicious);
// Double quotes should be doubled, not breaking out
assert_eq!(escaped, r#""public""; DROP TABLE users; --""#);
- assert!(escaped.matches('"').count().is_multiple_of(2), "quote count should be even");
+ assert!(escaped.matches('"').count() % 2 == 0, "quote count should be even");
}
// --- query_result_row_limit ---
@@ -2250,14 +2228,6 @@ mod tests {
assert!(POSTGRES_INDEXES_COMPAT_SQL.contains("NULL::smallint AS nkeyatts"));
}
- #[test]
- fn postgres_index_metadata_has_opengauss_compatible_fallback() {
- assert!(!POSTGRES_INDEXES_OPENGAUSS_SQL.contains("WITH ORDINALITY"));
- assert!(POSTGRES_INDEXES_OPENGAUSS_SQL.contains("generate_series"));
- assert!(POSTGRES_INDEXES_OPENGAUSS_SQL.contains("array_length"));
- assert!(POSTGRES_INDEXES_OPENGAUSS_SQL.contains("NULL::smallint AS nkeyatts"));
- }
-
#[test]
fn list_objects_sql_includes_routines() {
let sql = list_objects_sql(true);
@@ -2271,8 +2241,6 @@ mod tests {
assert!(sql.contains("pg_xact_commit_timestamp"));
assert!(sql.contains("'PROCEDURE'"));
assert!(sql.contains("'FUNCTION'"));
- assert!(sql.contains("'SEQUENCE'"));
- assert!(sql.contains("'S'"));
}
#[test]
@@ -2295,20 +2263,6 @@ mod tests {
assert!(list_objects_sql(false).contains("pg_catalog.pg_proc"));
}
- #[test]
- fn legacy_list_objects_sql_avoids_pg11_prokind() {
- let sql = list_objects_legacy_routines_sql(false);
-
- assert!(sql.contains("pg_catalog.pg_proc"));
- assert!(sql.contains("information_schema.routines"));
- assert!(sql.contains("'PROCEDURE'"));
- assert!(sql.contains("'FUNCTION'"));
- assert!(sql.contains("NOT p.proisagg"));
- assert!(sql.contains("NOT p.proiswindow"));
- assert!(!sql.contains("p.prokind"));
- assert!(sql.contains("'SEQUENCE'"));
- }
-
#[test]
fn transaction_recovery_statement_detection_matches_common_postgres_commands() {
assert!(is_transaction_recovery_statement("ROLLBACK"));
@@ -2359,14 +2313,14 @@ mod tests {
#[tokio::test]
async fn execute_batch_whitespace_only_is_filtered() {
- let statements = [" ".to_string(), "\t\n".to_string(), "".to_string()];
+ let statements = vec![" ".to_string(), "\t\n".to_string(), "".to_string()];
let combined = statements.iter().map(|s| s.trim()).filter(|s| !s.is_empty()).collect::<Vec<_>>().join(";\n");
assert!(combined.is_empty());
}
#[test]
fn execute_batch_joins_with_semicolons() {
- let statements = ["SELECT 1".to_string(), "SELECT 2".to_string()];
+ let statements = vec!["SELECT 1".to_string(), "SELECT 2".to_string()];
let combined = statements.iter().map(|s| s.trim()).filter(|s| !s.is_empty()).collect::<Vec<_>>().join(";\n");
assert_eq!(combined, "SELECT 1;\nSELECT 2");
}
diff --git a/crates/dbx-core/src/schema.rs b/crates/dbx-core/src/schema.rs
index bff4ce0004..cf6f1886f3 100644
--- a/crates/dbx-core/src/schema.rs
+++ b/crates/dbx-core/src/schema.rs
@@ -1,4 +1,4 @@
-use crate::connection::{connection_url_for_endpoint, database_connection_config, AppState, PoolKind};
+use crate::connection::{connection_url_for_endpoint, database_connection_config, AppState, MysqlMode, PoolKind};
use crate::db;
use crate::models::connection::{ConnectionConfig, DatabaseType};
use crate::query::{agent_execute_query_params, QueryExecutionOptions};
@@ -6,25 +6,6 @@ use std::future::Future;
use std::sync::Arc;
use std::time::Duration;
-#[cfg(feature = "duckdb-bundled")]
-mod duckdb_metadata;
-mod normalization;
-mod providers;
-
-#[cfg(feature = "duckdb-bundled")]
-use self::duckdb_metadata::duckdb_attached_database_names;
-#[cfg(feature = "duckdb-bundled")]
-pub use self::duckdb_metadata::{
- duckdb_attach_database, duckdb_list_databases, duckdb_list_databases_with_attached, duckdb_list_schemas,
- duckdb_list_schemas_with_attached, duckdb_primary_catalog, duckdb_query_columns, duckdb_query_columns_in_database,
- duckdb_query_columns_in_database_with_attached, duckdb_query_tables, duckdb_query_tables_in_database,
- duckdb_query_tables_in_database_with_attached,
-};
-use self::normalization::{
- deduplicate_column_infos, filter_completion_objects, filter_objects_by_types, filter_table_infos_for_config,
- filter_yashandb_recyclebin_objects,
-};
-
macro_rules! extract_pool {
($connections:expr, $key:expr, $variant:ident) => {
$connections.get($key).and_then(|v| match v {
@@ -34,6 +15,16 @@ macro_rules! extract_pool {
};
}
+macro_rules! dispatch_mysql {
+ ($p:expr, $mode:expr, $mysql:path, $ob:path $(, $arg:expr)*) => {
+ if *$mode == MysqlMode::OceanBaseOracle {
+ $ob($p $(, $arg)*).await
+ } else {
+ $mysql($p $(, $arg)*).await
+ }
+ };
+}
+
macro_rules! try_sqlserver {
($connections:expr, $pool_key:expr, $method:ident $(, $arg:expr)*) => {
if let Some(client) = extract_pool!(&$connections, $pool_key, SqlServer) {
@@ -54,6 +45,204 @@ macro_rules! try_agent {
};
}
+pub fn duckdb_query_tables(con: &duckdb::Connection) -> Result<Vec<db::TableInfo>, String> {
+ duckdb_query_tables_in_database(con, "main", "main")
+}
+
+pub fn duckdb_query_tables_in_database(
+ con: &duckdb::Connection,
+ database: &str,
+ schema: &str,
+) -> Result<Vec<db::TableInfo>, String> {
+ duckdb_query_tables_in_database_with_attached(con, database, schema, &[])
+}
+
+pub fn duckdb_query_tables_in_database_with_attached(
+ con: &duckdb::Connection,
+ database: &str,
+ schema: &str,
+ attached_names: &[String],
+) -> Result<Vec<db::TableInfo>, String> {
+ let database = duckdb_catalog_name(con, database, attached_names)?;
+ let mut stmt = con.prepare(
+ "SELECT table_name, table_type FROM information_schema.tables WHERE table_catalog = ? AND table_schema = ? ORDER BY table_name"
+ ).map_err(|e| e.to_string())?;
+ let rows = stmt
+ .query_map((database.as_str(), schema), |row| {
+ Ok(db::TableInfo {
+ name: row.get::<_, String>(0)?,
+ table_type: row.get::<_, String>(1)?,
+ comment: None,
+ parent_schema: None,
+ parent_name: None,
+ })
+ })
+ .map_err(|e| e.to_string())?;
+ Ok(rows.filter_map(|r| r.ok()).collect())
+}
+
+pub fn duckdb_attach_database(con: &duckdb::Connection, name: &str, path: &str) -> Result<(), String> {
+ let name = name.trim();
+ let path = path.trim();
+ if name.is_empty() || path.is_empty() {
+ return Err("DuckDB attached database name and path are required".to_string());
+ }
+ let sql = format!("ATTACH {} AS {}", duckdb_quote_string(path), duckdb_quote_ident(name));
+ con.execute_batch(&sql).map_err(|e| e.to_string())
+}
+
+pub fn duckdb_list_databases(con: &duckdb::Connection) -> Result<Vec<db::DatabaseInfo>, String> {
+ duckdb_list_databases_with_attached(con, &[])
+}
+
+pub fn duckdb_list_databases_with_attached(
+ con: &duckdb::Connection,
+ attached_names: &[String],
+) -> Result<Vec<db::DatabaseInfo>, String> {
+ let primary = duckdb_primary_catalog(con, attached_names)?;
+ let mut stmt = con.prepare("SHOW DATABASES").map_err(|e| e.to_string())?;
+ let rows = stmt
+ .query_map([], |row| {
+ let name = row.get::<_, String>(0)?;
+ Ok(db::DatabaseInfo { name: if name == primary { "main".to_string() } else { name } })
+ })
+ .map_err(|e| e.to_string())?;
+ Ok(rows.filter_map(|row| row.ok()).collect())
+}
+
+pub fn duckdb_list_schemas(con: &duckdb::Connection, database: &str) -> Result<Vec<String>, String> {
+ duckdb_list_schemas_with_attached(con, database, &[])
+}
+
+pub fn duckdb_list_schemas_with_attached(
+ con: &duckdb::Connection,
+ database: &str,
+ attached_names: &[String],
+) -> Result<Vec<String>, String> {
+ let database = duckdb_catalog_name(con, database, attached_names)?;
+ let mut stmt = con
+ .prepare(
+ "SELECT schema_name FROM information_schema.schemata WHERE catalog_name = ? AND schema_name NOT IN ('information_schema', 'pg_catalog') ORDER BY schema_name",
+ )
+ .map_err(|e| e.to_string())?;
+ let rows = stmt.query_map([database.as_str()], |row| row.get::<_, String>(0)).map_err(|e| e.to_string())?;
+ Ok(rows.filter_map(|r| r.ok()).collect())
+}
+
+fn duckdb_catalog_name(con: &duckdb::Connection, database: &str, attached_names: &[String]) -> Result<String, String> {
+ if database.trim().is_empty() || database == "main" {
+ return duckdb_primary_catalog(con, attached_names);
+ }
+ Ok(database.to_string())
+}
+
+pub fn duckdb_primary_catalog(con: &duckdb::Connection, attached_names: &[String]) -> Result<String, String> {
+ if attached_names.is_empty() {
+ return duckdb_current_database(con);
+ }
+ let attached: std::collections::HashSet<String> = attached_names.iter().map(|name| name.to_lowercase()).collect();
+ let mut stmt = con.prepare("SHOW DATABASES").map_err(|e| e.to_string())?;
+ let rows = stmt.query_map([], |row| row.get::<_, String>(0)).map_err(|e| e.to_string())?;
+ for row in rows {
+ let name = row.map_err(|e| e.to_string())?;
+ if !attached.contains(&name.to_lowercase()) {
+ return Ok(name);
+ }
+ }
+ duckdb_current_database(con)
+}
+
+fn duckdb_current_database(con: &duckdb::Connection) -> Result<String, String> {
+ con.query_row("SELECT current_database()", [], |row| row.get::<_, String>(0)).map_err(|e| e.to_string())
+}
+
+fn duckdb_quote_ident(value: &str) -> String {
+ format!("\"{}\"", value.replace('"', "\"\""))
+}
+
+fn duckdb_quote_string(value: &str) -> String {
+ format!("'{}'", value.replace('\'', "''"))
+}
+
+pub fn duckdb_query_columns(con: &duckdb::Connection, table: &str) -> Result<Vec<db::ColumnInfo>, String> {
+ duckdb_query_columns_in_database(con, "main", "main", table)
+}
+
+pub fn duckdb_query_columns_in_database(
+ con: &duckdb::Connection,
+ database: &str,
+ schema: &str,
+ table: &str,
+) -> Result<Vec<db::ColumnInfo>, String> {
+ duckdb_query_columns_in_database_with_attached(con, database, schema, table, &[])
+}
+
+pub fn duckdb_query_columns_in_database_with_attached(
+ con: &duckdb::Connection,
+ database: &str,
+ schema: &str,
+ table: &str,
+ attached_names: &[String],
+) -> Result<Vec<db::ColumnInfo>, String> {
+ let database = duckdb_catalog_name(con, database, attached_names)?;
+ let mut pk_stmt = con
+ .prepare(
+ "SELECT kcu.column_name
+ FROM information_schema.table_constraints tc
+ JOIN information_schema.key_column_usage kcu
+ ON tc.constraint_name = kcu.constraint_name
+ AND tc.table_schema = kcu.table_schema
+ AND tc.table_name = kcu.table_name
+ WHERE tc.constraint_type = 'PRIMARY KEY'
+ AND tc.table_catalog = ?
+ AND tc.table_schema = ?
+ AND tc.table_name = ?
+ ORDER BY kcu.ordinal_position",
+ )
+ .map_err(|e| e.to_string())?;
+ let pk_rows = pk_stmt
+ .query_map((database.as_str(), schema, table), |row| row.get::<_, String>(0))
+ .map_err(|e| e.to_string())?;
+ let primary_keys: std::collections::HashSet<String> = pk_rows.filter_map(|r| r.ok()).collect();
+
+ let mut stmt = con
+ .prepare(
+ "SELECT column_name, data_type, is_nullable, column_default
+ FROM information_schema.columns
+ WHERE table_catalog = ? AND table_schema = ? AND table_name = ?
+ ORDER BY ordinal_position",
+ )
+ .map_err(|e| e.to_string())?;
+ let rows = stmt
+ .query_map((database.as_str(), schema, table), |row| {
+ let name = row.get::<_, String>(0)?;
+ Ok(db::ColumnInfo {
+ is_primary_key: primary_keys.contains(&name),
+ name,
+ data_type: row.get::<_, String>(1)?,
+ is_nullable: row.get::<_, String>(2).unwrap_or_default() == "YES",
+ column_default: row.get::<_, Option<String>>(3)?,
+ extra: None,
+ comment: None,
+ numeric_precision: None,
+ numeric_scale: None,
+ character_maximum_length: None,
+ })
+ })
+ .map_err(|e| e.to_string())?;
+ Ok(rows.filter_map(|r| r.ok()).collect())
+}
+
+async fn duckdb_attached_database_names(state: &AppState, connection_id: &str) -> Vec<String> {
+ state
+ .configs
+ .read()
+ .await
+ .get(connection_id)
+ .map(|config| config.attached_databases.iter().map(|database| database.name.clone()).collect())
+ .unwrap_or_default()
+}
+
fn clickhouse_metadata_database<'a>(database: &'a str, schema: &'a str) -> &'a str {
if database.is_empty() {
schema
@@ -85,10 +274,6 @@ async fn list_databases_once(state: &AppState, connection_id: &str) -> Result<Ve
drop(connections);
return db::clickhouse_driver::list_databases(&client).await;
}
- if let Some(client) = extract_pool!(&connections, connection_id, InfluxDb) {
- drop(connections);
- return db::influxdb_driver::list_databases(&client).await;
- }
try_sqlserver!(connections, connection_id, list_databases);
if let Some(client) = extract_pool!(&connections, connection_id, Agent) {
let is_mongo =
@@ -104,19 +289,25 @@ async fn list_databases_once(state: &AppState, connection_id: &str) -> Result<Ve
}
}
- #[cfg(feature = "duckdb-bundled")]
let duckdb_attached_names = duckdb_attached_database_names(state, connection_id).await;
let db_config = connection_config(state, connection_id).await;
let connections = state.connections.read().await;
let pool = connections.get(connection_id).ok_or("Connection not found")?;
- #[cfg(feature = "duckdb-bundled")]
- if let PoolKind::DuckDb(con) = pool {
- let con = con.lock().map_err(|e| e.to_string())?;
- return duckdb_list_databases_with_attached(&con, &duckdb_attached_names);
+ match pool {
+ PoolKind::Mysql(p, _) if db_config.as_ref().is_some_and(is_doris_family_config) => {
+ db::mysql::list_databases_show(p).await
+ }
+ PoolKind::Mysql(p, mode) => dispatch_mysql!(p, mode, db::mysql::list_databases, db::ob_oracle::list_databases),
+ PoolKind::Postgres(p) => db::postgres::list_databases(p).await,
+ PoolKind::Sqlite(p) => db::sqlite::list_databases(p).await,
+ PoolKind::Rqlite(client) => db::rqlite_driver::list_databases(client).await,
+ PoolKind::DuckDb(con) => {
+ let con = con.lock().map_err(|e| e.to_string())?;
+ duckdb_list_databases_with_attached(&con, &duckdb_attached_names)
+ }
+ _ => Ok(vec![]),
}
-
- providers::native::list_databases(pool, db_config.as_ref()).await
}
pub async fn list_schemas_core(state: &AppState, connection_id: &str, database: &str) -> Result<Vec<String>, String> {
@@ -186,14 +377,15 @@ async fn list_schemas_once(state: &AppState, connection_id: &str, database: &str
let connections = state.connections.read().await;
let pool = connections.get(&pool_key).ok_or("Pool not found")?;
- #[cfg(feature = "duckdb-bundled")]
- if let PoolKind::DuckDb(con) = pool {
- let duckdb_attached_names = duckdb_attached_database_names(state, connection_id).await;
- let con = con.lock().map_err(|e| e.to_string())?;
- return duckdb_list_schemas_with_attached(&con, database, &duckdb_attached_names);
+ match pool {
+ PoolKind::Postgres(p) => db::postgres::list_schemas(p).await,
+ PoolKind::DuckDb(con) => {
+ let duckdb_attached_names = duckdb_attached_database_names(state, connection_id).await;
+ let con = con.lock().map_err(|e| e.to_string())?;
+ duckdb_list_schemas_with_attached(&con, database, &duckdb_attached_names)
+ }
+ _ => Ok(vec![]),
}
-
- providers::native::list_schemas(pool).await
}
pub async fn list_tables_core(
@@ -219,13 +411,11 @@ async fn list_tables_once(
limit: Option<usize>,
) -> Result<Vec<db::TableInfo>, String> {
let pool_key = state.get_or_create_pool(connection_id, Some(database)).await?;
- #[cfg(feature = "duckdb-bundled")]
let duckdb_attached_names = duckdb_attached_database_names(state, connection_id).await;
let db_config = connection_config(state, connection_id).await;
{
let connections = state.connections.read().await;
- #[cfg(feature = "duckdb-bundled")]
if let Some(ext_pool) = extract_pool!(&connections, &pool_key, ExternalTabular) {
drop(connections);
let cache = ext_pool.cache.clone();
@@ -247,7 +437,6 @@ async fn list_tables_once(
)
.await;
}
- #[cfg(feature = "duckdb-bundled")]
if let Some(con) = extract_pool!(&connections, &pool_key, DuckDb) {
drop(connections);
let con = con.lock().map_err(|e| e.to_string())?;
@@ -257,30 +446,22 @@ async fn list_tables_once(
drop(connections);
return db::clickhouse_driver::list_tables(&client, clickhouse_metadata_database(database, schema)).await;
}
- if let Some(client) = extract_pool!(&connections, &pool_key, InfluxDb) {
- drop(connections);
- return db::influxdb_driver::list_tables(&client, database).await;
- }
try_sqlserver!(connections, &pool_key, list_tables, schema, filter, limit);
if let Some(client) = extract_pool!(&connections, &pool_key, Agent) {
let fallback_config = db_config.clone();
drop(connections);
let mut client = client.lock().await;
match client.list_tables::<Vec<db::TableInfo>>(database, schema).await {
- Ok(tables) if !tables.is_empty() => {
- return Ok(filter_table_infos_for_config(tables, filter, limit, db_config.as_ref()))
- }
+ Ok(tables) if !tables.is_empty() => return Ok(filter_table_infos(tables, filter, limit)),
Ok(tables) => {
if let Some(config) = fallback_config.as_ref() {
match native_postgres_metadata_pool(state, connection_id, database, config).await {
Ok(Some(pool)) => {
- return db::postgres::list_tables(&pool, schema).await.map(|tables| {
- filter_table_infos_for_config(tables, filter, limit, db_config.as_ref())
- });
- }
- Ok(None) => {
- return Ok(filter_table_infos_for_config(tables, filter, limit, db_config.as_ref()))
+ return db::postgres::list_tables(&pool, schema)
+ .await
+ .map(|tables| filter_table_infos(tables, filter, limit));
}
+ Ok(None) => return Ok(filter_table_infos(tables, filter, limit)),
Err(error) => {
log::warn!(
"[schema][agent:list_tables:fallback-failed] connection_id={} database={} schema={} error={}",
@@ -292,7 +473,7 @@ async fn list_tables_once(
}
}
}
- return Ok(filter_table_infos_for_config(tables, filter, limit, db_config.as_ref()));
+ return Ok(filter_table_infos(tables, filter, limit));
}
Err(agent_error) => {
if let Some(config) = fallback_config.as_ref() {
@@ -301,7 +482,7 @@ async fn list_tables_once(
{
return db::postgres::list_tables(&pool, schema)
.await
- .map(|tables| filter_table_infos_for_config(tables, filter, limit, db_config.as_ref()))
+ .map(|tables| filter_table_infos(tables, filter, limit))
.map_err(|fallback_error| {
format!(
"{agent_error}\n\nNative PostgreSQL metadata fallback failed: {fallback_error}"
@@ -318,17 +499,80 @@ async fn list_tables_once(
let connections = state.connections.read().await;
let pool = connections.get(&pool_key).ok_or("Pool not found")?;
- providers::native::list_tables(pool, db_config.as_ref(), database, schema)
- .await
- .map(|tables| filter_table_infos_for_config(tables, filter, limit, db_config.as_ref()))
+ match pool {
+ PoolKind::Mysql(p, _) if db_config.as_ref().is_some_and(is_doris_family_config) => {
+ db::mysql::list_tables_show(p, database).await.map(|tables| filter_table_infos(tables, filter, limit))
+ }
+ PoolKind::Mysql(p, mode) => {
+ dispatch_mysql!(p, mode, db::mysql::list_tables, db::ob_oracle::list_tables, schema)
+ .map(|tables| filter_table_infos(tables, filter, limit))
+ }
+ PoolKind::Postgres(p) => {
+ db::postgres::list_tables(p, schema).await.map(|tables| filter_table_infos(tables, filter, limit))
+ }
+ PoolKind::Sqlite(p) => {
+ db::sqlite::list_tables(p, schema).await.map(|tables| filter_table_infos(tables, filter, limit))
+ }
+ PoolKind::Rqlite(client) => {
+ db::rqlite_driver::list_tables(client, schema).await.map(|tables| filter_table_infos(tables, filter, limit))
+ }
+ PoolKind::MongoDb(client) => db::mongo_driver::list_collections(client, database)
+ .await
+ .map(|names| collection_names_to_tables(names, "COLLECTION"))
+ .map(|tables| filter_table_infos(tables, filter, limit)),
+ PoolKind::Elasticsearch(client) => db::elasticsearch_driver::list_indices(client)
+ .await
+ .map(|names| collection_names_to_tables(names, "INDEX"))
+ .map(|tables| filter_table_infos(tables, filter, limit)),
+ _ => Ok(vec![]),
+ }
+}
+
+fn collection_names_to_tables(names: Vec<String>, table_type: &str) -> Vec<db::TableInfo> {
+ names
+ .into_iter()
+ .map(|name| db::TableInfo {
+ name,
+ table_type: table_type.to_string(),
+ comment: None,
+ parent_schema: None,
+ parent_name: None,
+ })
+ .collect()
+}
+
+fn filter_table_infos(tables: Vec<db::TableInfo>, filter: Option<&str>, limit: Option<usize>) -> Vec<db::TableInfo> {
+ let filter = filter.unwrap_or("").to_lowercase();
+ let limit = limit.unwrap_or(usize::MAX);
+ tables
+ .into_iter()
+ .filter(|table| filter.is_empty() || table.name.to_lowercase().contains(&filter))
+ .take(limit)
+ .collect()
}
#[cfg(test)]
mod tests {
- use super::{clickhouse_metadata_database, is_agent_postgres_metadata_fallback_config};
- #[cfg(feature = "duckdb-bundled")]
- use super::{duckdb_attach_database, duckdb_list_databases, duckdb_query_tables_in_database};
- use crate::models::connection::{default_redis_key_separator, ConnectionConfig, DatabaseType};
+ use super::{
+ clickhouse_metadata_database, deduplicate_column_infos, duckdb_attach_database, duckdb_list_databases,
+ duckdb_query_tables_in_database, is_agent_postgres_metadata_fallback_config,
+ };
+ use crate::models::connection::{ConnectionConfig, DatabaseType};
+
+ fn test_column(name: &str, comment: Option<&str>, is_primary_key: bool) -> super::db::ColumnInfo {
+ super::db::ColumnInfo {
+ name: name.to_string(),
+ data_type: "VARCHAR".to_string(),
+ is_nullable: true,
+ column_default: None,
+ is_primary_key,
+ extra: None,
+ comment: comment.map(|value| value.to_string()),
+ numeric_precision: None,
+ numeric_scale: None,
+ character_maximum_length: None,
+ }
+ }
fn test_connection_config(db_type: DatabaseType) -> ConnectionConfig {
ConnectionConfig {
@@ -364,7 +608,7 @@ mod tests {
redis_sentinel_password: String::new(),
redis_sentinel_tls: false,
redis_cluster_nodes: String::new(),
- redis_key_separator: default_redis_key_separator(),
+ redis_key_separator: crate::models::connection::default_redis_key_separator(),
etcd_endpoints: String::new(),
external_config: None,
jdbc_driver_class: None,
@@ -374,7 +618,6 @@ mod tests {
}
}
- #[cfg(feature = "duckdb-bundled")]
#[test]
fn duckdb_list_databases_includes_attached_database() {
let unique = uuid::Uuid::new_v4();
@@ -391,7 +634,6 @@ mod tests {
let _ = std::fs::remove_file(path);
}
- #[cfg(feature = "duckdb-bundled")]
#[test]
fn duckdb_query_tables_filters_by_attached_database() {
let unique = uuid::Uuid::new_v4();
@@ -421,6 +663,23 @@ mod tests {
assert_eq!(clickhouse_metadata_database("default", "testdb"), "default");
}
+ #[test]
+ fn deduplicates_columns_and_preserves_later_comment() {
+ let columns = deduplicate_column_infos(vec![
+ test_column("ID", None, false),
+ test_column("ID", Some("源主键"), true),
+ test_column("TFBH", Some(""), false),
+ test_column("TFBH", Some("台账编号"), false),
+ ]);
+
+ assert_eq!(columns.len(), 2);
+ assert_eq!(columns[0].name, "ID");
+ assert_eq!(columns[0].comment.as_deref(), Some("源主键"));
+ assert!(columns[0].is_primary_key);
+ assert_eq!(columns[1].name, "TFBH");
+ assert_eq!(columns[1].comment.as_deref(), Some("台账编号"));
+ }
+
#[test]
fn postgres_like_agent_metadata_fallback_targets_pg_compatible_agents() {
assert!(is_agent_postgres_metadata_fallback_config(&test_connection_config(DatabaseType::Kingbase)));
@@ -436,10 +695,9 @@ pub async fn list_objects_core(
connection_id: &str,
database: &str,
schema: &str,
- object_types: Option<Vec<String>>,
) -> Result<Vec<db::ObjectInfo>, String> {
retry_metadata_connection(state, connection_id, Some(database), || {
- list_objects_once(state, connection_id, database, schema, object_types.as_deref())
+ list_objects_once(state, connection_id, database, schema)
})
.await
}
@@ -461,27 +719,12 @@ async fn list_objects_once(
connection_id: &str,
database: &str,
schema: &str,
- object_types: Option<&[String]>,
-) -> Result<Vec<db::ObjectInfo>, String> {
- let db_config = connection_config(state, connection_id).await;
- list_objects_once_unfiltered(state, connection_id, database, schema)
- .await
- .map(|objects| filter_yashandb_recyclebin_objects(objects, db_config.as_ref()))
- .map(|objects| filter_objects_by_types(objects, object_types))
-}
-
-async fn list_objects_once_unfiltered(
- state: &AppState,
- connection_id: &str,
- database: &str,
- schema: &str,
) -> Result<Vec<db::ObjectInfo>, String> {
let pool_key = state.get_or_create_pool(connection_id, Some(database)).await?;
let db_config = connection_config(state, connection_id).await;
{
let connections = state.connections.read().await;
- #[cfg(feature = "duckdb-bundled")]
if let Some(ext_pool) = extract_pool!(&connections, &pool_key, ExternalTabular) {
drop(connections);
let cache = ext_pool.cache.clone();
@@ -517,11 +760,11 @@ async fn list_objects_once_unfiltered(
}
try_sqlserver!(connections, &pool_key, list_objects, schema);
if let Some(client) = extract_pool!(&connections, &pool_key, Agent) {
- let oracle_object_options = db_config.as_ref().and_then(oracle_agent_object_options);
+ let is_oracle = db_config.as_ref().is_some_and(|config| config.db_type == DatabaseType::Oracle);
let fallback_config = db_config.clone();
drop(connections);
- if let Some(options) = oracle_object_options {
- return oracle_agent_list_objects(client, database, schema, options).await;
+ if is_oracle {
+ return oracle_agent_list_objects(client, database, schema).await;
}
let mut client = client.lock().await;
match client.list_objects::<Vec<db::ObjectInfo>>(database, schema).await {
@@ -563,24 +806,36 @@ async fn list_objects_once_unfiltered(
let connections = state.connections.read().await;
let pool = connections.get(&pool_key).ok_or("Pool not found")?;
- if let Some(objects) = providers::native::list_objects(pool, db_config.as_ref(), database, schema).await? {
- return Ok(objects);
+ match pool {
+ PoolKind::Mysql(p, mode) => {
+ // Note: mysql and ob_oracle take different second args (database vs schema)
+ if *mode == MysqlMode::OceanBaseOracle {
+ db::ob_oracle::list_objects(p, schema).await
+ } else if db_config.as_ref().is_some_and(is_doris_family_config) {
+ db::mysql::list_table_objects_show(p, database).await
+ } else {
+ db::mysql::list_objects(p, database).await
+ }
+ }
+ PoolKind::Postgres(p) => db::postgres::list_objects(p, schema).await,
+ _ => {
+ drop(connections);
+ Ok(list_tables_core(state, connection_id, database, schema, None, None)
+ .await?
+ .into_iter()
+ .map(|table| db::ObjectInfo {
+ name: table.name,
+ object_type: table.table_type,
+ schema: if schema.is_empty() { None } else { Some(schema.to_string()) },
+ comment: table.comment,
+ created_at: None,
+ updated_at: None,
+ parent_schema: table.parent_schema,
+ parent_name: table.parent_name,
+ })
+ .collect())
+ }
}
- drop(connections);
- Ok(list_tables_core(state, connection_id, database, schema, None, None)
- .await?
- .into_iter()
- .map(|table| db::ObjectInfo {
- name: table.name,
- object_type: table.table_type,
- schema: if schema.is_empty() { None } else { Some(schema.to_string()) },
- comment: table.comment,
- created_at: None,
- updated_at: None,
- parent_schema: table.parent_schema,
- parent_name: table.parent_name,
- })
- .collect())
}
async fn list_completion_objects_once(
@@ -606,11 +861,11 @@ async fn list_completion_objects_once(
.map(filter_completion_objects);
}
if let Some(client) = extract_pool!(&connections, &pool_key, Agent) {
- let oracle_object_options = db_config.as_ref().and_then(oracle_agent_object_options);
+ let is_oracle = db_config.as_ref().is_some_and(|config| config.db_type == DatabaseType::Oracle);
let fallback_config = db_config.clone();
drop(connections);
- let objects = if let Some(options) = oracle_object_options {
- oracle_agent_list_objects(client, database, schema, options).await?
+ let objects = if is_oracle {
+ oracle_agent_list_objects(client, database, schema).await?
} else {
let mut client = client.lock().await;
match client.list_objects::<Vec<db::ObjectInfo>>(database, schema).await {
@@ -656,22 +911,37 @@ async fn list_completion_objects_once(
}
}
};
- let objects = filter_yashandb_recyclebin_objects(objects, fallback_config.as_ref());
return Ok(filter_completion_objects(objects));
}
let pool = connections.get(&pool_key).ok_or("Pool not found")?;
- match providers::native::list_completion_objects(pool, database, schema).await? {
- Some(objects) => Ok(filter_completion_objects(objects)),
- None if matches!(pool, PoolKind::SqlServer(_)) => {
+ match pool {
+ PoolKind::Mysql(p, mode) if *mode != MysqlMode::OceanBaseOracle => {
+ db::mysql::list_completion_objects(p, database).await
+ }
+ PoolKind::Mysql(p, mode) if *mode == MysqlMode::OceanBaseOracle => {
+ db::ob_oracle::list_objects(p, schema).await.map(filter_completion_objects)
+ }
+ PoolKind::Postgres(p) => db::postgres::list_objects(p, schema).await.map(filter_completion_objects),
+ PoolKind::SqlServer(_) => {
drop(connections);
- let objects = list_objects_once(state, connection_id, database, schema, None).await?;
+ let objects = list_objects_once(state, connection_id, database, schema).await?;
Ok(filter_completion_objects(objects))
}
- None => Ok(Vec::new()),
+ _ => Ok(Vec::new()),
}
}
+fn filter_completion_objects(objects: Vec<db::ObjectInfo>) -> Vec<db::ObjectInfo> {
+ objects
+ .into_iter()
+ .filter(|object| {
+ let object_type = object.object_type.to_ascii_uppercase();
+ object_type.contains("PROCEDURE") || object_type.contains("FUNCTION") || object_type.contains("TRIGGER")
+ })
+ .collect()
+}
+
fn is_agent_postgres_metadata_fallback_config(config: &ConnectionConfig) -> bool {
matches!(config.db_type, DatabaseType::Kingbase | DatabaseType::Highgo | DatabaseType::Vastbase)
}
@@ -722,13 +992,11 @@ pub async fn get_columns_core(
table: &str,
) -> Result<Vec<db::ColumnInfo>, String> {
let pool_key = state.get_or_create_pool(connection_id, Some(database)).await?;
- #[cfg(feature = "duckdb-bundled")]
let duckdb_attached_names = duckdb_attached_database_names(state, connection_id).await;
let db_config = connection_config(state, connection_id).await;
{
let connections = state.connections.read().await;
- #[cfg(feature = "duckdb-bundled")]
if let Some(ext_pool) = extract_pool!(&connections, &pool_key, ExternalTabular) {
drop(connections);
let cache = ext_pool.cache.clone();
@@ -757,7 +1025,6 @@ pub async fn get_columns_core(
.await?;
return Ok(deduplicate_column_infos(columns));
}
- #[cfg(feature = "duckdb-bundled")]
if let Some(con) = extract_pool!(&connections, &pool_key, DuckDb) {
drop(connections);
let con = con.lock().map_err(|e| e.to_string())?;
@@ -775,10 +1042,6 @@ pub async fn get_columns_core(
.await
.map(deduplicate_column_infos);
}
- if let Some(client) = extract_pool!(&connections, &pool_key, InfluxDb) {
- drop(connections);
- return db::influxdb_driver::get_columns(&client, database, table).await.map(deduplicate_column_infos);
- }
try_sqlserver!(connections, &pool_key, get_columns, schema, table);
if let Some(client) = extract_pool!(&connections, &pool_key, Agent) {
let fallback_config = db_config.clone();
@@ -833,9 +1096,64 @@ pub async fn get_columns_core(
let connections = state.connections.read().await;
let pool = connections.get(&pool_key).ok_or("Pool not found")?;
- providers::native::get_columns(pool, db_config.as_ref(), database, schema, table)
- .await
- .map(deduplicate_column_infos)
+ match pool {
+ PoolKind::Mysql(p, _) if db_config.as_ref().is_some_and(is_doris_family_config) => {
+ db::mysql::get_columns_show(p, database, table).await.map(deduplicate_column_infos)
+ }
+ PoolKind::Mysql(p, mode) => {
+ dispatch_mysql!(p, mode, db::mysql::get_columns, db::ob_oracle::get_columns, database, table)
+ .map(deduplicate_column_infos)
+ }
+ PoolKind::Postgres(p) => db::postgres::get_columns(p, schema, table).await.map(deduplicate_column_infos),
+ PoolKind::Sqlite(p) => db::sqlite::get_columns(p, schema, table).await.map(deduplicate_column_infos),
+ PoolKind::Rqlite(client) => {
+ db::rqlite_driver::get_columns(client, schema, table).await.map(deduplicate_column_infos)
+ }
+ _ => Ok(vec![]),
+ }
+}
+
+fn deduplicate_column_infos(columns: Vec<db::ColumnInfo>) -> Vec<db::ColumnInfo> {
+ let mut result: Vec<db::ColumnInfo> = Vec::with_capacity(columns.len());
+ for column in columns {
+ if let Some(existing) = result.iter_mut().find(|existing| existing.name == column.name) {
+ existing.is_primary_key |= column.is_primary_key;
+ existing.is_nullable &= column.is_nullable;
+ merge_optional_string(&mut existing.column_default, column.column_default);
+ merge_optional_string(&mut existing.extra, column.extra);
+ merge_optional_string(&mut existing.comment, column.comment);
+ if existing.numeric_precision.is_none() {
+ existing.numeric_precision = column.numeric_precision;
+ }
+ if existing.numeric_scale.is_none() {
+ existing.numeric_scale = column.numeric_scale;
+ }
+ if existing.character_maximum_length.is_none() {
+ existing.character_maximum_length = column.character_maximum_length;
+ }
+ if existing.data_type.trim().is_empty() && !column.data_type.trim().is_empty() {
+ existing.data_type = column.data_type;
+ }
+ } else {
+ result.push(column);
+ }
+ }
+ result
+}
+
+fn merge_optional_string(target: &mut Option<String>, candidate: Option<String>) {
+ let Some(candidate) = candidate else {
+ return;
+ };
+ if candidate.trim().is_empty() {
+ if target.is_none() {
+ *target = Some(candidate);
+ }
+ return;
+ }
+ if target.as_ref().map_or(true, |value| value.trim().is_empty()) {
+ *target = Some(candidate);
+ }
}
pub async fn list_indexes_core(
@@ -856,7 +1174,15 @@ pub async fn list_indexes_core(
let connections = state.connections.read().await;
let pool = connections.get(&pool_key).ok_or("Pool not found")?;
- providers::native::list_indexes(pool, database, schema, table).await
+ match pool {
+ PoolKind::Mysql(p, mode) => {
+ dispatch_mysql!(p, mode, db::mysql::list_indexes, db::ob_oracle::list_indexes, schema, table)
+ }
+ PoolKind::Postgres(p) => db::postgres::list_indexes(p, schema, table).await,
+ PoolKind::Sqlite(p) => db::sqlite::list_indexes(p, schema, table).await,
+ PoolKind::Rqlite(client) => db::rqlite_driver::list_indexes(client, schema, table).await,
+ _ => Ok(vec![]),
+ }
}
pub async fn list_foreign_keys_core(
@@ -877,7 +1203,15 @@ pub async fn list_foreign_keys_core(
let connections = state.connections.read().await;
let pool = connections.get(&pool_key).ok_or("Pool not found")?;
- providers::native::list_foreign_keys(pool, schema, table).await
+ match pool {
+ PoolKind::Mysql(p, mode) => {
+ dispatch_mysql!(p, mode, db::mysql::list_foreign_keys, db::ob_oracle::list_foreign_keys, schema, table)
+ }
+ PoolKind::Postgres(p) => db::postgres::list_foreign_keys(p, schema, table).await,
+ PoolKind::Sqlite(p) => db::sqlite::list_foreign_keys(p, schema, table).await,
+ PoolKind::Rqlite(client) => db::rqlite_driver::list_foreign_keys(client, schema, table).await,
+ _ => Ok(vec![]),
+ }
}
pub async fn list_triggers_core(
@@ -898,7 +1232,80 @@ pub async fn list_triggers_core(
let connections = state.connections.read().await;
let pool = connections.get(&pool_key).ok_or("Pool not found")?;
- providers::native::list_triggers(pool, schema, table).await
+ match pool {
+ PoolKind::Mysql(p, mode) => {
+ dispatch_mysql!(p, mode, db::mysql::list_triggers, db::ob_oracle::list_triggers, schema, table)
+ }
+ PoolKind::Postgres(p) => db::postgres::list_triggers(p, schema, table).await,
+ PoolKind::Sqlite(p) => db::sqlite::list_triggers(p, schema, table).await,
+ PoolKind::Rqlite(client) => db::rqlite_driver::list_triggers(client, schema, table).await,
+ _ => Ok(vec![]),
+ }
+}
+
+pub async fn list_functions_core(
+ state: &AppState,
+ connection_id: &str,
+ database: &str,
+ schema: &str,
+) -> Result<Vec<db::FunctionInfo>, String> {
+ let pool_key = state.get_or_create_pool(connection_id, Some(database)).await?;
+ let connections = state.connections.read().await;
+ let pool = connections.get(&pool_key).ok_or("Pool not found")?;
+
+ match pool {
+ PoolKind::Postgres(p) => db::postgres::list_functions(p, schema).await,
+ _ => Ok(vec![]),
+ }
+}
+
+pub async fn list_sequences_core(
+ state: &AppState,
+ connection_id: &str,
+ database: &str,
+ schema: &str,
+ with_last_values: bool,
+) -> Result<Vec<db::SequenceInfo>, String> {
+ let pool_key = state.get_or_create_pool(connection_id, Some(database)).await?;
+ let connections = state.connections.read().await;
+ let pool = connections.get(&pool_key).ok_or("Pool not found")?;
+
+ match pool {
+ PoolKind::Postgres(p) => db::postgres::list_sequences(p, schema, with_last_values).await,
+ _ => Ok(vec![]),
+ }
+}
+
+pub async fn list_rules_core(
+ state: &AppState,
+ connection_id: &str,
+ database: &str,
+ schema: &str,
+) -> Result<Vec<db::RuleInfo>, String> {
+ let pool_key = state.get_or_create_pool(connection_id, Some(database)).await?;
+ let connections = state.connections.read().await;
+ let pool = connections.get(&pool_key).ok_or("Pool not found")?;
+
+ match pool {
+ PoolKind::Postgres(p) => db::postgres::list_rules(p, schema).await,
+ _ => Ok(vec![]),
+ }
+}
+
+pub async fn list_owners_core(
+ state: &AppState,
+ connection_id: &str,
+ database: &str,
+ schema: &str,
+) -> Result<Vec<db::OwnerInfo>, String> {
+ let pool_key = state.get_or_create_pool(connection_id, Some(database)).await?;
+ let connections = state.connections.read().await;
+ let pool = connections.get(&pool_key).ok_or("Pool not found")?;
+
+ match pool {
+ PoolKind::Postgres(p) => db::postgres::list_owners(p, schema).await,
+ _ => Ok(vec![]),
+ }
}
pub async fn get_table_ddl_core(
@@ -912,7 +1319,6 @@ pub async fn get_table_ddl_core(
{
let connections = state.connections.read().await;
- #[cfg(feature = "duckdb-bundled")]
if let Some(con) = extract_pool!(&connections, &pool_key, DuckDb) {
drop(connections);
let tbl = table.replace('\'', "''");
@@ -955,13 +1361,35 @@ pub async fn get_table_ddl_core(
let pool = connections.get(&pool_key).ok_or("Pool not found")?;
let db_config = connection_config(state, connection_id).await;
- providers::native::table_ddl(pool, db_config.as_ref(), schema, table).await
+ match pool {
+ PoolKind::Mysql(p, _) => mysql_ddl(p, table).await,
+ PoolKind::Postgres(p) if db_config.as_ref().is_some_and(is_opengauss_family_config) => {
+ match opengauss_table_ddl(p, schema, table).await {
+ Ok(ddl) => Ok(ddl),
+ Err(_) => pg_ddl(p, schema, table).await,
+ }
+ }
+ PoolKind::Postgres(p) => pg_ddl(p, schema, table).await,
+ PoolKind::Sqlite(p) => sqlite_ddl(p, table).await,
+ PoolKind::Rqlite(client) => db::rqlite_driver::table_ddl(client, table).await,
+ _ => Err("DDL not supported for this database type".to_string()),
+ }
}
async fn connection_config(state: &AppState, connection_id: &str) -> Option<ConnectionConfig> {
state.configs.read().await.get(connection_id).cloned()
}
+fn is_opengauss_family_config(config: &ConnectionConfig) -> bool {
+ matches!(config.db_type, DatabaseType::OpenGauss | DatabaseType::Gaussdb)
+ || matches!(config.driver_profile.as_deref(), Some("opengauss" | "gaussdb"))
+}
+
+fn is_doris_family_config(config: &ConnectionConfig) -> bool {
+ matches!(config.db_type, DatabaseType::Doris | DatabaseType::StarRocks)
+ || matches!(config.driver_profile.as_deref(), Some("doris" | "selectdb" | "starrocks"))
+}
+
fn sql_string(value: &str) -> String {
format!("'{}'", value.replace('\'', "''"))
}
@@ -1060,19 +1488,6 @@ pub fn postgres_object_source_sql(schema: &str, name: &str, kind: &db::ObjectSou
}
}
-pub fn postgres_routine_object_source_legacy_sql(schema: &str, name: &str) -> String {
- format!(
- "SELECT pg_get_functiondef(p.oid) \
- FROM pg_proc p \
- JOIN pg_namespace n ON n.oid = p.pronamespace \
- WHERE n.nspname = {} AND p.proname = {} \
- AND NOT p.proisagg AND NOT p.proiswindow \
- ORDER BY p.oid LIMIT 1",
- sql_string(schema),
- sql_string(name)
- )
-}
-
pub fn oracle_object_source_sql(schema: &str, name: &str, kind: &db::ObjectSourceKind) -> String {
let object_type = match kind {
db::ObjectSourceKind::View => "VIEW",
@@ -1204,11 +1619,25 @@ pub async fn get_object_source_core(
return Ok(result);
}
} else {
- let pool = connections.get(&pool_key).ok_or("Pool not found")?;
- if let Some(source) = providers::native::object_source(pool, database, schema, name, &object_type).await? {
- source
- } else {
- return Err("Object source is not supported for this database type".to_string());
+ match connections.get(&pool_key).ok_or("Pool not found")? {
+ PoolKind::Mysql(pool, _) => mysql_object_source(pool, name, &object_type).await?,
+ PoolKind::Postgres(pool) => postgres_object_source(pool, schema, name, &object_type).await?,
+ PoolKind::Sqlite(pool) => first_string_cell(
+ db::sqlite::execute_query(pool, &sqlite_object_source_sql(name, &object_type)).await?,
+ )?,
+ PoolKind::Rqlite(client) => {
+ return db::rqlite_driver::object_source(client, name, &object_type).await;
+ }
+ PoolKind::ClickHouse(client) if matches!(object_type, db::ObjectSourceKind::View) => {
+ let result = db::clickhouse_driver::execute_query(
+ client,
+ database,
+ &format!("SHOW CREATE TABLE {}", mysql_ident(name)),
+ )
+ .await?;
+ first_string_cell(result)?
+ }
+ _ => return Err("Object source is not supported for this database type".to_string()),
}
}
};
@@ -1230,28 +1659,13 @@ fn oracle_owner_filter(schema: &str) -> String {
}
}
-#[derive(Debug, Clone, Copy)]
-struct OracleAgentObjectOptions {
- hide_recyclebin_objects: bool,
-}
-
-fn oracle_agent_object_options(config: &ConnectionConfig) -> Option<OracleAgentObjectOptions> {
- match config.db_type {
- DatabaseType::Oracle => Some(OracleAgentObjectOptions { hide_recyclebin_objects: false }),
- DatabaseType::Yashandb => Some(OracleAgentObjectOptions { hide_recyclebin_objects: true }),
- _ => None,
- }
-}
-
-pub fn oracle_list_objects_sql(schema: &str, hide_recyclebin_objects: bool) -> String {
- let recyclebin_filter = if hide_recyclebin_objects { " AND object_name NOT LIKE 'BIN$%'" } else { "" };
+pub fn oracle_list_objects_sql(schema: &str) -> String {
format!(
"SELECT object_name, CASE object_type WHEN 'PACKAGE BODY' THEN 'PACKAGE_BODY' ELSE object_type END AS object_type, owner \
FROM all_objects \
- WHERE owner = {} AND object_type IN ('TABLE', 'VIEW', 'PROCEDURE', 'FUNCTION', 'PACKAGE', 'PACKAGE BODY'){} \
+ WHERE owner = {} AND object_type IN ('TABLE', 'VIEW', 'PROCEDURE', 'FUNCTION', 'PACKAGE', 'PACKAGE BODY') \
ORDER BY CASE object_type WHEN 'TABLE' THEN 0 WHEN 'VIEW' THEN 1 WHEN 'PROCEDURE' THEN 2 WHEN 'FUNCTION' THEN 3 WHEN 'PACKAGE' THEN 4 ELSE 5 END, object_name",
- oracle_owner_filter(schema),
- recyclebin_filter
+ oracle_owner_filter(schema)
)
}
@@ -1259,9 +1673,8 @@ async fn oracle_agent_list_objects(
client: Arc<tokio::sync::Mutex<db::agent_driver::AgentDriverClient>>,
database: &str,
schema: &str,
- options: OracleAgentObjectOptions,
) -> Result<Vec<db::ObjectInfo>, String> {
- let sql = oracle_list_objects_sql(schema, options.hide_recyclebin_objects);
+ let sql = oracle_list_objects_sql(schema);
let params = agent_execute_query_params(
&sql,
if database.is_empty() { None } else { Some(database) },
@@ -1326,13 +1739,6 @@ async fn postgres_object_source(
.and_then(first_string_cell)
.map_err(|fallback_err| format!("{primary_err}; fallback failed: {fallback_err}"))
}
- Err(primary_err) if matches!(object_type, db::ObjectSourceKind::Procedure | db::ObjectSourceKind::Function) => {
- let fallback_sql = postgres_routine_object_source_legacy_sql(schema, name);
- db::postgres::execute_query(pool, &fallback_sql)
- .await
- .and_then(first_string_cell)
- .map_err(|fallback_err| format!("{primary_err}; fallback failed: {fallback_err}"))
- }
Err(err) => Err(err),
}
}
@@ -1362,35 +1768,6 @@ mod object_source_tests {
);
}
- #[test]
- fn builds_postgres_legacy_routine_source_sql_without_prokind() {
- let sql = postgres_routine_object_source_legacy_sql("public", "recalc_score");
-
- assert!(sql.contains("pg_get_functiondef(p.oid)"));
- assert!(sql.contains("NOT p.proisagg"));
- assert!(sql.contains("NOT p.proiswindow"));
- assert!(!sql.contains("p.prokind"));
- }
-
- #[test]
- fn builds_postgres_object_source_sql_for_sequences() {
- let sql = postgres_object_source_sql("tenant's schema", "order id seq", &ObjectSourceKind::Sequence);
-
- assert!(sql.contains("-- auto-generated definition"));
- assert!(sql.contains("create sequence"));
- assert!(sql.contains("alter sequence"));
- assert!(sql.contains("owner to"));
- assert!(sql.contains("owned by"));
- assert!(sql.contains("pg_catalog.pg_sequence"));
- assert!(sql.contains("n.nspname = 'tenant''s schema'"));
- assert!(sql.contains("c.relname = 'order id seq'"));
- assert!(sql.contains("c.relkind = 'S'"));
- assert!(!sql.contains("MINVALUE"));
- assert!(!sql.contains("START WITH"));
- assert!(!sql.contains("CACHE"));
- assert!(!sql.contains("NO CYCLE"));
- }
-
#[test]
fn builds_postgres_view_source_sql_without_regclass_cast() {
let sql = postgres_object_source_sql("tenant's schema", "active users", &ObjectSourceKind::View);
@@ -1428,20 +1805,12 @@ mod object_source_tests {
#[test]
fn builds_oracle_list_objects_sql_with_packages() {
- let sql = oracle_list_objects_sql("hr", false);
+ let sql = oracle_list_objects_sql("hr");
assert!(sql.contains("'PACKAGE'"));
assert!(sql.contains("'PACKAGE BODY'"));
assert!(sql.contains("CASE object_type WHEN 'PACKAGE BODY' THEN 'PACKAGE_BODY'"));
assert!(sql.contains("owner = 'HR'"));
- assert!(!sql.contains("BIN$"));
- }
-
- #[test]
- fn builds_yashandb_list_objects_sql_without_recyclebin_objects() {
- let sql = oracle_list_objects_sql("hr", true);
-
- assert!(sql.contains("object_name NOT LIKE 'BIN$%'"));
}
}
@@ -1482,67 +1851,6 @@ mod ddl_tests {
"SELECT pg_get_tabledef('\"tenant''s schema\".\"active users\"')"
);
}
-
- #[test]
- fn sqlserver_comment_ddl_includes_table_comment() {
- let ddl = render_sqlserver_comment_ddl("dbo", "users", Some("User accounts table"), &[], &[]);
-
- assert!(ddl.contains("EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'User accounts table'"));
- assert!(ddl.contains("@level0type=N'SCHEMA', @level0name=N'dbo'"));
- assert!(ddl.contains("@level1type=N'TABLE', @level1name=N'users'"));
- }
-
- #[test]
- fn sqlserver_comment_ddl_includes_column_comments() {
- let mut email_col = column("email", "nvarchar(255)");
- email_col.comment = Some("User's email address".to_string());
- let mut name_col = column("name", "nvarchar(100)");
- name_col.comment = Some("User's display name".to_string());
- let columns = vec![email_col, name_col];
-
- let ddl = render_sqlserver_comment_ddl("dbo", "users", None, &columns, &[]);
-
- assert!(ddl.contains("@level2type=N'COLUMN', @level2name=N'email'"));
- assert!(ddl.contains("@value=N'User''s email address'"));
- assert!(ddl.contains("@level2type=N'COLUMN', @level2name=N'name'"));
- assert!(ddl.contains("@value=N'User''s display name'"));
- }
-
- #[test]
- fn sqlserver_comment_ddl_includes_index_comments() {
- let idx = db::IndexInfo {
- name: "IX_users_email".to_string(),
- columns: vec!["email".to_string()],
- is_unique: true,
- is_primary: false,
- filter: None,
- index_type: Some("NONCLUSTERED".to_string()),
- included_columns: None,
- comment: Some("Unique email index".to_string()),
- };
- let indexes = vec![idx];
-
- let ddl = render_sqlserver_comment_ddl("dbo", "users", None, &[], &indexes);
-
- assert!(ddl.contains("@level2type=N'INDEX', @level2name=N'IX_users_email'"));
- assert!(ddl.contains("@value=N'Unique email index'"));
- }
-
- #[test]
- fn sqlserver_comment_ddl_skips_empty_comments() {
- let ddl = render_sqlserver_comment_ddl("dbo", "users", Some(""), &[], &[]);
- assert!(ddl.is_empty());
-
- let ddl = render_sqlserver_comment_ddl("dbo", "users", None, &[], &[]);
- assert!(ddl.is_empty());
- }
-
- #[test]
- fn sqlserver_comment_ddl_escapes_single_quotes() {
- let ddl = render_sqlserver_comment_ddl("dbo", "users", Some("User's table for 'admin'"), &[], &[]);
-
- assert!(ddl.contains("@value=N'User''s table for ''admin'''"));
- }
}
pub async fn mysql_ddl(pool: &db::mysql::MySqlPool, table: &str) -> Result<String, String> {
@@ -1596,7 +1904,7 @@ pub async fn pg_ddl(pool: &deadpool_postgres::Pool, schema: &str, table: &str) -
Ok(render_postgres_table_ddl(schema, table, &columns, &indexes, &fkeys))
}
-fn render_postgres_table_ddl(
+pub fn render_postgres_table_ddl(
schema: &str,
table: &str,
columns: &[db::ColumnInfo],
@@ -1683,7 +1991,6 @@ pub async fn build_sqlserver_ddl(
let columns = db::sqlserver::get_columns(client, schema, table).await?;
let indexes = db::sqlserver::list_indexes(client, schema, table).await?;
let fkeys = db::sqlserver::list_foreign_keys(client, schema, table).await?;
- let table_comment = db::sqlserver::get_table_comment(client, schema, table).await?;
let mut ddl = format!("CREATE TABLE [{schema}].[{table}] (\n");
let col_lines: Vec<String> = columns
@@ -1735,61 +2042,5 @@ pub async fn build_sqlserver_ddl(
idx.name
));
}
-
- let comment_ddl = render_sqlserver_comment_ddl(schema, table, table_comment.as_deref(), &columns, &indexes);
- if !comment_ddl.is_empty() {
- ddl.push('\n');
- ddl.push_str(comment_ddl.trim_end());
- }
-
Ok(ddl)
}
-
-fn render_sqlserver_comment_ddl(
- schema: &str,
- table: &str,
- table_comment: Option<&str>,
- columns: &[db::ColumnInfo],
- indexes: &[db::IndexInfo],
-) -> String {
- let mut ddl = String::new();
- let escaped_schema = schema.replace('\'', "''");
- let escaped_table = table.replace('\'', "''");
-
- if let Some(comment) = table_comment.filter(|s| !s.is_empty()) {
- let escaped_comment = comment.replace('\'', "''");
- ddl.push_str(&format!(
- "EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'{escaped_comment}', \
- @level0type=N'SCHEMA', @level0name=N'{escaped_schema}', \
- @level1type=N'TABLE', @level1name=N'{escaped_table}';\n"
- ));
- }
-
- for col in columns {
- if let Some(comment) = col.comment.as_deref().filter(|s| !s.is_empty()) {
- let escaped_comment = comment.replace('\'', "''");
- let escaped_col = col.name.replace('\'', "''");
- ddl.push_str(&format!(
- "EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'{escaped_comment}', \
- @level0type=N'SCHEMA', @level0name=N'{escaped_schema}', \
- @level1type=N'TABLE', @level1name=N'{escaped_table}', \
- @level2type=N'COLUMN', @level2name=N'{escaped_col}';\n"
- ));
- }
- }
-
- for idx in indexes {
- if let Some(comment) = idx.comment.as_deref().filter(|s| !s.is_empty()) {
- let escaped_comment = comment.replace('\'', "''");
- let escaped_idx = idx.name.replace('\'', "''");
- ddl.push_str(&format!(
- "EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'{escaped_comment}', \
- @level0type=N'SCHEMA', @level0name=N'{escaped_schema}', \
- @level1type=N'TABLE', @level1name=N'{escaped_table}', \
- @level2type=N'INDEX', @level2name=N'{escaped_idx}';\n"
- ));
- }
- }
-
- ddl
-}
diff --git a/crates/dbx-core/src/schema_diff.rs b/crates/dbx-core/src/schema_diff.rs
index 989bad6e5c..b69e28902e 100644
--- a/crates/dbx-core/src/schema_diff.rs
+++ b/crates/dbx-core/src/schema_diff.rs
@@ -3,7 +3,9 @@ use std::collections::{HashMap, HashSet};
use serde::{Deserialize, Serialize};
use crate::models::connection::DatabaseType;
-use crate::types::{ColumnInfo, ForeignKeyInfo, IndexInfo, TableInfo, TriggerInfo};
+use crate::types::{
+ ColumnInfo, ForeignKeyInfo, FunctionInfo, IndexInfo, OwnerInfo, RuleInfo, SequenceInfo, TableInfo, TriggerInfo,
+};
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
@@ -61,6 +63,62 @@ pub struct TriggerDiff {
pub changes: Vec<String>,
}
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct FunctionDiff {
+ #[serde(rename = "type")]
+ pub diff_type: String,
+ pub name: String,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub source: Option<FunctionInfo>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub target: Option<FunctionInfo>,
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub changes: Vec<String>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct SequenceDiff {
+ #[serde(rename = "type")]
+ pub diff_type: String,
+ pub name: String,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub source: Option<SequenceInfo>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub target: Option<SequenceInfo>,
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub changes: Vec<String>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct RuleDiff {
+ #[serde(rename = "type")]
+ pub diff_type: String,
+ pub name: String,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub source: Option<RuleInfo>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub target: Option<RuleInfo>,
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub changes: Vec<String>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct OwnerDiff {
+ #[serde(rename = "type")]
+ pub diff_type: String,
+ pub object_name: String,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub source: Option<OwnerInfo>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub target: Option<OwnerInfo>,
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub changes: Vec<String>,
+}
+
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TableDiff {
@@ -80,6 +138,8 @@ pub struct TableDiff {
#[serde(skip_serializing_if = "Option::is_none")]
pub ddl: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
+ pub target_ddl: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
pub source_table_comment: Option<Option<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub target_table_comment: Option<Option<String>>,
@@ -112,24 +172,63 @@ pub struct SchemaDiffPreparationOptions {
pub source_details: Vec<TableSchemaDetail>,
#[serde(default)]
pub target_details: Vec<TableSchemaDetail>,
+ #[serde(default)]
+ pub source_functions: Vec<FunctionInfo>,
+ #[serde(default)]
+ pub target_functions: Vec<FunctionInfo>,
+ #[serde(default)]
+ pub source_sequences: Vec<SequenceInfo>,
+ #[serde(default)]
+ pub target_sequences: Vec<SequenceInfo>,
+ #[serde(default)]
+ pub source_rules: Vec<RuleInfo>,
+ #[serde(default)]
+ pub target_rules: Vec<RuleInfo>,
+ #[serde(default)]
+ pub source_owners: Vec<OwnerInfo>,
+ #[serde(default)]
+ pub target_owners: Vec<OwnerInfo>,
pub database_type: DatabaseType,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub target_schema: Option<String>,
#[serde(default)]
pub ignore_comments: bool,
+ #[serde(default)]
+ pub cascade_delete: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SchemaDiffPreparation {
pub diffs: Vec<TableDiff>,
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub function_diffs: Vec<FunctionDiff>,
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub sequence_diffs: Vec<SequenceDiff>,
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub rule_diffs: Vec<RuleDiff>,
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub owner_diffs: Vec<OwnerDiff>,
pub sync_sql: String,
}
pub fn prepare_schema_diff(options: SchemaDiffPreparationOptions) -> SchemaDiffPreparation {
let diffs = diff_schema(&options);
- let sync_sql = generate_schema_sync_sql(&diffs, options.database_type, options.target_schema.as_deref());
- SchemaDiffPreparation { diffs, sync_sql }
+ let function_diffs = diff_functions(&options.source_functions, &options.target_functions);
+ let sequence_diffs = diff_sequences(&options.source_sequences, &options.target_sequences);
+ let rule_diffs = diff_rules(&options.source_rules, &options.target_rules);
+ let owner_diffs = diff_owners(&options.source_owners, &options.target_owners);
+ let sync_sql = generate_schema_sync_sql(
+ &diffs,
+ &function_diffs,
+ &sequence_diffs,
+ &rule_diffs,
+ &owner_diffs,
+ options.database_type,
+ options.target_schema.as_deref(),
+ options.cascade_delete,
+ );
+ SchemaDiffPreparation { diffs, function_diffs, sequence_diffs, rule_diffs, owner_diffs, sync_sql }
}
fn diff_schema(options: &SchemaDiffPreparationOptions) -> Vec<TableDiff> {
@@ -176,6 +275,7 @@ fn diff_schema(options: &SchemaDiffPreparationOptions) -> Vec<TableDiff> {
diff_type: "added".to_string(),
object_type: Some("table".to_string()),
ddl: source_details.get(name.as_str()).and_then(|detail| detail.ddl.clone()),
+ target_ddl: None,
name,
columns: None,
indexes: None,
@@ -187,6 +287,7 @@ fn diff_schema(options: &SchemaDiffPreparationOptions) -> Vec<TableDiff> {
}
for name in removed {
+ let name_clone = name.clone();
result.push(TableDiff {
diff_type: "removed".to_string(),
object_type: Some("table".to_string()),
@@ -196,12 +297,14 @@ fn diff_schema(options: &SchemaDiffPreparationOptions) -> Vec<TableDiff> {
foreign_keys: None,
triggers: None,
ddl: None,
+ target_ddl: target_details.get(name_clone.as_str()).and_then(|detail| detail.ddl.clone()),
source_table_comment: None,
target_table_comment: None,
});
}
for name in added_views {
+ let name_clone = name.clone();
result.push(TableDiff {
diff_type: "added".to_string(),
object_type: Some("view".to_string()),
@@ -210,13 +313,15 @@ fn diff_schema(options: &SchemaDiffPreparationOptions) -> Vec<TableDiff> {
indexes: None,
foreign_keys: None,
triggers: None,
- ddl: None,
+ ddl: source_details.get(name_clone.as_str()).and_then(|detail| detail.ddl.clone()),
+ target_ddl: None,
source_table_comment: None,
target_table_comment: None,
});
}
for name in removed_views {
+ let name_clone = name.clone();
result.push(TableDiff {
diff_type: "removed".to_string(),
object_type: Some("view".to_string()),
@@ -226,6 +331,7 @@ fn diff_schema(options: &SchemaDiffPreparationOptions) -> Vec<TableDiff> {
foreign_keys: None,
triggers: None,
ddl: None,
+ target_ddl: target_details.get(name_clone.as_str()).and_then(|detail| detail.ddl.clone()),
source_table_comment: None,
target_table_comment: None,
});
@@ -243,27 +349,29 @@ fn diff_schema(options: &SchemaDiffPreparationOptions) -> Vec<TableDiff> {
let comment_changed = !options.ignore_comments
&& source_comment.clone().unwrap_or_default() != target_comment.clone().unwrap_or_default();
- if !column_diffs.is_empty()
+ let has_diff = !column_diffs.is_empty()
|| !index_diffs.is_empty()
|| !foreign_key_diffs.is_empty()
|| !trigger_diffs.is_empty()
- || comment_changed
- {
- result.push(TableDiff {
- diff_type: "modified".to_string(),
- object_type: Some("table".to_string()),
- name,
- columns: (!column_diffs.is_empty()).then_some(column_diffs),
- indexes: (!index_diffs.is_empty()).then_some(index_diffs),
- foreign_keys: (!foreign_key_diffs.is_empty()).then_some(foreign_key_diffs),
- triggers: (!trigger_diffs.is_empty()).then_some(trigger_diffs),
- ddl: None,
- source_table_comment: comment_changed.then_some(source_comment),
- target_table_comment: comment_changed.then_some(target_comment),
- });
- }
+ || comment_changed;
+
+ let name_clone = name.clone();
+ result.push(TableDiff {
+ diff_type: if has_diff { "modified".to_string() } else { "none".to_string() },
+ object_type: Some("table".to_string()),
+ name,
+ columns: if has_diff { (!column_diffs.is_empty()).then_some(column_diffs) } else { None },
+ indexes: if has_diff { (!index_diffs.is_empty()).then_some(index_diffs) } else { None },
+ foreign_keys: if has_diff { (!foreign_key_diffs.is_empty()).then_some(foreign_key_diffs) } else { None },
+ triggers: if has_diff { (!trigger_diffs.is_empty()).then_some(trigger_diffs) } else { None },
+ ddl: source_details.get(name_clone.as_str()).and_then(|detail| detail.ddl.clone()),
+ target_ddl: target_details.get(name_clone.as_str()).and_then(|detail| detail.ddl.clone()),
+ source_table_comment: if has_diff { comment_changed.then_some(source_comment) } else { None },
+ target_table_comment: if has_diff { comment_changed.then_some(target_comment) } else { None },
+ });
}
+ result.retain(|diff| diff.diff_type != "none");
result
}
@@ -563,6 +671,220 @@ fn is_mysql_like(db_type: DatabaseType) -> bool {
)
}
+/// Normalize a function definition for comparison by:
+/// - Converting CRLF to LF
+/// - Collapsing all whitespace (tabs, multiple spaces) to single spaces
+/// - Trimming each line and rejoining
+fn normalize_definition(def: &str) -> String {
+ def.replace("\r\n", "\n")
+ .split('\n')
+ .map(|line| line.split_whitespace().collect::<Vec<_>>().join(" "))
+ .collect::<Vec<_>>()
+ .join("\n")
+}
+
+pub fn diff_functions(source: &[FunctionInfo], target: &[FunctionInfo]) -> Vec<FunctionDiff> {
+ let mut diffs = Vec::new();
+ // Use (name, arguments) as key to support PostgreSQL function overloading
+ let target_map: HashMap<(&str, &str), &FunctionInfo> =
+ target.iter().map(|f| ((f.name.as_str(), f.arguments.as_str()), f)).collect();
+ let source_map: HashMap<(&str, &str), &FunctionInfo> =
+ source.iter().map(|f| ((f.name.as_str(), f.arguments.as_str()), f)).collect();
+
+ for source_fn in source {
+ let key = (source_fn.name.as_str(), source_fn.arguments.as_str());
+ let Some(target_fn) = target_map.get(&key) else {
+ diffs.push(FunctionDiff {
+ diff_type: "added".to_string(),
+ name: source_fn.name.clone(),
+ source: Some(source_fn.clone()),
+ target: None,
+ changes: Vec::new(),
+ });
+ continue;
+ };
+
+ let mut changes = Vec::new();
+ if source_fn.function_type != target_fn.function_type {
+ changes.push(format!("type: {} → {}", target_fn.function_type, source_fn.function_type));
+ }
+ if source_fn.data_type != target_fn.data_type {
+ changes.push(format!("return type: {} → {}", target_fn.data_type, source_fn.data_type));
+ }
+ if normalize_definition(&source_fn.definition) != normalize_definition(&target_fn.definition) {
+ changes.push("definition changed".to_string());
+ }
+ if !changes.is_empty() {
+ diffs.push(FunctionDiff {
+ diff_type: "modified".to_string(),
+ name: source_fn.name.clone(),
+ source: Some(source_fn.clone()),
+ target: Some((*target_fn).clone()),
+ changes,
+ });
+ }
+ }
+
+ for target_fn in target {
+ let key = (target_fn.name.as_str(), target_fn.arguments.as_str());
+ if !source_map.contains_key(&key) {
+ diffs.push(FunctionDiff {
+ diff_type: "removed".to_string(),
+ name: target_fn.name.clone(),
+ source: None,
+ target: Some(target_fn.clone()),
+ changes: Vec::new(),
+ });
+ }
+ }
+
+ diffs
+}
+
+pub fn diff_sequences(source: &[SequenceInfo], target: &[SequenceInfo]) -> Vec<SequenceDiff> {
+ let mut diffs = Vec::new();
+ let target_map: HashMap<&str, &SequenceInfo> = target.iter().map(|s| (s.name.as_str(), s)).collect();
+ let source_map: HashMap<&str, &SequenceInfo> = source.iter().map(|s| (s.name.as_str(), s)).collect();
+
+ for source_seq in source {
+ let Some(target_seq) = target_map.get(source_seq.name.as_str()) else {
+ diffs.push(SequenceDiff {
+ diff_type: "added".to_string(),
+ name: source_seq.name.clone(),
+ source: Some(source_seq.clone()),
+ target: None,
+ changes: Vec::new(),
+ });
+ continue;
+ };
+
+ let mut changes = Vec::new();
+ if source_seq.data_type != target_seq.data_type {
+ changes.push(format!("data_type: {} → {}", target_seq.data_type, source_seq.data_type));
+ }
+ if source_seq.start_value != target_seq.start_value {
+ changes.push(format!("start: {} → {}", target_seq.start_value, source_seq.start_value));
+ }
+ if source_seq.min_value != target_seq.min_value {
+ changes.push(format!("min: {} → {}", target_seq.min_value, source_seq.min_value));
+ }
+ if source_seq.max_value != target_seq.max_value {
+ changes.push(format!("max: {} → {}", target_seq.max_value, source_seq.max_value));
+ }
+ if source_seq.increment != target_seq.increment {
+ changes.push(format!("increment: {} → {}", target_seq.increment, source_seq.increment));
+ }
+ if source_seq.cycle != target_seq.cycle {
+ changes.push(format!("cycle: {} → {}", target_seq.cycle, source_seq.cycle));
+ }
+ // Only compare last_value when both sides successfully retrieved it.
+ // Avoid false positives when one side lacks permission (returns None).
+ if let (Some(s), Some(t)) = (&source_seq.last_value, &target_seq.last_value) {
+ if s != t {
+ changes.push(format!("last_value: {} → {}", t, s));
+ }
+ }
+ if !changes.is_empty() {
+ diffs.push(SequenceDiff {
+ diff_type: "modified".to_string(),
+ name: source_seq.name.clone(),
+ source: Some(source_seq.clone()),
+ target: Some((*target_seq).clone()),
+ changes,
+ });
+ }
+ }
+
+ for target_seq in target {
+ if !source_map.contains_key(target_seq.name.as_str()) {
+ diffs.push(SequenceDiff {
+ diff_type: "removed".to_string(),
+ name: target_seq.name.clone(),
+ source: None,
+ target: Some(target_seq.clone()),
+ changes: Vec::new(),
+ });
+ }
+ }
+
+ diffs
+}
+
+pub fn diff_rules(source: &[RuleInfo], target: &[RuleInfo]) -> Vec<RuleDiff> {
+ let mut diffs = Vec::new();
+ let target_map: HashMap<&str, &RuleInfo> = target.iter().map(|r| (r.name.as_str(), r)).collect();
+ let source_map: HashMap<&str, &RuleInfo> = source.iter().map(|r| (r.name.as_str(), r)).collect();
+
+ for source_rule in source {
+ let Some(target_rule) = target_map.get(source_rule.name.as_str()) else {
+ diffs.push(RuleDiff {
+ diff_type: "added".to_string(),
+ name: source_rule.name.clone(),
+ source: Some(source_rule.clone()),
+ target: None,
+ changes: Vec::new(),
+ });
+ continue;
+ };
+
+ let mut changes = Vec::new();
+ if source_rule.definition != target_rule.definition {
+ changes.push("definition changed".to_string());
+ }
+ if !changes.is_empty() {
+ diffs.push(RuleDiff {
+ diff_type: "modified".to_string(),
+ name: source_rule.name.clone(),
+ source: Some(source_rule.clone()),
+ target: Some((*target_rule).clone()),
+ changes,
+ });
+ }
+ }
+
+ for target_rule in target {
+ if !source_map.contains_key(target_rule.name.as_str()) {
+ diffs.push(RuleDiff {
+ diff_type: "removed".to_string(),
+ name: target_rule.name.clone(),
+ source: None,
+ target: Some(target_rule.clone()),
+ changes: Vec::new(),
+ });
+ }
+ }
+
+ diffs
+}
+
+pub fn diff_owners(source: &[OwnerInfo], target: &[OwnerInfo]) -> Vec<OwnerDiff> {
+ let mut diffs = Vec::new();
+ let target_map: HashMap<&str, &OwnerInfo> = target.iter().map(|o| (o.object_name.as_str(), o)).collect();
+ let _source_map: HashMap<&str, &OwnerInfo> = source.iter().map(|o| (o.object_name.as_str(), o)).collect();
+
+ for source_owner in source {
+ let Some(target_owner) = target_map.get(source_owner.object_name.as_str()) else {
+ continue; // skip added/removed objects, only compare owners for common objects
+ };
+
+ let mut changes = Vec::new();
+ if source_owner.owner != target_owner.owner {
+ changes.push(format!("owner: {} → {}", target_owner.owner, source_owner.owner));
+ }
+ if !changes.is_empty() {
+ diffs.push(OwnerDiff {
+ diff_type: "modified".to_string(),
+ object_name: source_owner.object_name.clone(),
+ source: Some(source_owner.clone()),
+ target: Some((*target_owner).clone()),
+ changes,
+ });
+ }
+ }
+
+ diffs
+}
+
fn quote_id(name: &str, db_type: DatabaseType) -> String {
if is_mysql_like(db_type) {
format!("`{}`", name.replace('`', "``"))
@@ -673,9 +995,9 @@ fn add_foreign_key_sql(table_name: &str, fk: &ForeignKeyInfo, db_type: DatabaseT
)
}
-fn drop_object_sql(diff: &TableDiff, db_type: DatabaseType, schema: Option<&str>) -> String {
+fn drop_object_sql(diff: &TableDiff, db_type: DatabaseType, schema: Option<&str>, cascade: &str) -> String {
let object_type = if diff.object_type.as_deref() == Some("view") { "VIEW" } else { "TABLE" };
- format!("DROP {object_type} IF EXISTS {};", qualified_name(&diff.name, db_type, schema))
+ format!("DROP {object_type} IF EXISTS {}{cascade};", qualified_name(&diff.name, db_type, schema))
}
fn comment_literal(comment: &str) -> String {
@@ -707,9 +1029,19 @@ fn table_comment_sql(table_name: &str, comment: &str, db_type: DatabaseType, sch
}
}
-pub fn generate_schema_sync_sql(diffs: &[TableDiff], db_type: DatabaseType, schema: Option<&str>) -> String {
+pub fn generate_schema_sync_sql(
+ diffs: &[TableDiff],
+ function_diffs: &[FunctionDiff],
+ sequence_diffs: &[SequenceDiff],
+ rule_diffs: &[RuleDiff],
+ owner_diffs: &[OwnerDiff],
+ db_type: DatabaseType,
+ schema: Option<&str>,
+ cascade_delete: bool,
+) -> String {
let mut lines = Vec::new();
let is_mysql = is_mysql_like(db_type);
+ let cascade = if cascade_delete { " CASCADE" } else { "" };
for diff in diffs {
let table = qualified_name(&diff.name, db_type, schema);
@@ -730,7 +1062,7 @@ pub fn generate_schema_sync_sql(diffs: &[TableDiff], db_type: DatabaseType, sche
if diff.diff_type == "removed" {
lines.push(format!("-- Drop {}: {}", diff.object_type.as_deref().unwrap_or("table"), diff.name));
- lines.push(drop_object_sql(diff, db_type, schema));
+ lines.push(drop_object_sql(diff, db_type, schema, cascade));
lines.push(String::new());
continue;
}
@@ -853,10 +1185,8 @@ pub fn generate_schema_sync_sql(diffs: &[TableDiff], db_type: DatabaseType, sche
if let Some(foreign_keys) = &diff.foreign_keys {
for fk in foreign_keys {
- if fk.diff_type == "added" || fk.diff_type == "modified" {
- if let Some(source) = fk.source.as_ref() {
- lines.push(add_foreign_key_sql(&diff.name, source, db_type, schema));
- }
+ if (fk.diff_type == "added" || fk.diff_type == "modified") && fk.source.is_some() {
+ lines.push(add_foreign_key_sql(&diff.name, fk.source.as_ref().unwrap(), db_type, schema));
}
}
}
@@ -885,6 +1215,148 @@ pub fn generate_schema_sync_sql(diffs: &[TableDiff], db_type: DatabaseType, sche
}
}
+ // Function diffs
+ if !function_diffs.is_empty() {
+ lines.push(String::new());
+ lines.push("-- Functions".to_string());
+ for diff in function_diffs {
+ match diff.diff_type.as_str() {
+ "added" => {
+ if let Some(source) = &diff.source {
+ lines.push(format!("-- Create function: {}", diff.name));
+ lines.push(format!(
+ "CREATE OR REPLACE FUNCTION {} {};",
+ qualified_name(&diff.name, db_type, schema),
+ source.definition
+ ));
+ }
+ }
+ "removed" => {
+ lines.push(format!("-- Drop function: {}", diff.name));
+ lines.push(format!(
+ "DROP FUNCTION IF EXISTS {}{cascade};",
+ qualified_name(&diff.name, db_type, schema)
+ ));
+ }
+ "modified" => {
+ if let Some(source) = &diff.source {
+ lines.push(format!("-- Alter function: {}", diff.name));
+ lines.push(format!(
+ "CREATE OR REPLACE FUNCTION {} {};",
+ qualified_name(&diff.name, db_type, schema),
+ source.definition
+ ));
+ }
+ }
+ _ => {}
+ }
+ }
+ }
+
+ // Sequence diffs
+ if !sequence_diffs.is_empty() {
+ lines.push(String::new());
+ lines.push("-- Sequences".to_string());
+ for diff in sequence_diffs {
+ match diff.diff_type.as_str() {
+ "added" => {
+ if let Some(source) = &diff.source {
+ lines.push(format!("-- Create sequence: {}", diff.name));
+ lines.push(format!(
+ "CREATE SEQUENCE {} AS {} START WITH {} INCREMENT BY {} MINVALUE {} MAXVALUE {} {};",
+ qualified_name(&diff.name, db_type, schema),
+ source.data_type,
+ source.start_value,
+ source.increment,
+ source.min_value,
+ source.max_value,
+ if source.cycle { "CYCLE" } else { "NO CYCLE" }
+ ));
+ }
+ }
+ "removed" => {
+ lines.push(format!("-- Drop sequence: {}", diff.name));
+ lines.push(format!("DROP SEQUENCE {}{cascade};", qualified_name(&diff.name, db_type, schema)));
+ }
+ "modified" => {
+ if let Some(source) = &diff.source {
+ lines.push(format!("-- Alter sequence: {}", diff.name));
+ lines.push(format!(
+ "ALTER SEQUENCE {} AS {} START WITH {} INCREMENT BY {} MINVALUE {} MAXVALUE {} {};",
+ qualified_name(&diff.name, db_type, schema),
+ source.data_type,
+ source.start_value,
+ source.increment,
+ source.min_value,
+ source.max_value,
+ if source.cycle { "CYCLE" } else { "NO CYCLE" }
+ ));
+ }
+ }
+ _ => {}
+ }
+ }
+ }
+
+ // Rule diffs
+ if !rule_diffs.is_empty() {
+ lines.push(String::new());
+ lines.push("-- Rules".to_string());
+ for diff in rule_diffs {
+ match diff.diff_type.as_str() {
+ "added" => {
+ if let Some(source) = &diff.source {
+ lines.push(format!("-- Create rule: {}", diff.name));
+ lines.push(source.definition.clone());
+ }
+ }
+ "removed" => {
+ lines.push(format!("-- Drop rule: {}", diff.name));
+ if let Some(source) = &diff.source {
+ lines.push(format!(
+ "DROP RULE IF EXISTS {} ON {};",
+ diff.name,
+ qualified_name(&source.table_name, db_type, schema)
+ ));
+ }
+ }
+ "modified" => {
+ if let Some(source) = &diff.source {
+ lines.push(format!("-- Alter rule: {}", diff.name));
+ lines.push(format!(
+ "DROP RULE IF EXISTS {} ON {};",
+ diff.name,
+ qualified_name(&source.table_name, db_type, schema)
+ ));
+ lines.push(source.definition.clone());
+ }
+ }
+ _ => {}
+ }
+ }
+ }
+
+ // Owner diffs
+ if !owner_diffs.is_empty() {
+ lines.push(String::new());
+ lines.push("-- Owners".to_string());
+ for diff in owner_diffs {
+ if let (Some(source), Some(_target)) = (&diff.source, &diff.target) {
+ let object_type = match source.object_type.as_str() {
+ "TABLE" => "TABLE",
+ "VIEW" => "VIEW",
+ "SEQUENCE" => "SEQUENCE",
+ _ => "TABLE",
+ };
+ lines.push(format!(
+ "ALTER {object_type} {} OWNER TO {};",
+ qualified_name(&diff.object_name, db_type, schema),
+ source.owner
+ ));
+ }
+ }
+ }
+
lines.join("\n").trim().to_string()
}
@@ -912,8 +1384,8 @@ mod tests {
ref_schema: overrides.ref_schema,
ref_table: if overrides.ref_table.is_empty() { "users".to_string() } else { overrides.ref_table },
ref_column: if overrides.ref_column.is_empty() { "id".to_string() } else { overrides.ref_column },
- on_update: None,
- on_delete: None,
+ on_update: overrides.on_update,
+ on_delete: overrides.on_delete,
}
}
@@ -1058,12 +1530,13 @@ mod tests {
}]),
triggers: None,
ddl: None,
+ target_ddl: None,
source_table_comment: None,
target_table_comment: None,
}];
assert_eq!(
- generate_schema_sync_sql(&diffs, DatabaseType::Postgres, None),
+ generate_schema_sync_sql(&diffs, &[], &[], &[], &[], DatabaseType::Postgres, None, false),
[
"ALTER TABLE \"orders\" DROP CONSTRAINT \"orders_user_id_fk\";",
"DROP INDEX IF EXISTS \"idx_orders_status\";",
@@ -1091,12 +1564,13 @@ mod tests {
foreign_keys: None,
triggers: None,
ddl: None,
+ target_ddl: None,
source_table_comment: Some(Some("用户表".to_string())),
target_table_comment: Some(Some("Users".to_string())),
}];
assert_eq!(
- generate_schema_sync_sql(&diffs, DatabaseType::Mysql, None),
+ generate_schema_sync_sql(&diffs, &[], &[], &[], &[], DatabaseType::Mysql, None, false),
[
"-- Alter table: users",
"ALTER TABLE `users`",
@@ -1141,9 +1615,18 @@ mod tests {
triggers: Vec::new(),
ddl: None,
}],
+ source_functions: Vec::new(),
+ target_functions: Vec::new(),
+ source_sequences: Vec::new(),
+ target_sequences: Vec::new(),
+ source_rules: Vec::new(),
+ target_rules: Vec::new(),
+ source_owners: Vec::new(),
+ target_owners: Vec::new(),
database_type: DatabaseType::Mysql,
target_schema: None,
ignore_comments: true,
+ cascade_delete: false,
};
let result = prepare_schema_diff(options);
@@ -1194,12 +1677,13 @@ mod tests {
foreign_keys: None,
triggers: None,
ddl: None,
+ target_ddl: None,
source_table_comment: None,
target_table_comment: None,
}];
assert_eq!(
- generate_schema_sync_sql(&diffs, DatabaseType::Postgres, Some("sales")),
+ generate_schema_sync_sql(&diffs, &[], &[], &[], &[], DatabaseType::Postgres, Some("sales"), false),
[
"-- Alter table: orders",
"ALTER TABLE \"sales\".\"orders\" ADD COLUMN \"status\" text;",
diff --git a/crates/dbx-core/src/types.rs b/crates/dbx-core/src/types.rs
index ad318387eb..ed41247ee4 100644
--- a/crates/dbx-core/src/types.rs
+++ b/crates/dbx-core/src/types.rs
@@ -116,3 +116,43 @@ pub struct TriggerInfo {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub statement: Option<String>,
}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct FunctionInfo {
+ pub name: String,
+ pub function_type: String,
+ pub data_type: String,
+ pub definition: String,
+ pub arguments: String,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct SequenceInfo {
+ pub name: String,
+ pub data_type: String,
+ pub start_value: String,
+ pub min_value: String,
+ pub max_value: String,
+ pub increment: String,
+ pub cycle: bool,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub last_value: Option<String>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct RuleInfo {
+ pub name: String,
+ pub table_name: String,
+ pub definition: String,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct OwnerInfo {
+ pub object_name: String,
+ pub object_type: String,
+ pub owner: String,
+}
diff --git a/crates/dbx-web/src/main.rs b/crates/dbx-web/src/main.rs
index 50df7aa7db..7eafe763f3 100644
--- a/crates/dbx-web/src/main.rs
+++ b/crates/dbx-web/src/main.rs
@@ -145,6 +145,10 @@ async fn main() {
.route("/schema/indexes", get(routes::schema::list_indexes))
.route("/schema/foreign-keys", get(routes::schema::list_foreign_keys))
.route("/schema/triggers", get(routes::schema::list_triggers))
+ .route("/schema/functions", get(routes::schema::list_functions))
+ .route("/schema/sequences", get(routes::schema::list_sequences))
+ .route("/schema/rules", get(routes::schema::list_rules))
+ .route("/schema/owners", get(routes::schema::list_owners))
.route("/schema/ddl", get(routes::schema::get_ddl))
.route("/schema-diff/prepare", post(routes::schema_diff::prepare_schema_diff))
.route("/schema-diff/generate-sync-sql", post(routes::schema_diff::generate_schema_sync_sql))
diff --git a/crates/dbx-web/src/routes/schema.rs b/crates/dbx-web/src/routes/schema.rs
index 49c5647611..2a54c93c7f 100644
--- a/crates/dbx-web/src/routes/schema.rs
+++ b/crates/dbx-web/src/routes/schema.rs
@@ -16,7 +16,6 @@ pub struct SchemaQuery {
pub filter: Option<String>,
pub limit: Option<usize>,
pub object_type: Option<dbx_core::db::ObjectSourceKind>,
- pub object_types: Option<String>,
}
pub async fn list_databases(
@@ -61,17 +60,11 @@ pub async fn list_objects(
) -> Result<Json<serde_json::Value>, AppError> {
let database = q.database.as_deref().unwrap_or("");
let schema = q.schema.as_deref().unwrap_or("");
- let object_types = q.object_types.as_deref().map(parse_object_types).filter(|types| !types.is_empty());
- let result = dbx_core::schema::list_objects_core(&state.app, &q.connection_id, database, schema, object_types)
- .await
- .map_err(AppError)?;
+ let result =
+ dbx_core::schema::list_objects_core(&state.app, &q.connection_id, database, schema).await.map_err(AppError)?;
Ok(Json(serde_json::to_value(result).map_err(|e| AppError(e.to_string()))?))
}
-fn parse_object_types(value: &str) -> Vec<String> {
- value.split(',').map(str::trim).filter(|value| !value.is_empty()).map(ToString::to_string).collect()
-}
-
pub async fn list_completion_objects(
State(state): State<Arc<WebState>>,
Query(q): Query<SchemaQuery>,
@@ -163,3 +156,63 @@ pub async fn get_ddl(
.map_err(AppError)?;
Ok(Json(result))
}
+
+pub async fn list_functions(
+ State(state): State<Arc<WebState>>,
+ Query(q): Query<SchemaQuery>,
+) -> Result<Json<serde_json::Value>, AppError> {
+ let database = q.database.as_deref().unwrap_or("");
+ let schema = q.schema.as_deref().unwrap_or("");
+ let result = dbx_core::schema::list_functions_core(&state.app, &q.connection_id, database, schema)
+ .await
+ .map_err(AppError)?;
+ Ok(Json(serde_json::to_value(result).map_err(|e| AppError(e.to_string()))?))
+}
+
+#[derive(Deserialize)]
+pub struct SequenceQuery {
+ pub connection_id: String,
+ pub database: Option<String>,
+ pub schema: Option<String>,
+ pub with_last_values: Option<bool>,
+}
+
+pub async fn list_sequences(
+ State(state): State<Arc<WebState>>,
+ Query(q): Query<SequenceQuery>,
+) -> Result<Json<serde_json::Value>, AppError> {
+ let database = q.database.as_deref().unwrap_or("");
+ let schema = q.schema.as_deref().unwrap_or("");
+ let result = dbx_core::schema::list_sequences_core(
+ &state.app,
+ &q.connection_id,
+ database,
+ schema,
+ q.with_last_values.unwrap_or(false),
+ )
+ .await
+ .map_err(AppError)?;
+ Ok(Json(serde_json::to_value(result).map_err(|e| AppError(e.to_string()))?))
+}
+
+pub async fn list_rules(
+ State(state): State<Arc<WebState>>,
+ Query(q): Query<SchemaQuery>,
+) -> Result<Json<serde_json::Value>, AppError> {
+ let database = q.database.as_deref().unwrap_or("");
+ let schema = q.schema.as_deref().unwrap_or("");
+ let result =
+ dbx_core::schema::list_rules_core(&state.app, &q.connection_id, database, schema).await.map_err(AppError)?;
+ Ok(Json(serde_json::to_value(result).map_err(|e| AppError(e.to_string()))?))
+}
+
+pub async fn list_owners(
+ State(state): State<Arc<WebState>>,
+ Query(q): Query<SchemaQuery>,
+) -> Result<Json<serde_json::Value>, AppError> {
+ let database = q.database.as_deref().unwrap_or("");
+ let schema = q.schema.as_deref().unwrap_or("");
+ let result =
+ dbx_core::schema::list_owners_core(&state.app, &q.connection_id, database, schema).await.map_err(AppError)?;
+ Ok(Json(serde_json::to_value(result).map_err(|e| AppError(e.to_string()))?))
+}
diff --git a/crates/dbx-web/src/routes/schema_diff.rs b/crates/dbx-web/src/routes/schema_diff.rs
index f8282d415a..97413e6dea 100644
--- a/crates/dbx-web/src/routes/schema_diff.rs
+++ b/crates/dbx-web/src/routes/schema_diff.rs
@@ -5,8 +5,13 @@ use serde::Deserialize;
#[serde(rename_all = "camelCase")]
pub struct GenerateSchemaSyncSqlRequest {
pub diffs: Vec<dbx_core::schema_diff::TableDiff>,
+ pub function_diffs: Option<Vec<dbx_core::schema_diff::FunctionDiff>>,
+ pub sequence_diffs: Option<Vec<dbx_core::schema_diff::SequenceDiff>>,
+ pub rule_diffs: Option<Vec<dbx_core::schema_diff::RuleDiff>>,
+ pub owner_diffs: Option<Vec<dbx_core::schema_diff::OwnerDiff>>,
pub database_type: dbx_core::models::connection::DatabaseType,
pub target_schema: Option<String>,
+ pub cascade_delete: Option<bool>,
}
pub async fn prepare_schema_diff(
@@ -16,5 +21,14 @@ pub async fn prepare_schema_diff(
}
pub async fn generate_schema_sync_sql(Json(req): Json<GenerateSchemaSyncSqlRequest>) -> Json<String> {
- Json(dbx_core::schema_diff::generate_schema_sync_sql(&req.diffs, req.database_type, req.target_schema.as_deref()))
+ Json(dbx_core::schema_diff::generate_schema_sync_sql(
+ &req.diffs,
+ req.function_diffs.as_deref().unwrap_or_default(),
+ req.sequence_diffs.as_deref().unwrap_or_default(),
+ req.rule_diffs.as_deref().unwrap_or_default(),
+ req.owner_diffs.as_deref().unwrap_or_default(),
+ req.database_type,
+ req.target_schema.as_deref(),
+ req.cascade_delete.unwrap_or(false),
+ ))
}
diff --git a/package.json b/package.json
index eeb1e5e60b..b0a3af637d 100644
--- a/package.json
+++ b/package.json
@@ -55,6 +55,7 @@
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"codemirror": "^6.0.2",
+ "diff": "^9.0.0",
"dom-to-image-more": "^3.7.2",
"echarts": "^6.1.0",
"leaflet": "^1.9.4",
@@ -73,6 +74,7 @@
"vue-virtual-scroller": "^3.0.4"
},
"devDependencies": {
+ "@lezer/highlight": "^1.2.3",
"@oxfmt/binding-darwin-arm64": "0.53.0",
"@oxlint/binding-darwin-arm64": "1.68.0",
"@tailwindcss/vite": "^4.3.0",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index f4a24b47d9..ce6f0845be 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -98,6 +98,9 @@ importers:
codemirror:
specifier: ^6.0.2
version: 6.0.2
+ diff:
+ specifier: ^9.0.0
+ version: 9.0.0
dom-to-image-more:
specifier: ^3.7.2
version: 3.7.2
@@ -1013,56 +1016,48 @@ packages:
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
- libc: [glibc]
resolution: {integrity: sha512-I6bhOTroqc3ThrwZ89l2k3ivKuELhdPLbAcJhRNyjWvlgwb0vjRgEnVL1XLx5Jud04/ypNRZBykAWrSk6l/D+g==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
- libc: [musl]
resolution: {integrity: sha512-w0p3JzB/PkkQjXALMJMqP9YfP3yq4w6zGsu5kezQmUnxRkN3b/Theg2l/nDgBsOcczxS3gL6Gam5XNAVrO6QJQ==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [ppc64]
os: [linux]
- libc: [glibc]
resolution: {integrity: sha512-mzBhF6k1Yq1K/dqDmVe/AAafnlJfEpx7yfUiksyeWXJk5iSzZqBSxcsa02zIytYgQFRZ7h6WPZfwHg/DoOE1Kw==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [riscv64]
os: [linux]
- libc: [glibc]
resolution: {integrity: sha512-AlFCpnRQhogQFzZXWbO6xB6/Udy745L+eQNmDPGg7G/OeWsYmJc4jZYfUN5pQg0reOPWSED2mOQqKZOJM1U8cA==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [riscv64]
os: [linux]
- libc: [musl]
resolution: {integrity: sha512-XD4ulY4f1DWbuuZXAqxhVn+gdPmrhnmojWtFN78ctVoupmS845fGhsUrk1HZXKQI+iymbaiz9vAjPsghHNQ7Ag==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [s390x]
os: [linux]
- libc: [glibc]
resolution: {integrity: sha512-xg8KWX0QnxmYWRe60CgHYWXI0ZOtBbqTsXvWiWrcl2XUHJ3fht2QerOk2iWvylzX3zNT2GpvBRxGoR4d3sxPRQ==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
- libc: [glibc]
resolution: {integrity: sha512-MWExpYBGvl+pIvVB/gj/CcWlN2al8AizT7rUbtaYaWNoQkhWARM6W3qpgoCr72CYSN9PborzPmM5MIRe2BrNdA==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
- libc: [musl]
resolution: {integrity: sha512-u4sajgO4nxgmJIgc/y2AqPhkdbOkQH8WugXpA1+pW0ESQhvGZ1oGq61Q4xMbJHJU1hFgtO18QNrcFYDPYH0gwQ==}
@@ -1135,56 +1130,48 @@ packages:
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
- libc: [glibc]
'@oxlint/[email protected]':
resolution: {integrity: sha512-qVKtCZNic+OoNnOr/hCQAu22HSQzflI7Fsq/Blzkw02SnLuv163k3kfmrVpZjSBlUHgsRKj6WgQiw30d3SX02Q==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
- libc: [musl]
'@oxlint/[email protected]':
resolution: {integrity: sha512-zExyZ8ZOUuAyQ0y9jpTcyjKUz62YY9JhKPyVxzvjTpXzZ3ujdqiVwfPWDdnA1SsIOrxdtxHn7KErDHLWskFjXg==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [ppc64]
os: [linux]
- libc: [glibc]
'@oxlint/[email protected]':
resolution: {integrity: sha512-6C4MPuwewyDavA7sxM14wzgRi5GGL68HPIxRCdVyS75U4MDbpFVYzKO9WNR6KLKTMPq2pcz3THwo1sK2uiqngw==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [riscv64]
os: [linux]
- libc: [glibc]
'@oxlint/[email protected]':
resolution: {integrity: sha512-bnZooVeHAcvA+dH0EDLgx+7HY/DRi6e0hFszg3P+OBatuUjV6EvfIyNIzWOusmqAVh4L6r21GGTZtiKE4iqM4Q==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [riscv64]
os: [linux]
- libc: [musl]
'@oxlint/[email protected]':
resolution: {integrity: sha512-dIqnZnJSmHCMOUpUcWQOiV14o3DDPVx1DSsMaSzvdhNjC1tB1iEPZbdiMSCIEYbkgbsYznHXWqFdKL8WUB3F8g==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [s390x]
os: [linux]
- libc: [glibc]
'@oxlint/[email protected]':
resolution: {integrity: sha512-zc9lEnfV/HreDTY6gdMlZe+irkwHSxQ4/B1pS9GyK7RVaA5LxhoZY/w6/o2vIwLLEYiXQ5ujGxOM1ZazeFAAIA==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
- libc: [glibc]
'@oxlint/[email protected]':
resolution: {integrity: sha512-Dl5QEX0TCo/40Cdh1o1JdPS//+YiWqjC+Hrrya5OQmStZZr4svAFtdlqcpCrU9yq2Mo3vRVyO9B3h0dzD8s36Q==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
- libc: [musl]
'@oxlint/[email protected]':
resolution: {integrity: sha512-/qy6dOvi4S3/LeXq0l5BT5pRKPYA7oj3uKwJOAZOr5HRLL+HK6jdBynvWuXIA2wwfE01RzNYmbBdM7vwYx00sA==}
@@ -1245,42 +1232,36 @@ packages:
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
- libc: [glibc]
'@rolldown/[email protected]':
resolution: {integrity: sha512-VWkUHwWriDciit80wleYwKILoR/KMvxh/IdwS/paX+ZgpuRpCrKLUdadJbc0NpBEiyhpYawsJ73j9aCvOH+f7Q==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
- libc: [musl]
'@rolldown/[email protected]':
resolution: {integrity: sha512-5f1laC0SlIR0yDbFCd8acUhvJIag6N3zC5P7oUPN6wX0aOma+uKJ0wBDH5aq7I1PVI2ttTlhJwzwRIBnLiSGEg==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [ppc64]
os: [linux]
- libc: [glibc]
'@rolldown/[email protected]':
resolution: {integrity: sha512-Iq4ko0r4XsgbrF/LunNgHtAGLRRVE2kXonAXQ/MV0mC6jQpMOhW1SvtZja2EhC/kd05++bP78dsqBeIQyYJ6Yg==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [s390x]
os: [linux]
- libc: [glibc]
'@rolldown/[email protected]':
resolution: {integrity: sha512-B8m6tD5+/N5FeNQFbKlLA/2yVq9ycQP1SeedyEYYKWBNR3ZQbkvIUcNnDNM03lO1l5F2roiiFJGgvoLLyZXtSg==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
- libc: [glibc]
'@rolldown/[email protected]':
resolution: {integrity: sha512-pSdpdUJHkuCxun9LE7jvgUB9qsRgaiyNNCX7m/AvHTcq67AiT/Yhoxvw5zPfhrM8k/BfP8ce/hMOpthKDpEUow==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
- libc: [musl]
'@rolldown/[email protected]':
resolution: {integrity: sha512-OXXS3RKJgX2uLwM+gYyuH5omcH8fL1LJs96pZGgtetVCahON57+d4SJHzTgZiOjxgGkSnpXpOsWuPDGAKAigEg==}
@@ -1383,28 +1364,24 @@ packages:
engines: {node: '>= 20'}
cpu: [arm64]
os: [linux]
- libc: [glibc]
'@tailwindcss/[email protected]':
resolution: {integrity: sha512-Z6sukiQsngnWO+l39X4pPbiWT81IC+PLKF+PHxIlyZbGNb9MODfYlXEVlFvej5BOZInWX01kVyzeLvHsXhfczQ==}
engines: {node: '>= 20'}
cpu: [arm64]
os: [linux]
- libc: [musl]
'@tailwindcss/[email protected]':
resolution: {integrity: sha512-DRNdQRpSGzRGfARVuVkxvM8Q12nh19l4BF/G7zGA1oe+9wcC6saFBHTISrpIcKzhiXtSrlSrluCfvMuledoCTQ==}
engines: {node: '>= 20'}
cpu: [x64]
os: [linux]
- libc: [glibc]
'@tailwindcss/[email protected]':
resolution: {integrity: sha512-Z0IADbDo8bh6I7h2IQMx601AdXBLfFpEdUotft86evd/8ZPflZe9COPO8Q1vw+pfLWIUo9zN/JGZvwuAJqduqg==}
engines: {node: '>= 20'}
cpu: [x64]
os: [linux]
- libc: [musl]
'@tailwindcss/[email protected]':
resolution: {integrity: sha512-HNZGOUxEmElksYR7S6sC5jTeNGpobAsy9u7Gu0AskJ8/20FR9GqebUyB+HBcU/ax6BHuiuJi+Oda4B+YX6H1yA==}
@@ -1473,35 +1450,30 @@ packages:
engines: {node: '>= 10'}
cpu: [arm64]
os: [linux]
- libc: [glibc]
'@tauri-apps/[email protected]':
resolution: {integrity: sha512-X1rm0BERqAAggtYTESSgXrS3sz4Sb/OiPiz54UqISlXW+GkR3vNIGnsy/lejNmoXGVqri3Q53BCfQiclOIyRPw==}
engines: {node: '>= 10'}
cpu: [arm64]
os: [linux]
- libc: [musl]
'@tauri-apps/[email protected]':
resolution: {integrity: sha512-usbMLJbT3KtkOrBMDVeGYNM35aTHXx38SJSzTMSqqjeUIOQ+iVPjb2yAGNAE+KqmBbAx4FOFIyMeKXx2M/JKGQ==}
engines: {node: '>= 10'}
cpu: [riscv64]
os: [linux]
- libc: [glibc]
'@tauri-apps/[email protected]':
resolution: {integrity: sha512-Ru4gwJKPG0ctVGchRGpRup4Y4lW2SSfFnrbQcyHhCliKy4g8Qz97TrUgCur4CbWyAgKxvGh3SjrkA0LDYzDGiw==}
engines: {node: '>= 10'}
cpu: [x64]
os: [linux]
- libc: [glibc]
'@tauri-apps/[email protected]':
resolution: {integrity: sha512-eUm7T6clN1MMmNSRQ9gaWsQdyehQx2Gmn5hht/QUlqZQI/qcP2OJK5dnaxqwFzCr2HdsEo9ydxaqcS1oJzMvUw==}
engines: {node: '>= 10'}
cpu: [x64]
os: [linux]
- libc: [musl]
'@tauri-apps/[email protected]':
resolution: {integrity: sha512-HeeZW80jU+gVTOEX4X/hC6NVSAdDVXajwP5fxIZ/3z9WvUC7qrudX2GMTilYq6Dg0e0sk0XgsAJD1hZ5wPBXUA==}
@@ -2144,6 +2116,10 @@ packages:
resolution: {integrity: sha512-DPi0FmjiSU5EvQV0++GFDOJ9ASQUVFh5kD+OzOnYdi7n3Wpm9hWWGfB/O2blfHcMVTL5WkQXSnRiK9makhrcnw==}
engines: {node: '>=0.3.1'}
+ resolution: {integrity: sha512-svtcdpS8CgJyqAjEQIXdb3OjhFVVYjzGAPO8WGCmRbrml64SPw/jJD4GoE98aR7r25A0XcgrK3F02yw9R/vhQw==}
+ engines: {node: '>=0.3.1'}
+
resolution: {integrity: sha512-c68LpLbO+7kP/b1Hr1qs8/BJ09F5khZGTxqxZuhzxpmwJKOgRFHJWIb9/KmqnqHhLdO55aOxFH/EGBvUQbL/RQ==}
@@ -2745,28 +2721,24 @@ packages:
engines: {node: '>= 12.0.0'}
cpu: [arm64]
os: [linux]
- libc: [glibc]
resolution: {integrity: sha512-UpQkoenr4UJEzgVIYpI80lDFvRmPVg6oqboNHfoH4CQIfNA+HOrZ7Mo7KZP02dC6LjghPQJeBsvXhJod/wnIBg==}
engines: {node: '>= 12.0.0'}
cpu: [arm64]
os: [linux]
- libc: [musl]
resolution: {integrity: sha512-V7Qr52IhZmdKPVr+Vtw8o+WLsQJYCTd8loIfpDaMRWGUZfBOYEJeyJIkqGIDMZPwPx24pUMfwSxxI8phr/MbOA==}
engines: {node: '>= 12.0.0'}
cpu: [x64]
os: [linux]
- libc: [glibc]
resolution: {integrity: sha512-bYcLp+Vb0awsiXg/80uCRezCYHNg1/l3mt0gzHnWV9XP1W5sKa5/TCdGWaR/zBM2PeF/HbsQv/j2URNOiVuxWg==}
engines: {node: '>= 12.0.0'}
cpu: [x64]
os: [linux]
- libc: [musl]
resolution: {integrity: sha512-8SbC8BR40pS6baCM8sbtYDSwEVQd4JlFTOlaD3gWGHfThTcABnNDBda6eTZeqbofalIJhFx0qKzgHJmcPTnGdw==}
@@ -5639,6 +5611,8 @@ snapshots:
+
diff --git a/src-tauri/src/commands/schema.rs b/src-tauri/src/commands/schema.rs
index 9b4c197e69..54e1df9966 100644
--- a/src-tauri/src/commands/schema.rs
+++ b/src-tauri/src/commands/schema.rs
@@ -39,9 +39,8 @@ pub async fn list_objects(
connection_id: String,
database: String,
schema: String,
- object_types: Option<Vec<String>>,
) -> Result<Vec<db::ObjectInfo>, String> {
- dbx_core::schema::list_objects_core(&state, &connection_id, &database, &schema, object_types).await
+ dbx_core::schema::list_objects_core(&state, &connection_id, &database, &schema).await
}
#[tauri::command]
@@ -120,3 +119,44 @@ pub async fn get_table_ddl(
) -> Result<String, String> {
dbx_core::schema::get_table_ddl_core(&state, &connection_id, &database, &schema, &table).await
}
+
+#[tauri::command]
+pub async fn list_functions(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ database: String,
+ schema: String,
+) -> Result<Vec<db::FunctionInfo>, String> {
+ dbx_core::schema::list_functions_core(&state, &connection_id, &database, &schema).await
+}
+
+#[tauri::command]
+pub async fn list_sequences(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ database: String,
+ schema: String,
+ with_last_values: bool,
+) -> Result<Vec<db::SequenceInfo>, String> {
+ dbx_core::schema::list_sequences_core(&state, &connection_id, &database, &schema, with_last_values).await
+}
+
+#[tauri::command]
+pub async fn list_rules(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ database: String,
+ schema: String,
+) -> Result<Vec<db::RuleInfo>, String> {
+ dbx_core::schema::list_rules_core(&state, &connection_id, &database, &schema).await
+}
+
+#[tauri::command]
+pub async fn list_owners(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ database: String,
+ schema: String,
+) -> Result<Vec<db::OwnerInfo>, String> {
+ dbx_core::schema::list_owners_core(&state, &connection_id, &database, &schema).await
+}
diff --git a/src-tauri/src/commands/schema_diff.rs b/src-tauri/src/commands/schema_diff.rs
index 5d8adba9b1..da490b2893 100644
--- a/src-tauri/src/commands/schema_diff.rs
+++ b/src-tauri/src/commands/schema_diff.rs
@@ -8,8 +8,22 @@ pub fn prepare_schema_diff(
#[tauri::command]
pub fn generate_schema_sync_sql(
diffs: Vec<dbx_core::schema_diff::TableDiff>,
+ function_diffs: Option<Vec<dbx_core::schema_diff::FunctionDiff>>,
+ sequence_diffs: Option<Vec<dbx_core::schema_diff::SequenceDiff>>,
+ rule_diffs: Option<Vec<dbx_core::schema_diff::RuleDiff>>,
+ owner_diffs: Option<Vec<dbx_core::schema_diff::OwnerDiff>>,
database_type: dbx_core::models::connection::DatabaseType,
target_schema: Option<String>,
+ cascade_delete: Option<bool>,
) -> Result<String, String> {
- Ok(dbx_core::schema_diff::generate_schema_sync_sql(&diffs, database_type, target_schema.as_deref()))
+ Ok(dbx_core::schema_diff::generate_schema_sync_sql(
+ &diffs,
+ function_diffs.as_deref().unwrap_or_default(),
+ sequence_diffs.as_deref().unwrap_or_default(),
+ rule_diffs.as_deref().unwrap_or_default(),
+ owner_diffs.as_deref().unwrap_or_default(),
+ database_type,
+ target_schema.as_deref(),
+ cascade_delete.unwrap_or(false),
+ ))
}
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index ac40d114a6..0d128aeeaf 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -369,6 +369,10 @@ pub fn run() {
commands::schema::list_foreign_keys,
commands::schema::list_triggers,
commands::schema::get_table_ddl,
+ commands::schema::list_functions,
+ commands::schema::list_sequences,
+ commands::schema::list_rules,
+ commands::schema::list_owners,
commands::schema_diff::prepare_schema_diff,
commands::schema_diff::generate_schema_sync_sql,
commands::schema_cache::save_schema_cache,