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 ConnectionGroupBadge from "@/components/connection/ConnectionGroupBadge.vue";
|
||||||
import { databaseBackupFileNamePatternIsValid, type DatabaseBackupExecutionConfig } from "@/lib/backup/scheduledDatabaseBackup";
|
import { databaseBackupFileNamePatternIsValid, type DatabaseBackupExecutionConfig } from "@/lib/backup/scheduledDatabaseBackup";
|
||||||
import type { ConnectionConfig } from "@/types/database";
|
import type { ConnectionConfig } from "@/types/database";
|
||||||
|
import BackupTableSelector from "./BackupTableSelector.vue";
|
||||||
|
import type { DatabaseBackupTableSelectionState } from "@/lib/backup/scheduledDatabaseBackup";
|
||||||
|
|
||||||
const props = withDefaults(
|
const props = withDefaults(
|
||||||
defineProps<{
|
defineProps<{
|
||||||
draft: DatabaseBackupExecutionConfig;
|
draft: DatabaseBackupExecutionConfig;
|
||||||
connections: Array<Pick<ConnectionConfig, "id" | "name">>;
|
connections: Array<Pick<ConnectionConfig, "id" | "name"> & Partial<Pick<ConnectionConfig, "db_type">>>;
|
||||||
allDatabases: boolean;
|
allDatabases: boolean;
|
||||||
selectedDatabases: string[];
|
selectedDatabases: string[];
|
||||||
databaseOptions: string[];
|
databaseOptions: string[];
|
||||||
@@ -34,6 +36,7 @@ const emit = defineEmits<{
|
|||||||
changeConnection: [connectionId: string];
|
changeConnection: [connectionId: string];
|
||||||
chooseDestination: [];
|
chooseDestination: [];
|
||||||
toggleDatabase: [database: string];
|
toggleDatabase: [database: string];
|
||||||
|
tableSelectionState: [state: DatabaseBackupTableSelectionState];
|
||||||
"update:allDatabases": [value: boolean];
|
"update:allDatabases": [value: boolean];
|
||||||
"update:tablePatternsInput": [value: string];
|
"update:tablePatternsInput": [value: string];
|
||||||
"update:runDirectoryPattern": [value: string];
|
"update:runDirectoryPattern": [value: string];
|
||||||
@@ -47,6 +50,7 @@ const connectionPickerTrigger = ref<ComponentPublicInstance | null>(null);
|
|||||||
const connectionPickerWidth = ref<number>();
|
const connectionPickerWidth = ref<number>();
|
||||||
|
|
||||||
const selectedConnectionName = computed(() => props.connections.find((connection) => connection.id === props.draft.connectionId)?.name || props.draft.connectionId);
|
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 filteredConnections = computed(() => {
|
||||||
const query = connectionSearch.value.trim().toLocaleLowerCase();
|
const query = connectionSearch.value.trim().toLocaleLowerCase();
|
||||||
if (!query) return props.connections;
|
if (!query) return props.connections;
|
||||||
@@ -234,15 +238,25 @@ watch(
|
|||||||
<SelectItem value="all">{{ t("databaseBackup.allTables") }}</SelectItem>
|
<SelectItem value="all">{{ t("databaseBackup.allTables") }}</SelectItem>
|
||||||
<SelectItem value="include">{{ t("databaseBackup.includeTables") }}</SelectItem>
|
<SelectItem value="include">{{ t("databaseBackup.includeTables") }}</SelectItem>
|
||||||
<SelectItem value="exclude">{{ t("databaseBackup.excludeTables") }}</SelectItem>
|
<SelectItem value="exclude">{{ t("databaseBackup.excludeTables") }}</SelectItem>
|
||||||
|
<SelectItem value="selected">{{ t("databaseBackup.exactTables") }}</SelectItem>
|
||||||
</SelectContent>
|
</SelectContent>
|
||||||
</Select>
|
</Select>
|
||||||
</div>
|
</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>
|
<Label>{{ t("databaseBackup.tablePatterns") }}</Label>
|
||||||
<Input :model-value="tablePatternsInput" :placeholder="t('databaseBackup.tablePatternsPlaceholder')" @update:model-value="(value: any) => emit('update:tablePatternsInput', String(value))" />
|
<Input :model-value="tablePatternsInput" :placeholder="t('databaseBackup.tablePatternsPlaceholder')" @update:model-value="(value: any) => emit('update:tablePatternsInput', String(value))" />
|
||||||
</div>
|
</div>
|
||||||
</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>
|
||||||
|
|
||||||
<div class="space-y-3">
|
<div class="space-y-3">
|
||||||
|
|||||||
@@ -32,6 +32,7 @@ import {
|
|||||||
type DatabaseBackupRun,
|
type DatabaseBackupRun,
|
||||||
type DatabaseBackupSchedule,
|
type DatabaseBackupSchedule,
|
||||||
} from "@/lib/backup/scheduledDatabaseBackup";
|
} from "@/lib/backup/scheduledDatabaseBackup";
|
||||||
|
import { databaseBackupTableSelectionScopeKey, normalizeDatabaseBackupTableTargets, type DatabaseBackupTableSelectionState } from "@/lib/backup/scheduledDatabaseBackup";
|
||||||
import { useConnectionStore } from "@/stores/connectionStore";
|
import { useConnectionStore } from "@/stores/connectionStore";
|
||||||
import { fetchNamespaceOptionsForConnection } from "@/composables/useDatabaseOptions";
|
import { fetchNamespaceOptionsForConnection } from "@/composables/useDatabaseOptions";
|
||||||
|
|
||||||
@@ -85,6 +86,27 @@ const databaseOptions = ref<string[]>([]);
|
|||||||
const allDatabases = ref(true);
|
const allDatabases = ref(true);
|
||||||
const selectedDatabases = ref<string[]>([]);
|
const selectedDatabases = ref<string[]>([]);
|
||||||
const tablePatternsInput = ref("");
|
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 expandedRunIds = reactive(new Set<string>());
|
||||||
const selectedRunIds = reactive(new Set<string>());
|
const selectedRunIds = reactive(new Set<string>());
|
||||||
const historyConnectionId = ref("");
|
const historyConnectionId = ref("");
|
||||||
@@ -187,7 +209,7 @@ function databaseLoadIsCurrent(generation: number, dialog: BackupDialogKind, tar
|
|||||||
const canSave = computed(() => {
|
const canSave = computed(() => {
|
||||||
const hasContent = draft.value.includeStructure || draft.value.includeData || draft.value.includeObjects;
|
const hasContent = draft.value.includeStructure || draft.value.includeData || draft.value.includeObjects;
|
||||||
const hasDatabaseScope = allDatabases.value || selectedDatabases.value.length > 0;
|
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 (
|
return (
|
||||||
!!draft.value.name.trim() &&
|
!!draft.value.name.trim() &&
|
||||||
!!draft.value.connectionId &&
|
!!draft.value.connectionId &&
|
||||||
@@ -236,7 +258,7 @@ const oneShotOutputPathPreview = computed(() => {
|
|||||||
const canStartOneShot = computed(() => {
|
const canStartOneShot = computed(() => {
|
||||||
const hasContent = oneShotDraft.value.includeStructure || oneShotDraft.value.includeData || oneShotDraft.value.includeObjects;
|
const hasContent = oneShotDraft.value.includeStructure || oneShotDraft.value.includeData || oneShotDraft.value.includeObjects;
|
||||||
const hasDatabaseScope = allDatabases.value || selectedDatabases.value.length > 0;
|
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;
|
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;
|
allDatabases.value = true;
|
||||||
targetDraft.tableFilterMode = "all";
|
targetDraft.tableFilterMode = "all";
|
||||||
targetDraft.tablePatterns = [];
|
targetDraft.tablePatterns = [];
|
||||||
|
targetDraft.selectedTables = [];
|
||||||
tablePatternsInput.value = "";
|
tablePatternsInput.value = "";
|
||||||
}
|
}
|
||||||
if (!connectionId) {
|
if (!connectionId) {
|
||||||
@@ -357,12 +380,15 @@ async function loadDatabases(dialog: BackupDialogKind, targetDraft: DatabaseBack
|
|||||||
}
|
}
|
||||||
|
|
||||||
function resetDatabaseScope(targetDraft: DatabaseBackupExecutionConfig) {
|
function resetDatabaseScope(targetDraft: DatabaseBackupExecutionConfig) {
|
||||||
|
scheduleTableSelectionState.value = { scopeKey: "", ready: false };
|
||||||
|
oneShotTableSelectionState.value = { scopeKey: "", ready: false };
|
||||||
databaseOptions.value = [];
|
databaseOptions.value = [];
|
||||||
databaseLoadError.value = "";
|
databaseLoadError.value = "";
|
||||||
allDatabases.value = true;
|
allDatabases.value = true;
|
||||||
selectedDatabases.value = [];
|
selectedDatabases.value = [];
|
||||||
targetDraft.tableFilterMode = "all";
|
targetDraft.tableFilterMode = "all";
|
||||||
targetDraft.tablePatterns = [];
|
targetDraft.tablePatterns = [];
|
||||||
|
targetDraft.selectedTables = [];
|
||||||
tablePatternsInput.value = "";
|
tablePatternsInput.value = "";
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -376,6 +402,7 @@ async function openCreateSchedule() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function openEditSchedule(schedule: DatabaseBackupSchedule) {
|
async function openEditSchedule(schedule: DatabaseBackupSchedule) {
|
||||||
|
scheduleTableSelectionState.value = { scopeKey: "", ready: false };
|
||||||
oneShotDialogOpen.value = false;
|
oneShotDialogOpen.value = false;
|
||||||
editingScheduleId.value = schedule.id;
|
editingScheduleId.value = schedule.id;
|
||||||
draft.value = { ...schedule, databases: [...schedule.databases], tablePatterns: [...schedule.tablePatterns] };
|
draft.value = { ...schedule, databases: [...schedule.databases], tablePatterns: [...schedule.tablePatterns] };
|
||||||
@@ -397,6 +424,7 @@ async function changeConnection(connectionId: string) {
|
|||||||
selectedDatabases.value = [];
|
selectedDatabases.value = [];
|
||||||
targetDraft.tableFilterMode = "all";
|
targetDraft.tableFilterMode = "all";
|
||||||
targetDraft.tablePatterns = [];
|
targetDraft.tablePatterns = [];
|
||||||
|
targetDraft.selectedTables = [];
|
||||||
tablePatternsInput.value = "";
|
tablePatternsInput.value = "";
|
||||||
if (!wasSelectingSpecificDatabases) {
|
if (!wasSelectingSpecificDatabases) {
|
||||||
allDatabases.value = true;
|
allDatabases.value = true;
|
||||||
@@ -439,7 +467,7 @@ async function submitSchedule() {
|
|||||||
await saveSchedule({
|
await saveSchedule({
|
||||||
...draft.value,
|
...draft.value,
|
||||||
databases: allDatabases.value ? [] : [...selectedDatabases.value],
|
databases: allDatabases.value ? [] : [...selectedDatabases.value],
|
||||||
tablePatterns: draft.value.tableFilterMode === "all" ? [] : normalizeDatabaseBackupTablePatterns(tablePatternsInput.value),
|
...backupTablePayload(draft.value),
|
||||||
});
|
});
|
||||||
scheduleDialogOpen.value = false;
|
scheduleDialogOpen.value = false;
|
||||||
toast(t(editingScheduleId.value ? "databaseBackup.scheduleUpdated" : "databaseBackup.scheduleCreated"), 2500);
|
toast(t(editingScheduleId.value ? "databaseBackup.scheduleUpdated" : "databaseBackup.scheduleCreated"), 2500);
|
||||||
@@ -451,6 +479,7 @@ async function submitSchedule() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function openOneShotBackup() {
|
async function openOneShotBackup() {
|
||||||
|
oneShotTableSelectionState.value = { scopeKey: "", ready: false };
|
||||||
scheduleDialogOpen.value = false;
|
scheduleDialogOpen.value = false;
|
||||||
const nextDraft = newBackupConfig();
|
const nextDraft = newBackupConfig();
|
||||||
oneShotDraft.value = nextDraft;
|
oneShotDraft.value = nextDraft;
|
||||||
@@ -467,7 +496,7 @@ async function startOneShotBackup() {
|
|||||||
{
|
{
|
||||||
...oneShotDraft.value,
|
...oneShotDraft.value,
|
||||||
databases: allDatabases.value ? [] : [...selectedDatabases.value],
|
databases: allDatabases.value ? [] : [...selectedDatabases.value],
|
||||||
tablePatterns: oneShotDraft.value.tableFilterMode === "all" ? [] : normalizeDatabaseBackupTablePatterns(tablePatternsInput.value),
|
...backupTablePayload(oneShotDraft.value),
|
||||||
},
|
},
|
||||||
t("databaseBackup.oneShotName"),
|
t("databaseBackup.oneShotName"),
|
||||||
);
|
);
|
||||||
@@ -898,6 +927,7 @@ async function restoreBackup(run: DatabaseBackupRun, file: DatabaseBackupFile) {
|
|||||||
@toggle-database="toggleDatabase"
|
@toggle-database="toggleDatabase"
|
||||||
@update:all-databases="setAllDatabases"
|
@update:all-databases="setAllDatabases"
|
||||||
@update:table-patterns-input="(value: string) => (tablePatternsInput = value)"
|
@update:table-patterns-input="(value: string) => (tablePatternsInput = value)"
|
||||||
|
@table-selection-state="(state) => (scheduleTableSelectionState = state)"
|
||||||
@update:run-directory-pattern="(value: string) => (draft.runDirectoryPattern = value)"
|
@update:run-directory-pattern="(value: string) => (draft.runDirectoryPattern = value)"
|
||||||
/>
|
/>
|
||||||
|
|
||||||
@@ -983,6 +1013,7 @@ async function restoreBackup(run: DatabaseBackupRun, file: DatabaseBackupFile) {
|
|||||||
@toggle-database="toggleDatabase"
|
@toggle-database="toggleDatabase"
|
||||||
@update:all-databases="setAllDatabases"
|
@update:all-databases="setAllDatabases"
|
||||||
@update:table-patterns-input="(value: string) => (tablePatternsInput = value)"
|
@update:table-patterns-input="(value: string) => (tablePatternsInput = value)"
|
||||||
|
@table-selection-state="(state) => (oneShotTableSelectionState = state)"
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<DialogFooter>
|
<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 () => {}),
|
ensureConnected: vi.fn(async () => {}),
|
||||||
recordConnectionLostError: vi.fn(() => false),
|
recordConnectionLostError: vi.fn(() => false),
|
||||||
listDatabases: vi.fn(async (_connectionId: string) => [{ name: "app" }]),
|
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),
|
databaseExportDestinationNeedsConfirmation: vi.fn(async (_directory: string) => false),
|
||||||
recordDatabaseExportDestination: vi.fn(async (_directory: string) => {}),
|
recordDatabaseExportDestination: vi.fn(async (_directory: string) => {}),
|
||||||
openDirectory: vi.fn(async (): Promise<string | null> => "/backups"),
|
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" })),
|
databaseBackupBackground: vi.fn(async () => ({ enabled: false, platform: "windows" })),
|
||||||
databaseBackupCommand: vi.fn(async () => "2026-09-13T02:00:00Z"),
|
databaseBackupCommand: vi.fn(async () => "2026-09-13T02:00:00Z"),
|
||||||
listDatabases: mocks.listDatabases,
|
listDatabases: mocks.listDatabases,
|
||||||
|
listSchemas: mocks.listSchemas,
|
||||||
|
listTables: mocks.listTables,
|
||||||
deleteDatabaseBackupFiles: vi.fn(),
|
deleteDatabaseBackupFiles: vi.fn(),
|
||||||
revealPathInFileManager: vi.fn(),
|
revealPathInFileManager: vi.fn(),
|
||||||
databaseExportDestinationNeedsConfirmation: mocks.databaseExportDestinationNeedsConfirmation,
|
databaseExportDestinationNeedsConfirmation: mocks.databaseExportDestinationNeedsConfirmation,
|
||||||
@@ -288,6 +292,10 @@ afterEach(() => {
|
|||||||
mocks.recordConnectionLostError.mockReturnValue(false);
|
mocks.recordConnectionLostError.mockReturnValue(false);
|
||||||
mocks.listDatabases.mockReset();
|
mocks.listDatabases.mockReset();
|
||||||
mocks.listDatabases.mockResolvedValue([{ name: "app" }]);
|
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.mockReset();
|
||||||
mocks.databaseExportDestinationNeedsConfirmation.mockResolvedValue(false);
|
mocks.databaseExportDestinationNeedsConfirmation.mockResolvedValue(false);
|
||||||
mocks.recordDatabaseExportDestination.mockReset();
|
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")));
|
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 () => {
|
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" });
|
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 }>>();
|
const firstLoad = deferred<Array<{ name: string }>>();
|
||||||
|
|||||||
@@ -16,6 +16,10 @@ const props = withDefaults(
|
|||||||
defineProps<{
|
defineProps<{
|
||||||
/** All available table names. */
|
/** All available table names. */
|
||||||
tables: string[];
|
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). */
|
/** Currently selected table names (v-model). */
|
||||||
modelValue: string[];
|
modelValue: string[];
|
||||||
/** Optional header label; falls back to `tableMultiSelect.tables`. */
|
/** 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 { t } = useI18n();
|
||||||
const search = ref("");
|
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 selectedSet = computed(() => new Set(props.modelValue));
|
||||||
const allFilteredSelected = computed(() => isEveryFilteredSelected(props.modelValue, filteredTables.value));
|
const allFilteredSelected = computed(() => isEveryFilteredSelected(props.modelValue, filteredTables.value));
|
||||||
const showSearch = computed(() => props.searchable && props.tables.length > 5);
|
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)">
|
<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" />
|
<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" />
|
<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>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -9632,6 +9632,10 @@ export default {
|
|||||||
tablePatterns: "Table name rules",
|
tablePatterns: "Table name rules",
|
||||||
tablePatternsPlaceholder: "orders, audit_*, public.users",
|
tablePatternsPlaceholder: "orders, audit_*, public.users",
|
||||||
tablePatternsHint: "Separate rules with commas. * and ? wildcards and schema.table are supported.",
|
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",
|
includedTablePatterns: "{count} include rules",
|
||||||
excludedTablePatterns: "{count} exclude rules",
|
excludedTablePatterns: "{count} exclude rules",
|
||||||
frequency: "Frequency",
|
frequency: "Frequency",
|
||||||
|
|||||||
@@ -10754,6 +10754,10 @@ export default withEnglishFallback({
|
|||||||
tablePatterns: "Reglas de nombres de tabla",
|
tablePatterns: "Reglas de nombres de tabla",
|
||||||
tablePatternsPlaceholder: "orders, audit_*, public.users",
|
tablePatternsPlaceholder: "orders, audit_*, public.users",
|
||||||
tablePatternsHint: "Separe las reglas con comas. Se admiten los comodines * y ? y schema.table.",
|
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",
|
includedTablePatterns: "{count} reglas de inclusión",
|
||||||
excludedTablePatterns: "{count} reglas de exclusión",
|
excludedTablePatterns: "{count} reglas de exclusión",
|
||||||
frequency: "Frecuencia de ejecución",
|
frequency: "Frecuencia de ejecución",
|
||||||
|
|||||||
@@ -9475,6 +9475,10 @@ export default withEnglishFallback({
|
|||||||
tablePatterns: "Aturan nama tabel",
|
tablePatterns: "Aturan nama tabel",
|
||||||
tablePatternsPlaceholder: "orders, audit_*, public.users",
|
tablePatternsPlaceholder: "orders, audit_*, public.users",
|
||||||
tablePatternsHint: "Pisahkan aturan dengan koma. Wildcard * dan ? serta schema.table didukung.",
|
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",
|
includedTablePatterns: "{count} aturan sertakan",
|
||||||
excludedTablePatterns: "{count} aturan kecualikan",
|
excludedTablePatterns: "{count} aturan kecualikan",
|
||||||
frequency: "Frekuensi",
|
frequency: "Frekuensi",
|
||||||
|
|||||||
@@ -10322,6 +10322,10 @@ export default withEnglishFallback({
|
|||||||
tablePatterns: "Regole nomi tabella",
|
tablePatterns: "Regole nomi tabella",
|
||||||
tablePatternsPlaceholder: "orders, audit_*, public.users",
|
tablePatternsPlaceholder: "orders, audit_*, public.users",
|
||||||
tablePatternsHint: "Separa le regole con virgole. Sono supportati i caratteri jolly * e ? e schema.table.",
|
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",
|
includedTablePatterns: "{count} regole di inclusione",
|
||||||
excludedTablePatterns: "{count} regole di esclusione",
|
excludedTablePatterns: "{count} regole di esclusione",
|
||||||
frequency: "Frequenza",
|
frequency: "Frequenza",
|
||||||
|
|||||||
@@ -10363,6 +10363,10 @@ export default withEnglishFallback({
|
|||||||
tablePatterns: "テーブル名ルール",
|
tablePatterns: "テーブル名ルール",
|
||||||
tablePatternsPlaceholder: "orders, audit_*, public.users",
|
tablePatternsPlaceholder: "orders, audit_*, public.users",
|
||||||
tablePatternsHint: "ルールはカンマで区切ります。*、? ワイルドカードと schema.table を使用できます。",
|
tablePatternsHint: "ルールはカンマで区切ります。*、? ワイルドカードと schema.table を使用できます。",
|
||||||
|
exactTables: "特定のテーブルを選択",
|
||||||
|
selectDatabasesForTables: "「すべてのデータベース」を解除してバックアップするデータベースを選び、個別のテーブルを選択してください。",
|
||||||
|
tableListLoadFailed: "テーブル一覧を読み込めませんでした。更新して再試行してください。",
|
||||||
|
selectedTablesUnavailable: "選択したテーブルの一部が存在しないか、利用できません。更新するか、該当する選択を解除してください。",
|
||||||
includedTablePatterns: "包含ルール {count} 件",
|
includedTablePatterns: "包含ルール {count} 件",
|
||||||
excludedTablePatterns: "除外ルール {count} 件",
|
excludedTablePatterns: "除外ルール {count} 件",
|
||||||
frequency: "実行頻度",
|
frequency: "実行頻度",
|
||||||
|
|||||||
@@ -8500,6 +8500,10 @@ export default withEnglishFallback({
|
|||||||
tablePatterns: "테이블 이름 규칙",
|
tablePatterns: "테이블 이름 규칙",
|
||||||
tablePatternsPlaceholder: "orders, audit_*, public.users",
|
tablePatternsPlaceholder: "orders, audit_*, public.users",
|
||||||
tablePatternsHint: "규칙은 쉼표로 구분하세요. *와 ? 와일드카드 및 schema.table을 지원합니다.",
|
tablePatternsHint: "규칙은 쉼표로 구분하세요. *와 ? 와일드카드 및 schema.table을 지원합니다.",
|
||||||
|
exactTables: "특정 테이블 선택",
|
||||||
|
selectDatabasesForTables: "‘모든 데이터베이스’를 해제하고 백업할 데이터베이스를 선택한 다음, 개별 테이블을 선택하세요.",
|
||||||
|
tableListLoadFailed: "테이블 목록을 불러올 수 없습니다. 새로 고침 후 다시 시도하세요.",
|
||||||
|
selectedTablesUnavailable: "선택한 일부 테이블이 없거나 사용할 수 없습니다. 새로 고침하거나 해당 선택을 제거하세요.",
|
||||||
includedTablePatterns: "포함 규칙 {count}개",
|
includedTablePatterns: "포함 규칙 {count}개",
|
||||||
excludedTablePatterns: "제외 규칙 {count}개",
|
excludedTablePatterns: "제외 규칙 {count}개",
|
||||||
frequency: "빈도",
|
frequency: "빈도",
|
||||||
|
|||||||
@@ -10322,6 +10322,10 @@ export default withEnglishFallback({
|
|||||||
tablePatterns: "Regras de nomes de tabela",
|
tablePatterns: "Regras de nomes de tabela",
|
||||||
tablePatternsPlaceholder: "orders, audit_*, public.users",
|
tablePatternsPlaceholder: "orders, audit_*, public.users",
|
||||||
tablePatternsHint: "Separe as regras com vírgulas. Há suporte a curingas * e ? e schema.table.",
|
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",
|
includedTablePatterns: "{count} regras de inclusão",
|
||||||
excludedTablePatterns: "{count} regras de exclusão",
|
excludedTablePatterns: "{count} regras de exclusão",
|
||||||
frequency: "Frequência",
|
frequency: "Frequência",
|
||||||
|
|||||||
@@ -10009,6 +10009,10 @@ export default withEnglishFallback({
|
|||||||
tablePatterns: "Правила имён таблиц",
|
tablePatterns: "Правила имён таблиц",
|
||||||
tablePatternsPlaceholder: "orders, audit_*, public.users",
|
tablePatternsPlaceholder: "orders, audit_*, public.users",
|
||||||
tablePatternsHint: "Разделяйте правила запятыми. Поддерживаются подстановочные знаки * и ?, а также schema.table.",
|
tablePatternsHint: "Разделяйте правила запятыми. Поддерживаются подстановочные знаки * и ?, а также schema.table.",
|
||||||
|
exactTables: "Выбрать конкретные таблицы",
|
||||||
|
selectDatabasesForTables: "Отключите «Все базы данных», выберите базы для резервного копирования, затем отметьте отдельные таблицы.",
|
||||||
|
tableListLoadFailed: "Не удалось загрузить список таблиц. Обновите и повторите попытку.",
|
||||||
|
selectedTablesUnavailable: "Некоторые выбранные таблицы отсутствуют или недоступны. Обновите список или снимите их выделение.",
|
||||||
includedTablePatterns: "Правил включения: {count}",
|
includedTablePatterns: "Правил включения: {count}",
|
||||||
excludedTablePatterns: "Правил исключения: {count}",
|
excludedTablePatterns: "Правил исключения: {count}",
|
||||||
frequency: "Частота",
|
frequency: "Частота",
|
||||||
|
|||||||
@@ -9594,6 +9594,10 @@ export default withEnglishFallback({
|
|||||||
tablePatterns: "表名规则",
|
tablePatterns: "表名规则",
|
||||||
tablePatternsPlaceholder: "例如:orders, audit_*, public.users",
|
tablePatternsPlaceholder: "例如:orders, audit_*, public.users",
|
||||||
tablePatternsHint: "用逗号分隔规则,支持 *、? 通配符和 schema.table。",
|
tablePatternsHint: "用逗号分隔规则,支持 *、? 通配符和 schema.table。",
|
||||||
|
exactTables: "精确选择表",
|
||||||
|
selectDatabasesForTables: "先取消“全部数据库”并选择需要备份的数据库,再勾选具体表。",
|
||||||
|
tableListLoadFailed: "加载表列表失败,请刷新重试。",
|
||||||
|
selectedTablesUnavailable: "部分已选表不存在或不可见,请刷新或移除这些选择。",
|
||||||
includedTablePatterns: "包含 {count} 条表规则",
|
includedTablePatterns: "包含 {count} 条表规则",
|
||||||
excludedTablePatterns: "排除 {count} 条表规则",
|
excludedTablePatterns: "排除 {count} 条表规则",
|
||||||
frequency: "执行频率",
|
frequency: "执行频率",
|
||||||
|
|||||||
@@ -10328,6 +10328,10 @@ export default withEnglishFallback({
|
|||||||
tablePatterns: "資料表名稱規則",
|
tablePatterns: "資料表名稱規則",
|
||||||
tablePatternsPlaceholder: "例如:orders, audit_*, public.users",
|
tablePatternsPlaceholder: "例如:orders, audit_*, public.users",
|
||||||
tablePatternsHint: "請用逗號分隔規則,支援 *、? 萬用字元和 schema.table。",
|
tablePatternsHint: "請用逗號分隔規則,支援 *、? 萬用字元和 schema.table。",
|
||||||
|
exactTables: "精確選取資料表",
|
||||||
|
selectDatabasesForTables: "先取消「全部資料庫」並選取需要備份的資料庫,再勾選個別資料表。",
|
||||||
|
tableListLoadFailed: "無法載入資料表清單,請重新整理後重試。",
|
||||||
|
selectedTablesUnavailable: "部分已選資料表不存在或無法檢視,請重新整理或移除這些選取項目。",
|
||||||
includedTablePatterns: "包含 {count} 條資料表規則",
|
includedTablePatterns: "包含 {count} 條資料表規則",
|
||||||
excludedTablePatterns: "排除 {count} 條資料表規則",
|
excludedTablePatterns: "排除 {count} 條資料表規則",
|
||||||
frequency: "執行頻率",
|
frequency: "執行頻率",
|
||||||
|
|||||||
@@ -10,6 +10,10 @@ import {
|
|||||||
normalizeDatabaseBackupRun,
|
normalizeDatabaseBackupRun,
|
||||||
resolveScheduledDatabaseBackupTableScope,
|
resolveScheduledDatabaseBackupTableScope,
|
||||||
type DatabaseBackupRun,
|
type DatabaseBackupRun,
|
||||||
|
normalizeDatabaseBackupTableTargets,
|
||||||
|
databaseBackupTableTargetKey,
|
||||||
|
normalizeDatabaseBackupSchedule,
|
||||||
|
toDatabaseBackupExecutionConfig,
|
||||||
} from "../../backup/scheduledDatabaseBackup";
|
} from "../../backup/scheduledDatabaseBackup";
|
||||||
|
|
||||||
const startedAt = "2026-08-12T00:00:00.000Z";
|
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");
|
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();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -14,7 +14,7 @@ export type DatabaseBackupExportStatus = "Running" | "Done" | "Error" | "Cancell
|
|||||||
export type DatabaseBackupRunStatus = "running" | "success" | "failed" | "cancelled";
|
export type DatabaseBackupRunStatus = "running" | "success" | "failed" | "cancelled";
|
||||||
export type DatabaseBackupRunTrigger = "manual" | "scheduled";
|
export type DatabaseBackupRunTrigger = "manual" | "scheduled";
|
||||||
export type DatabaseBackupRunSource = "scheduled" | "one-shot";
|
export type DatabaseBackupRunSource = "scheduled" | "one-shot";
|
||||||
export type DatabaseBackupTableFilterMode = "all" | "include" | "exclude";
|
export type DatabaseBackupTableFilterMode = "all" | "include" | "exclude" | "selected";
|
||||||
export type DatabaseBackupOutputCompression = "none" | "gzip";
|
export type DatabaseBackupOutputCompression = "none" | "gzip";
|
||||||
|
|
||||||
const CONSISTENT_BACKUP_DATABASE_TYPES = new Set(["mysql", "postgres"]);
|
const CONSISTENT_BACKUP_DATABASE_TYPES = new Set(["mysql", "postgres"]);
|
||||||
@@ -98,6 +98,7 @@ export function databaseBackupTableNamesAreCaseSensitive(databaseType: DatabaseT
|
|||||||
export function resolveScheduledDatabaseBackupTableScope(mode: DatabaseBackupTableFilterMode, patterns: readonly string[], availableTables: readonly string[], database = "", schema = "", caseSensitive = true): DatabaseBackupTableScope {
|
export 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))];
|
const available = [...new Set(availableTables.map((table) => table.trim()).filter(Boolean))];
|
||||||
if (mode === "all") return { includedTables: available };
|
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 normalizedPatterns = normalizeDatabaseBackupTablePatterns(patterns);
|
||||||
const matching = available.filter((table) => databaseBackupTableMatchesPattern(table, normalizedPatterns, database, schema, caseSensitive));
|
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 {
|
export interface DatabaseBackupExecutionConfig {
|
||||||
connectionId: string;
|
connectionId: string;
|
||||||
databases: string[];
|
databases: string[];
|
||||||
tableFilterMode: DatabaseBackupTableFilterMode;
|
tableFilterMode: DatabaseBackupTableFilterMode;
|
||||||
tablePatterns: string[];
|
tablePatterns: string[];
|
||||||
|
selectedTables?: DatabaseBackupTableTarget[];
|
||||||
destinationDirectory: string;
|
destinationDirectory: string;
|
||||||
includeStructure: boolean;
|
includeStructure: boolean;
|
||||||
includeData: boolean;
|
includeData: boolean;
|
||||||
@@ -150,6 +190,7 @@ export function toDatabaseBackupExecutionConfig(schedule: DatabaseBackupSchedule
|
|||||||
databases: [...schedule.databases],
|
databases: [...schedule.databases],
|
||||||
tableFilterMode: schedule.tableFilterMode,
|
tableFilterMode: schedule.tableFilterMode,
|
||||||
tablePatterns: [...schedule.tablePatterns],
|
tablePatterns: [...schedule.tablePatterns],
|
||||||
|
...(schedule.tableFilterMode === "selected" ? { selectedTables: normalizeDatabaseBackupTableTargets(schedule.selectedTables) } : {}),
|
||||||
destinationDirectory: schedule.destinationDirectory,
|
destinationDirectory: schedule.destinationDirectory,
|
||||||
includeStructure: schedule.includeStructure,
|
includeStructure: schedule.includeStructure,
|
||||||
includeData: schedule.includeData,
|
includeData: schedule.includeData,
|
||||||
@@ -238,6 +279,14 @@ export function normalizeDatabaseBackupSchedule(value: unknown, now = new Date()
|
|||||||
const destinationDirectory = stringValue(input.destinationDirectory).trim();
|
const destinationDirectory = stringValue(input.destinationDirectory).trim();
|
||||||
if (!id || !connectionId || !destinationDirectory) return null;
|
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 nowIso = now.toISOString();
|
||||||
const frequency: DatabaseBackupFrequency = input.frequency === "daily" || input.frequency === "weekly" ? input.frequency : "hourly";
|
const frequency: DatabaseBackupFrequency = input.frequency === "daily" || input.frequency === "weekly" ? input.frequency : "hourly";
|
||||||
const schedule: DatabaseBackupSchedule = {
|
const schedule: DatabaseBackupSchedule = {
|
||||||
@@ -246,8 +295,9 @@ export function normalizeDatabaseBackupSchedule(value: unknown, now = new Date()
|
|||||||
enabled: booleanValue(input.enabled, true),
|
enabled: booleanValue(input.enabled, true),
|
||||||
connectionId,
|
connectionId,
|
||||||
databases: Array.isArray(input.databases) ? [...new Set(input.databases.map((database) => stringValue(database).trim()).filter(Boolean))] : [],
|
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),
|
tablePatterns: normalizeDatabaseBackupTablePatterns(input.tablePatterns),
|
||||||
|
...(selectedTables ? { selectedTables } : {}),
|
||||||
destinationDirectory,
|
destinationDirectory,
|
||||||
frequency,
|
frequency,
|
||||||
intervalHours: boundedInteger(input.intervalHours, 6, 1, 168),
|
intervalHours: boundedInteger(input.intervalHours, 6, 1, 168),
|
||||||
|
|||||||
Generated
+1
-1
@@ -61,4 +61,4 @@ ${this.parser.parse(e)}</blockquote>
|
|||||||
${e}</tr>
|
${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}>
|
`}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.levelLine truncated
|
`}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.levelLine truncated
|
||||||
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=[`t
Line truncated
|
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=[`t
Line truncated
|
||||||
@@ -36,7 +36,7 @@
|
|||||||
"apps/desktop/src/i18n/locales/docs/pt-BR.ts": "f92c0b95b1b807c60a5136677808ed5014d9061dffd970aa5866eb1c82300dc5",
|
"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-CN.ts": "2092c39277f2a6774405124d1f167bbcbc5f633d8f82bbd2b28ff5e12d78f3f7",
|
||||||
"apps/desktop/src/i18n/locales/docs/zh-TW.ts": "691cf502248dbd09358c6c276990945013b26c52fb682bcd56b26f378daea29c",
|
"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/common/utils.ts": "76c4b2af1e03edeb8db389d9b2c1b56b72a57a1b5198d4e224671c1445c527da",
|
||||||
"apps/desktop/src/lib/diagram/erDiagram.ts": "c22416a9a5ec5e619acc2d8bc5451254a25abe29fc518e9fb4f611e076fe7b1f",
|
"apps/desktop/src/lib/diagram/erDiagram.ts": "c22416a9a5ec5e619acc2d8bc5451254a25abe29fc518e9fb4f611e076fe7b1f",
|
||||||
"apps/desktop/src/styles/tokens.css": "5b8f747a1eb93905dd797ed2c97b4aa3d18ebed866c2e1f150ff0d9cf52162f5",
|
"apps/desktop/src/styles/tokens.css": "5b8f747a1eb93905dd797ed2c97b4aa3d18ebed866c2e1f150ff0d9cf52162f5",
|
||||||
|
|||||||
@@ -233,6 +233,7 @@ impl BackupService {
|
|||||||
}
|
}
|
||||||
// Metadata discovery may be slow; finish it before starting the snapshot idle timeout.
|
// Metadata discovery may be slow; finish it before starting the snapshot idle timeout.
|
||||||
let mut targets = Vec::new();
|
let mut targets = Vec::new();
|
||||||
|
let mut found_selected_tables = std::collections::HashSet::new();
|
||||||
for schema_name in &schemas {
|
for schema_name in &schemas {
|
||||||
check_cancel(stop)?;
|
check_cancel(stop)?;
|
||||||
let mut selected_tables = Vec::new();
|
let mut selected_tables = Vec::new();
|
||||||
@@ -250,7 +251,21 @@ impl BackupService {
|
|||||||
None,
|
None,
|
||||||
)
|
)
|
||||||
.await?;
|
.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 {
|
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
|
let matched = job
|
||||||
.config
|
.config
|
||||||
.table_patterns
|
.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()
|
selected_tables.len()
|
||||||
} else {
|
} else {
|
||||||
tables.len() - excluded_tables.len()
|
tables.len() - excluded_tables.len()
|
||||||
@@ -276,6 +291,21 @@ impl BackupService {
|
|||||||
}
|
}
|
||||||
targets.push((schema_name.clone(), selected_tables, excluded_tables));
|
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() {
|
if targets.is_empty() {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ mod store;
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests;
|
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 service::{BackupCommand, BackupService};
|
||||||
pub use store::{BackupSnapshot, BackupStore};
|
pub use store::{BackupSnapshot, BackupStore};
|
||||||
|
|
||||||
|
|||||||
@@ -5,6 +5,14 @@ use serde::{Deserialize, Serialize};
|
|||||||
pub const DEFAULT_DIRECTORY: &str = "dbx-backup__{schedule}__{timestamp}__{runId}";
|
pub const DEFAULT_DIRECTORY: &str = "dbx-backup__{schedule}__{timestamp}__{runId}";
|
||||||
pub const DEFAULT_FILE: &str = "dbx-backup__{schedule}__{timestamp}__{database}__{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)]
|
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||||
#[serde(rename_all = "camelCase")]
|
#[serde(rename_all = "camelCase")]
|
||||||
pub struct BackupConfig {
|
pub struct BackupConfig {
|
||||||
@@ -15,6 +23,8 @@ pub struct BackupConfig {
|
|||||||
pub table_filter_mode: String,
|
pub table_filter_mode: String,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub table_patterns: Vec<String>,
|
pub table_patterns: Vec<String>,
|
||||||
|
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||||
|
pub selected_tables: Vec<BackupTableTarget>,
|
||||||
pub destination_directory: String,
|
pub destination_directory: String,
|
||||||
pub include_structure: bool,
|
pub include_structure: bool,
|
||||||
pub include_data: bool,
|
pub include_data: bool,
|
||||||
@@ -145,7 +155,7 @@ impl BackupConfig {
|
|||||||
if !matches!(self.output_compression.as_str(), "none" | "gzip") {
|
if !matches!(self.output_compression.as_str(), "none" | "gzip") {
|
||||||
return Err("Unsupported backup compression".into());
|
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());
|
return Err("Unsupported backup table filter".into());
|
||||||
}
|
}
|
||||||
if self.databases.len() > 10_000 || self.table_patterns.len() > 1000 {
|
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()) {
|
for value in self.databases.iter().chain(self.table_patterns.iter()) {
|
||||||
bounded_text(value, 1024, "Backup target")?;
|
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());
|
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)
|
validate_template(self.file_name_pattern.as_deref().unwrap_or(DEFAULT_FILE), false)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -56,6 +56,29 @@ fn invalid_schedule_and_path_templates_are_rejected() {
|
|||||||
assert!(super::models::matches_pattern("PUBLIC.*", "users", "app", "public", false));
|
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]
|
#[tokio::test]
|
||||||
async fn schedule_survives_reopen_and_rejects_stale_edit() {
|
async fn schedule_survives_reopen_and_rejects_stale_edit() {
|
||||||
let dir = tempfile::tempdir().unwrap();
|
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.error.as_deref().unwrap().contains("No tables matched"));
|
||||||
assert!(completed.files.is_empty());
|
assert!(completed.files.is_empty());
|
||||||
assert!(previous.unwrap().exists());
|
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>(())
|
Ok::<_, String>(())
|
||||||
})
|
})
|
||||||
.catch_unwind()
|
.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.storage.save_connections(std::slice::from_ref(&admin)).await.unwrap();
|
||||||
service.state.configs.write().await.insert(admin.id.clone(), admin);
|
service.state.configs.write().await.insert(admin.id.clone(), admin);
|
||||||
let database = format!("dbx_pg_backup_{}", uuid::Uuid::new_v4().simple());
|
let database = format!("dbx_pg_backup_{}", uuid::Uuid::new_v4().simple());
|
||||||
|
eprintln!("Backup source test database: {database}");
|
||||||
execute_sql_statement(
|
execute_sql_statement(
|
||||||
&service.state,
|
&service.state,
|
||||||
admin_id,
|
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.
|
// A view inside the same schema is not part of a table-name scope.
|
||||||
assert!(!sql.contains("big_orders"), "{sql}");
|
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
|
// Patterns are case-sensitive on PostgreSQL, and a scope that matches
|
||||||
// nothing must fail without leaving a partial file behind.
|
// nothing must fail without leaving a partial file behind.
|
||||||
let mut empty = plan_with_id(dir.path(), "empty");
|
let mut empty = plan_with_id(dir.path(), "empty");
|
||||||
|
|||||||
Binary file not shown.
|
After Width: | Height: | Size: 65 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 75 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 72 KiB |
Reference in new issue
Block a user