feat(backup): support exact table selection by database and schema
This commit is contained in:
27 files changed
+741
-17
No files matched your search
@@ -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>
|
||||
@@ -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">
|
||||
|
||||
@@ -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, tar
|
||||
const 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: DatabaseBack
|
||||
allDatabases.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>
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
+47
@@ -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 }>>();
|
||||
|
||||
@@ -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>
|
||||
|
||||
Reference in new issue
Block a user