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。
TypeScript aicliclickhousedatabasedatabase-clientdatabase-managementdockerguimcpmongodbmysqlpostgresqlredisrustsql-serversqlitetaurivue
feat(backup): support exact table selection by database and schema
zipg312673cadf80
diff --git a/apps/desktop/src/components/backup/BackupTableSelector.vue b/apps/desktop/src/components/backup/BackupTableSelector.vuenew file mode 100644index 0000000000..77b398ec5a--- /dev/null+++ b/apps/desktop/src/components/backup/BackupTableSelector.vue@@ -0,0 +1,128 @@+<script setup lang="ts">+import { computed, onBeforeUnmount, ref, watch } from "vue";+import { useI18n } from "vue-i18n";+import * as api from "@/lib/backend/api";+import { Button } from "@/components/ui/button";+import TableMultiSelect from "@/components/diff/TableMultiSelect.vue";+import { databaseBackupTableSelectionScopeKey, databaseBackupTableTargetKey, type DatabaseBackupTableTarget, type DatabaseBackupTableSelectionState } from "@/lib/backup/scheduledDatabaseBackup";++const props = defineProps<{+ connectionId: string;+ databaseType?: string;+ databases: string[];+ modelValue: DatabaseBackupTableTarget[];+}>();+const emit = defineEmits<{+ "update:modelValue": [value: DatabaseBackupTableTarget[]];+ stateChange: [value: DatabaseBackupTableSelectionState];+}>();+const { t } = useI18n();+const tables = ref<DatabaseBackupTableTarget[]>([]);+const loading = ref(false);+const loadError = ref(false);+const loaded = ref(false);+const loadedScopeKey = ref("");+let generation = 0;+const scopeKey = computed(() => databaseBackupTableSelectionScopeKey(props.connectionId, props.databaseType, props.databases));+const available = computed(() => new Map(tables.value.map((target) => [databaseBackupTableTargetKey(target), target])));+const selectedKeys = computed(() => props.modelValue.map(databaseBackupTableTargetKey));+const missing = computed(() => (loaded.value && !loadError.value ? props.modelValue.filter((target) => !available.value.has(databaseBackupTableTargetKey(target))) : []));+const labels = computed(() => Object.fromEntries(tables.value.map((target) => [databaseBackupTableTargetKey(target), label(target)])));+const searchValues = computed(() => Object.fromEntries(tables.value.map((target) => [databaseBackupTableTargetKey(target), [target.database, target.schema, target.table].join(".")])));+const ready = computed(() => loadedScopeKey.value === scopeKey.value && loaded.value && !loading.value && !loadError.value && props.databases.length > 0 && props.modelValue.length > 0 && missing.value.length === 0);+watch(+ () => ({ scopeKey: scopeKey.value, ready: ready.value }),+ (state) => emit("stateChange", state),+ { immediate: true, flush: "sync" },+);++function label(target: DatabaseBackupTableTarget): string {+ // Quoting each part makes names containing dots unambiguous in the picker.+ const parts = props.databaseType === "mysql" ? [target.database, target.table] : [target.database, target.schema, target.table];+ const quote = props.databaseType === "mysql" ? "`" : '"';+ return parts.map((part) => `${quote}${part.replaceAll(quote, quote + quote)}${quote}`).join(".");+}++async function loadTables() {+ const current = ++generation;+ const requestedScopeKey = scopeKey.value;+ const connectionId = props.connectionId;+ const databaseType = props.databaseType;+ const databases = [...props.databases];+ tables.value = [];+ loaded.value = false;+ loadError.value = false;+ loading.value = !!connectionId && databases.length > 0;+ if (!connectionId || databases.length === 0) return;+ try {+ if (databaseType !== "mysql" && databaseType !== "postgres") throw new Error("Unsupported backup connection");+ const result = await Promise.all(+ databases.map(async (database) => {+ const schemas = databaseType === "mysql" ? [database] : (await api.listSchemas(connectionId, database)).filter((schema) => schema !== "information_schema" && !schema.startsWith("pg_"));+ const groups = await Promise.all(schemas.map(async (schema) => (await api.listTables(connectionId, database, schema)).map((table) => ({ database, schema, table: table.name }))));+ return groups.flat();+ }),+ );+ if (current !== generation) return;+ tables.value = [...new Map(result.flat().map((target) => [databaseBackupTableTargetKey(target), target])).values()].sort((left, right) => label(left).localeCompare(label(right)));+ loadedScopeKey.value = requestedScopeKey;+ loaded.value = true;+ } catch {+ if (current === generation) loadError.value = true;+ } finally {+ if (current === generation) loading.value = false;+ }+}++watch(+ scopeKey,+ (_next, previous) => {+ if (previous) {+ // Removing a database explicitly removes its selected tables too. A new+ // connection must never inherit a table selection from the prior source.+ const oldConnectionId = JSON.parse(previous)[0];+ const kept = oldConnectionId === props.connectionId ? props.modelValue.filter((target) => props.databases.includes(target.database)) : [];+ if (kept.length !== props.modelValue.length) emit("update:modelValue", kept);+ }+ void loadTables();+ },+ { immediate: true, flush: "sync" },+);++function selectKeys(keys: string[]) {+ if (loading.value || loadError.value) return;+ const previous = new Map(props.modelValue.map((target) => [databaseBackupTableTargetKey(target), target]));+ emit(+ "update:modelValue",+ keys.map((key) => available.value.get(key) ?? previous.get(key)).filter((target): target is DatabaseBackupTableTarget => !!target),+ );+}+function removeMissing(target: DatabaseBackupTableTarget) {+ emit(+ "update:modelValue",+ props.modelValue.filter((value) => databaseBackupTableTargetKey(value) !== databaseBackupTableTargetKey(target)),+ );+}+onBeforeUnmount(() => {+ generation += 1;+});+</script>++<template>+ <div class="space-y-2" data-backup-table-selector>+ <p v-if="databases.length === 0" class="text-xs text-muted-foreground">{{ t("databaseBackup.selectDatabasesForTables") }}</p>+ <template v-else>+ <div class="flex items-center justify-between gap-2">+ <Button type="button" variant="outline" size="sm" :disabled="loading" @click="loadTables">{{ t("common.refresh") }}</Button>+ <Button type="button" variant="ghost" size="sm" :disabled="modelValue.length === 0" @click="emit('update:modelValue', [])">{{ t("common.clear") }}</Button>+ </div>+ <p v-if="loading" class="text-xs text-muted-foreground">{{ t("common.loading") }}</p>+ <p v-if="loadError" class="text-xs text-destructive">{{ t("databaseBackup.tableListLoadFailed") }}</p>+ <TableMultiSelect :tables="[...available.keys()]" :labels="labels" :search-values="searchValues" :model-value="selectedKeys" :disabled="loading || loadError" @update:model-value="selectKeys" />+ <div v-if="missing.length" class="space-y-1 text-xs text-destructive">+ <p>{{ t("databaseBackup.selectedTablesUnavailable") }}</p>+ <button v-for="target in missing" :key="databaseBackupTableTargetKey(target)" type="button" class="block text-left underline" :aria-label="`${t('common.remove')}: ${label(target)}`" @click="removeMissing(target)">{{ label(target) }} · {{ t("common.remove") }}</button>+ </div>+ </template>+ </div>+</template>diff --git a/apps/desktop/src/components/backup/DatabaseBackupConfigFields.vue b/apps/desktop/src/components/backup/DatabaseBackupConfigFields.vueindex 416eee9be8..f044c76ff3 100644--- a/apps/desktop/src/components/backup/DatabaseBackupConfigFields.vue+++ b/apps/desktop/src/components/backup/DatabaseBackupConfigFields.vue@@ -12,11 +12,13 @@ import { Check, ChevronDown, FolderOpen, Loader2, Search } from "@lucide/vue";import ConnectionGroupBadge from "@/components/connection/ConnectionGroupBadge.vue";import { databaseBackupFileNamePatternIsValid, type DatabaseBackupExecutionConfig } from "@/lib/backup/scheduledDatabaseBackup";import type { ConnectionConfig } from "@/types/database";+import BackupTableSelector from "./BackupTableSelector.vue";+import type { DatabaseBackupTableSelectionState } from "@/lib/backup/scheduledDatabaseBackup";const props = withDefaults(defineProps<{draft: DatabaseBackupExecutionConfig;- connections: Array<Pick<ConnectionConfig, "id" | "name">>;+ connections: Array<Pick<ConnectionConfig, "id" | "name"> & Partial<Pick<ConnectionConfig, "db_type">>>;allDatabases: boolean;selectedDatabases: string[];databaseOptions: string[];@@ -34,6 +36,7 @@ const emit = defineEmits<{changeConnection: [connectionId: string];chooseDestination: [];toggleDatabase: [database: string];+ tableSelectionState: [state: DatabaseBackupTableSelectionState];"update:allDatabases": [value: boolean];"update:tablePatternsInput": [value: string];"update:runDirectoryPattern": [value: string];@@ -47,6 +50,7 @@ const connectionPickerTrigger = ref<ComponentPublicInstance | null>(null);const connectionPickerWidth = ref<number>();const selectedConnectionName = computed(() => props.connections.find((connection) => connection.id === props.draft.connectionId)?.name || props.draft.connectionId);+const selectedConnectionType = computed(() => props.connections.find((connection) => connection.id === props.draft.connectionId)?.db_type);const filteredConnections = computed(() => {const query = connectionSearch.value.trim().toLocaleLowerCase();if (!query) return props.connections;@@ -234,15 +238,25 @@ watch(<SelectItem value="all">{{ t("databaseBackup.allTables") }}</SelectItem><SelectItem value="include">{{ t("databaseBackup.includeTables") }}</SelectItem><SelectItem value="exclude">{{ t("databaseBackup.excludeTables") }}</SelectItem>+ <SelectItem value="selected">{{ t("databaseBackup.exactTables") }}</SelectItem></SelectContent></Select></div>- <div v-if="draft.tableFilterMode !== 'all'" class="space-y-2">+ <div v-if="draft.tableFilterMode === 'include' || draft.tableFilterMode === 'exclude'" class="space-y-2"><Label>{{ t("databaseBackup.tablePatterns") }}</Label><Input :model-value="tablePatternsInput" :placeholder="t('databaseBackup.tablePatternsPlaceholder')" @update:model-value="(value: any) => emit('update:tablePatternsInput', String(value))" /></div></div>- <p v-if="draft.tableFilterMode !== 'all'" class="text-xs text-muted-foreground">{{ t("databaseBackup.tablePatternsHint") }}</p>+ <p v-if="draft.tableFilterMode === 'include' || draft.tableFilterMode === 'exclude'" class="text-xs text-muted-foreground">{{ t("databaseBackup.tablePatternsHint") }}</p>+ <BackupTableSelector+ v-if="draft.tableFilterMode === 'selected'"+ :connection-id="draft.connectionId"+ :database-type="selectedConnectionType"+ :databases="allDatabases ? [] : selectedDatabases"+ :model-value="draft.selectedTables ?? []"+ @update:model-value="(value) => (draft.selectedTables = value)"+ @state-change="(state) => emit('tableSelectionState', state)"+ /></div><div class="space-y-3">diff --git a/apps/desktop/src/components/backup/ScheduledDatabaseBackupSettings.vue b/apps/desktop/src/components/backup/ScheduledDatabaseBackupSettings.vueindex 032b42b714..efaaddee36 100644--- a/apps/desktop/src/components/backup/ScheduledDatabaseBackupSettings.vue+++ b/apps/desktop/src/components/backup/ScheduledDatabaseBackupSettings.vue@@ -32,6 +32,7 @@ import {type DatabaseBackupRun,type DatabaseBackupSchedule,} from "@/lib/backup/scheduledDatabaseBackup";+import { databaseBackupTableSelectionScopeKey, normalizeDatabaseBackupTableTargets, type DatabaseBackupTableSelectionState } from "@/lib/backup/scheduledDatabaseBackup";import { useConnectionStore } from "@/stores/connectionStore";import { fetchNamespaceOptionsForConnection } from "@/composables/useDatabaseOptions";@@ -85,6 +86,27 @@ const databaseOptions = ref<string[]>([]);const allDatabases = ref(true);const selectedDatabases = ref<string[]>([]);const tablePatternsInput = ref("");+const scheduleTableSelectionState = ref<DatabaseBackupTableSelectionState>({ scopeKey: "", ready: false });+const oneShotTableSelectionState = ref<DatabaseBackupTableSelectionState>({ scopeKey: "", ready: false });+function tableScopeReady(config: DatabaseBackupExecutionConfig, state: DatabaseBackupTableSelectionState): boolean {+ if (config.tableFilterMode !== "selected") return config.tableFilterMode === "all" || normalizeDatabaseBackupTablePatterns(tablePatternsInput.value).length > 0;+ const targets = config.selectedTables ?? [];+ return (+ !allDatabases.value &&+ selectedDatabases.value.length > 0 &&+ targets.length > 0 &&+ targets.every((target) => selectedDatabases.value.includes(target.database)) &&+ state.ready &&+ state.scopeKey === databaseBackupTableSelectionScopeKey(config.connectionId, connectionStore.getConfig(config.connectionId)?.db_type, selectedDatabases.value)+ );+}+function backupTablePayload(config: DatabaseBackupExecutionConfig) {+ return {+ tablePatterns: config.tableFilterMode === "include" || config.tableFilterMode === "exclude" ? normalizeDatabaseBackupTablePatterns(tablePatternsInput.value) : [],+ // Override any inactive selection carried by the draft before JSON serialization.+ selectedTables: config.tableFilterMode === "selected" ? normalizeDatabaseBackupTableTargets(config.selectedTables) : undefined,+ };+}const expandedRunIds = reactive(new Set<string>());const selectedRunIds = reactive(new Set<string>());const historyConnectionId = ref("");@@ -187,7 +209,7 @@ function databaseLoadIsCurrent(generation: number, dialog: BackupDialogKind, tarconst canSave = computed(() => {const hasContent = draft.value.includeStructure || draft.value.includeData || draft.value.includeObjects;const hasDatabaseScope = allDatabases.value || selectedDatabases.value.length > 0;- const hasTableScope = draft.value.tableFilterMode === "all" || normalizeDatabaseBackupTablePatterns(tablePatternsInput.value).length > 0;+ const hasTableScope = tableScopeReady(draft.value, scheduleTableSelectionState.value);return (!!draft.value.name.trim() &&!!draft.value.connectionId &&@@ -236,7 +258,7 @@ const oneShotOutputPathPreview = computed(() => {const canStartOneShot = computed(() => {const hasContent = oneShotDraft.value.includeStructure || oneShotDraft.value.includeData || oneShotDraft.value.includeObjects;const hasDatabaseScope = allDatabases.value || selectedDatabases.value.length > 0;- const hasTableScope = oneShotDraft.value.tableFilterMode === "all" || normalizeDatabaseBackupTablePatterns(tablePatternsInput.value).length > 0;+ const hasTableScope = tableScopeReady(oneShotDraft.value, oneShotTableSelectionState.value);return !!oneShotDraft.value.connectionId && !!oneShotDraft.value.destinationDirectory.trim() && databaseBackupFileNamePatternIsValid(oneShotDraft.value.fileNamePattern || "") && hasContent && hasDatabaseScope && hasTableScope && !oneShotStarting.value && !loadingDatabases.value;});@@ -319,6 +341,7 @@ async function loadDatabases(dialog: BackupDialogKind, targetDraft: DatabaseBackallDatabases.value = true;targetDraft.tableFilterMode = "all";targetDraft.tablePatterns = [];+ targetDraft.selectedTables = [];tablePatternsInput.value = "";}if (!connectionId) {@@ -357,12 +380,15 @@ async function loadDatabases(dialog: BackupDialogKind, targetDraft: DatabaseBack}function resetDatabaseScope(targetDraft: DatabaseBackupExecutionConfig) {+ scheduleTableSelectionState.value = { scopeKey: "", ready: false };+ oneShotTableSelectionState.value = { scopeKey: "", ready: false };databaseOptions.value = [];databaseLoadError.value = "";allDatabases.value = true;selectedDatabases.value = [];targetDraft.tableFilterMode = "all";targetDraft.tablePatterns = [];+ targetDraft.selectedTables = [];tablePatternsInput.value = "";}@@ -376,6 +402,7 @@ async function openCreateSchedule() {}async function openEditSchedule(schedule: DatabaseBackupSchedule) {+ scheduleTableSelectionState.value = { scopeKey: "", ready: false };oneShotDialogOpen.value = false;editingScheduleId.value = schedule.id;draft.value = { ...schedule, databases: [...schedule.databases], tablePatterns: [...schedule.tablePatterns] };@@ -397,6 +424,7 @@ async function changeConnection(connectionId: string) {selectedDatabases.value = [];targetDraft.tableFilterMode = "all";targetDraft.tablePatterns = [];+ targetDraft.selectedTables = [];tablePatternsInput.value = "";if (!wasSelectingSpecificDatabases) {allDatabases.value = true;@@ -439,7 +467,7 @@ async function submitSchedule() {await saveSchedule({...draft.value,databases: allDatabases.value ? [] : [...selectedDatabases.value],- tablePatterns: draft.value.tableFilterMode === "all" ? [] : normalizeDatabaseBackupTablePatterns(tablePatternsInput.value),+ ...backupTablePayload(draft.value),});scheduleDialogOpen.value = false;toast(t(editingScheduleId.value ? "databaseBackup.scheduleUpdated" : "databaseBackup.scheduleCreated"), 2500);@@ -451,6 +479,7 @@ async function submitSchedule() {}async function openOneShotBackup() {+ oneShotTableSelectionState.value = { scopeKey: "", ready: false };scheduleDialogOpen.value = false;const nextDraft = newBackupConfig();oneShotDraft.value = nextDraft;@@ -467,7 +496,7 @@ async function startOneShotBackup() {{...oneShotDraft.value,databases: allDatabases.value ? [] : [...selectedDatabases.value],- tablePatterns: oneShotDraft.value.tableFilterMode === "all" ? [] : normalizeDatabaseBackupTablePatterns(tablePatternsInput.value),+ ...backupTablePayload(oneShotDraft.value),},t("databaseBackup.oneShotName"),);@@ -898,6 +927,7 @@ async function restoreBackup(run: DatabaseBackupRun, file: DatabaseBackupFile) {@toggle-database="toggleDatabase"@update:all-databases="setAllDatabases"@update:table-patterns-input="(value: string) => (tablePatternsInput = value)"+ @table-selection-state="(state) => (scheduleTableSelectionState = state)"@update:run-directory-pattern="(value: string) => (draft.runDirectoryPattern = value)"/>@@ -983,6 +1013,7 @@ async function restoreBackup(run: DatabaseBackupRun, file: DatabaseBackupFile) {@toggle-database="toggleDatabase"@update:all-databases="setAllDatabases"@update:table-patterns-input="(value: string) => (tablePatternsInput = value)"+ @table-selection-state="(state) => (oneShotTableSelectionState = state)"/><DialogFooter>diff --git a/apps/desktop/src/components/backup/__tests__/BackupTableSelector.spec.ts b/apps/desktop/src/components/backup/__tests__/BackupTableSelector.spec.tsnew file mode 100644index 0000000000..21b534635c--- /dev/null+++ b/apps/desktop/src/components/backup/__tests__/BackupTableSelector.spec.ts@@ -0,0 +1,144 @@+// @vitest-environment happy-dom+import { createApp, h, nextTick, reactive, ref } from "vue";+import { afterEach, describe, expect, it, vi } from "vitest";+import i18n from "@/i18n";+import BackupTableSelector from "../BackupTableSelector.vue";+import type { DatabaseBackupTableTarget, DatabaseBackupTableSelectionState } from "@/lib/backup/scheduledDatabaseBackup";++const apiMock = vi.hoisted(() => ({ listSchemas: vi.fn(), listTables: vi.fn() }));+vi.mock("@/lib/backend/api", () => apiMock);+const cleanups: Array<() => void> = [];+afterEach(() => {+ while (cleanups.length) cleanups.pop()?.();+ vi.resetAllMocks();+});+const settle = async () => {+ await new Promise((resolve) => setTimeout(resolve, 0));+ await nextTick();+};+function mount(initial: DatabaseBackupTableTarget[] = []) {+ const scope = reactive({ connectionId: "source", databaseType: "postgres", databases: ["app"] });+ const selection = ref(initial);+ const states: DatabaseBackupTableSelectionState[] = [];+ const container = document.createElement("div");+ document.body.append(container);+ const app = createApp({+ render: () =>+ h(BackupTableSelector, {+ ...scope,+ modelValue: selection.value,+ "onUpdate:modelValue": (value: DatabaseBackupTableTarget[]) => {+ selection.value = value;+ },+ onStateChange: (state: DatabaseBackupTableSelectionState) => states.push(state),+ }),+ });+ app.use(i18n);+ app.mount(container);+ cleanups.push(() => {+ app.unmount();+ container.remove();+ });+ return { scope, selection, states, container };+}+function button(container: HTMLElement, key: string) {+ return Array.from(container.querySelectorAll<HTMLButtonElement>("button")).find((value) => value.textContent?.trim() === i18n.global.t(key))!;+}++describe("exact backup table selection", () => {+ it("selects literal wildcard/comma/dot names with their database and schema", async () => {+ apiMock.listSchemas.mockResolvedValue(["public", "audit", "pg_catalog", "information_schema"]);+ apiMock.listTables.mockImplementation(async (_id, _db, schema) => (schema === "public" ? [{ name: "odd*,name.with.dot" }] : [{ name: "same" }]));+ const { container, selection, states } = mount();+ await settle();+ expect(apiMock.listTables).toHaveBeenCalledTimes(2);+ expect(states.at(-1)?.ready).toBe(false);+ const row = container.querySelector<HTMLButtonElement>("[data-table-name]")!;+ const target = JSON.parse(row.getAttribute("data-table-name")!);+ row.click();+ await settle();+ expect(selection.value).toEqual([{ database: target[0], schema: target[1], table: target[2] }]);+ expect(states.at(-1)?.ready).toBe(true);+ button(container, "tableMultiSelect.selectAll").click();+ await settle();+ expect(selection.value).toHaveLength(2);+ expect(selection.value).toContainEqual({ database: "app", schema: "public", table: "odd*,name.with.dot" });+ button(container, "common.clear").click();+ await settle();+ expect(selection.value).toEqual([]);+ expect(states.at(-1)?.ready).toBe(false);+ });++ it("searches raw identifier text even when labels quote it", async () => {+ apiMock.listSchemas.mockResolvedValue(["public"]);+ apiMock.listTables.mockResolvedValue([{ name: 'a"b' }, ...Array.from({ length: 5 }, (_, index) => ({ name: `plain${index}` }))]);+ const { container, selection } = mount();+ await settle();+ const search = container.querySelector<HTMLInputElement>("input")!;+ search.value = 'a"b';+ search.dispatchEvent(new Event("input", { bubbles: true }));+ await settle();+ const rows = container.querySelectorAll<HTMLButtonElement>("[data-table-name]");+ expect(rows).toHaveLength(1);+ rows[0].click();+ await settle();+ expect(selection.value).toEqual([{ database: "app", schema: "public", table: 'a"b' }]);+ });++ it("does not apply late metadata from a previous connection with the same database name", async () => {+ let resolveOld!: (rows: Array<{ name: string }>) => void;+ apiMock.listSchemas.mockResolvedValue(["public"]);+ apiMock.listTables.mockImplementation((id) =>+ id === "source"+ ? new Promise((resolve) => {+ resolveOld = resolve;+ })+ : Promise.resolve([{ name: "new_table" }]),+ );+ const { scope, selection, states, container } = mount([{ database: "app", schema: "public", table: "old_table" }]);+ await settle();+ scope.connectionId = "new-source";+ await settle();+ expect(selection.value).toEqual([]);+ expect(states.at(-1)?.ready).toBe(false);+ container.querySelector<HTMLButtonElement>("[data-table-name]")!.click();+ await settle();+ expect(selection.value).toEqual([{ database: "app", schema: "public", table: "new_table" }]);+ expect(states.at(-1)?.ready).toBe(true);+ resolveOld([{ name: "old_table" }]);+ await settle();+ expect(container.textContent).not.toContain("old_table");+ expect(selection.value[0].table).toBe("new_table");+ expect(JSON.parse(states.at(-1)!.scopeKey)[0]).toBe("new-source");+ });++ it("retains missing saved selections until explicitly removed and blocks execution", async () => {+ apiMock.listSchemas.mockResolvedValue(["public"]);+ apiMock.listTables.mockResolvedValue([{ name: "available" }]);+ const { container, selection, states } = mount([{ database: "app", schema: "public", table: "dropped" }]);+ await settle();+ expect(selection.value[0].table).toBe("dropped");+ expect(states.at(-1)?.ready).toBe(false);+ expect(container.textContent).toContain(i18n.global.t("databaseBackup.selectedTablesUnavailable"));+ container.querySelector<HTMLButtonElement>("button[aria-label]")!.click();+ await settle();+ expect(selection.value).toEqual([]);+ expect(states.at(-1)?.ready).toBe(false);+ container.querySelector<HTMLButtonElement>("[data-table-name]")!.click();+ await settle();+ expect(states.at(-1)?.ready).toBe(true);+ });++ it("blocks an unreadable catalog and clears selection without falling back to all tables", async () => {+ apiMock.listSchemas.mockRejectedValue(new Error("metadata unavailable"));+ const { container, selection, states } = mount([{ database: "app", schema: "public", table: "chosen" }]);+ await settle();+ expect(states.at(-1)?.ready).toBe(false);+ expect(container.textContent).toContain(i18n.global.t("databaseBackup.tableListLoadFailed"));+ expect(selection.value).toHaveLength(1);+ button(container, "common.clear").click();+ await settle();+ expect(selection.value).toEqual([]);+ expect(states.at(-1)?.ready).toBe(false);+ });+});diff --git a/apps/desktop/src/components/backup/__tests__/ScheduledDatabaseBackupSettings.spec.ts b/apps/desktop/src/components/backup/__tests__/ScheduledDatabaseBackupSettings.spec.tsindex b145949d75..3e04eb0e8b 100644--- a/apps/desktop/src/components/backup/__tests__/ScheduledDatabaseBackupSettings.spec.ts+++ b/apps/desktop/src/components/backup/__tests__/ScheduledDatabaseBackupSettings.spec.ts@@ -19,6 +19,8 @@ const mocks = vi.hoisted(() => ({ensureConnected: vi.fn(async () => {}),recordConnectionLostError: vi.fn(() => false),listDatabases: vi.fn(async (_connectionId: string) => [{ name: "app" }]),+ listSchemas: vi.fn(async () => ["public"]),+ listTables: vi.fn(async () => [{ name: "odd*,name.with.dot" }, { name: "unselected" }]),databaseExportDestinationNeedsConfirmation: vi.fn(async (_directory: string) => false),recordDatabaseExportDestination: vi.fn(async (_directory: string) => {}),openDirectory: vi.fn(async (): Promise<string | null> => "/backups"),@@ -96,6 +98,8 @@ vi.mock("@/lib/backend/api", () => ({databaseBackupBackground: vi.fn(async () => ({ enabled: false, platform: "windows" })),databaseBackupCommand: vi.fn(async () => "2026-09-13T02:00:00Z"),listDatabases: mocks.listDatabases,+ listSchemas: mocks.listSchemas,+ listTables: mocks.listTables,deleteDatabaseBackupFiles: vi.fn(),revealPathInFileManager: vi.fn(),databaseExportDestinationNeedsConfirmation: mocks.databaseExportDestinationNeedsConfirmation,@@ -288,6 +292,10 @@ afterEach(() => {mocks.recordConnectionLostError.mockReturnValue(false);mocks.listDatabases.mockReset();mocks.listDatabases.mockResolvedValue([{ name: "app" }]);+ mocks.listSchemas.mockReset();+ mocks.listSchemas.mockResolvedValue(["public"]);+ mocks.listTables.mockReset();+ mocks.listTables.mockResolvedValue([{ name: "odd*,name.with.dot" }, { name: "unselected" }]);mocks.databaseExportDestinationNeedsConfirmation.mockReset();mocks.databaseExportDestinationNeedsConfirmation.mockResolvedValue(false);mocks.recordDatabaseExportDestination.mockReset();@@ -599,6 +607,45 @@ describe("ScheduledDatabaseBackupSettings schedule dialog", () => {expect(mocks.runOneShot).toHaveBeenCalledWith(expect.objectContaining({ connectionId: "mysql-1", destinationDirectory: "/backups", databases: [] }), String(i18n.global.t("databaseBackup.oneShotName")));});+ it("sends an exact one-shot table whitelist and prevents an empty selection from starting", async () => {+ mocks.connections.push({ id: "pg-1", name: "Local PostgreSQL", db_type: "postgres" });+ await mountSettings();+ buttonWithText(String(i18n.global.t("databaseBackup.oneShotBackup"))).click();+ await flush();+ buttonWithTitle(String(i18n.global.t("databaseBackup.selectDestination"))).click();+ await flush();+ await showDatabaseOptions();+ const database = Array.from(currentDialog().querySelectorAll<HTMLInputElement>('input[type="checkbox"]')).find((item) => item.parentElement?.textContent?.trim() === "app")!;+ database.checked = true;+ database.dispatchEvent(new Event("change", { bubbles: true }));+ await flush();+ await selectDialogOption(0, String(i18n.global.t("databaseBackup.exactTables")));+ await flush();+ const start = Array.from(currentDialog().querySelectorAll<HTMLButtonElement>("button")).find((item) => item.textContent?.trim() === String(i18n.global.t("databaseBackup.startBackup")))!;+ expect(start.disabled).toBe(true);+ const row = currentDialog().querySelector<HTMLButtonElement>("[data-backup-table-selector] [data-table-name]")!;+ row.click();+ await flush();+ expect(start.disabled).toBe(false);+ buttonWithText(String(i18n.global.t("common.clear"))).click();+ await flush();+ expect(start.disabled).toBe(true);+ row.click();+ await flush();+ start.click();+ await flush();+ expect(mocks.runOneShot).toHaveBeenCalledWith(+ expect.objectContaining({+ connectionId: "pg-1",+ databases: ["app"],+ tableFilterMode: "selected",+ tablePatterns: [],+ selectedTables: [{ database: "app", schema: "public", table: "odd*,name.with.dot" }],+ }),+ String(i18n.global.t("databaseBackup.oneShotName")),+ );+ });+it("keeps the newer connection database list when an older response finishes last", async () => {mocks.connections.push({ id: "mysql-a", name: "MySQL A", db_type: "mysql" }, { id: "mysql-b", name: "MySQL B", db_type: "mysql" });const firstLoad = deferred<Array<{ name: string }>>();diff --git a/apps/desktop/src/components/diff/TableMultiSelect.vue b/apps/desktop/src/components/diff/TableMultiSelect.vueindex beb216f85a..f477973965 100644--- a/apps/desktop/src/components/diff/TableMultiSelect.vue+++ b/apps/desktop/src/components/diff/TableMultiSelect.vue@@ -16,6 +16,10 @@ const props = withDefaults(defineProps<{/** All available table names. */tables: string[];+ /** Optional display labels for opaque selection keys. */+ labels?: Record<string, string>;+ /** Plain text to search when display labels escape identifier characters. */+ searchValues?: Record<string, string>;/** Currently selected table names (v-model). */modelValue: string[];/** Optional header label; falls back to `tableMultiSelect.tables`. */@@ -42,7 +46,11 @@ const emit = defineEmits<{ (e: "update:modelValue", value: string[]): void }>();const { t } = useI18n();const search = ref("");-const filteredTables = computed(() => filterTableNames(props.tables, search.value));+const filteredTables = computed(() => {+ if (!props.labels) return filterTableNames(props.tables, search.value);+ const query = search.value.trim().toLocaleLowerCase();+ return props.tables.filter((key) => (props.searchValues?.[key] ?? props.labels?.[key] ?? key).toLocaleLowerCase().includes(query));+});const selectedSet = computed(() => new Set(props.modelValue));const allFilteredSelected = computed(() => isEveryFilteredSelected(props.modelValue, filteredTables.value));const showSearch = computed(() => props.searchable && props.tables.length > 5);@@ -82,7 +90,7 @@ function toggleSelectAll() {<button v-for="table in filteredTables" :key="table" type="button" :data-table-name="table" :disabled="disabled" class="flex w-full items-center gap-2 px-2.5 py-1.5 text-left text-xs hover:bg-muted/50 disabled:opacity-50" @click="toggle(table)"><CheckSquare v-if="selectedSet.has(table)" class="h-3.5 w-3.5 shrink-0 text-primary" /><Square v-else class="h-3.5 w-3.5 shrink-0 text-muted-foreground/40" />- <span class="truncate">{{ table }}</span>+ <span class="truncate" :title="labels?.[table] ?? table">{{ labels?.[table] ?? table }}</span></button></div></div>diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.tsindex 477f3e3786..c3cf9c1af2 100644--- a/apps/desktop/src/i18n/locales/en.ts+++ b/apps/desktop/src/i18n/locales/en.ts@@ -9632,6 +9632,10 @@ export default {tablePatterns: "Table name rules",tablePatternsPlaceholder: "orders, audit_*, public.users",tablePatternsHint: "Separate rules with commas. * and ? wildcards and schema.table are supported.",+ exactTables: "Select specific tables",+ selectDatabasesForTables: "Turn off “All databases” and select the databases to back up, then choose individual tables.",+ tableListLoadFailed: "Could not load the table list. Refresh to retry.",+ selectedTablesUnavailable: "Some selected tables are missing or unavailable. Refresh or remove these selections.",includedTablePatterns: "{count} include rules",excludedTablePatterns: "{count} exclude rules",frequency: "Frequency",diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.tsindex 11e0e56a1b..9fedc59015 100644--- a/apps/desktop/src/i18n/locales/es.ts+++ b/apps/desktop/src/i18n/locales/es.ts@@ -10754,6 +10754,10 @@ export default withEnglishFallback({tablePatterns: "Reglas de nombres de tabla",tablePatternsPlaceholder: "orders, audit_*, public.users",tablePatternsHint: "Separe las reglas con comas. Se admiten los comodines * y ? y schema.table.",+ exactTables: "Seleccionar tablas específicas",+ selectDatabasesForTables: "Desmarca «Todas las bases de datos» y selecciona las bases que quieres respaldar; después, elige las tablas.",+ tableListLoadFailed: "No se pudo cargar la lista de tablas. Actualiza para reintentarlo.",+ selectedTablesUnavailable: "Algunas tablas seleccionadas no existen o no están disponibles. Actualiza o elimina estas selecciones.",includedTablePatterns: "{count} reglas de inclusión",excludedTablePatterns: "{count} reglas de exclusión",frequency: "Frecuencia de ejecución",diff --git a/apps/desktop/src/i18n/locales/id.ts b/apps/desktop/src/i18n/locales/id.tsindex 1e82bfa4dc..8b0adf8452 100644--- a/apps/desktop/src/i18n/locales/id.ts+++ b/apps/desktop/src/i18n/locales/id.ts@@ -9475,6 +9475,10 @@ export default withEnglishFallback({tablePatterns: "Aturan nama tabel",tablePatternsPlaceholder: "orders, audit_*, public.users",tablePatternsHint: "Pisahkan aturan dengan koma. Wildcard * dan ? serta schema.table didukung.",+ exactTables: "Pilih tabel tertentu",+ selectDatabasesForTables: "Nonaktifkan “Semua database” dan pilih database yang ingin dicadangkan, lalu pilih tabel satu per satu.",+ tableListLoadFailed: "Daftar tabel tidak dapat dimuat. Segarkan untuk mencoba lagi.",+ selectedTablesUnavailable: "Beberapa tabel yang dipilih tidak ada atau tidak tersedia. Segarkan atau hapus pilihan tersebut.",includedTablePatterns: "{count} aturan sertakan",excludedTablePatterns: "{count} aturan kecualikan",frequency: "Frekuensi",diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.tsindex fd149f5c5f..871f332afc 100644--- a/apps/desktop/src/i18n/locales/it.ts+++ b/apps/desktop/src/i18n/locales/it.ts@@ -10322,6 +10322,10 @@ export default withEnglishFallback({tablePatterns: "Regole nomi tabella",tablePatternsPlaceholder: "orders, audit_*, public.users",tablePatternsHint: "Separa le regole con virgole. Sono supportati i caratteri jolly * e ? e schema.table.",+ exactTables: "Seleziona tabelle specifiche",+ selectDatabasesForTables: "Deseleziona «Tutti i database» e scegli i database da salvare, quindi seleziona le singole tabelle.",+ tableListLoadFailed: "Impossibile caricare l’elenco delle tabelle. Aggiorna per riprovare.",+ selectedTablesUnavailable: "Alcune tabelle selezionate non esistono o non sono disponibili. Aggiorna o rimuovi queste selezioni.",includedTablePatterns: "{count} regole di inclusione",excludedTablePatterns: "{count} regole di esclusione",frequency: "Frequenza",diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.tsindex 559a5848c5..6b7a965b4d 100644--- a/apps/desktop/src/i18n/locales/ja.ts+++ b/apps/desktop/src/i18n/locales/ja.ts@@ -10363,6 +10363,10 @@ export default withEnglishFallback({tablePatterns: "テーブル名ルール",tablePatternsPlaceholder: "orders, audit_*, public.users",tablePatternsHint: "ルールはカンマで区切ります。*、? ワイルドカードと schema.table を使用できます。",+ exactTables: "特定のテーブルを選択",+ selectDatabasesForTables: "「すべてのデータベース」を解除してバックアップするデータベースを選び、個別のテーブルを選択してください。",+ tableListLoadFailed: "テーブル一覧を読み込めませんでした。更新して再試行してください。",+ selectedTablesUnavailable: "選択したテーブルの一部が存在しないか、利用できません。更新するか、該当する選択を解除してください。",includedTablePatterns: "包含ルール {count} 件",excludedTablePatterns: "除外ルール {count} 件",frequency: "実行頻度",diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.tsindex 1ed7b95e84..685f355209 100644--- a/apps/desktop/src/i18n/locales/ko.ts+++ b/apps/desktop/src/i18n/locales/ko.ts@@ -8500,6 +8500,10 @@ export default withEnglishFallback({tablePatterns: "테이블 이름 규칙",tablePatternsPlaceholder: "orders, audit_*, public.users",tablePatternsHint: "규칙은 쉼표로 구분하세요. *와 ? 와일드카드 및 schema.table을 지원합니다.",+ exactTables: "특정 테이블 선택",+ selectDatabasesForTables: "‘모든 데이터베이스’를 해제하고 백업할 데이터베이스를 선택한 다음, 개별 테이블을 선택하세요.",+ tableListLoadFailed: "테이블 목록을 불러올 수 없습니다. 새로 고침 후 다시 시도하세요.",+ selectedTablesUnavailable: "선택한 일부 테이블이 없거나 사용할 수 없습니다. 새로 고침하거나 해당 선택을 제거하세요.",includedTablePatterns: "포함 규칙 {count}개",excludedTablePatterns: "제외 규칙 {count}개",frequency: "빈도",diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.tsindex 07d967a0da..077b6a00a1 100644--- a/apps/desktop/src/i18n/locales/pt-BR.ts+++ b/apps/desktop/src/i18n/locales/pt-BR.ts@@ -10322,6 +10322,10 @@ export default withEnglishFallback({tablePatterns: "Regras de nomes de tabela",tablePatternsPlaceholder: "orders, audit_*, public.users",tablePatternsHint: "Separe as regras com vírgulas. Há suporte a curingas * e ? e schema.table.",+ exactTables: "Selecionar tabelas específicas",+ selectDatabasesForTables: "Desmarque “Todos os bancos de dados” e escolha os bancos para o backup; depois, selecione as tabelas.",+ tableListLoadFailed: "Não foi possível carregar a lista de tabelas. Atualize para tentar novamente.",+ selectedTablesUnavailable: "Algumas tabelas selecionadas não existem ou não estão disponíveis. Atualize ou remova essas seleções.",includedTablePatterns: "{count} regras de inclusão",excludedTablePatterns: "{count} regras de exclusão",frequency: "Frequência",diff --git a/apps/desktop/src/i18n/locales/ru.ts b/apps/desktop/src/i18n/locales/ru.tsindex 2e855bc499..7015c3b92f 100644--- a/apps/desktop/src/i18n/locales/ru.ts+++ b/apps/desktop/src/i18n/locales/ru.ts@@ -10009,6 +10009,10 @@ export default withEnglishFallback({tablePatterns: "Правила имён таблиц",tablePatternsPlaceholder: "orders, audit_*, public.users",tablePatternsHint: "Разделяйте правила запятыми. Поддерживаются подстановочные знаки * и ?, а также schema.table.",+ exactTables: "Выбрать конкретные таблицы",+ selectDatabasesForTables: "Отключите «Все базы данных», выберите базы для резервного копирования, затем отметьте отдельные таблицы.",+ tableListLoadFailed: "Не удалось загрузить список таблиц. Обновите и повторите попытку.",+ selectedTablesUnavailable: "Некоторые выбранные таблицы отсутствуют или недоступны. Обновите список или снимите их выделение.",includedTablePatterns: "Правил включения: {count}",excludedTablePatterns: "Правил исключения: {count}",frequency: "Частота",diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.tsindex c15479637a..9a9dfdfe01 100644--- a/apps/desktop/src/i18n/locales/zh-CN.ts+++ b/apps/desktop/src/i18n/locales/zh-CN.ts@@ -9594,6 +9594,10 @@ export default withEnglishFallback({tablePatterns: "表名规则",tablePatternsPlaceholder: "例如:orders, audit_*, public.users",tablePatternsHint: "用逗号分隔规则,支持 *、? 通配符和 schema.table。",+ exactTables: "精确选择表",+ selectDatabasesForTables: "先取消“全部数据库”并选择需要备份的数据库,再勾选具体表。",+ tableListLoadFailed: "加载表列表失败,请刷新重试。",+ selectedTablesUnavailable: "部分已选表不存在或不可见,请刷新或移除这些选择。",includedTablePatterns: "包含 {count} 条表规则",excludedTablePatterns: "排除 {count} 条表规则",frequency: "执行频率",diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.tsindex eb13d2ddc7..c90559a342 100644--- a/apps/desktop/src/i18n/locales/zh-TW.ts+++ b/apps/desktop/src/i18n/locales/zh-TW.ts@@ -10328,6 +10328,10 @@ export default withEnglishFallback({tablePatterns: "資料表名稱規則",tablePatternsPlaceholder: "例如:orders, audit_*, public.users",tablePatternsHint: "請用逗號分隔規則,支援 *、? 萬用字元和 schema.table。",+ exactTables: "精確選取資料表",+ selectDatabasesForTables: "先取消「全部資料庫」並選取需要備份的資料庫,再勾選個別資料表。",+ tableListLoadFailed: "無法載入資料表清單,請重新整理後重試。",+ selectedTablesUnavailable: "部分已選資料表不存在或無法檢視,請重新整理或移除這些選取項目。",includedTablePatterns: "包含 {count} 條資料表規則",excludedTablePatterns: "排除 {count} 條資料表規則",frequency: "執行頻率",diff --git a/apps/desktop/src/lib/__tests__/backup/scheduledDatabaseBackup.spec.ts b/apps/desktop/src/lib/__tests__/backup/scheduledDatabaseBackup.spec.tsindex cc7921dc3f..9c09cdf2a1 100644--- a/apps/desktop/src/lib/__tests__/backup/scheduledDatabaseBackup.spec.ts+++ b/apps/desktop/src/lib/__tests__/backup/scheduledDatabaseBackup.spec.ts@@ -10,6 +10,10 @@ import {normalizeDatabaseBackupRun,resolveScheduledDatabaseBackupTableScope,type DatabaseBackupRun,+ normalizeDatabaseBackupTableTargets,+ databaseBackupTableTargetKey,+ normalizeDatabaseBackupSchedule,+ toDatabaseBackupExecutionConfig,} from "../../backup/scheduledDatabaseBackup";const startedAt = "2026-08-12T00:00:00.000Z";@@ -125,3 +129,22 @@ describe("database backup file name segment sanitization", () => {expect(sanitizeDatabaseBackupFileSegment("con_backup")).toBe("con_backup");});});++describe("exact backup target persistence", () => {+ it("keeps literal identifiers and distinguishes dotted schema and table names", () => {+ const first = { database: "app", schema: "a.b", table: " odd*,name' " };+ const second = { database: "app", schema: "a", table: "b. odd*,name' " };+ expect(databaseBackupTableTargetKey(first)).not.toBe(databaseBackupTableTargetKey(second));+ expect(normalizeDatabaseBackupTableTargets([first, first, second])).toEqual([first, second]);+ const plan = normalizeDatabaseBackupSchedule({ id: "exact", connectionId: "source", destinationDirectory: "/backups", tableFilterMode: "selected", databases: ["app"], selectedTables: [first, second] })!;+ expect(plan.tableFilterMode).toBe("selected");+ expect(toDatabaseBackupExecutionConfig(plan).selectedTables).toEqual([first, second]);+ });++ it("rejects a malformed selection instead of silently dropping part of backup coverage", () => {+ const valid = { database: "app", schema: "public", table: "chosen" };+ expect(() => normalizeDatabaseBackupTableTargets([valid, { database: "app", table: "broken" }])).toThrow();+ expect(normalizeDatabaseBackupSchedule({ id: "exact", connectionId: "source", destinationDirectory: "/backups", tableFilterMode: "selected", selectedTables: [valid, { table: "broken" }] })).toBeNull();+ expect(() => resolveScheduledDatabaseBackupTableScope("selected", [], ["chosen"])).toThrow();+ });+});diff --git a/apps/desktop/src/lib/backup/scheduledDatabaseBackup.ts b/apps/desktop/src/lib/backup/scheduledDatabaseBackup.tsindex c686260d34..26ed458f3b 100644--- a/apps/desktop/src/lib/backup/scheduledDatabaseBackup.ts+++ b/apps/desktop/src/lib/backup/scheduledDatabaseBackup.ts@@ -14,7 +14,7 @@ export type DatabaseBackupExportStatus = "Running" | "Done" | "Error" | "Cancellexport type DatabaseBackupRunStatus = "running" | "success" | "failed" | "cancelled";export type DatabaseBackupRunTrigger = "manual" | "scheduled";export type DatabaseBackupRunSource = "scheduled" | "one-shot";-export type DatabaseBackupTableFilterMode = "all" | "include" | "exclude";+export type DatabaseBackupTableFilterMode = "all" | "include" | "exclude" | "selected";export type DatabaseBackupOutputCompression = "none" | "gzip";const CONSISTENT_BACKUP_DATABASE_TYPES = new Set(["mysql", "postgres"]);@@ -98,6 +98,7 @@ export function databaseBackupTableNamesAreCaseSensitive(databaseType: DatabaseTexport function resolveScheduledDatabaseBackupTableScope(mode: DatabaseBackupTableFilterMode, patterns: readonly string[], availableTables: readonly string[], database = "", schema = "", caseSensitive = true): DatabaseBackupTableScope {const available = [...new Set(availableTables.map((table) => table.trim()).filter(Boolean))];if (mode === "all") return { includedTables: available };+ if (mode === "selected") throw new Error("Exact table selection requires database and schema identities");const normalizedPatterns = normalizeDatabaseBackupTablePatterns(patterns);const matching = available.filter((table) => databaseBackupTableMatchesPattern(table, normalizedPatterns, database, schema, caseSensitive));@@ -110,11 +111,50 @@ export function resolveScheduledDatabaseBackupTableScope(mode: DatabaseBackupTab};}+export interface DatabaseBackupTableTarget {+ database: string;+ schema: string;+ table: string;+}++export interface DatabaseBackupTableSelectionState {+ scopeKey: string;+ ready: boolean;+}++export function databaseBackupTableTargetKey(target: DatabaseBackupTableTarget): string {+ return JSON.stringify([target.database, target.schema, target.table]);+}++export function databaseBackupTableSelectionScopeKey(connectionId: string, databaseType: string | undefined, databases: readonly string[]): string {+ return JSON.stringify([connectionId, databaseType ?? "", [...new Set(databases)].sort()]);+}++export function normalizeDatabaseBackupTableTargets(value: unknown): DatabaseBackupTableTarget[] {+ if (value == null) return [];+ if (!Array.isArray(value)) throw new Error("Invalid selected backup tables");+ const result: DatabaseBackupTableTarget[] = [];+ const seen = new Set<string>();+ for (const entry of value) {+ if (!entry || typeof entry !== "object") throw new Error("Invalid selected backup table");+ const { database, schema, table } = entry as Record<string, unknown>;+ if (typeof database !== "string" || typeof schema !== "string" || typeof table !== "string" || !database.trim() || !schema.trim() || !table.trim()) throw new Error("Invalid selected backup table identity");+ const target = { database, schema, table };+ const key = databaseBackupTableTargetKey(target);+ if (!seen.has(key)) {+ seen.add(key);+ result.push(target);+ }+ }+ return result;+}+export interface DatabaseBackupExecutionConfig {connectionId: string;databases: string[];tableFilterMode: DatabaseBackupTableFilterMode;tablePatterns: string[];+ selectedTables?: DatabaseBackupTableTarget[];destinationDirectory: string;includeStructure: boolean;includeData: boolean;@@ -150,6 +190,7 @@ export function toDatabaseBackupExecutionConfig(schedule: DatabaseBackupScheduledatabases: [...schedule.databases],tableFilterMode: schedule.tableFilterMode,tablePatterns: [...schedule.tablePatterns],+ ...(schedule.tableFilterMode === "selected" ? { selectedTables: normalizeDatabaseBackupTableTargets(schedule.selectedTables) } : {}),destinationDirectory: schedule.destinationDirectory,includeStructure: schedule.includeStructure,includeData: schedule.includeData,@@ -238,6 +279,14 @@ export function normalizeDatabaseBackupSchedule(value: unknown, now = new Date()const destinationDirectory = stringValue(input.destinationDirectory).trim();if (!id || !connectionId || !destinationDirectory) return null;+ let selectedTables: DatabaseBackupTableTarget[] | undefined;+ if (input.tableFilterMode === "selected") {+ try {+ selectedTables = normalizeDatabaseBackupTableTargets(input.selectedTables);+ } catch {+ return null;+ }+ }const nowIso = now.toISOString();const frequency: DatabaseBackupFrequency = input.frequency === "daily" || input.frequency === "weekly" ? input.frequency : "hourly";const schedule: DatabaseBackupSchedule = {@@ -246,8 +295,9 @@ export function normalizeDatabaseBackupSchedule(value: unknown, now = new Date()enabled: booleanValue(input.enabled, true),connectionId,databases: Array.isArray(input.databases) ? [...new Set(input.databases.map((database) => stringValue(database).trim()).filter(Boolean))] : [],- tableFilterMode: input.tableFilterMode === "include" || input.tableFilterMode === "exclude" ? input.tableFilterMode : "all",+ tableFilterMode: input.tableFilterMode === "include" || input.tableFilterMode === "exclude" || input.tableFilterMode === "selected" ? input.tableFilterMode : "all",tablePatterns: normalizeDatabaseBackupTablePatterns(input.tablePatterns),+ ...(selectedTables ? { selectedTables } : {}),destinationDirectory,frequency,intervalHours: boundedInteger(input.intervalHours, 6, 1, 168),diff --git a/crates/dbx-core/assets/docs-export.js b/crates/dbx-core/assets/docs-export.jsindex 387b40345d..5e794cfeb8 100644--- a/crates/dbx-core/assets/docs-export.js+++ b/crates/dbx-core/assets/docs-export.js@@ -61,4 +61,4 @@ ${this.parser.parse(e)}</blockquote>${e}</tr>`}tablecell(e){let t=this.parser.parseInline(e.tokens),n=e.header?`th`:`td`;return(e.align?`<${n} align="${e.align}">`:`<${n}>`)+t+`</${n}>`}strong({tokens:e}){return`<strong>${this.parser.parseInline(e)}</strong>`}em({tokens:e}){return`<em>${this.parser.parseInline(e)}</em>`}codespan({text:e}){return`<code>${ec(e,!0)}</code>`}br(e){return`<br>`}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:t,tokens:n}){let r=this.parser.parseInline(n),i=tc(e);if(i===null)return r;e=i;let a=`<a href="`+e+`"`;return t&&(a+=` title="`+ec(t)+`"`),a+=`>`+r+`</a>`,a}image({href:e,title:t,text:n,tokens:r}){r&&(n=this.parser.parseInline(r,this.parser.textRenderer));let i=tc(e);if(i===null)return ec(n);e=i;let a=`<img src="${e}" alt="${ec(n)}"`;return t&&(a+=` title="${ec(t)}"`),a+=`>`,a}text(e){return`tokens`in e&&e.tokens?this.parser.parseInline(e.tokens):`escaped`in e&&e.escaped?e.text:ec(e.text)}},fc=class{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return``+e}image({text:e}){return``+e}br(){return``}checkbox({raw:e}){return e}},pc=class e{options;renderer;textRenderer;constructor(e){this.options=e||Ho,this.options.renderer=this.options.renderer||new dc,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new fc}static parse(t,n){return new e(n).parse(t)}static parseInline(t,n){return new e(n).parseInline(t)}parse(e){this.renderer.parser=this;let t=``;for(let n=0;n<e.length;n++){let r=e[n];if(this.options.extensions?.renderers?.[r.type]){let e=r,n=this.options.extensions.renderers[e.type].call({parser:this},e);if(n!==!1||![`space`,`hr`,`heading`,`code`,`table`,`blockquote`,`list`,`html`,`def`,`paragraph`,`text`].includes(e.type)){t+=n||``;continue}}let i=r;switch(i.type){case`space`:t+=this.renderer.space(i);break;case`hr`:t+=this.renderer.hr(i);break;case`heading`:t+=this.renderer.heading(i);break;case`code`:t+=this.renderer.code(i);break;case`table`:t+=this.renderer.table(i);break;case`blockquote`:t+=this.renderer.blockquote(i);break;case`list`:t+=this.renderer.list(i);break;case`checkbox`:t+=this.renderer.checkbox(i);break;case`html`:t+=this.renderer.html(i);break;case`def`:t+=this.renderer.def(i);break;case`paragraph`:t+=this.renderer.paragraph(i);break;case`text`:t+=this.renderer.text(i);break;default:{let e=`Token with "`+i.type+`" type was not found.`;if(this.options.silent)return console.error(e),``;throw Error(e)}}}return t}parseInline(e,t=this.renderer){this.renderer.parser=this;let n=``;for(let r=0;r<e.length;r++){let i=e[r];if(this.options.extensions?.renderers?.[i.type]){let e=this.options.extensions.renderers[i.type].call({parser:this},i);if(e!==!1||![`escape`,`html`,`link`,`image`,`strong`,`em`,`codespan`,`br`,`del`,`text`].includes(i.type)){n+=e||``;continue}}let a=i;switch(a.type){case`escape`:n+=t.text(a);break;case`html`:n+=t.html(a);break;case`link`:n+=t.link(a);break;case`image`:n+=t.image(a);break;case`checkbox`:n+=t.checkbox(a);break;case`strong`:n+=t.strong(a);break;case`em`:n+=t.em(a);break;case`codespan`:n+=t.codespan(a);break;case`br`:n+=t.br(a);break;case`del`:n+=t.del(a);break;case`text`:n+=t.text(a);break;default:{let e=`Token with "`+a.type+`" type was not found.`;if(this.options.silent)return console.error(e),``;throw Error(e)}}}return n}},mc=class{options;block;constructor(e){this.options=e||Ho}static passThroughHooks=new Set([`preprocess`,`postprocess`,`processAllTokens`,`emStrongMask`]);static passThroughHooksRespectAsync=new Set([`preprocess`,`postprocess`,`processAllTokens`]);preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}emStrongMask(e){return e}provideLexer(e=this.block){return e?uc.lex:uc.lexInline}provideParser(e=this.block){return e?pc.parse:pc.parseInline}},hc=class{defaults=Vo();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=pc;Renderer=dc;TextRenderer=fc;Lexer=uc;Tokenizer=lc;Hooks=mc;constructor(...e){this.use(...e)}walkTokens(e,t){let n=[];for(let r of e)switch(n=n.concat(t.call(this,r)),r.type){case`table`:{let e=r;for(let r of e.header)n=n.concat(this.walkTokens(r.tokens,t));for(let r of e.rows)for(let e of r)n=n.concat(this.walkTokens(e.tokens,t));break}case`list`:{let e=r;n=n.concat(this.walkTokens(e.items,t));break}default:{let e=r;this.defaults.extensions?.childTokens?.[e.type]?this.defaults.extensions.childTokens[e.type].forEach(r=>{let i=e[r].flat(1/0);n=n.concat(this.walkTokens(i,t))}):e.tokens&&(n=n.concat(this.walkTokens(e.tokens,t)))}}return n}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(e=>{let n={...e};if(n.async=this.defaults.async||n.async||!1,e.extensions&&(e.extensions.forEach(e=>{if(!e.name)throw Error(`extension name required`);if(`renderer`in e){let n=t.renderers[e.name];n?t.renderers[e.name]=function(...t){let r=e.renderer.apply(this,t);return r===!1&&(r=n.apply(this,t)),r}:t.renderers[e.name]=e.renderer}if(`tokenizer`in e){if(!e.level||e.level!==`block`&&e.level!==`inline`)throw Error(`extension level must be 'block' or 'inline'`);let n=t[e.level];n?n.unshift(e.tokenizer):t[e.level]=[e.tokenizer],e.start&&(e.level===`block`?t.startBlock?t.startBlock.push(e.start):t.startBlock=[e.start]:e.level===`inline`&&(t.startInline?t.startInline.push(e.start):t.startInline=[e.start]))}`childTokens`in e&&e.childTokens&&(t.childTokens[e.name]=e.childTokens)}),n.extensions=t),e.renderer){let t=this.defaults.renderer||new dc(this.defaults);for(let n in e.renderer){if(!(n in t))throw Error(`renderer '${n}' does not exist`);if([`options`,`parser`].includes(n))continue;let r=n,i=e.renderer[r],a=t[r];t[r]=(...e)=>{let n=i.apply(t,e);return n===!1&&(n=a.apply(t,e)),n||``}}n.renderer=t}if(e.tokenizer){let t=this.defaults.tokenizer||new lc(this.defaults);for(let n in e.tokenizer){if(!(n in t))throw Error(`tokenizer '${n}' does not exist`);if([`options`,`rules`,`lexer`].includes(n))continue;let r=n,i=e.tokenizer[r],a=t[r];t[r]=(...e)=>{let n=i.apply(t,e);return n===!1&&(n=a.apply(t,e)),n}}n.tokenizer=t}if(e.hooks){let t=this.defaults.hooks||new mc;for(let n in e.hooks){if(!(n in t))throw Error(`hook '${n}' does not exist`);if([`options`,`block`].includes(n))continue;let r=n,i=e.hooks[r],a=t[r];t[r]=mc.passThroughHooks.has(n)?e=>{if(this.defaults.async&&mc.passThroughHooksRespectAsync.has(n))return(async()=>{let n=await i.call(t,e);return a.call(t,n)})();let r=i.call(t,e);return a.call(t,r)}:(...e)=>{if(this.defaults.async)return(async()=>{let n=await i.apply(t,e);return n===!1&&(n=await a.apply(t,e)),n})();let n=i.apply(t,e);return n===!1&&(n=a.apply(t,e)),n}}n.hooks=t}if(e.walkTokens){let t=this.defaults.walkTokens,r=e.walkTokens;n.walkTokens=function(e){let n=[];return n.push(r.call(this,e)),t&&(n=n.concat(t.call(this,e))),n}}this.defaults={...this.defaults,...n}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return uc.lex(e,t??this.defaults)}parser(e,t){return pc.parse(e,t??this.defaults)}parseMarkdown(e){return(t,n)=>{let r={...n},i={...this.defaults,...r},a=this.onError(!!i.silent,!!i.async);if(this.defaults.async===!0&&r.async===!1)return a(Error(`marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise.`));if(typeof t>`u`||t===null)return a(Error(`marked(): input parameter is undefined or null`));if(typeof t!=`string`)return a(Error(`marked(): input parameter is of type `+Object.prototype.toString.call(t)+`, string expected`));if(i.hooks&&(i.hooks.options=i,i.hooks.block=e),i.async)return(async()=>{let n=i.hooks?await i.hooks.preprocess(t):t,r=await(i.hooks?await i.hooks.provideLexer(e):e?uc.lex:uc.lexInline)(n,i),a=i.hooks?await i.hooks.processAllTokens(r):r;i.walkTokens&&await Promise.all(this.walkTokens(a,i.walkTokens));let o=await(i.hooks?await i.hooks.provideParser(e):e?pc.parse:pc.parseInline)(a,i);return i.hooks?await i.hooks.postprocess(o):o})().catch(a);try{i.hooks&&(t=i.hooks.preprocess(t));let n=(i.hooks?i.hooks.provideLexer(e):e?uc.lex:uc.lexInline)(t,i);i.hooks&&(n=i.hooks.processAllTokens(n)),i.walkTokens&&this.walkTokens(n,i.walkTokens);let r=(i.hooks?i.hooks.provideParser(e):e?pc.parse:pc.parseInline)(n,i);return i.hooks&&(r=i.hooks.postprocess(r)),r}catch(e){return a(e)}}}onError(e,t){return n=>{if(n.message+=`-Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error occurred:</p><pre>`+ec(n.message+``,!0)+`</pre>`;return t?Promise.resolve(e):e}if(t)return Promise.reject(n);throw n}}},gc=new hc;function $(e,t){return gc.parse(e,t)}$.options=$.setOptions=function(e){return gc.setOptions(e),$.defaults=gc.defaults,Uo($.defaults),$},$.getDefaults=Vo,$.defaults=Ho,$.use=function(...e){return gc.use(...e),$.defaults=gc.defaults,Uo($.defaults),$},$.walkTokens=function(e,t){return gc.walkTokens(e,t)},$.parseInline=gc.parseInline,$.Parser=pc,$.parser=pc.parse,$.Renderer=dc,$.TextRenderer=fc,$.Lexer=uc,$.lexer=uc.lex,$.Tokenizer=lc,$.Hooks=mc,$.parse=$,$.options,$.setOptions,$.use,$.walkTokens,$.parseInline,pc.parse,uc.lex;function _c(e){return String(e??``).replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`).replace(/'/g,`'`)}var vc=/^(https?:|mailto:)/i;function yc(e){let t=String(e??``).trim();return t===``||/^[/\\]{2}/.test(t)?null:t.startsWith(`#`)||t.startsWith(`/`)||t.startsWith(`./`)||t.startsWith(`../`)||vc.test(t)?t:null}var bc=new hc({renderer:{html({text:e}){return _c(e)},link({href:e,title:t,tokens:n}){let r=this.parser.parseInline(n),i=yc(e);if(i===null)return r;let a=t?` title="${_c(t)}"`:``;return`<a href="${_c(i)}"${a}>${r}</a>`},image({href:e,title:t,text:n}){let r=yc(e);if(r===null)return _c(n);let i=t?` title="${_c(t)}"`:``;return`<img src="${_c(r)}" alt="${_c(n)}"${i}>`}}});function xc(e){return e===null||e.trim()===``?``:bc.parse(e)}var Sc={class:`text-sm text-muted-foreground`},Cc=[`title`,`innerHTML`],wc=L({__name:`NoteEditor`,props:{modelValue:{},readonly:{type:Boolean},translate:{type:Function}},emits:[`update:modelValue`],setup(e,{emit:t}){let n=e,r=t,i=P(!1),a=P(``),o=P(null);async function s(){n.readonly||(a.value=n.modelValue,i.value=!0,await hn(),o.value?.focus())}function c(){i.value=!1,a.value!==n.modelValue&&r(`update:modelValue`,a.value)}function l(){a.value=n.modelValue,i.value=!1}return(t,n)=>(U(),W(`div`,Sc,[i.value?On((U(),W(`textarea`,{key:0,ref_key:`input`,ref:o,"onUpdate:modelValue":n[0]||=e=>a.value=e,rows:`4`,class:`w-full resize-y rounded border border-border bg-background p-2 font-mono text-xs text-foreground outline-none focus:border-ring`,onBlur:n[1]||=e=>c(),onKeydown:n[2]||=lo(e=>l(),[`escape`])},null,544)),[[to,a.value]]):e.modelValue.trim()===``?e.readonly?q(``,!0):(U(),W(`button`,{key:2,type:`button`,class:`rounded border border-dashed border-border px-2 py-1 text-xs text-muted-foreground transition-colors hover:bg-muted/40`,onClick:n[4]||=e=>s()},O(e.translate(`docs.addNote`)),1)):(U(),W(`div`,{key:1,class:D([`leading-relaxed`,e.readonly?``:`cursor-text rounded transition-colors hover:bg-muted/30`]),title:e.readonly?void 0:e.translate(`docs.editNote`),onClick:n[3]||=e=>s(),innerHTML:F(xc)(e.modelValue)},null,10,Cc))]))}}),Tc={class:`flex flex-col gap-5`},Ec={class:`flex flex-col gap-2`},Dc={class:`flex flex-wrap items-center gap-2`},Oc={class:`font-mono text-lg font-semibold text-foreground`},kc={key:0,class:`rounded bg-muted/50 px-1.5 py-0.5 text-[10px] uppercase text-muted-foreground`},Ac={class:`mb-1.5 text-xs font-semibold uppercase tracking-wide text-muted-foreground`},jc={class:`flex flex-wrap gap-1`},Mc={class:`mb-1.5 text-xs font-semibold uppercase tracking-wide text-muted-foreground`},Nc={key:0,class:`text-xs text-muted-foreground`},Pc={key:1,class:`flex flex-col gap-1`},Fc=[`onClick`],Ic=L({__name:`EnumPage`,props:{enumType:{},snapshot:{},translate:{type:Function}},emits:[`select`],setup(e,{emit:t}){let n=e,r=t,i=Y(()=>n.enumType.schema?`${n.enumType.schema}.${n.enumType.name}`:n.enumType.name),a=Y(()=>Bo(n.snapshot,n.enumType.name));return(t,n)=>(U(),W(`article`,Tc,[G(`header`,Ec,[G(`div`,Dc,[G(`h2`,Oc,O(i.value),1),e.enumType.synthesized?(U(),W(`span`,kc,`synthesized`)):q(``,!0)]),K(wc,{"model-value":e.enumType.note??``,readonly:``,translate:e.translate},null,8,[`model-value`,`translate`])]),G(`section`,null,[G(`h3`,Ac,O(e.translate(`docs.enumValues`)),1),G(`ul`,jc,[(U(!0),W(V,null,R(e.enumType.values,e=>(U(),W(`li`,{key:e,class:`rounded bg-muted/50 px-1.5 py-0.5 font-mono text-[11px] text-foreground`},O(e),1))),128))])]),G(`section`,null,[G(`h3`,Mc,O(e.translate(`docs.usedBy`)),1),a.value.length===0?(U(),W(`p`,Nc,`No column uses this enum.`)):(U(),W(`ul`,Pc,[(U(!0),W(V,null,R(a.value,e=>(U(),W(`li`,{key:`${e.tableKey}.${e.column}`,class:`text-xs`},[G(`button`,{type:`button`,class:`w-full rounded border border-border bg-background px-2 py-1.5 text-left font-mono transition-colors hover:bg-muted/40`,onClick:t=>r(`select`,e.tableKey)},O(e.tableKey)+`.`+O(e.column),9,Fc)]))),128))]))])]))}}),Lc={class:`flex flex-col gap-3`},Rc={class:`flex flex-col gap-1`},zc={class:`text-[10px] uppercase tracking-wide text-muted-foreground`},Bc=[`value`,`placeholder`],Vc={class:`flex flex-col gap-2`},Hc={class:`text-[10px] uppercase tracking-wide text-muted-foreground`},Uc={class:`flex items-center gap-1.5`},Wc=[`title`,`onClick`],Gc=[`value`,`title`],Kc={class:`grid grid-cols-2 gap-2`},qc={class:`docs-ground-light flex items-center gap-2 overflow-hidden rounded border border-border bg-white p-2`},Jc={class:`dark flex items-center gap-2 overflow-hidden rounded border border-border bg-neutral-900 p-2`},Yc={class:`flex justify-end`},Xc=L({__name:`GroupEditor`,props:{group:{},translate:{type:Function}},emits:[`update:group`,`delete`],setup(e,{emit:t}){let n=e,r=t,i=Array.from({length:12},(e,t)=>t*30);function a(e){r(`update:group`,{...n.group,name:e.target.value})}function o(e){r(`update:group`,{...n.group,hue:e})}function s(e){o(Number(e.target.value))}function c(e){return`${n.translate(`docs.groupColour`)} ${e}°`}return(t,n)=>(U(),W(`div`,Lc,[G(`label`,Rc,[G(`span`,zc,O(e.translate(`docs.groupName`)),1),G(`input`,{type:`text`,value:e.group.name,placeholder:e.translate(`docs.groupName`),class:`rounded border border-border bg-background px-2 py-1 text-sm text-foreground outline-none focus:border-ring`,onInput:n[0]||=e=>a(e)},null,40,Bc)]),G(`div`,Vc,[G(`span`,Hc,O(e.translate(`docs.groupColour`)),1),G(`div`,Uc,[(U(!0),W(V,null,R(F(i),t=>(U(),W(`button`,{key:t,type:`button`,class:D([`docs-group h-6 w-6 rounded-full border ring-offset-background transition hover:scale-105`,e.group.hue===t?`ring-2 ring-ring ring-offset-2`:`border-border`]),style:E([{"background-color":`var(--group-c)`},F(Oo)(t)]),title:c(t),onClick:e=>o(t)},null,14,Wc))),128))]),G(`input`,{type:`range`,min:`0`,max:`359`,value:e.group.hue,class:`w-full`,title:c(e.group.hue),onInput:n[1]||=e=>s(e)},null,40,Gc),G(`div`,Kc,[G(`div`,qc,[G(`span`,{class:`docs-group h-4 w-4 shrink-0 rounded-full`,style:E([{"background-color":`var(--group-c)`},F(Oo)(e.group.hue)])},null,4),G(`span`,{class:`docs-group truncate rounded px-1.5 py-0.5 text-[11px] font-medium`,style:E([{"background-color":`var(--group-tint)`,color:`var(--group-c)`},F(Oo)(e.group.hue)])},O(e.group.name),5)]),G(`div`,Jc,[G(`span`,{class:`docs-group h-4 w-4 shrink-0 rounded-full`,style:E([{"background-color":`var(--group-c)`},F(Oo)(e.group.hue)])},null,4),G(`span`,{class:`docs-group truncate rounded px-1.5 py-0.5 text-[11px] font-medium`,style:E([{"background-color":`var(--group-tint)`,color:`var(--group-c)`},F(Oo)(e.group.hue)])},O(e.group.name),5)])])]),G(`div`,Yc,[G(`button`,{type:`button`,class:`rounded border border-border px-2 py-1 text-xs text-muted-foreground transition-colors hover:bg-muted/40`,onClick:n[2]||=t=>r(`delete`,e.group.id)},O(e.translate(`docs.deleteGroup`)),1)])]))}});function Zc(e,t={},n=!1){let r=Math.max(1,t.columnsPerRow??Math.ceil(Math.sqrt(Math.max(e.length,1)))),i=t.cardWidth??260,a=t.gapX??56,o=t.gapY??40,s=t.margin??40,c=t.rowHeight,l=e=>c??44+(e.columns?.length??0)*24+12,u={},d=s;for(let t=0;t<e.length;t+=r){let c=e.slice(t,t+r),f=Math.max(...c.map(l));c.forEach((e,t)=>{let r={x:s+t*(i+a),y:d};u[e.name]=r,n&&e.schema&&(u[`${e.schema}.${e.name}`]=r)}),d+=f+o}return u}function Qc(e,t,n){let r=t.x-e.x,i=t.y-e.y;if(r===0&&i===0)return{x:e.x,y:e.y};let a=r===0?1/0:n.width/Math.abs(r),o=i===0?1/0:n.height/Math.abs(i),s=Math.min(a,o);return{x:e.x+r*s,y:e.y+i*s}}var $c={class:`overflow-auto`},el=[`width`,`height`,`viewBox`],tl=[`x1`,`y1`,`x2`,`y2`],nl=[`x`,`y`,`onClick`],rl=[`x`,`y`],il=[`x`,`y`],al=260,ol=220,sl=40,cl=8,ll=L({__name:`SchemaDiagram`,props:{snapshot:{}},emits:[`select`],setup(e,{emit:t}){let n=e,r=t,i={width:al/2,height:ol/2},a=Y(()=>Zc(n.snapshot.tables.map(e=>({name:X(e),columns:e.columns})))),o=Y(()=>new Map(n.snapshot.groups.map(e=>[e.id,e]))),s=Y(()=>n.snapshot.tables.map(e=>{let t=X(e),n=a.value[t]??{x:sl,y:sl},r=e.groupId?o.value.get(e.groupId)??null:null;return{key:t,x:n.x,y:n.y,hue:r?.hue??null,columns:e.columns.slice(0,cl).map(e=>e.name)}}));function c(e){let t=a.value[e]??{x:sl,y:sl};return{x:t.x+al/2,y:t.y+ol/2}}let l=Y(()=>{let e=new Set(Object.keys(a.value));return n.snapshot.relationships.map(e=>({relationship:e,fromKey:X({schema:e.from.schema,name:e.from.table}),toKey:X({schema:e.to.schema,name:e.to.table})})).filter(({fromKey:t,toKey:n})=>e.has(t)&&e.has(n)).map(({relationship:e,fromKey:t,toKey:n})=>{let r=c(t),a=c(n);return{id:e.id,from:Qc(r,a,i),to:Qc(a,r,i)}})}),u=Y(()=>Math.max(0,...s.value.map(e=>e.x+al))+sl),d=Y(()=>Math.max(0,...s.value.map(e=>e.y+ol))+sl);function f(e){return e===null?{}:{...Oo(e),fill:`var(--group-tint)`}}return(e,t)=>(U(),W(`div`,$c,[(U(),W(`svg`,{width:u.value,height:d.value,viewBox:`0 0 ${u.value} ${d.value}`,class:`block`},[(U(!0),W(V,null,R(l.value,e=>(U(),W(`line`,{key:e.id,x1:e.from.x,y1:e.from.y,x2:e.to.x,y2:e.to.y,class:`stroke-border`,"stroke-width":`1.5`},null,8,tl))),128)),(U(!0),W(V,null,R(s.value,e=>(U(),W(`g`,{key:e.key},[G(`rect`,{x:e.x,y:e.y,width:al,height:ol,rx:`6`,class:D([`cursor-pointer stroke-border`,e.hue===null?`fill-card`:`docs-group`]),style:E(f(e.hue)),"stroke-width":`1`,onClick:t=>r(`select`,e.key)},null,14,nl),G(`text`,{x:e.x+10,y:e.y+22,class:`pointer-events-none fill-foreground font-mono text-[11px] font-semibold`},O(e.key),9,rl),(U(!0),W(V,null,R(e.columns,(t,n)=>(U(),W(`text`,{key:t,x:e.x+10,y:e.y+42+n*18,class:`pointer-events-none fill-muted-foreground font-mono text-[10px]`},O(t),9,il))),128))]))),128))],8,el))]))}}),ul={class:`overflow-hidden rounded-md border border-border`},dl={class:`w-full text-xs`},fl={class:`bg-muted/30`},pl={class:`px-2 py-1.5 text-left font-medium text-muted-foreground`},ml={class:`px-2 py-1.5 text-left font-medium text-muted-foreground`},hl={class:`px-2 py-1.5 text-left font-medium text-muted-foreground`},gl={class:`px-2 py-1.5 text-left font-medium text-muted-foreground`},_l={class:`px-2 py-1.5 font-mono font-medium text-foreground`},vl={class:`px-2 py-1.5 font-mono text-muted-foreground`},yl={class:`px-2 py-1.5`},bl={class:`flex flex-wrap gap-1`},xl={class:`px-2 py-1.5 text-muted-foreground`},Sl={class:`flex items-start gap-1`},Cl=[`title`],wl=L({__name:`ColumnTable`,props:{columns:{},columnNotes:{},tableKey:{},readonly:{type:Boolean},translate:{type:Function}},emits:[`edit`],setup(e,{emit:t}){let n=e,r=t;function i(e){let t=e.data_type.trim();if(t.includes(`(`))return t;if(e.character_maximum_length!==null)return`${t}(${e.character_maximum_length})`;if(e.numeric_precision!==null){let n=e.numeric_scale===null?``:`,${e.numeric_scale}`;return`${t}(${e.numeric_precision}${n})`}return t}function a(e){let t=[];return e.is_primary_key&&t.push(`pk`),e.is_nullable||t.push(`not null`),e.column_default!==null&&t.push(`default: ${e.column_default}`),e.extra!==null&&e.extra!==``&&t.push(e.extra),e.enum_values!==void 0&&e.enum_values.length>0&&t.push(`enum: ${e.enum_values.join(`, `)}`),t}function o(e){return n.columnNotes[e.name]??null}function s(e){let t=o(e)?.shadowed;return t?`Database comment: ${t}`:void 0}return(t,n)=>(U(),W(`div`,ul,[G(`table`,dl,[G(`thead`,null,[G(`tr`,fl,[G(`th`,pl,O(e.translate(`docs.columnHeader`)),1),G(`th`,ml,O(e.translate(`docs.typeHeader`)),1),G(`th`,hl,O(e.translate(`docs.settingsHeader`)),1),G(`th`,gl,O(e.translate(`docs.noteHeader`)),1)])]),G(`tbody`,null,[(U(!0),W(V,null,R(e.columns,t=>(U(),W(`tr`,{key:t.name,class:`border-t border-border align-top`},[G(`td`,_l,O(t.name),1),G(`td`,vl,O(i(t)),1),G(`td`,yl,[G(`div`,bl,[(U(!0),W(V,null,R(a(t),e=>(U(),W(`span`,{key:e,class:`rounded bg-muted/50 px-1.5 py-0.5 text-[10px] text-muted-foreground`},O(e),1))),128))])]),G(`td`,xl,[G(`div`,Sl,[o(t)?.source===`LOCAL`?(U(),W(`span`,{key:0,class:`mt-0.5 shrink-0 text-[10px] font-medium`,title:s(t)},`⬤ `+O(e.translate(`docs.localNote`)),9,Cl)):q(``,!0),K(wc,{class:`min-w-0 flex-1`,"model-value":o(t)?.note??``,readonly:e.readonly,translate:e.translate,"onUpdate:modelValue":n=>r(`edit`,{kind:`columnNote`,tableKey:e.tableKey,column:t.name,note:n})},null,8,[`model-value`,`readonly`,`translate`,`onUpdate:modelValue`])])])]))),128))])])]))}}),Tl={class:`flex items-center gap-1.5`},El=[`value`],Dl={value:``},Ol=[`value`],kl=`__dbx_new_group__`,Al=L({__name:`GroupPicker`,props:{groups:{},modelValue:{},translate:{type:Function}},emits:[`update:modelValue`,`create`],setup(e,{emit:t}){let n=e,r=t,i=Y(()=>n.groups.find(e=>e.id===n.modelValue)??null);function a(e){let t=e.target;if(t.value===kl&&!n.groups.some(e=>e.id===kl)){t.value=n.modelValue??``,r(`create`);return}r(`update:modelValue`,t.value===``?null:t.value)}return(t,n)=>(U(),W(`div`,Tl,[i.value?(U(),W(`span`,{key:0,class:`docs-group h-3 w-3 shrink-0 rounded-full`,style:E([{"background-color":`var(--group-c)`},F(Oo)(i.value.hue)])},null,4)):q(``,!0),G(`select`,{value:e.modelValue??``,class:`rounded border border-border bg-background px-2 py-1 text-xs text-foreground outline-none focus:border-ring`,onChange:n[0]||=e=>a(e)},[G(`option`,Dl,O(e.translate(`docs.noGroup`)),1),(U(!0),W(V,null,R(e.groups,e=>(U(),W(`option`,{key:e.id,value:e.id},O(e.name),9,Ol))),128)),G(`option`,{value:kl},O(e.translate(`docs.newGroup`)),1)],40,El)]))}}),jl={class:`grid gap-4 sm:grid-cols-2`},Ml={class:`mb-1.5 text-xs font-medium text-muted-foreground`},Nl={key:0,class:`text-xs text-muted-foreground`},Pl={key:1,class:`flex flex-col gap-1`},Fl=[`onClick`],Il={class:`font-mono`},Ll={class:`mx-1.5 text-muted-foreground`},Rl={class:`font-mono`},zl={key:0,class:`ml-1.5 text-[10px] text-muted-foreground`},Bl={class:`mb-1.5 text-xs font-medium text-muted-foreground`},Vl={key:0,class:`text-xs text-muted-foreground`},Hl={key:1,class:`flex flex-col gap-1`},Ul=[`onClick`],Wl={class:`font-mono`},Gl={class:`mx-1.5 text-muted-foreground`},Kl={class:`font-mono`},ql={key:0,class:`ml-1.5 text-[10px] text-muted-foreground`},Jl=L({__name:`RelationshipList`,props:{relationships:{},schema:{},table:{},translate:{type:Function}},emits:[`select`],setup(e,{emit:t}){let n=e,r=t;function i(e){return e.table===n.table&&(e.schema??null)===n.schema}function a(e){return X({schema:e.schema,name:e.table})}function o(e){return`${a(e)}.${e.column}`}function s(e){return e.cardinality===`ONE_TO_ONE`?`1 – 1`:`* – 1`}function c(e){let t=[];return e.onUpdate&&t.push(`on update ${e.onUpdate}`),e.onDelete&&t.push(`on delete ${e.onDelete}`),t}let l=Y(()=>n.relationships.filter(e=>i(e.from))),u=Y(()=>n.relationships.filter(e=>i(e.to)));return(t,n)=>(U(),W(`div`,jl,[G(`section`,null,[G(`h4`,Ml,O(e.translate(`docs.references`))+` (`+O(l.value.length)+`)`,1),l.value.length===0?(U(),W(`p`,Nl,O(e.translate(`docs.noOutgoingRelationships`)),1)):(U(),W(`ul`,Pl,[(U(!0),W(V,null,R(l.value,e=>(U(),W(`li`,{key:e.id,class:`text-xs`},[G(`button`,{type:`button`,class:`w-full rounded border border-border bg-background px-2 py-1.5 text-left transition-colors hover:bg-muted/40`,onClick:t=>r(`select`,a(e.to))},[G(`span`,Il,O(e.from.column),1),G(`span`,Ll,O(s(e)),1),G(`span`,Rl,O(o(e.to)),1),c(e).length>0?(U(),W(`span`,zl,O(c(e).join(`, `)),1)):q(``,!0)],8,Fl)]))),128))]))]),G(`section`,null,[G(`h4`,Bl,O(e.translate(`docs.referencedBy`))+` (`+O(u.value.length)+`)`,1),u.value.length===0?(U(),W(`p`,Vl,O(e.translate(`docs.noIncomingRelationships`)),1)):(U(),W(`ul`,Hl,[(U(!0),W(V,null,R(u.value,e=>(U(),W(`li`,{key:e.id,class:`text-xs`},[G(`button`,{type:`button`,class:`w-full rounded border border-border bg-background px-2 py-1.5 text-left transition-colors hover:bg-muted/40`,onClick:t=>r(`select`,a(e.from))},[G(`span`,Wl,O(o(e.from)),1),G(`span`,Gl,O(s(e)),1),G(`span`,Kl,O(e.to.column),1),c(e).length>0?(U(),W(`span`,ql,O(c(e).join(`, `)),1)):q(``,!0)],8,Ul)]))),128))]))])]))}}),Yl={class:`flex flex-col gap-5`},Xl={class:`flex flex-col gap-2`},Zl={class:`flex flex-wrap items-center gap-2`},Ql={class:`font-mono text-lg font-semibold text-foreground`},$l={class:`rounded bg-muted/50 px-1.5 py-0.5 text-[10px] uppercase text-muted-foreground`},eu={key:1,class:`text-[10px] text-muted-foreground`},tu={class:`flex items-start gap-2`},nu=[`title`],ru={class:`mb-1.5 text-xs font-semibold uppercase tracking-wide text-muted-foreground`},iu={key:0},au={class:`mb-1.5 text-xs font-semibold uppercase tracking-wide text-muted-foreground`},ou={class:`overflow-hidden rounded-md border border-border`},su={class:`w-full text-xs`},cu={class:`bg-muted/30`},lu={class:`px-2 py-1.5 text-left font-medium text-muted-foreground`},uu={class:`px-2 py-1.5 text-left font-medium text-muted-foreground`},du={class:`px-2 py-1.5 text-left font-medium text-muted-foreground`},fu={class:`px-2 py-1.5 font-mono`},pu={class:`px-2 py-1.5 font-mono text-muted-foreground`},mu={class:`px-2 py-1.5`},hu={class:`flex flex-wrap gap-1 text-[10px] text-muted-foreground`},gu={key:0,class:`rounded bg-muted/50 px-1.5 py-0.5`},_u={key:1,class:`rounded bg-muted/50 px-1.5 py-0.5`},vu={key:2,class:`rounded bg-muted/50 px-1.5 py-0.5`},yu={key:3,class:`rounded bg-muted/50 px-1.5 py-0.5`},bu={class:`mb-1.5 text-xs font-semibold uppercase tracking-wide text-muted-foreground`},xu={key:1},Su={class:`mb-1.5 text-xs font-semibold uppercase tracking-wide text-muted-foreground`},Cu={class:`overflow-x-auto rounded-md border border-border bg-muted/20 p-2 font-mono text-xs`},wu=L({__name:`TablePage`,props:{table:{},relationships:{},group:{},annotationGroups:{},readonly:{type:Boolean},translate:{type:Function}},emits:[`select`,`edit`,`createGroup`],setup(e,{emit:t}){let n=e,r=t,i=Y(()=>X(n.table)),a=Y(()=>n.table.kind.toLowerCase().replace(/_/g,` `)),o=Y(()=>n.table.shadowedNote?`Database comment: ${n.table.shadowedNote}`:void 0);return(t,n)=>(U(),W(`article`,Yl,[G(`header`,Xl,[G(`div`,Zl,[G(`h2`,Ql,O(i.value),1),G(`span`,$l,O(a.value),1),e.group?(U(),W(`span`,{key:0,class:`docs-group rounded px-1.5 py-0.5 text-[10px] font-medium`,style:E([{"background-color":`var(--group-tint)`,color:`var(--group-c)`},F(Oo)(e.group.hue)])},O(e.group.name),5)):q(``,!0),e.table.estimatedRows===null?q(``,!0):(U(),W(`span`,eu,` ~`+O(e.table.estimatedRows)+` rows `,1))]),G(`div`,tu,[e.table.noteSource===`LOCAL`?(U(),W(`span`,{key:0,class:`mt-0.5 shrink-0 text-[10px] font-medium text-muted-foreground`,title:o.value},`⬤ `+O(e.translate(`docs.localNote`)),9,nu)):q(``,!0),K(wc,{class:`min-w-0 flex-1`,"model-value":e.table.note??``,readonly:e.readonly,translate:e.translate,"onUpdate:modelValue":n[0]||=e=>r(`edit`,{kind:`tableNote`,tableKey:i.value,note:e})},null,8,[`model-value`,`readonly`,`translate`])]),e.readonly?q(``,!0):(U(),ji(Al,{key:0,groups:e.annotationGroups,"model-value":e.table.groupId,translate:e.translate,"onUpdate:modelValue":n[1]||=e=>r(`edit`,{kind:`tableGroup`,tableKey:i.value,groupId:e}),onCreate:n[2]||=e=>r(`createGroup`,i.value)},null,8,[`groups`,`model-value`,`translate`]))]),G(`section`,null,[G(`h3`,ru,O(e.translate(`docs.columns`)),1),K(wl,{columns:e.table.columns,"column-notes":e.table.columnNotes,"table-key":i.value,readonly:e.readonly,translate:e.translate,onEdit:n[3]||=e=>r(`edit`,e)},null,8,[`columns`,`column-notes`,`table-key`,`readonly`,`translate`])]),e.table.indexes.length>0?(U(),W(`section`,iu,[G(`h3`,au,O(e.translate(`docs.indexes`)),1),G(`div`,ou,[G(`table`,su,[G(`thead`,null,[G(`tr`,cu,[G(`th`,lu,O(e.translate(`docs.nameHeader`)),1),G(`th`,uu,O(e.translate(`docs.columns`)),1),G(`th`,du,O(e.translate(`docs.settingsHeader`)),1)])]),G(`tbody`,null,[(U(!0),W(V,null,R(e.table.indexes,e=>(U(),W(`tr`,{key:e.name,class:`border-t border-border align-top`},[G(`td`,fu,O(e.name),1),G(`td`,pu,[zi(O(e.columns.join(`, `)),1),e.included_columns&&e.included_columns.length>0?(U(),W(V,{key:0},[zi(` (include `+O(e.included_columns.join(`, `))+`) `,1)],64)):q(``,!0)]),G(`td`,mu,[G(`div`,hu,[e.is_primary?(U(),W(`span`,gu,`pk`)):q(``,!0),e.is_unique?(U(),W(`span`,_u,`unique`)):q(``,!0),e.index_type?(U(),W(`span`,vu,O(e.index_type),1)):q(``,!0),e.filter?(U(),W(`span`,yu,`where `+O(e.filter),1)):q(``,!0)])])]))),128))])])])])):q(``,!0),G(`section`,null,[G(`h3`,bu,O(e.translate(`docs.relationships`)),1),K(Jl,{relationships:e.relationships,schema:e.table.schema,table:e.table.name,translate:e.translate,onSelect:n[4]||=e=>r(`select`,e)},null,8,[`relationships`,`schema`,`table`,`translate`])]),e.table.viewDefinition?(U(),W(`section`,xu,[G(`h3`,Su,O(e.translate(`docs.definitionHeader`)),1),G(`pre`,Cu,O(e.table.viewDefinition),1)])):q(``,!0)]))}});function Tu(e,t){switch(e.kind){case`tableSkipped`:return{severity:`warning`,title:t(`docs.warnings.tableSkipped.title`),detail:t(`docs.warnings.tableSkipped.detail`,{table:e.table,reason:e.reason})};case`noForeignKeyMetadata`:return{severity:`info`,title:t(`docs.warnings.noForeignKeyMetadata.title`),detail:t(`docs.warnings.noForeignKeyMetadata.detail`,{engine:e.engine})};case`commentsUnsupported`:return{severity:`info`,title:t(`docs.warnings.commentsUnsupported.title`),detail:t(`docs.warnings.commentsUnsupported.detail`,{engine:e.engine})};case`orphanedNotes`:return{severity:`warning`,title:t(`docs.warnings.orphanedNotes.title`),detail:t(`docs.warnings.orphanedNotes.detail`,{count:e.count})};case`dbmlOmitted`:return{severity:`info`,title:t(`docs.warnings.dbmlOmitted.title`),detail:t(`docs.warnings.dbmlOmitted.detail`,{item:e.item,table:e.table,reason:e.reason})}}}var Eu={key:0,class:`flex flex-col gap-2`},Du={class:`font-medium`},Ou={class:`mt-0.5 leading-relaxed`},ku=L({__name:`WarningBanner`,props:{warnings:{},translate:{type:Function}},setup(e){let t=e,n=Y(()=>t.warnings.map((e,n)=>({key:`${e.kind}-${n}`,...Tu(e,t.translate)})));return(e,t)=>n.value.length>0?(U(),W(`div`,Eu,[(U(!0),W(V,null,R(n.value,e=>(U(),W(`div`,{key:e.key,class:D([`rounded-md border px-3 py-2 text-xs`,e.severity===`warning`?`border-amber-300 bg-amber-50 text-amber-900 dark:border-amber-900/40 dark:bg-amber-950/30 dark:text-amber-200`:`border-border bg-muted/30 text-muted-foreground`])},[G(`div`,Du,O(e.title),1),G(`div`,Ou,O(e.detail),1)],2))),128))])):q(``,!0)}}),Au={class:`flex flex-col gap-6`},ju={class:`flex items-baseline gap-2`},Mu={class:`text-sm font-semibold text-foreground`},Nu={class:`text-xs text-muted-foreground`},Pu=[`innerHTML`],Fu={class:`grid gap-1 sm:grid-cols-2 lg:grid-cols-3`},Iu=[`onClick`],Lu={class:`font-mono text-xs font-medium text-foreground`},Ru={key:0,class:`text-[10px] uppercase text-muted-foreground`},zu=[`innerHTML`],Bu=L({__name:`WikiIndex`,props:{sections:{},translate:{type:Function}},emits:[`select`],setup(e,{emit:t}){let n=t;return(t,r)=>(U(),W(`div`,Au,[(U(!0),W(V,null,R(e.sections,t=>(U(),W(`section`,{key:t.key,class:`flex flex-col gap-2`},[G(`div`,{class:D([`flex flex-col gap-1 border-l-2 pl-3`,{"docs-group":t.hue!==null}]),style:E([{"border-color":`var(--group-c, var(--border))`},F(Oo)(t.hue)])},[G(`div`,ju,[G(`h2`,Mu,O(t.label||e.translate(t.fallbackKey)),1),G(`span`,Nu,O(t.tables.length)+` tables`,1)]),t.note?(U(),W(`div`,{key:0,class:`text-xs text-muted-foreground`,innerHTML:F(xc)(t.note)},null,8,Pu)):q(``,!0)],6),G(`ul`,Fu,[(U(!0),W(V,null,R(t.tables,e=>(U(),W(`li`,{key:F(X)(e),class:`flex flex-col gap-0.5 rounded border border-border bg-background px-2 py-1.5 transition-colors hover:bg-muted/40`},[G(`button`,{type:`button`,class:`flex w-full items-baseline gap-1.5 text-left`,onClick:t=>n(`select`,F(X)(e))},[G(`span`,Lu,O(e.name),1),e.kind===`TABLE`?q(``,!0):(U(),W(`span`,Ru,O(e.kind.toLowerCase().replace(/_/g,` `)),1))],8,Iu),e.note?(U(),W(`div`,{key:0,class:`line-clamp-2 text-[11px] text-muted-foreground`,innerHTML:F(xc)(e.note)},null,8,zu)):q(``,!0)]))),128))])]))),128))]))}});function Vu(){if(typeof crypto<`u`&&typeof crypto.randomUUID==`function`)return crypto.randomUUID();if(typeof crypto<`u`&&typeof crypto.getRandomValues==`function`){let e=crypto.getRandomValues(new Uint8Array(16));return e[6]=e[6]&15|64,e[8]=e[8]&63|128,Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``).replace(/^(.{8})(.{4})(.{4})(.{4})(.{12})$/,`$1-$2-$3-$4-$5`)}return`xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx`.replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e===`x`?t:t&3|8).toString(16)})}var Hu={class:`flex h-full min-h-0 bg-background text-foreground`},Uu={class:`flex h-full min-h-0 w-64 shrink-0 flex-col`},Wu={class:`flex min-w-0 flex-1 flex-col gap-4 overflow-y-auto p-4`},Gu={class:`flex flex-wrap items-start justify-between gap-3`},Ku={class:`flex flex-col gap-1`},qu={class:`text-base font-semibold`},Ju={class:`text-xs text-muted-foreground`},Yu={key:0,class:`flex flex-col gap-4`},Xu={key:0,class:`flex flex-col gap-2`},Zu={class:`text-xs font-semibold uppercase tracking-wide text-muted-foreground`},Qu=L({__name:`DocsApp`,props:{snapshot:{},annotations:{},readonly:{type:Boolean},translate:{},route:{},diagram:{default:`external`}},emits:[`edit`,`update:route`],setup(e,{emit:t}){let n=e,r=t,i=Y(()=>n.readonly??!1),a=Y(()=>n.annotations.groups??[]),o=P(n.snapshot.groups.length>0?`group`:`schema`),s=P(null),c=P(null),l=P(!1),u=Y(()=>n.route?n.route:l.value?{kind:`diagram`}:c.value===null?s.value===null?{kind:`index`}:{kind:`table`,key:s.value}:{kind:`enum`,name:c.value}),d=Y(()=>u.value.kind===`table`?u.value.key:null),f=Y(()=>u.value.kind===`enum`?u.value.name:null),p=Y(()=>o.value===`schema`?Ro(n.snapshot):zo(n.snapshot)),m=Y(()=>n.snapshot.tables.find(e=>X(e)===d.value)??null),h=Y(()=>f.value===null?null:n.snapshot.enums.find(e=>e.name===f.value)??null),g=Y(()=>u.value.kind===`diagram`?`diagram`:h.value===null?m.value===null?`index`:`table`:`enum`),_=Y(()=>{let e=m.value?.groupId;return e?n.snapshot.groups.find(t=>t.id===e)??null:null});function v(e){n.snapshot.tables.some(t=>X(t)===e)&&(c.value=null,l.value=!1,s.value=e,r(`update:route`,{kind:`table`,key:e}))}function y(e){n.snapshot.enums.some(t=>t.name===e)&&(s.value=null,l.value=!1,c.value=e,r(`update:route`,{kind:`enum`,name:e}))}function b(){s.value=null,c.value=null,l.value=!0,r(`update:route`,{kind:`diagram`})}function x(){s.value=null,c.value=null,l.value=!1,r(`update:route`,{kind:`index`})}function ee(e){let t={id:Vu(),name:n.translate(`docs.newGroup`),hue:a.value.length*47%360};r(`edit`,{kind:`upsertGroup`,group:t}),r(`edit`,{kind:`tableGroup`,tableKey:e,groupId:t.id})}return(t,n)=>(U(),W(`div`,Hu,[G(`div`,Uu,[K(Io,{class:`min-h-0 flex-1`,sections:p.value,mode:o.value,"active-key":d.value,translate:e.translate,"onUpdate:mode":n[0]||=e=>o.value=e,onSelect:v,onHome:n[1]||=e=>x()},null,8,[`sections`,`mode`,`active-key`,`translate`]),e.diagram===`inline`?(U(),W(`button`,{key:0,type:`button`,class:D([`shrink-0 border-t border-r border-border bg-background px-3 py-2 text-left text-xs font-medium transition-colors`,g.value===`diagram`?`bg-muted text-foreground`:`text-muted-foreground hover:bg-muted/40`]),onClick:n[2]||=e=>b()},O(e.translate(`docs.diagram`)),3)):q(``,!0)]),G(`main`,Wu,[G(`header`,Gu,[G(`div`,Ku,[G(`h1`,qu,O(e.snapshot.project.name),1),G(`p`,Ju,[zi(O(e.snapshot.project.databaseType),1),e.snapshot.project.database?(U(),W(V,{key:0},[zi(` · `+O(e.snapshot.project.database),1)],64)):q(``,!0),zi(` · `+O(e.snapshot.tables.length)+` tables · generated `+O(e.snapshot.project.generatedAt),1)])]),K(Do,{snapshot:e.snapshot,translate:e.translate,onSelect:v,onSelectEnum:y},null,8,[`snapshot`,`translate`])]),K(ku,{warnings:e.snapshot.warnings,translate:e.translate},null,8,[`warnings`,`translate`]),g.value===`index`?(U(),W(`div`,Yu,[K(wc,{"model-value":e.snapshot.project.note??``,readonly:i.value,translate:e.translate,"onUpdate:modelValue":n[3]||=e=>r(`edit`,{kind:`projectNote`,note:e})},null,8,[`model-value`,`readonly`,`translate`]),K(Bu,{sections:p.value,translate:e.translate,onSelect:v},null,8,[`sections`,`translate`]),!i.value&&a.value.length>0?(U(),W(`section`,Xu,[G(`h2`,Zu,O(e.translate(`docs.groups`)),1),(U(!0),W(V,null,R(a.value,t=>(U(),ji(Xc,{key:t.id,group:t,translate:e.translate,"onUpdate:group":n[4]||=e=>r(`edit`,{kind:`upsertGroup`,group:e}),onDelete:n[5]||=e=>r(`edit`,{kind:`removeGroup`,groupId:e})},null,8,[`group`,`translate`]))),128))])):q(``,!0)])):g.value===`table`&&m.value?(U(),ji(wu,{key:1,table:m.value,relationships:e.snapshot.relationships,group:_.value,"annotation-groups":a.value,readonly:i.value,translate:e.translate,onSelect:v,onEdit:n[6]||=e=>r(`edit`,e),onCreateGroup:ee},null,8,[`table`,`relationships`,`group`,`annotation-groups`,`readonly`,`translate`])):h.value?(U(),ji(Ic,{key:2,"enum-type":h.value,snapshot:e.snapshot,translate:e.translate,onSelect:v},null,8,[`enum-type`,`snapshot`,`translate`])):g.value===`diagram`?(U(),ji(ll,{key:3,snapshot:e.snapshot,onSelect:v},null,8,[`snapshot`])):q(``,!0)])]))}}),$u={kind:`index`};function ed(e,t,n){if(!e.startsWith(`#`))return $u;let[r,...i]=e.slice(1).replace(/^\//,``).split(`/`),a=i.join(`/`);if(r===`diagram`&&a===``)return n?{kind:`diagram`}:$u;if(a===``)return $u;let o;try{o=decodeURIComponent(a)}catch{return $u}return r===`table`?t.tables.some(e=>X(e)===o)?{kind:`table`,key:o}:$u:r===`enum`&&(t.enums??[]).some(e=>e.name===o)?{kind:`enum`,name:o}:$u}function td(e){switch(e.kind){case`table`:return`#/table/${encodeURIComponent(e.key)}`;case`enum`:return`#/enum/${encodeURIComponent(e.name)}`;case`diagram`:return`#/diagram`;default:return`#/`}}var nd=[{value:`en`,flag:`🇺🇸`,label:`English`},{value:`az`,flag:`🇦🇿`,label:`Azərbaycan`},{value:`es`,flag:`🇪🇸`,label:`Español`},{value:`it`,flag:`🇮🇹`,label:`Italiano`},{value:`ja`,flag:`🇯🇵`,label:`日本語`},{value:`ko`,flag:`🇰🇷`,label:`한국어`},{value:`pt-BR`,flag:`🇧🇷`,label:`Português`},{value:`ru`,flag:`🇷🇺`,label:`Русский`},{value:`tr`,flag:`🇹🇷`,label:`Türkçe`},{value:`zh-CN`,flag:`🇨🇳`,label:`简体中文`},{value:`zh-TW`,flag:`繁`,label:`繁體中文`}],rd={en:{title:`Documentation`,groupBySchema:`Schemas`,groupByTableGroup:`Table Groups`,noGroup:`(no group)`,noSchema:`(no schema)`,search:`Search tables, columns, groups…`,columns:`Columns`,indexes:`Indexes`,references:`References`,referencedBy:`Referenced by`,localNote:`LOCAL`,shadowedComment:`Database comment: {comment}`,addNote:`Add a note`,editNote:`Edit note`,newGroup:`New group…`,groupName:`Group name`,groupColour:`Colour`,deleteGroup:`Delete group`,enumValues:`Values`,usedBy:`Used by`,openDiagram:`Open schema diagram`,saving:`Saving…`,saved:`Saved`,saveFailed:`Could not save notes: {error}`,overview:`Overview`,groupBy:`Group by`,searchLabel:`Search`,groups:`Groups`,relationships:`Relationships`,columnHeader:`Column`,typeHeader:`Type`,settingsHeader:`Settings`,noteHeader:`Note`,nameHeader:`Name`,definitionHeader:`Definition`,noOutgoingRelationships:`This table references no other table.`,noIncomingRelationships:`No table references this one.`,diagram:`Diagram`,language:`Language`,theme:`Theme`,themeLight:`Light`,themeDark:`Dark`,exportHtml:`Export HTML…`,exporting:`Exporting…`,exportFailed:`Could not export: {error}`,warnings:{tableSkipped:{title:`A table could not be documented`,detail:`{table} was skipped: {reason}. It is missing from this documentation.`},noForeignKeyMetadata:{title:`No relationships available`,detail:`{engine} does not report foreign key metadata, so no relationship edges could be derived. The diagram is complete for this engine.`},commentsUnsupported:{title:`Database comments unavailable`,detail:`{engine} does not support table or column comments, so every description here comes from this project's own notes.`},orphanedNotes:{title:`Some notes no longer match anything`,detail:`{count} note(s) refer to a table or column that no longer exists. Nothing was deleted — re-map or remove them in the notes file.`},dbmlOmitted:{title:`Not representable in DBML`,detail:`{item} on {table} is documented here but omitted from the exported DBML: {reason}.`}}},es:{title:`Documentación`,groupBySchema:`Esquemas`,groupByTableGroup:`Grupos de tablas`,noGroup:`(sin grupo)`,noSchema:`(sin esquema)`,search:`Buscar tablas, columnas, grupos…`,columns:`Columnas`,indexes:`Índices`,references:`Referencias`,referencedBy:`Referenciado por`,localNote:`LOCAL`,shadowedComment:`Comentario de la base de datos: {comment}`,addNote:`Agregar una nota`,editNote:`Editar nota`,newGroup:`Nuevo grupo…`,groupName:`Nombre del grupo`,groupColour:`Color`,deleteGroup:`Eliminar grupo`,enumValues:`Valores`,usedBy:`Usado por`,openDiagram:`Abrir diagrama del esquema`,saving:`Guardando…`,saved:`Guardado`,saveFailed:`No se pudieron guardar las notas: {error}`,overview:`Información general`,groupBy:`Agrupar por`,searchLabel:`Buscar`,groups:`Grupos`,relationships:`Relaciones`,columnHeader:`Columna`,typeHeader:`Tipo`,settingsHeader:`Configuración`,noteHeader:`Nota`,nameHeader:`Nombre`,definitionHeader:`Definición`,noOutgoingRelationships:`Esta tabla no referencia ninguna otra tabla.`,noIncomingRelationships:`Ninguna tabla referencia esta.`,diagram:`Diagrama`,language:`Idioma`,theme:`Tema`,themeLight:`Claro`,themeDark:`Oscuro`,exportHtml:`Exportar HTML…`,exporting:`Exportando…`,exportFailed:`No se pudo exportar: {error}`,warnings:{tableSkipped:{title:`No se pudo documentar una tabla`,detail:`{table} fue omitida: {reason}. Falta en esta documentación.`},noForeignKeyMetadata:{title:`No hay relaciones disponibles`,detail:`{engine} no reporta metadatos de claves foráneas, por lo que no se pudieron derivar relaciones. El diagrama está completo para este motor.`},commentsUnsupported:{title:`Comentarios de base de datos no disponibles`,detail:`{engine} no admite comentarios en tablas o columnas, por lo que toda descripción aquí proviene de las notas de este proyecto.`},orphanedNotes:{title:`Algunas notas ya no coinciden con nada`,detail:`{count} nota(s) hacen referencia a una tabla o columna que ya no existe. No se eliminó nada — vuelva a asignarlas o elimínelas en el archivo de notas.`},dbmlOmitted:{title:`No representable en DBML`,detail:`{item} en {table} está documentado aquí pero se omitió del DBML exportado: {reason}.`}}},it:{title:`Documentazione`,groupBySchema:`Schemi`,groupByTableGroup:`Gruppi di tabelle`,noGroup:`(nessun gruppo)`,noSchema:`(nessuno schema)`,search:`Cerca tabelle, colonne, gruppi…`,columns:`Colonne`,indexes:`Indici`,references:`Riferimenti`,referencedBy:`Referenziato da`,localNote:`LOCALE`,shadowedComment:`Commento del database: {comment}`,addNote:`Aggiungi una nota`,editNote:`Modifica nota`,newGroup:`Nuovo gruppo…`,groupName:`Nome del gruppo`,groupColour:`Colore`,deleteGroup:`Elimina gruppo`,enumValues:`Valori`,usedBy:`Usato da`,openDiagram:`Apri diagramma dello schema`,saving:`Salvataggio…`,saved:`Salvato`,saveFailed:`Impossibile salvare le note: {error}`,overview:`Panoramica`,groupBy:`Raggruppa per`,searchLabel:`Cerca`,groups:`Gruppi`,relationships:`Relazioni`,columnHeader:`Colonna`,typeHeader:`Tipo`,settingsHeader:`Impostazioni`,noteHeader:`Nota`,nameHeader:`Nome`,definitionHeader:`Definizione`,noOutgoingRelationships:`Questa tabella non fa riferimento a nessun'altra tabella.`,noIncomingRelationships:`Nessuna tabella fa riferimento a questa.`,diagram:`Diagramma`,language:`Lingua`,theme:`Tema`,themeLight:`Chiaro`,themeDark:`Scuro`,exportHtml:`Esporta HTML…`,exporting:`Esportazione…`,exportFailed:`Impossibile esportare: {error}`,warnings:{tableSkipped:{title:`Impossibile documentare una tabella`,detail:`{table} è stata saltata: {reason}. Manca da questa documentazione.`},noForeignKeyMetadata:{title:`Nessuna relazione disponibile`,detail:`{engine} non riporta i metadati delle chiavi esterne, quindi non è stato possibile derivare alcuna relazione. Il diagramma è completo per questo motore.`},commentsUnsupported:{title:`Commenti del database non disponibili`,detail:`{engine} non supporta i commenti su tabelle o colonne, quindi ogni descrizione qui proviene dalle note di questo progetto.`},orphanedNotes:{title:`Alcune note non corrispondono più a nulla`,detail:`{count} nota/e fanno riferimento a una tabella o colonna che non esiste più. Nulla è stato eliminato — rimappa o rimuovi queste note nel file delle note.`},dbmlOmitted:{title:`Non rappresentabile in DBML`,detail:`{item} su {table} è documentato qui ma omesso dal DBML esportato: {reason}.`}}},ja:{title:`ドキュメント`,groupBySchema:`スキーマ`,groupByTableGroup:`テーブルグループ`,noGroup:`(グループなし)`,noSchema:`(スキーマなし)`,search:`テーブル、カラム、グループを検索…`,columns:`カラム`,indexes:`インデックス`,references:`参照`,referencedBy:`参照元`,localNote:`ローカル`,shadowedComment:`データベースのコメント: {comment}`,addNote:`メモを追加`,editNote:`メモを編集`,newGroup:`新しいグループ…`,groupName:`グループ名`,groupColour:`色`,deleteGroup:`グループを削除`,enumValues:`値`,usedBy:`使用元`,openDiagram:`スキーマ図を開く`,saving:`保存中…`,saved:`保存済み`,saveFailed:`メモを保存できませんでした: {error}`,overview:`概要`,groupBy:`グループ化`,searchLabel:`検索`,groups:`グループ`,relationships:`リレーションシップ`,columnHeader:`カラム`,typeHeader:`型`,settingsHeader:`設定`,noteHeader:`メモ`,nameHeader:`名前`,definitionHeader:`定義`,noOutgoingRelationships:`このテーブルは他のテーブルを参照していません。`,noIncomingRelationships:`このテーブルを参照しているテーブルはありません。`,diagram:`図`,language:`言語`,theme:`テーマ`,themeLight:`ライト`,themeDark:`ダーク`,exportHtml:`HTMLをエクスポート…`,exporting:`エクスポート中…`,exportFailed:`エクスポートできませんでした: {error}`,warnings:{tableSkipped:{title:`ドキュメント化できないテーブルがあります`,detail:`{table} はスキップされました: {reason}。このドキュメントには含まれていません。`},noForeignKeyMetadata:{title:`リレーションシップを表示できません`,detail:`{engine} は外部キーのメタデータを報告しないため、リレーションシップを導出できませんでした。この図はこのエンジンについては完全です。`},commentsUnsupported:{title:`データベースのコメントは利用できません`,detail:`{engine} はテーブルやカラムのコメントをサポートしていないため、ここでの説明はすべてこのプロジェクトのメモから提供されています。`},orphanedNotes:{title:`対象がなくなったメモがあります`,detail:`{count} 件のメモが、既に存在しないテーブルまたはカラムを参照しています。何も削除されていません。メモファイルで再割り当てまたは削除してください。`},dbmlOmitted:{title:`DBMLでは表現できません`,detail:`{table} の {item} はここに記載されていますが、エクスポートされたDBMLからは除外されています: {reason}。`}}},ko:{title:`문서`,groupBySchema:`스키마`,groupByTableGroup:`테이블 그룹`,noGroup:`(그룹 없음)`,noSchema:`(스키마 없음)`,search:`테이블, 컬럼, 그룹 검색…`,columns:`컬럼`,indexes:`인덱스`,references:`참조`,referencedBy:`참조된 위치`,localNote:`로컬`,shadowedComment:`데이터베이스 코멘트: {comment}`,addNote:`메모 추가`,editNote:`메모 편집`,newGroup:`새 그룹…`,groupName:`그룹 이름`,groupColour:`색상`,deleteGroup:`그룹 삭제`,enumValues:`값`,usedBy:`사용처`,openDiagram:`스키마 다이어그램 열기`,saving:`저장 중…`,saved:`저장됨`,saveFailed:`메모를 저장할 수 없습니다: {error}`,overview:`개요`,groupBy:`그룹화 기준`,searchLabel:`검색`,groups:`그룹`,relationships:`관계`,columnHeader:`컬럼`,typeHeader:`유형`,settingsHeader:`설정`,noteHeader:`메모`,nameHeader:`이름`,definitionHeader:`정의`,noOutgoingRelationships:`이 테이블은 다른 테이블을 참조하지 않습니다.`,noIncomingRelationships:`이 테이블을 참조하는 테이블이 없습니다.`,diagram:`다이어그램`,language:`언어`,theme:`테마`,themeLight:`라이트`,themeDark:`다크`,exportHtml:`HTML 내보내기…`,exporting:`내보내는 중…`,exportFailed:`내보낼 수 없습니다: {error}`,warnings:{tableSkipped:{title:`문서화할 수 없는 테이블이 있습니다`,detail:`{table} 을(를) 건너뛰었습니다: {reason}. 이 문서에서 누락되었습니다.`},noForeignKeyMetadata:{title:`표시할 관계가 없습니다`,detail:`{engine} 은(는) 외래 키 메타데이터를 보고하지 않으므로 관계를 도출할 수 없습니다. 이 엔진에 대해서는 다이어그램이 완전합니다.`},commentsUnsupported:{title:`데이터베이스 코멘트를 사용할 수 없습니다`,detail:`{engine} 은(는) 테이블 또는 컬럼 코멘트를 지원하지 않으므로 여기의 모든 설명은 이 프로젝트의 메모에서만 제공됩니다.`},orphanedNotes:{title:`더 이상 일치하는 대상이 없는 메모가 있습니다`,detail:`{count} 개의 메모가 더 이상 존재하지 않는 테이블 또는 컬럼을 참조하고 있습니다. 삭제된 항목은 없습니다 — 메모 파일에서 다시 매핑하거나 제거하세요.`},dbmlOmitted:{title:`DBML로 표현할 수 없습니다`,detail:`{table} 의 {item} 은(는) 여기에 문서화되어 있지만 내보낸 DBML에서는 제외되었습니다: {reason}.`}}},"pt-BR":{title:`Documentação`,groupBySchema:`Schemas`,groupByTableGroup:`Grupos de tabelas`,noGroup:`(sem grupo)`,noSchema:`(sem schema)`,search:`Buscar tabelas, colunas, grupos…`,columns:`Colunas`,indexes:`Índices`,references:`Referências`,referencedBy:`Referenciado por`,localNote:`LOCAL`,shadowedComment:`Comentário do banco de dados: {comment}`,addNote:`Adicionar uma nota`,editNote:`Editar nota`,newGroup:`Novo grupo…`,groupName:`Nome do grupo`,groupColour:`Cor`,deleteGroup:`Excluir grupo`,enumValues:`Valores`,usedBy:`Usado por`,openDiagram:`Abrir diagrama do schema`,saving:`Salvando…`,saved:`Salvo`,saveFailed:`Não foi possível salvar as notas: {error}`,overview:`Visão geral`,groupBy:`Agrupar por`,searchLabel:`Buscar`,groups:`Grupos`,relationships:`Relacionamentos`,columnHeader:`Coluna`,typeHeader:`Tipo`,settingsHeader:`Configurações`,noteHeader:`Nota`,nameHeader:`Nome`,definitionHeader:`Definição`,noOutgoingRelationships:`Esta tabela não referencia nenhuma outra tabela.`,noIncomingRelationships:`Nenhuma tabela referencia esta.`,diagram:`Diagrama`,language:`Idioma`,theme:`Tema`,themeLight:`Claro`,themeDark:`Escuro`,exportHtml:`Exportar HTML…`,exporting:`Exportando…`,exportFailed:`Não foi possível exportar: {error}`,warnings:{tableSkipped:{title:`Uma tabela não pôde ser documentada`,detail:`{table} foi ignorada: {reason}. Ela está faltando nesta documentação.`},noForeignKeyMetadata:{title:`Nenhum relacionamento disponível`,detail:`{engine} não reporta metadados de foreign key, então nenhum relacionamento pôde ser derivado. O diagrama está completo para este engine.`},commentsUnsupported:{title:`Comentários do banco de dados indisponíveis`,detail:`{engine} não suporta comentários em tabelas ou colunas, então toda descrição aqui vem apenas das notas deste projeto.`},orphanedNotes:{title:`Algumas notas não correspondem mais a nada`,detail:`{count} nota(s) referenciam uma tabela ou coluna que não existe mais. Nada foi excluído — remapeie ou remova essas notas no arquivo de notas.`},dbmlOmitted:{title:`Não representável em DBML`,detail:`{item} em {table} está documentado aqui mas foi omitido do DBML exportado: {reason}.`}}},"zh-CN":{title:`文档`,groupBySchema:`Schema`,groupByTableGroup:`表分组`,noGroup:`(无分组)`,noSchema:`(无 Schema)`,search:`搜索表、列、分组…`,columns:`列`,indexes:`索引`,references:`引用`,referencedBy:`被引用`,localNote:`本地`,shadowedComment:`数据库注释: {comment}`,addNote:`添加备注`,editNote:`编辑备注`,newGroup:`新建分组…`,groupName:`分组名称`,groupColour:`颜色`,deleteGroup:`删除分组`,enumValues:`值`,usedBy:`被使用于`,openDiagram:`打开 Schema 图`,saving:`保存中…`,saved:`已保存`,saveFailed:`无法保存备注: {error}`,overview:`概览`,groupBy:`分组方式`,searchLabel:`搜索`,groups:`分组`,relationships:`关系`,columnHeader:`列`,typeHeader:`类型`,settingsHeader:`设置`,noteHeader:`备注`,nameHeader:`名称`,definitionHeader:`定义`,noOutgoingRelationships:`此表未引用任何其他表。`,noIncomingRelationships:`没有表引用此表。`,diagram:`图`,language:`语言`,theme:`主题`,themeLight:`浅色`,themeDark:`深色`,exportHtml:`导出 HTML…`,exporting:`导出中…`,exportFailed:`无法导出: {error}`,warnings:{tableSkipped:{title:`有一张表无法生成文档`,detail:`{table} 被跳过: {reason}。此文档中缺少该表。`},noForeignKeyMetadata:{title:`没有可用的关系`,detail:`{engine} 不报告外键元数据,因此无法推导出任何关系。此图对该数据库引擎而言已经完整。`},commentsUnsupported:{title:`数据库注释不可用`,detail:`{engine} 不支持表或列注释,因此这里的所有描述均仅来自本项目的备注。`},orphanedNotes:{title:`部分备注已不再对应任何内容`,detail:`{count} 条备注引用的表或列已不存在。没有任何内容被删除 — 请在备注文件中重新映射或移除它们。`},dbmlOmitted:{title:`无法在 DBML 中表示`,detail:`{table} 上的 {item} 已在此处记录,但已从导出的 DBML 中省略: {reason}。`}}},"zh-TW":{title:`文件`,groupBySchema:`Schema`,groupByTableGroup:`資料表分組`,noGroup:`(無分組)`,noSchema:`(無 Schema)`,search:`搜尋資料表、欄位、分組…`,columns:`欄位`,indexes:`索引`,references:`參照`,referencedBy:`被參照`,localNote:`本機`,shadowedComment:`資料庫註解: {comment}`,addNote:`新增備註`,editNote:`編輯備註`,newGroup:`新增分組…`,groupName:`分組名稱`,groupColour:`顏色`,deleteGroup:`刪除分組`,enumValues:`值`,usedBy:`被使用於`,openDiagram:`開啟 Schema 圖`,saving:`儲存中…`,saved:`已儲存`,saveFailed:`無法儲存備註: {error}`,overview:`總覽`,groupBy:`分組方式`,searchLabel:`搜尋`,groups:`分組`,relationships:`關聯`,columnHeader:`欄位`,typeHeader:`類型`,settingsHeader:`設定`,noteHeader:`備註`,nameHeader:`名稱`,definitionHeader:`定義`,noOutgoingRelationships:`此資料表未參照任何其他資料表。`,noIncomingRelationships:`沒有資料表參照此資料表。`,diagram:`圖表`,language:`語言`,theme:`主題`,themeLight:`淺色`,themeDark:`深色`,exportHtml:`匯出 HTML…`,exporting:`匯出中…`,exportFailed:`無法匯出: {error}`,warnings:{tableSkipped:{title:`有一張資料表無法產生文件`,detail:`{table} 被略過: {reason}。此文件中缺少該資料表。`},noForeignKeyMetadata:{title:`沒有可用的關聯`,detail:`{engine} 未回報外鍵中繼資料,因此無法推導出任何關聯。此圖對該資料庫引擎而言已經完整。`},commentsUnsupported:{title:`資料庫註解無法使用`,detail:`{engine} 不支援資料表或欄位註解,因此這裡的所有說明均僅來自本專案的備註。`},orphanedNotes:{title:`部分備註已不再對應任何內容`,detail:`{count} 筆備註參照的資料表或欄位已不存在。沒有任何內容被刪除 — 請在備註檔案中重新對應或移除它們。`},dbmlOmitted:{title:`無法在 DBML 中表示`,detail:`{table} 上的 {item} 已在此處記錄,但已從匯出的 DBML 中省略: {reason}。`}}}};function id(e,t){let n=t.split(`.`).reduce((e,t)=>e&&typeof e==`object`?e[t]:void 0,e);return typeof n==`string`?n:null}function ad(e){let t=rd[e]??rd.en;return(e,n)=>{let r=e.startsWith(`docs.`)?e.slice(5):e,i=id(t,r)??id(rd.en,r);return i===null?e:n?i.replace(/\{(\w+)\}/g,(e,t)=>t in n?String(n[t]):e):i}}var od={class:`flex h-full min-h-0 flex-col bg-background text-foreground`},sd={class:`flex shrink-0 flex-wrap items-center justify-end gap-4 border-b border-border px-4 py-2`},cd={class:`flex items-center gap-2 text-xs text-muted-foreground`},ld={value:`light`},ud={value:`dark`},dd={class:`flex items-center gap-2 text-xs text-muted-foreground`},fd=[`value`],pd=L({__name:`ExportApp`,props:{payload:{}},setup(e){let t=e,n=P(t.payload.lang in rd?t.payload.lang:`en`),r=Y(()=>ad(n.value)),i=nd.filter(e=>e.value in rd),a=P(typeof window<`u`&&window.matchMedia?.(`(prefers-color-scheme: dark)`).matches?`dark`:`light`);Pn(a,e=>{let t=document.documentElement;t.classList.toggle(`dark`,e===`dark`),t.style.colorScheme=e},{immediate:!0}),Pn(n,e=>{document.documentElement.lang=e},{immediate:!0});let o=P(ed(location.hash,t.payload.snapshot,!0));function s(){o.value=ed(location.hash,t.payload.snapshot,!0)}function c(e){o.value=e;let t=td(e);location.hash!==t&&(location.hash=t)}return nr(()=>window.addEventListener(`hashchange`,s)),ar(()=>window.removeEventListener(`hashchange`,s)),(t,s)=>(U(),W(`div`,od,[G(`div`,sd,[G(`label`,cd,[zi(O(r.value(`docs.theme`))+` `,1),On(G(`select`,{"onUpdate:modelValue":s[0]||=e=>a.value=e,class:`rounded border border-border bg-background px-2 py-1 text-xs text-foreground`},[G(`option`,ld,O(r.value(`docs.themeLight`)),1),G(`option`,ud,O(r.value(`docs.themeDark`)),1)],512),[[no,a.value]])]),G(`label`,dd,[zi(O(r.value(`docs.language`))+` `,1),On(G(`select`,{"onUpdate:modelValue":s[1]||=e=>n.value=e,class:`rounded border border-border bg-background px-2 py-1 text-xs text-foreground`},[(U(!0),W(V,null,R(F(i),e=>(U(),W(`option`,{key:e.value,value:e.value},O(e.label),9,fd))),128))],512),[[no,n.value]])])]),K(Qu,{class:`min-h-0 flex-1`,snapshot:e.payload.snapshot,annotations:e.payload.annotations,readonly:!0,translate:r.value,route:o.value,diagram:`inline`,"onUpdate:route":c},null,8,[`snapshot`,`annotations`,`translate`,`route`])]))}});function md(){let e=document.querySelector(`script[type='application/dbx-snapshot']`);if(e===null)throw Error(`no <script type='application/dbx-snapshot'> in this document`);let t=atob((e.textContent??``).trim()),n=Uint8Array.from(t,e=>e.charCodeAt(0));return JSON.parse(new TextDecoder().decode(n))}try{mo(pd,{payload:md()}).mount(`#app`)}catch(e){let t=document.createElement(`p`);t.style.cssText=`margin:2rem;font-family:system-ui,sans-serif`,t.textContent=`This documentation file could not be read: ${e instanceof Error?e.message:String(e)}`,document.querySelector(`#app`)?.replaceChildren(t)}})();\ No newline at end of file+Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error occurred:</p><pre>`+ec(n.message+``,!0)+`</pre>`;return t?Promise.resolve(e):e}if(t)return Promise.reject(n);throw n}}},gc=new hc;function $(e,t){return gc.parse(e,t)}$.options=$.setOptions=function(e){return gc.setOptions(e),$.defaults=gc.defaults,Uo($.defaults),$},$.getDefaults=Vo,$.defaults=Ho,$.use=function(...e){return gc.use(...e),$.defaults=gc.defaults,Uo($.defaults),$},$.walkTokens=function(e,t){return gc.walkTokens(e,t)},$.parseInline=gc.parseInline,$.Parser=pc,$.parser=pc.parse,$.Renderer=dc,$.TextRenderer=fc,$.Lexer=uc,$.lexer=uc.lex,$.Tokenizer=lc,$.Hooks=mc,$.parse=$,$.options,$.setOptions,$.use,$.walkTokens,$.parseInline,pc.parse,uc.lex;function _c(e){return String(e??``).replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`).replace(/'/g,`'`)}var vc=/^(https?:|mailto:)/i;function yc(e){let t=String(e??``).trim();return t===``||/^[/\\]{2}/.test(t)?null:t.startsWith(`#`)||t.startsWith(`/`)||t.startsWith(`./`)||t.startsWith(`../`)||vc.test(t)?t:null}var bc=new hc({renderer:{html({text:e}){return _c(e)},link({href:e,title:t,tokens:n}){let r=this.parser.parseInline(n),i=yc(e);if(i===null)return r;let a=t?` title="${_c(t)}"`:``;return`<a href="${_c(i)}"${a}>${r}</a>`},image({href:e,title:t,text:n}){let r=yc(e);if(r===null)return _c(n);let i=t?` title="${_c(t)}"`:``;return`<img src="${_c(r)}" alt="${_c(n)}"${i}>`}}});function xc(e){return e===null||e.trim()===``?``:bc.parse(e)}var Sc={class:`text-sm text-muted-foreground`},Cc=[`title`,`innerHTML`],wc=L({__name:`NoteEditor`,props:{modelValue:{},readonly:{type:Boolean},translate:{type:Function}},emits:[`update:modelValue`],setup(e,{emit:t}){let n=e,r=t,i=P(!1),a=P(``),o=P(null);async function s(){n.readonly||(a.value=n.modelValue,i.value=!0,await hn(),o.value?.focus())}function c(){i.value=!1,a.value!==n.modelValue&&r(`update:modelValue`,a.value)}function l(){a.value=n.modelValue,i.value=!1}return(t,n)=>(U(),W(`div`,Sc,[i.value?On((U(),W(`textarea`,{key:0,ref_key:`input`,ref:o,"onUpdate:modelValue":n[0]||=e=>a.value=e,rows:`4`,class:`w-full resize-y rounded border border-border bg-background p-2 font-mono text-xs text-foreground outline-none focus:border-ring`,onBlur:n[1]||=e=>c(),onKeydown:n[2]||=lo(e=>l(),[`escape`])},null,544)),[[to,a.value]]):e.modelValue.trim()===``?e.readonly?q(``,!0):(U(),W(`button`,{key:2,type:`button`,class:`rounded border border-dashed border-border px-2 py-1 text-xs text-muted-foreground transition-colors hover:bg-muted/40`,onClick:n[4]||=e=>s()},O(e.translate(`docs.addNote`)),1)):(U(),W(`div`,{key:1,class:D([`leading-relaxed`,e.readonly?``:`cursor-text rounded transition-colors hover:bg-muted/30`]),title:e.readonly?void 0:e.translate(`docs.editNote`),onClick:n[3]||=e=>s(),innerHTML:F(xc)(e.modelValue)},null,10,Cc))]))}}),Tc={class:`flex flex-col gap-5`},Ec={class:`flex flex-col gap-2`},Dc={class:`flex flex-wrap items-center gap-2`},Oc={class:`font-mono text-lg font-semibold text-foreground`},kc={key:0,class:`rounded bg-muted/50 px-1.5 py-0.5 text-[10px] uppercase text-muted-foreground`},Ac={class:`mb-1.5 text-xs font-semibold uppercase tracking-wide text-muted-foreground`},jc={class:`flex flex-wrap gap-1`},Mc={class:`mb-1.5 text-xs font-semibold uppercase tracking-wide text-muted-foreground`},Nc={key:0,class:`text-xs text-muted-foreground`},Pc={key:1,class:`flex flex-col gap-1`},Fc=[`onClick`],Ic=L({__name:`EnumPage`,props:{enumType:{},snapshot:{},translate:{type:Function}},emits:[`select`],setup(e,{emit:t}){let n=e,r=t,i=Y(()=>n.enumType.schema?`${n.enumType.schema}.${n.enumType.name}`:n.enumType.name),a=Y(()=>Bo(n.snapshot,n.enumType.name));return(t,n)=>(U(),W(`article`,Tc,[G(`header`,Ec,[G(`div`,Dc,[G(`h2`,Oc,O(i.value),1),e.enumType.synthesized?(U(),W(`span`,kc,`synthesized`)):q(``,!0)]),K(wc,{"model-value":e.enumType.note??``,readonly:``,translate:e.translate},null,8,[`model-value`,`translate`])]),G(`section`,null,[G(`h3`,Ac,O(e.translate(`docs.enumValues`)),1),G(`ul`,jc,[(U(!0),W(V,null,R(e.enumType.values,e=>(U(),W(`li`,{key:e,class:`rounded bg-muted/50 px-1.5 py-0.5 font-mono text-[11px] text-foreground`},O(e),1))),128))])]),G(`section`,null,[G(`h3`,Mc,O(e.translate(`docs.usedBy`)),1),a.value.length===0?(U(),W(`p`,Nc,`No column uses this enum.`)):(U(),W(`ul`,Pc,[(U(!0),W(V,null,R(a.value,e=>(U(),W(`li`,{key:`${e.tableKey}.${e.column}`,class:`text-xs`},[G(`button`,{type:`button`,class:`w-full rounded border border-border bg-background px-2 py-1.5 text-left font-mono transition-colors hover:bg-muted/40`,onClick:t=>r(`select`,e.tableKey)},O(e.tableKey)+`.`+O(e.column),9,Fc)]))),128))]))])]))}}),Lc={class:`flex flex-col gap-3`},Rc={class:`flex flex-col gap-1`},zc={class:`text-[10px] uppercase tracking-wide text-muted-foreground`},Bc=[`value`,`placeholder`],Vc={class:`flex flex-col gap-2`},Hc={class:`text-[10px] uppercase tracking-wide text-muted-foreground`},Uc={class:`flex items-center gap-1.5`},Wc=[`title`,`onClick`],Gc=[`value`,`title`],Kc={class:`grid grid-cols-2 gap-2`},qc={class:`docs-ground-light flex items-center gap-2 overflow-hidden rounded border border-border bg-white p-2`},Jc={class:`dark flex items-center gap-2 overflow-hidden rounded border border-border bg-neutral-900 p-2`},Yc={class:`flex justify-end`},Xc=L({__name:`GroupEditor`,props:{group:{},translate:{type:Function}},emits:[`update:group`,`delete`],setup(e,{emit:t}){let n=e,r=t,i=Array.from({length:12},(e,t)=>t*30);function a(e){r(`update:group`,{...n.group,name:e.target.value})}function o(e){r(`update:group`,{...n.group,hue:e})}function s(e){o(Number(e.target.value))}function c(e){return`${n.translate(`docs.groupColour`)} ${e}°`}return(t,n)=>(U(),W(`div`,Lc,[G(`label`,Rc,[G(`span`,zc,O(e.translate(`docs.groupName`)),1),G(`input`,{type:`text`,value:e.group.name,placeholder:e.translate(`docs.groupName`),class:`rounded border border-border bg-background px-2 py-1 text-sm text-foreground outline-none focus:border-ring`,onInput:n[0]||=e=>a(e)},null,40,Bc)]),G(`div`,Vc,[G(`span`,Hc,O(e.translate(`docs.groupColour`)),1),G(`div`,Uc,[(U(!0),W(V,null,R(F(i),t=>(U(),W(`button`,{key:t,type:`button`,class:D([`docs-group h-6 w-6 rounded-full border ring-offset-background transition hover:scale-105`,e.group.hue===t?`ring-2 ring-ring ring-offset-2`:`border-border`]),style:E([{"background-color":`var(--group-c)`},F(Oo)(t)]),title:c(t),onClick:e=>o(t)},null,14,Wc))),128))]),G(`input`,{type:`range`,min:`0`,max:`359`,value:e.group.hue,class:`w-full`,title:c(e.group.hue),onInput:n[1]||=e=>s(e)},null,40,Gc),G(`div`,Kc,[G(`div`,qc,[G(`span`,{class:`docs-group h-4 w-4 shrink-0 rounded-full`,style:E([{"background-color":`var(--group-c)`},F(Oo)(e.group.hue)])},null,4),G(`span`,{class:`docs-group truncate rounded px-1.5 py-0.5 text-[11px] font-medium`,style:E([{"background-color":`var(--group-tint)`,color:`var(--group-c)`},F(Oo)(e.group.hue)])},O(e.group.name),5)]),G(`div`,Jc,[G(`span`,{class:`docs-group h-4 w-4 shrink-0 rounded-full`,style:E([{"background-color":`var(--group-c)`},F(Oo)(e.group.hue)])},null,4),G(`span`,{class:`docs-group truncate rounded px-1.5 py-0.5 text-[11px] font-medium`,style:E([{"background-color":`var(--group-tint)`,color:`var(--group-c)`},F(Oo)(e.group.hue)])},O(e.group.name),5)])])]),G(`div`,Yc,[G(`button`,{type:`button`,class:`rounded border border-border px-2 py-1 text-xs text-muted-foreground transition-colors hover:bg-muted/40`,onClick:n[2]||=t=>r(`delete`,e.group.id)},O(e.translate(`docs.deleteGroup`)),1)])]))}});function Zc(e,t={},n=!1){let r=Math.max(1,t.columnsPerRow??Math.ceil(Math.sqrt(Math.max(e.length,1)))),i=t.cardWidth??260,a=t.gapX??56,o=t.gapY??40,s=t.margin??40,c=t.rowHeight,l=e=>c??44+(e.columns?.length??0)*24+12,u={},d=s;for(let t=0;t<e.length;t+=r){let c=e.slice(t,t+r),f=Math.max(...c.map(l));c.forEach((e,t)=>{let r={x:s+t*(i+a),y:d};u[e.name]=r,n&&e.schema&&(u[`${e.schema}.${e.name}`]=r)}),d+=f+o}return u}function Qc(e,t,n){let r=t.x-e.x,i=t.y-e.y;if(r===0&&i===0)return{x:e.x,y:e.y};let a=r===0?1/0:n.width/Math.abs(r),o=i===0?1/0:n.height/Math.abs(i),s=Math.min(a,o);return{x:e.x+r*s,y:e.y+i*s}}var $c={class:`overflow-auto`},el=[`width`,`height`,`viewBox`],tl=[`x1`,`y1`,`x2`,`y2`],nl=[`x`,`y`,`onClick`],rl=[`x`,`y`],il=[`x`,`y`],al=260,ol=220,sl=40,cl=8,ll=L({__name:`SchemaDiagram`,props:{snapshot:{}},emits:[`select`],setup(e,{emit:t}){let n=e,r=t,i={width:al/2,height:ol/2},a=Y(()=>Zc(n.snapshot.tables.map(e=>({name:X(e),columns:e.columns})))),o=Y(()=>new Map(n.snapshot.groups.map(e=>[e.id,e]))),s=Y(()=>n.snapshot.tables.map(e=>{let t=X(e),n=a.value[t]??{x:sl,y:sl},r=e.groupId?o.value.get(e.groupId)??null:null;return{key:t,x:n.x,y:n.y,hue:r?.hue??null,columns:e.columns.slice(0,cl).map(e=>e.name)}}));function c(e){let t=a.value[e]??{x:sl,y:sl};return{x:t.x+al/2,y:t.y+ol/2}}let l=Y(()=>{let e=new Set(Object.keys(a.value));return n.snapshot.relationships.map(e=>({relationship:e,fromKey:X({schema:e.from.schema,name:e.from.table}),toKey:X({schema:e.to.schema,name:e.to.table})})).filter(({fromKey:t,toKey:n})=>e.has(t)&&e.has(n)).map(({relationship:e,fromKey:t,toKey:n})=>{let r=c(t),a=c(n);return{id:e.id,from:Qc(r,a,i),to:Qc(a,r,i)}})}),u=Y(()=>Math.max(0,...s.value.map(e=>e.x+al))+sl),d=Y(()=>Math.max(0,...s.value.map(e=>e.y+ol))+sl);function f(e){return e===null?{}:{...Oo(e),fill:`var(--group-tint)`}}return(e,t)=>(U(),W(`div`,$c,[(U(),W(`svg`,{width:u.value,height:d.value,viewBox:`0 0 ${u.value} ${d.value}`,class:`block`},[(U(!0),W(V,null,R(l.value,e=>(U(),W(`line`,{key:e.id,x1:e.from.x,y1:e.from.y,x2:e.to.x,y2:e.to.y,class:`stroke-border`,"stroke-width":`1.5`},null,8,tl))),128)),(U(!0),W(V,null,R(s.value,e=>(U(),W(`g`,{key:e.key},[G(`rect`,{x:e.x,y:e.y,width:al,height:ol,rx:`6`,class:D([`cursor-pointer stroke-border`,e.hue===null?`fill-card`:`docs-group`]),style:E(f(e.hue)),"stroke-width":`1`,onClick:t=>r(`select`,e.key)},null,14,nl),G(`text`,{x:e.x+10,y:e.y+22,class:`pointer-events-none fill-foreground font-mono text-[11px] font-semibold`},O(e.key),9,rl),(U(!0),W(V,null,R(e.columns,(t,n)=>(U(),W(`text`,{key:t,x:e.x+10,y:e.y+42+n*18,class:`pointer-events-none fill-muted-foreground font-mono text-[10px]`},O(t),9,il))),128))]))),128))],8,el))]))}}),ul={class:`overflow-hidden rounded-md border border-border`},dl={class:`w-full text-xs`},fl={class:`bg-muted/30`},pl={class:`px-2 py-1.5 text-left font-medium text-muted-foreground`},ml={class:`px-2 py-1.5 text-left font-medium text-muted-foreground`},hl={class:`px-2 py-1.5 text-left font-medium text-muted-foreground`},gl={class:`px-2 py-1.5 text-left font-medium text-muted-foreground`},_l={class:`px-2 py-1.5 font-mono font-medium text-foreground`},vl={class:`px-2 py-1.5 font-mono text-muted-foreground`},yl={class:`px-2 py-1.5`},bl={class:`flex flex-wrap gap-1`},xl={class:`px-2 py-1.5 text-muted-foreground`},Sl={class:`flex items-start gap-1`},Cl=[`title`],wl=L({__name:`ColumnTable`,props:{columns:{},columnNotes:{},tableKey:{},readonly:{type:Boolean},translate:{type:Function}},emits:[`edit`],setup(e,{emit:t}){let n=e,r=t;function i(e){let t=e.data_type.trim();if(t.includes(`(`))return t;if(e.character_maximum_length!==null)return`${t}(${e.character_maximum_length})`;if(e.numeric_precision!==null){let n=e.numeric_scale===null?``:`,${e.numeric_scale}`;return`${t}(${e.numeric_precision}${n})`}return t}function a(e){let t=[];return e.is_primary_key&&t.push(`pk`),e.is_nullable||t.push(`not null`),e.column_default!==null&&t.push(`default: ${e.column_default}`),e.extra!==null&&e.extra!==``&&t.push(e.extra),e.enum_values!==void 0&&e.enum_values.length>0&&t.push(`enum: ${e.enum_values.join(`, `)}`),t}function o(e){return n.columnNotes[e.name]??null}function s(e){let t=o(e)?.shadowed;return t?`Database comment: ${t}`:void 0}return(t,n)=>(U(),W(`div`,ul,[G(`table`,dl,[G(`thead`,null,[G(`tr`,fl,[G(`th`,pl,O(e.translate(`docs.columnHeader`)),1),G(`th`,ml,O(e.translate(`docs.typeHeader`)),1),G(`th`,hl,O(e.translate(`docs.settingsHeader`)),1),G(`th`,gl,O(e.translate(`docs.noteHeader`)),1)])]),G(`tbody`,null,[(U(!0),W(V,null,R(e.columns,t=>(U(),W(`tr`,{key:t.name,class:`border-t border-border align-top`},[G(`td`,_l,O(t.name),1),G(`td`,vl,O(i(t)),1),G(`td`,yl,[G(`div`,bl,[(U(!0),W(V,null,R(a(t),e=>(U(),W(`span`,{key:e,class:`rounded bg-muted/50 px-1.5 py-0.5 text-[10px] text-muted-foreground`},O(e),1))),128))])]),G(`td`,xl,[G(`div`,Sl,[o(t)?.source===`LOCAL`?(U(),W(`span`,{key:0,class:`mt-0.5 shrink-0 text-[10px] font-medium`,title:s(t)},`⬤ `+O(e.translate(`docs.localNote`)),9,Cl)):q(``,!0),K(wc,{class:`min-w-0 flex-1`,"model-value":o(t)?.note??``,readonly:e.readonly,translate:e.translate,"onUpdate:modelValue":n=>r(`edit`,{kind:`columnNote`,tableKey:e.tableKey,column:t.name,note:n})},null,8,[`model-value`,`readonly`,`translate`,`onUpdate:modelValue`])])])]))),128))])])]))}}),Tl={class:`flex items-center gap-1.5`},El=[`value`],Dl={value:``},Ol=[`value`],kl=`__dbx_new_group__`,Al=L({__name:`GroupPicker`,props:{groups:{},modelValue:{},translate:{type:Function}},emits:[`update:modelValue`,`create`],setup(e,{emit:t}){let n=e,r=t,i=Y(()=>n.groups.find(e=>e.id===n.modelValue)??null);function a(e){let t=e.target;if(t.value===kl&&!n.groups.some(e=>e.id===kl)){t.value=n.modelValue??``,r(`create`);return}r(`update:modelValue`,t.value===``?null:t.value)}return(t,n)=>(U(),W(`div`,Tl,[i.value?(U(),W(`span`,{key:0,class:`docs-group h-3 w-3 shrink-0 rounded-full`,style:E([{"background-color":`var(--group-c)`},F(Oo)(i.value.hue)])},null,4)):q(``,!0),G(`select`,{value:e.modelValue??``,class:`rounded border border-border bg-background px-2 py-1 text-xs text-foreground outline-none focus:border-ring`,onChange:n[0]||=e=>a(e)},[G(`option`,Dl,O(e.translate(`docs.noGroup`)),1),(U(!0),W(V,null,R(e.groups,e=>(U(),W(`option`,{key:e.id,value:e.id},O(e.name),9,Ol))),128)),G(`option`,{value:kl},O(e.translate(`docs.newGroup`)),1)],40,El)]))}}),jl={class:`grid gap-4 sm:grid-cols-2`},Ml={class:`mb-1.5 text-xs font-medium text-muted-foreground`},Nl={key:0,class:`text-xs text-muted-foreground`},Pl={key:1,class:`flex flex-col gap-1`},Fl=[`onClick`],Il={class:`font-mono`},Ll={class:`mx-1.5 text-muted-foreground`},Rl={class:`font-mono`},zl={key:0,class:`ml-1.5 text-[10px] text-muted-foreground`},Bl={class:`mb-1.5 text-xs font-medium text-muted-foreground`},Vl={key:0,class:`text-xs text-muted-foreground`},Hl={key:1,class:`flex flex-col gap-1`},Ul=[`onClick`],Wl={class:`font-mono`},Gl={class:`mx-1.5 text-muted-foreground`},Kl={class:`font-mono`},ql={key:0,class:`ml-1.5 text-[10px] text-muted-foreground`},Jl=L({__name:`RelationshipList`,props:{relationships:{},schema:{},table:{},translate:{type:Function}},emits:[`select`],setup(e,{emit:t}){let n=e,r=t;function i(e){return e.table===n.table&&(e.schema??null)===n.schema}function a(e){return X({schema:e.schema,name:e.table})}function o(e){return`${a(e)}.${e.column}`}function s(e){return e.cardinality===`ONE_TO_ONE`?`1 – 1`:`* – 1`}function c(e){let t=[];return e.onUpdate&&t.push(`on update ${e.onUpdate}`),e.onDelete&&t.push(`on delete ${e.onDelete}`),t}let l=Y(()=>n.relationships.filter(e=>i(e.from))),u=Y(()=>n.relationships.filter(e=>i(e.to)));return(t,n)=>(U(),W(`div`,jl,[G(`section`,null,[G(`h4`,Ml,O(e.translate(`docs.references`))+` (`+O(l.value.length)+`)`,1),l.value.length===0?(U(),W(`p`,Nl,O(e.translate(`docs.noOutgoingRelationships`)),1)):(U(),W(`ul`,Pl,[(U(!0),W(V,null,R(l.value,e=>(U(),W(`li`,{key:e.id,class:`text-xs`},[G(`button`,{type:`button`,class:`w-full rounded border border-border bg-background px-2 py-1.5 text-left transition-colors hover:bg-muted/40`,onClick:t=>r(`select`,a(e.to))},[G(`span`,Il,O(e.from.column),1),G(`span`,Ll,O(s(e)),1),G(`span`,Rl,O(o(e.to)),1),c(e).length>0?(U(),W(`span`,zl,O(c(e).join(`, `)),1)):q(``,!0)],8,Fl)]))),128))]))]),G(`section`,null,[G(`h4`,Bl,O(e.translate(`docs.referencedBy`))+` (`+O(u.value.length)+`)`,1),u.value.length===0?(U(),W(`p`,Vl,O(e.translate(`docs.noIncomingRelationships`)),1)):(U(),W(`ul`,Hl,[(U(!0),W(V,null,R(u.value,e=>(U(),W(`li`,{key:e.id,class:`text-xs`},[G(`button`,{type:`button`,class:`w-full rounded border border-border bg-background px-2 py-1.5 text-left transition-colors hover:bg-muted/40`,onClick:t=>r(`select`,a(e.from))},[G(`span`,Wl,O(o(e.from)),1),G(`span`,Gl,O(s(e)),1),G(`span`,Kl,O(e.to.column),1),c(e).length>0?(U(),W(`span`,ql,O(c(e).join(`, `)),1)):q(``,!0)],8,Ul)]))),128))]))])]))}}),Yl={class:`flex flex-col gap-5`},Xl={class:`flex flex-col gap-2`},Zl={class:`flex flex-wrap items-center gap-2`},Ql={class:`font-mono text-lg font-semibold text-foreground`},$l={class:`rounded bg-muted/50 px-1.5 py-0.5 text-[10px] uppercase text-muted-foreground`},eu={key:1,class:`text-[10px] text-muted-foreground`},tu={class:`flex items-start gap-2`},nu=[`title`],ru={class:`mb-1.5 text-xs font-semibold uppercase tracking-wide text-muted-foreground`},iu={key:0},au={class:`mb-1.5 text-xs font-semibold uppercase tracking-wide text-muted-foreground`},ou={class:`overflow-hidden rounded-md border border-border`},su={class:`w-full text-xs`},cu={class:`bg-muted/30`},lu={class:`px-2 py-1.5 text-left font-medium text-muted-foreground`},uu={class:`px-2 py-1.5 text-left font-medium text-muted-foreground`},du={class:`px-2 py-1.5 text-left font-medium text-muted-foreground`},fu={class:`px-2 py-1.5 font-mono`},pu={class:`px-2 py-1.5 font-mono text-muted-foreground`},mu={class:`px-2 py-1.5`},hu={class:`flex flex-wrap gap-1 text-[10px] text-muted-foreground`},gu={key:0,class:`rounded bg-muted/50 px-1.5 py-0.5`},_u={key:1,class:`rounded bg-muted/50 px-1.5 py-0.5`},vu={key:2,class:`rounded bg-muted/50 px-1.5 py-0.5`},yu={key:3,class:`rounded bg-muted/50 px-1.5 py-0.5`},bu={class:`mb-1.5 text-xs font-semibold uppercase tracking-wide text-muted-foreground`},xu={key:1},Su={class:`mb-1.5 text-xs font-semibold uppercase tracking-wide text-muted-foreground`},Cu={class:`overflow-x-auto rounded-md border border-border bg-muted/20 p-2 font-mono text-xs`},wu=L({__name:`TablePage`,props:{table:{},relationships:{},group:{},annotationGroups:{},readonly:{type:Boolean},translate:{type:Function}},emits:[`select`,`edit`,`createGroup`],setup(e,{emit:t}){let n=e,r=t,i=Y(()=>X(n.table)),a=Y(()=>n.table.kind.toLowerCase().replace(/_/g,` `)),o=Y(()=>n.table.shadowedNote?`Database comment: ${n.table.shadowedNote}`:void 0);return(t,n)=>(U(),W(`article`,Yl,[G(`header`,Xl,[G(`div`,Zl,[G(`h2`,Ql,O(i.value),1),G(`span`,$l,O(a.value),1),e.group?(U(),W(`span`,{key:0,class:`docs-group rounded px-1.5 py-0.5 text-[10px] font-medium`,style:E([{"background-color":`var(--group-tint)`,color:`var(--group-c)`},F(Oo)(e.group.hue)])},O(e.group.name),5)):q(``,!0),e.table.estimatedRows===null?q(``,!0):(U(),W(`span`,eu,` ~`+O(e.table.estimatedRows)+` rows `,1))]),G(`div`,tu,[e.table.noteSource===`LOCAL`?(U(),W(`span`,{key:0,class:`mt-0.5 shrink-0 text-[10px] font-medium text-muted-foreground`,title:o.value},`⬤ `+O(e.translate(`docs.localNote`)),9,nu)):q(``,!0),K(wc,{class:`min-w-0 flex-1`,"model-value":e.table.note??``,readonly:e.readonly,translate:e.translate,"onUpdate:modelValue":n[0]||=e=>r(`edit`,{kind:`tableNote`,tableKey:i.value,note:e})},null,8,[`model-value`,`readonly`,`translate`])]),e.readonly?q(``,!0):(U(),ji(Al,{key:0,groups:e.annotationGroups,"model-value":e.table.groupId,translate:e.translate,"onUpdate:modelValue":n[1]||=e=>r(`edit`,{kind:`tableGroup`,tableKey:i.value,groupId:e}),onCreate:n[2]||=e=>r(`createGroup`,i.value)},null,8,[`groups`,`model-value`,`translate`]))]),G(`section`,null,[G(`h3`,ru,O(e.translate(`docs.columns`)),1),K(wl,{columns:e.table.columns,"column-notes":e.table.columnNotes,"table-key":i.value,readonly:e.readonly,translate:e.translate,onEdit:n[3]||=e=>r(`edit`,e)},null,8,[`columns`,`column-notes`,`table-key`,`readonly`,`translate`])]),e.table.indexes.length>0?(U(),W(`section`,iu,[G(`h3`,au,O(e.translate(`docs.indexes`)),1),G(`div`,ou,[G(`table`,su,[G(`thead`,null,[G(`tr`,cu,[G(`th`,lu,O(e.translate(`docs.nameHeader`)),1),G(`th`,uu,O(e.translate(`docs.columns`)),1),G(`th`,du,O(e.translate(`docs.settingsHeader`)),1)])]),G(`tbody`,null,[(U(!0),W(V,null,R(e.table.indexes,e=>(U(),W(`tr`,{key:e.name,class:`border-t border-border align-top`},[G(`td`,fu,O(e.name),1),G(`td`,pu,[zi(O(e.columns.join(`, `)),1),e.included_columns&&e.included_columns.length>0?(U(),W(V,{key:0},[zi(` (include `+O(e.included_columns.join(`, `))+`) `,1)],64)):q(``,!0)]),G(`td`,mu,[G(`div`,hu,[e.is_primary?(U(),W(`span`,gu,`pk`)):q(``,!0),e.is_unique?(U(),W(`span`,_u,`unique`)):q(``,!0),e.index_type?(U(),W(`span`,vu,O(e.index_type),1)):q(``,!0),e.filter?(U(),W(`span`,yu,`where `+O(e.filter),1)):q(``,!0)])])]))),128))])])])])):q(``,!0),G(`section`,null,[G(`h3`,bu,O(e.translate(`docs.relationships`)),1),K(Jl,{relationships:e.relationships,schema:e.table.schema,table:e.table.name,translate:e.translate,onSelect:n[4]||=e=>r(`select`,e)},null,8,[`relationships`,`schema`,`table`,`translate`])]),e.table.viewDefinition?(U(),W(`section`,xu,[G(`h3`,Su,O(e.translate(`docs.definitionHeader`)),1),G(`pre`,Cu,O(e.table.viewDefinition),1)])):q(``,!0)]))}});function Tu(e,t){switch(e.kind){case`tableSkipped`:return{severity:`warning`,title:t(`docs.warnings.tableSkipped.title`),detail:t(`docs.warnings.tableSkipped.detail`,{table:e.table,reason:e.reason})};case`noForeignKeyMetadata`:return{severity:`info`,title:t(`docs.warnings.noForeignKeyMetadata.title`),detail:t(`docs.warnings.noForeignKeyMetadata.detail`,{engine:e.engine})};case`commentsUnsupported`:return{severity:`info`,title:t(`docs.warnings.commentsUnsupported.title`),detail:t(`docs.warnings.commentsUnsupported.detail`,{engine:e.engine})};case`orphanedNotes`:return{severity:`warning`,title:t(`docs.warnings.orphanedNotes.title`),detail:t(`docs.warnings.orphanedNotes.detail`,{count:e.count})};case`dbmlOmitted`:return{severity:`info`,title:t(`docs.warnings.dbmlOmitted.title`),detail:t(`docs.warnings.dbmlOmitted.detail`,{item:e.item,table:e.table,reason:e.reason})}}}var Eu={key:0,class:`flex flex-col gap-2`},Du={class:`font-medium`},Ou={class:`mt-0.5 leading-relaxed`},ku=L({__name:`WarningBanner`,props:{warnings:{},translate:{type:Function}},setup(e){let t=e,n=Y(()=>t.warnings.map((e,n)=>({key:`${e.kind}-${n}`,...Tu(e,t.translate)})));return(e,t)=>n.value.length>0?(U(),W(`div`,Eu,[(U(!0),W(V,null,R(n.value,e=>(U(),W(`div`,{key:e.key,class:D([`rounded-md border px-3 py-2 text-xs`,e.severity===`warning`?`border-amber-300 bg-amber-50 text-amber-900 dark:border-amber-900/40 dark:bg-amber-950/30 dark:text-amber-200`:`border-border bg-muted/30 text-muted-foreground`])},[G(`div`,Du,O(e.title),1),G(`div`,Ou,O(e.detail),1)],2))),128))])):q(``,!0)}}),Au={class:`flex flex-col gap-6`},ju={class:`flex items-baseline gap-2`},Mu={class:`text-sm font-semibold text-foreground`},Nu={class:`text-xs text-muted-foreground`},Pu=[`innerHTML`],Fu={class:`grid gap-1 sm:grid-cols-2 lg:grid-cols-3`},Iu=[`onClick`],Lu={class:`font-mono text-xs font-medium text-foreground`},Ru={key:0,class:`text-[10px] uppercase text-muted-foreground`},zu=[`innerHTML`],Bu=L({__name:`WikiIndex`,props:{sections:{},translate:{type:Function}},emits:[`select`],setup(e,{emit:t}){let n=t;return(t,r)=>(U(),W(`div`,Au,[(U(!0),W(V,null,R(e.sections,t=>(U(),W(`section`,{key:t.key,class:`flex flex-col gap-2`},[G(`div`,{class:D([`flex flex-col gap-1 border-l-2 pl-3`,{"docs-group":t.hue!==null}]),style:E([{"border-color":`var(--group-c, var(--border))`},F(Oo)(t.hue)])},[G(`div`,ju,[G(`h2`,Mu,O(t.label||e.translate(t.fallbackKey)),1),G(`span`,Nu,O(t.tables.length)+` tables`,1)]),t.note?(U(),W(`div`,{key:0,class:`text-xs text-muted-foreground`,innerHTML:F(xc)(t.note)},null,8,Pu)):q(``,!0)],6),G(`ul`,Fu,[(U(!0),W(V,null,R(t.tables,e=>(U(),W(`li`,{key:F(X)(e),class:`flex flex-col gap-0.5 rounded border border-border bg-background px-2 py-1.5 transition-colors hover:bg-muted/40`},[G(`button`,{type:`button`,class:`flex w-full items-baseline gap-1.5 text-left`,onClick:t=>n(`select`,F(X)(e))},[G(`span`,Lu,O(e.name),1),e.kind===`TABLE`?q(``,!0):(U(),W(`span`,Ru,O(e.kind.toLowerCase().replace(/_/g,` `)),1))],8,Iu),e.note?(U(),W(`div`,{key:0,class:`line-clamp-2 text-[11px] text-muted-foreground`,innerHTML:F(xc)(e.note)},null,8,zu)):q(``,!0)]))),128))])]))),128))]))}});function Vu(){if(typeof crypto<`u`&&typeof crypto.randomUUID==`function`)return crypto.randomUUID();if(typeof crypto<`u`&&typeof crypto.getRandomValues==`function`){let e=crypto.getRandomValues(new Uint8Array(16));return e[6]=e[6]&15|64,e[8]=e[8]&63|128,Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``).replace(/^(.{8})(.{4})(.{4})(.{4})(.{12})$/,`$1-$2-$3-$4-$5`)}return`xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx`.replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e===`x`?t:t&3|8).toString(16)})}var Hu={class:`flex h-full min-h-0 bg-background text-foreground`},Uu={class:`flex h-full min-h-0 w-64 shrink-0 flex-col`},Wu={class:`flex min-w-0 flex-1 flex-col gap-4 overflow-y-auto p-4`},Gu={class:`flex flex-wrap items-start justify-between gap-3`},Ku={class:`flex flex-col gap-1`},qu={class:`text-base font-semibold`},Ju={class:`text-xs text-muted-foreground`},Yu={key:0,class:`flex flex-col gap-4`},Xu={key:0,class:`flex flex-col gap-2`},Zu={class:`text-xs font-semibold uppercase tracking-wide text-muted-foreground`},Qu=L({__name:`DocsApp`,props:{snapshot:{},annotations:{},readonly:{type:Boolean},translate:{},route:{},diagram:{default:`external`}},emits:[`edit`,`update:route`],setup(e,{emit:t}){let n=e,r=t,i=Y(()=>n.readonly??!1),a=Y(()=>n.annotations.groups??[]),o=P(n.snapshot.groups.length>0?`group`:`schema`),s=P(null),c=P(null),l=P(!1),u=Y(()=>n.route?n.route:l.value?{kind:`diagram`}:c.value===null?s.value===null?{kind:`index`}:{kind:`table`,key:s.value}:{kind:`enum`,name:c.value}),d=Y(()=>u.value.kind===`table`?u.value.key:null),f=Y(()=>u.value.kind===`enum`?u.value.name:null),p=Y(()=>o.value===`schema`?Ro(n.snapshot):zo(n.snapshot)),m=Y(()=>n.snapshot.tables.find(e=>X(e)===d.value)??null),h=Y(()=>f.value===null?null:n.snapshot.enums.find(e=>e.name===f.value)??null),g=Y(()=>u.value.kind===`diagram`?`diagram`:h.value===null?m.value===null?`index`:`table`:`enum`),_=Y(()=>{let e=m.value?.groupId;return e?n.snapshot.groups.find(t=>t.id===e)??null:null});function v(e){n.snapshot.tables.some(t=>X(t)===e)&&(c.value=null,l.value=!1,s.value=e,r(`update:route`,{kind:`table`,key:e}))}function y(e){n.snapshot.enums.some(t=>t.name===e)&&(s.value=null,l.value=!1,c.value=e,r(`update:route`,{kind:`enum`,name:e}))}function b(){s.value=null,c.value=null,l.value=!0,r(`update:route`,{kind:`diagram`})}function x(){s.value=null,c.value=null,l.value=!1,r(`update:route`,{kind:`index`})}function ee(e){let t={id:Vu(),name:n.translate(`docs.newGroup`),hue:a.value.length*47%360};r(`edit`,{kind:`upsertGroup`,group:t}),r(`edit`,{kind:`tableGroup`,tableKey:e,groupId:t.id})}return(t,n)=>(U(),W(`div`,Hu,[G(`div`,Uu,[K(Io,{class:`min-h-0 flex-1`,sections:p.value,mode:o.value,"active-key":d.value,translate:e.translate,"onUpdate:mode":n[0]||=e=>o.value=e,onSelect:v,onHome:n[1]||=e=>x()},null,8,[`sections`,`mode`,`active-key`,`translate`]),e.diagram===`inline`?(U(),W(`button`,{key:0,type:`button`,class:D([`shrink-0 border-t border-r border-border bg-background px-3 py-2 text-left text-xs font-medium transition-colors`,g.value===`diagram`?`bg-muted text-foreground`:`text-muted-foreground hover:bg-muted/40`]),onClick:n[2]||=e=>b()},O(e.translate(`docs.diagram`)),3)):q(``,!0)]),G(`main`,Wu,[G(`header`,Gu,[G(`div`,Ku,[G(`h1`,qu,O(e.snapshot.project.name),1),G(`p`,Ju,[zi(O(e.snapshot.project.databaseType),1),e.snapshot.project.database?(U(),W(V,{key:0},[zi(` · `+O(e.snapshot.project.database),1)],64)):q(``,!0),zi(` · `+O(e.snapshot.tables.length)+` tables · generated `+O(e.snapshot.project.generatedAt),1)])]),K(Do,{snapshot:e.snapshot,translate:e.translate,onSelect:v,onSelectEnum:y},null,8,[`snapshot`,`translate`])]),K(ku,{warnings:e.snapshot.warnings,translate:e.translate},null,8,[`warnings`,`translate`]),g.value===`index`?(U(),W(`div`,Yu,[K(wc,{"model-value":e.snapshot.project.note??``,readonly:i.value,translate:e.translate,"onUpdate:modelValue":n[3]||=e=>r(`edit`,{kind:`projectNote`,note:e})},null,8,[`model-value`,`readonly`,`translate`]),K(Bu,{sections:p.value,translate:e.translate,onSelect:v},null,8,[`sections`,`translate`]),!i.value&&a.value.length>0?(U(),W(`section`,Xu,[G(`h2`,Zu,O(e.translate(`docs.groups`)),1),(U(!0),W(V,null,R(a.value,t=>(U(),ji(Xc,{key:t.id,group:t,translate:e.translate,"onUpdate:group":n[4]||=e=>r(`edit`,{kind:`upsertGroup`,group:e}),onDelete:n[5]||=e=>r(`edit`,{kind:`removeGroup`,groupId:e})},null,8,[`group`,`translate`]))),128))])):q(``,!0)])):g.value===`table`&&m.value?(U(),ji(wu,{key:1,table:m.value,relationships:e.snapshot.relationships,group:_.value,"annotation-groups":a.value,readonly:i.value,translate:e.translate,onSelect:v,onEdit:n[6]||=e=>r(`edit`,e),onCreateGroup:ee},null,8,[`table`,`relationships`,`group`,`annotation-groups`,`readonly`,`translate`])):h.value?(U(),ji(Ic,{key:2,"enum-type":h.value,snapshot:e.snapshot,translate:e.translate,onSelect:v},null,8,[`enum-type`,`snapshot`,`translate`])):g.value===`diagram`?(U(),ji(ll,{key:3,snapshot:e.snapshot,onSelect:v},null,8,[`snapshot`])):q(``,!0)])]))}}),$u={kind:`index`};function ed(e,t,n){if(!e.startsWith(`#`))return $u;let[r,...i]=e.slice(1).replace(/^\//,``).split(`/`),a=i.join(`/`);if(r===`diagram`&&a===``)return n?{kind:`diagram`}:$u;if(a===``)return $u;let o;try{o=decodeURIComponent(a)}catch{return $u}return r===`table`?t.tables.some(e=>X(e)===o)?{kind:`table`,key:o}:$u:r===`enum`&&(t.enums??[]).some(e=>e.name===o)?{kind:`enum`,name:o}:$u}function td(e){switch(e.kind){case`table`:return`#/table/${encodeURIComponent(e.key)}`;case`enum`:return`#/enum/${encodeURIComponent(e.name)}`;case`diagram`:return`#/diagram`;default:return`#/`}}var nd=[{value:`en`,flag:`🇺🇸`,label:`English`},{value:`az`,flag:`🇦🇿`,label:`Azərbaycan`},{value:`es`,flag:`🇪🇸`,label:`Español`},{value:`id`,flag:`🇮🇩`,label:`Bahasa Indonesia`},{value:`it`,flag:`🇮🇹`,label:`Italiano`},{value:`ja`,flag:`🇯🇵`,label:`日本語`},{value:`ko`,flag:`🇰🇷`,label:`한국어`},{value:`pt-BR`,flag:`🇧🇷`,label:`Português`},{value:`ru`,flag:`🇷🇺`,label:`Русский`},{value:`tr`,flag:`🇹🇷`,label:`Türkçe`},{value:`zh-CN`,flag:`🇨🇳`,label:`简体中文`},{value:`zh-TW`,flag:`繁`,label:`繁體中文`}],rd={en:{title:`Documentation`,groupBySchema:`Schemas`,groupByTableGroup:`Table Groups`,noGroup:`(no group)`,noSchema:`(no schema)`,search:`Search tables, columns, groups…`,columns:`Columns`,indexes:`Indexes`,references:`References`,referencedBy:`Referenced by`,localNote:`LOCAL`,shadowedComment:`Database comment: {comment}`,addNote:`Add a note`,editNote:`Edit note`,newGroup:`New group…`,groupName:`Group name`,groupColour:`Colour`,deleteGroup:`Delete group`,enumValues:`Values`,usedBy:`Used by`,openDiagram:`Open schema diagram`,saving:`Saving…`,saved:`Saved`,saveFailed:`Could not save notes: {error}`,overview:`Overview`,groupBy:`Group by`,searchLabel:`Search`,groups:`Groups`,relationships:`Relationships`,columnHeader:`Column`,typeHeader:`Type`,settingsHeader:`Settings`,noteHeader:`Note`,nameHeader:`Name`,definitionHeader:`Definition`,noOutgoingRelationships:`This table references no other table.`,noIncomingRelationships:`No table references this one.`,diagram:`Diagram`,language:`Language`,theme:`Theme`,themeLight:`Light`,themeDark:`Dark`,exportHtml:`Export HTML…`,exporting:`Exporting…`,exportFailed:`Could not export: {error}`,warnings:{tableSkipped:{title:`A table could not be documented`,detail:`{table} was skipped: {reason}. It is missing from this documentation.`},noForeignKeyMetadata:{title:`No relationships available`,detail:`{engine} does not report foreign key metadata, so no relationship edges could be derived. The diagram is complete for this engine.`},commentsUnsupported:{title:`Database comments unavailable`,detail:`{engine} does not support table or column comments, so every description here comes from this project's own notes.`},orphanedNotes:{title:`Some notes no longer match anything`,detail:`{count} note(s) refer to a table or column that no longer exists. Nothing was deleted — re-map or remove them in the notes file.`},dbmlOmitted:{title:`Not representable in DBML`,detail:`{item} on {table} is documented here but omitted from the exported DBML: {reason}.`}}},es:{title:`Documentación`,groupBySchema:`Esquemas`,groupByTableGroup:`Grupos de tablas`,noGroup:`(sin grupo)`,noSchema:`(sin esquema)`,search:`Buscar tablas, columnas, grupos…`,columns:`Columnas`,indexes:`Índices`,references:`Referencias`,referencedBy:`Referenciado por`,localNote:`LOCAL`,shadowedComment:`Comentario de la base de datos: {comment}`,addNote:`Agregar una nota`,editNote:`Editar nota`,newGroup:`Nuevo grupo…`,groupName:`Nombre del grupo`,groupColour:`Color`,deleteGroup:`Eliminar grupo`,enumValues:`Valores`,usedBy:`Usado por`,openDiagram:`Abrir diagrama del esquema`,saving:`Guardando…`,saved:`Guardado`,saveFailed:`No se pudieron guardar las notas: {error}`,overview:`Información general`,groupBy:`Agrupar por`,searchLabel:`Buscar`,groups:`Grupos`,relationships:`Relaciones`,columnHeader:`Columna`,typeHeader:`Tipo`,settingsHeader:`Configuración`,noteHeader:`Nota`,nameHeader:`Nombre`,definitionHeader:`Definición`,noOutgoingRelationships:`Esta tabla no referencia ninguna otra tabla.`,noIncomingRelationships:`Ninguna tabla referencia esta.`,diagram:`Diagrama`,language:`Idioma`,theme:`Tema`,themeLight:`Claro`,themeDark:`Oscuro`,exportHtml:`Exportar HTML…`,exporting:`Exportando…`,exportFailed:`No se pudo exportar: {error}`,warnings:{tableSkipped:{title:`No se pudo documentar una tabla`,detail:`{table} fue omitida: {reason}. Falta en esta documentación.`},noForeignKeyMetadata:{title:`No hay relaciones disponibles`,detail:`{engine} no reporta metadatos de claves foráneas, por lo que no se pudieron derivar relaciones. El diagrama está completo para este motor.`},commentsUnsupported:{title:`Comentarios de base de datos no disponibles`,detail:`{engine} no admite comentarios en tablas o columnas, por lo que toda descripción aquí proviene de las notas de este proyecto.`},orphanedNotes:{title:`Algunas notas ya no coinciden con nada`,detail:`{count} nota(s) hacen referencia a una tabla o columna que ya no existe. No se eliminó nada — vuelva a asignarlas o elimínelas en el archivo de notas.`},dbmlOmitted:{title:`No representable en DBML`,detail:`{item} en {table} está documentado aquí pero se omitió del DBML exportado: {reason}.`}}},it:{title:`Documentazione`,groupBySchema:`Schemi`,groupByTableGroup:`Gruppi di tabelle`,noGroup:`(nessun gruppo)`,noSchema:`(nessuno schema)`,search:`Cerca tabelle, colonne, gruppi…`,columns:`Colonne`,indexes:`Indici`,references:`Riferimenti`,referencedBy:`Referenziato da`,localNote:`LOCALE`,shadowedComment:`Commento del database: {comment}`,addNote:`Aggiungi una nota`,editNote:`Modifica nota`,newGroup:`Nuovo gruppo…`,groupName:`Nome del gruppo`,groupColour:`Colore`,deleteGroup:`Elimina gruppo`,enumValues:`Valori`,usedBy:`Usato da`,openDiagram:`Apri diagramma dello schema`,saving:`Salvataggio…`,saved:`Salvato`,saveFailed:`Impossibile salvare le note: {error}`,overview:`Panoramica`,groupBy:`Raggruppa per`,searchLabel:`Cerca`,groups:`Gruppi`,relationships:`Relazioni`,columnHeader:`Colonna`,typeHeader:`Tipo`,settingsHeader:`Impostazioni`,noteHeader:`Nota`,nameHeader:`Nome`,definitionHeader:`Definizione`,noOutgoingRelationships:`Questa tabella non fa riferimento a nessun'altra tabella.`,noIncomingRelationships:`Nessuna tabella fa riferimento a questa.`,diagram:`Diagramma`,language:`Lingua`,theme:`Tema`,themeLight:`Chiaro`,themeDark:`Scuro`,exportHtml:`Esporta HTML…`,exporting:`Esportazione…`,exportFailed:`Impossibile esportare: {error}`,warnings:{tableSkipped:{title:`Impossibile documentare una tabella`,detail:`{table} è stata saltata: {reason}. Manca da questa documentazione.`},noForeignKeyMetadata:{title:`Nessuna relazione disponibile`,detail:`{engine} non riporta i metadati delle chiavi esterne, quindi non è stato possibile derivare alcuna relazione. Il diagramma è completo per questo motore.`},commentsUnsupported:{title:`Commenti del database non disponibili`,detail:`{engine} non supporta i commenti su tabelle o colonne, quindi ogni descrizione qui proviene dalle note di questo progetto.`},orphanedNotes:{title:`Alcune note non corrispondono più a nulla`,detail:`{count} nota/e fanno riferimento a una tabella o colonna che non esiste più. Nulla è stato eliminato — rimappa o rimuovi queste note nel file delle note.`},dbmlOmitted:{title:`Non rappresentabile in DBML`,detail:`{item} su {table} è documentato qui ma omesso dal DBML esportato: {reason}.`}}},ja:{title:`ドキュメント`,groupBySchema:`スキーマ`,groupByTableGroup:`テーブルグループ`,noGroup:`(グループなし)`,noSchema:`(スキーマなし)`,search:`テーブル、カラム、グループを検索…`,columns:`カラム`,indexes:`インデックス`,references:`参照`,referencedBy:`参照元`,localNote:`ローカル`,shadowedComment:`データベースのコメント: {comment}`,addNote:`メモを追加`,editNote:`メモを編集`,newGroup:`新しいグループ…`,groupName:`グループ名`,groupColour:`色`,deleteGroup:`グループを削除`,enumValues:`値`,usedBy:`使用元`,openDiagram:`スキーマ図を開く`,saving:`保存中…`,saved:`保存済み`,saveFailed:`メモを保存できませんでした: {error}`,overview:`概要`,groupBy:`グループ化`,searchLabel:`検索`,groups:`グループ`,relationships:`リレーションシップ`,columnHeader:`カラム`,typeHeader:`型`,settingsHeader:`設定`,noteHeader:`メモ`,nameHeader:`名前`,definitionHeader:`定義`,noOutgoingRelationships:`このテーブルは他のテーブルを参照していません。`,noIncomingRelationships:`このテーブルを参照しているテーブルはありません。`,diagram:`図`,language:`言語`,theme:`テーマ`,themeLight:`ライト`,themeDark:`ダーク`,exportHtml:`HTMLをエクスポート…`,exporting:`エクスポート中…`,exportFailed:`エクスポートできませんでした: {error}`,warnings:{tableSkipped:{title:`ドキュメント化できないテーブルがあります`,detail:`{table} はスキップされました: {reason}。このドキュメントには含まれていません。`},noForeignKeyMetadata:{title:`リレーションシップを表示できません`,detail:`{engine} は外部キーのメタデータを報告しないため、リレーションシップを導出できませんでした。この図はこのエンジンについては完全です。`},commentsUnsupported:{title:`データベースのコメントは利用できません`,detail:`{engine} はテーブルやカラムのコメントをサポートしていないため、ここでの説明はすべてこのプロジェクトのメモから提供されています。`},orphanedNotes:{title:`対象がなくなったメモがあります`,detail:`{count} 件のメモが、既に存在しないテーブルまたはカラムを参照しています。何も削除されていません。メモファイルで再割り当てまたは削除してください。`},dbmlOmitted:{title:`DBMLでは表現できません`,detail:`{table} の {item} はここに記載されていますが、エクスポートされたDBMLからは除外されています: {reason}。`}}},ko:{title:`문서`,groupBySchema:`스키마`,groupByTableGroup:`테이블 그룹`,noGroup:`(그룹 없음)`,noSchema:`(스키마 없음)`,search:`테이블, 컬럼, 그룹 검색…`,columns:`컬럼`,indexes:`인덱스`,references:`참조`,referencedBy:`참조된 위치`,localNote:`로컬`,shadowedComment:`데이터베이스 코멘트: {comment}`,addNote:`메모 추가`,editNote:`메모 편집`,newGroup:`새 그룹…`,groupName:`그룹 이름`,groupColour:`색상`,deleteGroup:`그룹 삭제`,enumValues:`값`,usedBy:`사용처`,openDiagram:`스키마 다이어그램 열기`,saving:`저장 중…`,saved:`저장됨`,saveFailed:`메모를 저장할 수 없습니다: {error}`,overview:`개요`,groupBy:`그룹화 기준`,searchLabel:`검색`,groups:`그룹`,relationships:`관계`,columnHeader:`컬럼`,typeHeader:`유형`,settingsHeader:`설정`,noteHeader:`메모`,nameHeader:`이름`,definitionHeader:`정의`,noOutgoingRelationships:`이 테이블은 다른 테이블을 참조하지 않습니다.`,noIncomingRelationships:`이 테이블을 참조하는 테이블이 없습니다.`,diagram:`다이어그램`,language:`언어`,theme:`테마`,themeLight:`라이트`,themeDark:`다크`,exportHtml:`HTML 내보내기…`,exporting:`내보내는 중…`,exportFailed:`내보낼 수 없습니다: {error}`,warnings:{tableSkipped:{title:`문서화할 수 없는 테이블이 있습니다`,detail:`{table} 을(를) 건너뛰었습니다: {reason}. 이 문서에서 누락되었습니다.`},noForeignKeyMetadata:{title:`표시할 관계가 없습니다`,detail:`{engine} 은(는) 외래 키 메타데이터를 보고하지 않으므로 관계를 도출할 수 없습니다. 이 엔진에 대해서는 다이어그램이 완전합니다.`},commentsUnsupported:{title:`데이터베이스 코멘트를 사용할 수 없습니다`,detail:`{engine} 은(는) 테이블 또는 컬럼 코멘트를 지원하지 않으므로 여기의 모든 설명은 이 프로젝트의 메모에서만 제공됩니다.`},orphanedNotes:{title:`더 이상 일치하는 대상이 없는 메모가 있습니다`,detail:`{count} 개의 메모가 더 이상 존재하지 않는 테이블 또는 컬럼을 참조하고 있습니다. 삭제된 항목은 없습니다 — 메모 파일에서 다시 매핑하거나 제거하세요.`},dbmlOmitted:{title:`DBML로 표현할 수 없습니다`,detail:`{table} 의 {item} 은(는) 여기에 문서화되어 있지만 내보낸 DBML에서는 제외되었습니다: {reason}.`}}},"pt-BR":{title:`Documentação`,groupBySchema:`Schemas`,groupByTableGroup:`Grupos de tabelas`,noGroup:`(sem grupo)`,noSchema:`(sem schema)`,search:`Buscar tabelas, colunas, grupos…`,columns:`Colunas`,indexes:`Índices`,references:`Referências`,referencedBy:`Referenciado por`,localNote:`LOCAL`,shadowedComment:`Comentário do banco de dados: {comment}`,addNote:`Adicionar uma nota`,editNote:`Editar nota`,newGroup:`Novo grupo…`,groupName:`Nome do grupo`,groupColour:`Cor`,deleteGroup:`Excluir grupo`,enumValues:`Valores`,usedBy:`Usado por`,openDiagram:`Abrir diagrama do schema`,saving:`Salvando…`,saved:`Salvo`,saveFailed:`Não foi possível salvar as notas: {error}`,overview:`Visão geral`,groupBy:`Agrupar por`,searchLabel:`Buscar`,groups:`Grupos`,relationships:`Relacionamentos`,columnHeader:`Coluna`,typeHeader:`Tipo`,settingsHeader:`Configurações`,noteHeader:`Nota`,nameHeader:`Nome`,definitionHeader:`Definição`,noOutgoingRelationships:`Esta tabela não referencia nenhuma outra tabela.`,noIncomingRelationships:`Nenhuma tabela referencia esta.`,diagram:`Diagrama`,language:`Idioma`,theme:`Tema`,themeLight:`Claro`,themeDark:`Escuro`,exportHtml:`Exportar HTML…`,exporting:`Exportando…`,exportFailed:`Não foi possível exportar: {error}`,warnings:{tableSkipped:{title:`Uma tabela não pôde ser documentada`,detail:`{table} foi ignorada: {reason}. Ela está faltando nesta documentação.`},noForeignKeyMetadata:{title:`Nenhum relacionamento disponível`,detail:`{engine} não reporta metadados de foreign key, então nenhum relacionamento pôde ser derivado. O diagrama está completo para este engine.`},commentsUnsupported:{title:`Comentários do banco de dados indisponíveis`,detail:`{engine} não suporta comentários em tabelas ou colunas, então toda descrição aqui vem apenas das notas deste projeto.`},orphanedNotes:{title:`Algumas notas não correspondem mais a nada`,detail:`{count} nota(s) referenciam uma tabela ou coluna que não existe mais. Nada foi excluído — remapeie ou remova essas notas no arquivo de notas.`},dbmlOmitted:{title:`Não representável em DBML`,detail:`{item} em {table} está documentado aqui mas foi omitido do DBML exportado: {reason}.`}}},"zh-CN":{title:`文档`,groupBySchema:`Schema`,groupByTableGroup:`表分组`,noGroup:`(无分组)`,noSchema:`(无 Schema)`,search:`搜索表、列、分组…`,columns:`列`,indexes:`索引`,references:`引用`,referencedBy:`被引用`,localNote:`本地`,shadowedComment:`数据库注释: {comment}`,addNote:`添加备注`,editNote:`编辑备注`,newGroup:`新建分组…`,groupName:`分组名称`,groupColour:`颜色`,deleteGroup:`删除分组`,enumValues:`值`,usedBy:`被使用于`,openDiagram:`打开 Schema 图`,saving:`保存中…`,saved:`已保存`,saveFailed:`无法保存备注: {error}`,overview:`概览`,groupBy:`分组方式`,searchLabel:`搜索`,groups:`分组`,relationships:`关系`,columnHeader:`列`,typeHeader:`类型`,settingsHeader:`设置`,noteHeader:`备注`,nameHeader:`名称`,definitionHeader:`定义`,noOutgoingRelationships:`此表未引用任何其他表。`,noIncomingRelationships:`没有表引用此表。`,diagram:`图`,language:`语言`,theme:`主题`,themeLight:`浅色`,themeDark:`深色`,exportHtml:`导出 HTML…`,exporting:`导出中…`,exportFailed:`无法导出: {error}`,warnings:{tableSkipped:{title:`有一张表无法生成文档`,detail:`{table} 被跳过: {reason}。此文档中缺少该表。`},noForeignKeyMetadata:{title:`没有可用的关系`,detail:`{engine} 不报告外键元数据,因此无法推导出任何关系。此图对该数据库引擎而言已经完整。`},commentsUnsupported:{title:`数据库注释不可用`,detail:`{engine} 不支持表或列注释,因此这里的所有描述均仅来自本项目的备注。`},orphanedNotes:{title:`部分备注已不再对应任何内容`,detail:`{count} 条备注引用的表或列已不存在。没有任何内容被删除 — 请在备注文件中重新映射或移除它们。`},dbmlOmitted:{title:`无法在 DBML 中表示`,detail:`{table} 上的 {item} 已在此处记录,但已从导出的 DBML 中省略: {reason}。`}}},"zh-TW":{title:`文件`,groupBySchema:`Schema`,groupByTableGroup:`資料表分組`,noGroup:`(無分組)`,noSchema:`(無 Schema)`,search:`搜尋資料表、欄位、分組…`,columns:`欄位`,indexes:`索引`,references:`參照`,referencedBy:`被參照`,localNote:`本機`,shadowedComment:`資料庫註解: {comment}`,addNote:`新增備註`,editNote:`編輯備註`,newGroup:`新增分組…`,groupName:`分組名稱`,groupColour:`顏色`,deleteGroup:`刪除分組`,enumValues:`值`,usedBy:`被使用於`,openDiagram:`開啟 Schema 圖`,saving:`儲存中…`,saved:`已儲存`,saveFailed:`無法儲存備註: {error}`,overview:`總覽`,groupBy:`分組方式`,searchLabel:`搜尋`,groups:`分組`,relationships:`關聯`,columnHeader:`欄位`,typeHeader:`類型`,settingsHeader:`設定`,noteHeader:`備註`,nameHeader:`名稱`,definitionHeader:`定義`,noOutgoingRelationships:`此資料表未參照任何其他資料表。`,noIncomingRelationships:`沒有資料表參照此資料表。`,diagram:`圖表`,language:`語言`,theme:`主題`,themeLight:`淺色`,themeDark:`深色`,exportHtml:`匯出 HTML…`,exporting:`匯出中…`,exportFailed:`無法匯出: {error}`,warnings:{tableSkipped:{title:`有一張資料表無法產生文件`,detail:`{table} 被略過: {reason}。此文件中缺少該資料表。`},noForeignKeyMetadata:{title:`沒有可用的關聯`,detail:`{engine} 未回報外鍵中繼資料,因此無法推導出任何關聯。此圖對該資料庫引擎而言已經完整。`},commentsUnsupported:{title:`資料庫註解無法使用`,detail:`{engine} 不支援資料表或欄位註解,因此這裡的所有說明均僅來自本專案的備註。`},orphanedNotes:{title:`部分備註已不再對應任何內容`,detail:`{count} 筆備註參照的資料表或欄位已不存在。沒有任何內容被刪除 — 請在備註檔案中重新對應或移除它們。`},dbmlOmitted:{title:`無法在 DBML 中表示`,detail:`{table} 上的 {item} 已在此處記錄,但已從匯出的 DBML 中省略: {reason}。`}}}};function id(e,t){let n=t.split(`.`).reduce((e,t)=>e&&typeof e==`object`?e[t]:void 0,e);return typeof n==`string`?n:null}function ad(e){let t=rd[e]??rd.en;return(e,n)=>{let r=e.startsWith(`docs.`)?e.slice(5):e,i=id(t,r)??id(rd.en,r);return i===null?e:n?i.replace(/\{(\w+)\}/g,(e,t)=>t in n?String(n[t]):e):i}}var od={class:`flex h-full min-h-0 flex-col bg-background text-foreground`},sd={class:`flex shrink-0 flex-wrap items-center justify-end gap-4 border-b border-border px-4 py-2`},cd={class:`flex items-center gap-2 text-xs text-muted-foreground`},ld={value:`light`},ud={value:`dark`},dd={class:`flex items-center gap-2 text-xs text-muted-foreground`},fd=[`value`],pd=L({__name:`ExportApp`,props:{payload:{}},setup(e){let t=e,n=P(t.payload.lang in rd?t.payload.lang:`en`),r=Y(()=>ad(n.value)),i=nd.filter(e=>e.value in rd),a=P(typeof window<`u`&&window.matchMedia?.(`(prefers-color-scheme: dark)`).matches?`dark`:`light`);Pn(a,e=>{let t=document.documentElement;t.classList.toggle(`dark`,e===`dark`),t.style.colorScheme=e},{immediate:!0}),Pn(n,e=>{document.documentElement.lang=e},{immediate:!0});let o=P(ed(location.hash,t.payload.snapshot,!0));function s(){o.value=ed(location.hash,t.payload.snapshot,!0)}function c(e){o.value=e;let t=td(e);location.hash!==t&&(location.hash=t)}return nr(()=>window.addEventListener(`hashchange`,s)),ar(()=>window.removeEventListener(`hashchange`,s)),(t,s)=>(U(),W(`div`,od,[G(`div`,sd,[G(`label`,cd,[zi(O(r.value(`docs.theme`))+` `,1),On(G(`select`,{"onUpdate:modelValue":s[0]||=e=>a.value=e,class:`rounded border border-border bg-background px-2 py-1 text-xs text-foreground`},[G(`option`,ld,O(r.value(`docs.themeLight`)),1),G(`option`,ud,O(r.value(`docs.themeDark`)),1)],512),[[no,a.value]])]),G(`label`,dd,[zi(O(r.value(`docs.language`))+` `,1),On(G(`select`,{"onUpdate:modelValue":s[1]||=e=>n.value=e,class:`rounded border border-border bg-background px-2 py-1 text-xs text-foreground`},[(U(!0),W(V,null,R(F(i),e=>(U(),W(`option`,{key:e.value,value:e.value},O(e.label),9,fd))),128))],512),[[no,n.value]])])]),K(Qu,{class:`min-h-0 flex-1`,snapshot:e.payload.snapshot,annotations:e.payload.annotations,readonly:!0,translate:r.value,route:o.value,diagram:`inline`,"onUpdate:route":c},null,8,[`snapshot`,`annotations`,`translate`,`route`])]))}});function md(){let e=document.querySelector(`script[type='application/dbx-snapshot']`);if(e===null)throw Error(`no <script type='application/dbx-snapshot'> in this document`);let t=atob((e.textContent??``).trim()),n=Uint8Array.from(t,e=>e.charCodeAt(0));return JSON.parse(new TextDecoder().decode(n))}try{mo(pd,{payload:md()}).mount(`#app`)}catch(e){let t=document.createElement(`p`);t.style.cssText=`margin:2rem;font-family:system-ui,sans-serif`,t.textContent=`This documentation file could not be read: ${e instanceof Error?e.message:String(e)}`,document.querySelector(`#app`)?.replaceChildren(t)}})();\ No newline at end of filediff --git a/crates/dbx-core/assets/docs-export.manifest.json b/crates/dbx-core/assets/docs-export.manifest.jsonindex cf50bc85ad..553b76e478 100644--- a/crates/dbx-core/assets/docs-export.manifest.json+++ b/crates/dbx-core/assets/docs-export.manifest.json@@ -36,7 +36,7 @@"apps/desktop/src/i18n/locales/docs/pt-BR.ts": "f92c0b95b1b807c60a5136677808ed5014d9061dffd970aa5866eb1c82300dc5","apps/desktop/src/i18n/locales/docs/zh-CN.ts": "2092c39277f2a6774405124d1f167bbcbc5f633d8f82bbd2b28ff5e12d78f3f7","apps/desktop/src/i18n/locales/docs/zh-TW.ts": "691cf502248dbd09358c6c276990945013b26c52fb682bcd56b26f378daea29c",- "apps/desktop/src/lib/app/localeOptions.ts": "3d33acbe797f75ca8de745ca572f71c0be4dc5fbb00714291b7a9db2d0345086",+ "apps/desktop/src/lib/app/localeOptions.ts": "ce38be921d938dbd97d22fde6035699fe40380be3eb4af2caa5371bacca0d945","apps/desktop/src/lib/common/utils.ts": "76c4b2af1e03edeb8db389d9b2c1b56b72a57a1b5198d4e224671c1445c527da","apps/desktop/src/lib/diagram/erDiagram.ts": "c22416a9a5ec5e619acc2d8bc5451254a25abe29fc518e9fb4f611e076fe7b1f","apps/desktop/src/styles/tokens.css": "5b8f747a1eb93905dd797ed2c97b4aa3d18ebed866c2e1f150ff0d9cf52162f5",diff --git a/crates/dbx-core/src/scheduled_backup/engine.rs b/crates/dbx-core/src/scheduled_backup/engine.rsindex e90ee30bd6..05435f5f8f 100644--- a/crates/dbx-core/src/scheduled_backup/engine.rs+++ b/crates/dbx-core/src/scheduled_backup/engine.rs@@ -233,6 +233,7 @@ impl BackupService {}// Metadata discovery may be slow; finish it before starting the snapshot idle timeout.let mut targets = Vec::new();+ let mut found_selected_tables = std::collections::HashSet::new();for schema_name in &schemas {check_cancel(stop)?;let mut selected_tables = Vec::new();@@ -250,7 +251,21 @@ impl BackupService {None,).await?;+ let exact_names = job+ .config+ .selected_tables+ .iter()+ .filter(|target| target.database == *database && target.schema == *schema_name)+ .map(|target| target.table.as_str())+ .collect::<std::collections::HashSet<_>>();for table in &tables {+ if job.config.table_filter_mode == "selected" {+ if exact_names.contains(table.name.as_str()) {+ selected_tables.push(table.name.clone());+ found_selected_tables.insert((schema_name.as_str(), table.name.clone()));+ }+ continue;+ }let matched = job.config.table_patterns@@ -264,7 +279,7 @@ impl BackupService {}}}- let included = if job.config.table_filter_mode == "include" {+ let included = if matches!(job.config.table_filter_mode.as_str(), "include" | "selected") {selected_tables.len()} else {tables.len() - excluded_tables.len()@@ -276,6 +291,21 @@ impl BackupService {}targets.push((schema_name.clone(), selected_tables, excluded_tables));}+ if job.config.table_filter_mode == "selected" {+ let missing = job+ .config+ .selected_tables+ .iter()+ .filter(|target| {+ target.database == *database+ && !found_selected_tables.contains(&(target.schema.as_str(), target.table.clone()))+ })+ .map(|target| format!("{}.{}.{}", target.database, target.schema, target.table))+ .collect::<Vec<_>>();+ if !missing.is_empty() {+ return Err(format!("Selected backup tables are unavailable: {}", missing.join(", ")));+ }+ }if targets.is_empty() {continue;}diff --git a/crates/dbx-core/src/scheduled_backup/mod.rs b/crates/dbx-core/src/scheduled_backup/mod.rsindex f0b87bb92f..041c1ec943 100644--- a/crates/dbx-core/src/scheduled_backup/mod.rs+++ b/crates/dbx-core/src/scheduled_backup/mod.rs@@ -6,7 +6,7 @@ mod store;#[cfg(test)]mod tests;-pub use models::{BackupConfig, BackupFile, BackupRun, BackupSchedule, Migration, RunRequest};+pub use models::{BackupConfig, BackupFile, BackupRun, BackupSchedule, BackupTableTarget, Migration, RunRequest};pub use service::{BackupCommand, BackupService};pub use store::{BackupSnapshot, BackupStore};diff --git a/crates/dbx-core/src/scheduled_backup/models.rs b/crates/dbx-core/src/scheduled_backup/models.rsindex de37ac2937..bd0ed7ea9a 100644--- a/crates/dbx-core/src/scheduled_backup/models.rs+++ b/crates/dbx-core/src/scheduled_backup/models.rs@@ -5,6 +5,14 @@ use serde::{Deserialize, Serialize};pub const DEFAULT_DIRECTORY: &str = "dbx-backup__{schedule}__{timestamp}__{runId}";pub const DEFAULT_FILE: &str = "dbx-backup__{schedule}__{timestamp}__{database}__{runId}";+#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct BackupTableTarget {+ pub database: String,+ pub schema: String,+ pub table: String,+}+#[derive(Clone, Debug, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct BackupConfig {@@ -15,6 +23,8 @@ pub struct BackupConfig {pub table_filter_mode: String,#[serde(default)]pub table_patterns: Vec<String>,+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub selected_tables: Vec<BackupTableTarget>,pub destination_directory: String,pub include_structure: bool,pub include_data: bool,@@ -145,7 +155,7 @@ impl BackupConfig {if !matches!(self.output_compression.as_str(), "none" | "gzip") {return Err("Unsupported backup compression".into());}- if !matches!(self.table_filter_mode.as_str(), "all" | "include" | "exclude") {+ if !matches!(self.table_filter_mode.as_str(), "all" | "include" | "exclude" | "selected") {return Err("Unsupported backup table filter".into());}if self.databases.len() > 10_000 || self.table_patterns.len() > 1000 {@@ -154,9 +164,25 @@ impl BackupConfig {for value in self.databases.iter().chain(self.table_patterns.iter()) {bounded_text(value, 1024, "Backup target")?;}- if self.table_filter_mode != "all" && self.table_patterns.is_empty() {+ if matches!(self.table_filter_mode.as_str(), "include" | "exclude") && self.table_patterns.is_empty() {return Err("Select backup table patterns".into());}+ if self.table_filter_mode == "selected" {+ if self.databases.is_empty() || self.selected_tables.is_empty() {+ return Err("Select backup databases and tables".into());+ }+ if self.selected_tables.len() > 10_000 {+ return Err("Too many selected backup tables".into());+ }+ for target in &self.selected_tables {+ bounded_text(&target.database, 1024, "Backup table database")?;+ bounded_text(&target.schema, 1024, "Backup table schema")?;+ bounded_text(&target.table, 1024, "Backup table name")?;+ if !self.databases.contains(&target.database) {+ return Err("Selected backup table is outside the database scope".into());+ }+ }+ }validate_template(self.file_name_pattern.as_deref().unwrap_or(DEFAULT_FILE), false)}}diff --git a/crates/dbx-core/src/scheduled_backup/tests.rs b/crates/dbx-core/src/scheduled_backup/tests.rsindex ee714ec97f..d0ae0da62b 100644--- a/crates/dbx-core/src/scheduled_backup/tests.rs+++ b/crates/dbx-core/src/scheduled_backup/tests.rs@@ -56,6 +56,29 @@ fn invalid_schedule_and_path_templates_are_rejected() {assert!(super::models::matches_pattern("PUBLIC.*", "users", "app", "public", false));}+#[test]+fn exact_backup_scope_preserves_literal_names_and_rejects_empty_or_foreign_scope() {+ let dir = tempfile::tempdir().unwrap();+ let mut config = schedule(dir.path()).config;+ let legacy = serde_json::to_value(&config).unwrap();+ assert!(legacy.get("selectedTables").is_none());+ assert!(serde_json::from_value::<BackupConfig>(legacy).unwrap().selected_tables.is_empty());+ config.table_filter_mode = "selected".into();+ assert!(config.validate().is_err());+ config.databases = vec!["app".into()];+ assert!(config.validate().is_err());+ config.selected_tables =+ vec![BackupTableTarget { database: "app".into(), schema: "a.b".into(), table: " odd*,?;客户'表 ".into() }];+ assert!(config.validate().is_ok());+ let roundtrip: BackupConfig = serde_json::from_value(serde_json::to_value(&config).unwrap()).unwrap();+ assert_eq!(roundtrip.selected_tables, config.selected_tables);+ config.selected_tables[0].database = "other".into();+ assert!(config.validate().unwrap_err().contains("outside"));+ config.selected_tables[0].database = "app".into();+ config.selected_tables[0].schema = String::new();+ assert!(config.validate().is_err());+}+#[tokio::test]async fn schedule_survives_reopen_and_rejects_stale_edit() {let dir = tempfile::tempdir().unwrap();@@ -438,6 +461,42 @@ async fn live_mysql_worker_scenario() {assert!(completed.error.as_deref().unwrap().contains("No tables matched"));assert!(completed.files.is_empty());assert!(previous.unwrap().exists());+ execute_sql_statement(+ &service.state,+ "mysql",+ &database,+ "CREATE TABLE `odd*,name.with.dot` (id INT PRIMARY KEY, value TEXT)",+ None,+ None,+ )+ .await?;+ execute_sql_statement(+ &service.state,+ "mysql",+ &database,+ "INSERT INTO `odd*,name.with.dot` VALUES (17, 'mysql-exact-scope-sentinel')",+ None,+ None,+ )+ .await?;+ let mut exact = plan_with_id(dir.path(), "mysql-exact");+ exact.config.connection_id = "mysql".into();+ exact.config.databases = vec![database.clone()];+ exact.config.table_filter_mode = "selected".into();+ exact.config.selected_tables = vec![BackupTableTarget {+ database: database.clone(),+ schema: database.clone(),+ table: "odd*,name.with.dot".into(),+ }];+ service.command(BackupCommand::Save { schedule: exact }).await?;+ let exact_run = enqueue_and_run(&service, "mysql-exact").await;+ assert_eq!(exact_run.status, "success", "{:?}", exact_run.error);+ assert_eq!(exact_run.files.len(), 1);+ let exact_sql = read_backup(&exact_run.files[0].file_path, false);+ assert!(exact_sql.contains("mysql-exact-scope-sentinel"));+ assert!(exact_sql.contains("odd*,name.with.dot"));+ assert!(!exact_sql.contains("CREATE TABLE `chosen`"));+ assert!(!exact_sql.contains("CREATE TABLE `skipped`"));Ok::<_, String>(())}).catch_unwind()@@ -533,6 +592,7 @@ fn live_postgres_worker_exports_selected_tables_across_schemas() {service.state.storage.save_connections(std::slice::from_ref(&admin)).await.unwrap();service.state.configs.write().await.insert(admin.id.clone(), admin);let database = format!("dbx_pg_backup_{}", uuid::Uuid::new_v4().simple());+ eprintln!("Backup source test database: {database}");execute_sql_statement(&service.state,admin_id,@@ -591,6 +651,129 @@ fn live_postgres_worker_exports_selected_tables_across_schemas() {// A view inside the same schema is not part of a table-name scope.assert!(!sql.contains("big_orders"), "{sql}");+ execute_sql_statement(+ &service.state,+ "postgres",+ &database,+ "CREATE TABLE app.\"odd*,name.with.dot\" (id integer PRIMARY KEY, note text)",+ None,+ None,+ )+ .await+ .unwrap();+ execute_sql_statement(+ &service.state,+ "postgres",+ &database,+ "CREATE TABLE audit.\"odd*,name.with.dot\" (id integer PRIMARY KEY, note text)",+ None,+ None,+ )+ .await+ .unwrap();+ execute_sql_statement(+ &service.state,+ "postgres",+ &database,+ "INSERT INTO app.\"odd*,name.with.dot\" VALUES (17, 'exact-scope-sentinel')",+ None,+ None,+ )+ .await+ .unwrap();+ let mut exact = plan_with_id(dir.path(), "exact");+ exact.config.connection_id = "postgres".into();+ exact.config.databases = vec![database.clone()];+ exact.config.table_filter_mode = "selected".into();+ exact.config.selected_tables = vec![BackupTableTarget {+ database: database.clone(),+ schema: "app".into(),+ table: "odd*,name.with.dot".into(),+ }];+ service.command(BackupCommand::Save { schedule: exact.clone() }).await.unwrap();+ let exact_run = enqueue_and_run(&service, "exact").await;+ assert_eq!(exact_run.status, "success", "{:?}", exact_run.error);+ assert_eq!(exact_run.files.len(), 1);+ assert_eq!(exact_run.files[0].schema, "app");+ let exact_sql = read_backup(&exact_run.files[0].file_path, false);+ assert!(exact_sql.contains("odd*,name.with.dot"));+ assert!(exact_sql.contains("exact-scope-sentinel"));+ assert!(!exact_sql.contains("orders"));+ assert!(!exact_sql.contains("accounts"));+ assert!(!exact_sql.contains("audit"));+ // Replay the real exported SQL into another disposable database.+ let restore_database = format!("dbx_pg_backup_restore_{}", uuid::Uuid::new_v4().simple());+ eprintln!("Backup replay test database: {restore_database}");+ execute_sql_statement(+ &service.state,+ admin_id,+ "postgres",+ &format!("CREATE DATABASE \"{restore_database}\""),+ None,+ None,+ )+ .await+ .unwrap();+ let restore_config = live_postgres_config("postgres-restore", &restore_database);+ service.state.storage.save_connections(std::slice::from_ref(&restore_config)).await.unwrap();+ service.state.configs.write().await.insert(restore_config.id.clone(), restore_config);+ // Selected-table dumps retain their source schema. Prepare the matching+ // namespace, as a restore into an existing application database does.+ execute_sql_statement(&service.state, "postgres-restore", &restore_database, "CREATE SCHEMA app", None, None)+ .await+ .unwrap();+ for statement in+ crate::sql::split_sql_statements_for_database(&exact_sql, crate::models::connection::DatabaseType::Postgres)+ {+ execute_sql_statement(&service.state, "postgres-restore", &restore_database, &statement, None, None)+ .await+ .unwrap();+ }+ let restored = execute_sql_statement(+ &service.state,+ "postgres-restore",+ &restore_database,+ "SELECT id, note FROM app.\"odd*,name.with.dot\"",+ None,+ None,+ )+ .await+ .unwrap();+ assert_eq!(restored.rows, vec![vec![json!(17), json!("exact-scope-sentinel")]]);+ let absent = execute_sql_statement(+ &service.state,+ "postgres-restore",+ &restore_database,+ "SELECT to_regclass('app.orders'), to_regclass('public.accounts')",+ None,+ None,+ )+ .await+ .unwrap();+ assert_eq!(absent.rows, vec![vec![serde_json::Value::Null, serde_json::Value::Null]]);+ execute_sql_statement(+ &service.state,+ admin_id,+ "postgres",+ &format!("DROP DATABASE \"{restore_database}\" WITH (FORCE)"),+ None,+ None,+ )+ .await+ .unwrap();++ exact.id = "exact-missing".into();+ exact.config.selected_tables.push(BackupTableTarget {+ database: database.clone(),+ schema: "missing_schema".into(),+ table: "not_there".into(),+ });+ service.command(BackupCommand::Save { schedule: exact }).await.unwrap();+ let missing_run = enqueue_and_run(&service, "exact-missing").await;+ assert_eq!(missing_run.status, "failed");+ assert!(missing_run.error.as_deref().unwrap().contains("unavailable"));+ assert!(missing_run.files.is_empty());+// Patterns are case-sensitive on PostgreSQL, and a scope that matches// nothing must fail without leaving a partial file behind.let mut empty = plan_with_id(dir.path(), "empty");diff --git a/docs/screenshots/issue-10804-after.jpg b/docs/screenshots/issue-10804-after.jpgnew file mode 100644index 0000000000..0ca1a1484fBinary files /dev/null and b/docs/screenshots/issue-10804-after.jpg differdiff --git a/docs/screenshots/issue-10804-before.jpg b/docs/screenshots/issue-10804-before.jpgnew file mode 100644index 0000000000..36872013c8Binary files /dev/null and b/docs/screenshots/issue-10804-before.jpg differdiff --git a/docs/screenshots/issue-10804-completed.jpg b/docs/screenshots/issue-10804-completed.jpgnew file mode 100644index 0000000000..0309b43fcdBinary files /dev/null and b/docs/screenshots/issue-10804-completed.jpg differ