30 files changed
+1373
-103
No files matched your search
@@ -29,6 +29,7 @@ let focusRestoreGeneration = 0;
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
sql?: string;
|
||||
copySql?: string | (() => string);
|
||||
title?: string;
|
||||
message?: string;
|
||||
details?: string;
|
||||
@@ -52,6 +53,7 @@ const props = withDefaults(
|
||||
}>(),
|
||||
{
|
||||
sql: "",
|
||||
copySql: "",
|
||||
title: "",
|
||||
message: "",
|
||||
details: "",
|
||||
@@ -155,7 +157,8 @@ function onConfirm() {
|
||||
}
|
||||
|
||||
async function copyFullCode() {
|
||||
await copyToClipboard(code.value);
|
||||
const copySql = typeof props.copySql === "function" ? props.copySql() : props.copySql;
|
||||
await copyToClipboard(copySql || code.value);
|
||||
copied.value = true;
|
||||
window.setTimeout(() => {
|
||||
copied.value = false;
|
||||
|
||||
@@ -121,6 +121,21 @@ describe("DangerConfirmDialog SQL preview", () => {
|
||||
expect(copyToClipboard).toHaveBeenCalledWith(sql);
|
||||
});
|
||||
|
||||
it("builds lazy full SQL only when the copy action is used", async () => {
|
||||
const fullSql = "DELETE FROM orders;\nDELETE FROM customers;";
|
||||
const getCopySql = vi.fn(() => fullSql);
|
||||
|
||||
await mountDialog("DELETE FROM orders;", { copySql: getCopySql });
|
||||
expect(getCopySql).not.toHaveBeenCalled();
|
||||
|
||||
const copyButton = Array.from(document.body.querySelectorAll("button")).find((button) => button.title === "Copy full text");
|
||||
copyButton?.click();
|
||||
await nextTick();
|
||||
|
||||
expect(getCopySql).toHaveBeenCalledOnce();
|
||||
expect(copyToClipboard).toHaveBeenCalledWith(fullSql);
|
||||
});
|
||||
|
||||
it("restores a previously focused CodeMirror editor through EditorView on close", async () => {
|
||||
const editorRoot = document.createElement("div");
|
||||
editorRoot.className = "cm-editor";
|
||||
|
||||
@@ -2921,6 +2921,7 @@ defineExpose({ focusSearch, createNewGroup, collapseAllTreeNodes, locateTabInSid
|
||||
:title="sidebarDangerDialogRequest.title"
|
||||
:message="sidebarDangerDialogRequest.message"
|
||||
:sql="sidebarDangerDialogRequest.sql"
|
||||
:copy-sql="sidebarDangerDialogRequest.copySql"
|
||||
:details="sidebarDangerDialogRequest.details"
|
||||
:details-text="sidebarDangerDialogRequest.detailsText"
|
||||
:confirm-label="sidebarDangerDialogRequest.confirmLabel"
|
||||
@@ -2933,9 +2934,9 @@ defineExpose({ focusSearch, createNewGroup, collapseAllTreeNodes, locateTabInSid
|
||||
@cancel-running="cancelSidebarDangerDialogRunning"
|
||||
>
|
||||
<template #options>
|
||||
<div v-if="sidebarDangerDialogConfirming && sidebarDangerDialogRequest.progress" class="mb-3 rounded-md border bg-muted/20 px-3 py-2.5">
|
||||
<div v-if="sidebarDangerDialogRequest.progress" class="mb-3 rounded-md border bg-muted/20 px-3 py-2.5">
|
||||
<div class="mb-1.5 flex items-center justify-between text-xs tabular-nums text-muted-foreground">
|
||||
<span>{{ sidebarDangerDialogRequest.progress.completed }} / {{ sidebarDangerDialogRequest.progress.total }}</span>
|
||||
<span>{{ sidebarDangerDialogRequest.progress.phase === "preparing" ? t("databaseEmpty.preparing", { database: sidebarDangerDialogRequest.target.database }) : "" }} {{ sidebarDangerDialogRequest.progress.completed }} / {{ sidebarDangerDialogRequest.progress.total }}</span>
|
||||
<span>{{ Math.round((sidebarDangerDialogRequest.progress.completed / sidebarDangerDialogRequest.progress.total) * 100) }}%</span>
|
||||
</div>
|
||||
<div class="h-2 overflow-hidden rounded-full bg-muted" role="progressbar" :aria-valuemin="0" :aria-valuemax="sidebarDangerDialogRequest.progress.total" :aria-valuenow="sidebarDangerDialogRequest.progress.completed">
|
||||
|
||||
@@ -11,6 +11,7 @@ import { useSidebarDatabaseSpecificMutationRuntime } from "@/composables/useSide
|
||||
import { useSidebarTableMutationRuntime } from "@/composables/useSidebarTableMutationRuntime";
|
||||
import { useSidebarTreeExportRuntime } from "@/composables/useSidebarTreeExportRuntime";
|
||||
import { useSidebarTreeToolRuntime } from "@/composables/useSidebarTreeToolRuntime";
|
||||
import { canDropDatabaseTables, canEmptyDatabaseTables, useDatabaseTableEmpty } from "@/composables/useDatabaseTableEmpty";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { translateBackendError } from "@/i18n/backend-errors";
|
||||
import {
|
||||
@@ -531,6 +532,8 @@ const emit = defineEmits<{
|
||||
"open-event-trigger-details": [node: TreeNode];
|
||||
}>();
|
||||
|
||||
const { requestEmptyDatabaseTables, requestDropDatabaseTables } = useDatabaseTableEmpty((request) => emit("open-danger-dialog", request));
|
||||
|
||||
const {
|
||||
setNodeAsDefaultDatabase,
|
||||
clearNodeDefaultDatabase,
|
||||
@@ -6222,6 +6225,12 @@ function buildDatabaseSidebarMenu(context: SidebarMenuFactoryContext): boolean {
|
||||
items.push({ label: t("dataDictionary.title"), action: openDataDictionary, icon: FileText });
|
||||
}
|
||||
const destructiveActions: ContextMenuItem[] = [];
|
||||
if (canEmptyDatabaseTables(node, node.connectionId ? connectionStore.getConfig(node.connectionId) : undefined)) {
|
||||
destructiveActions.push({ label: t("databaseEmpty.menu"), action: () => void requestEmptyDatabaseTables(node), icon: Eraser, variant: "destructive" as const });
|
||||
}
|
||||
if (canDropDatabaseTables(node, node.connectionId ? connectionStore.getConfig(node.connectionId) : undefined)) {
|
||||
destructiveActions.push({ label: t("databaseDrop.menu"), action: () => void requestDropDatabaseTables(node), icon: Trash2, variant: "destructive" as const });
|
||||
}
|
||||
if (canDropDatabase.value) {
|
||||
destructiveActions.push({
|
||||
label: t("contextMenu.dropDatabase"),
|
||||
|
||||
@@ -0,0 +1,253 @@
|
||||
import { ref, shallowRef } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { useToast } from "@/composables/useToast";
|
||||
import { useConnectionStore } from "@/stores/connectionStore";
|
||||
import { useQueryStore } from "@/stores/queryStore";
|
||||
import * as api from "@/lib/backend/api";
|
||||
import { connectionObjectTreeNodeSchema } from "@/lib/database/jdbcDialect";
|
||||
import { connectionIsEffectivelyReadOnly } from "@/lib/database/readOnlyWriteAccess";
|
||||
import { executeWithProductionSqlGuard } from "@/lib/database/productionExecutionGuard";
|
||||
import { translateBackendError } from "@/i18n/backend-errors";
|
||||
import { getTableMutationHistoryStoreOrNull, recordTableMutationHistory } from "@/lib/history/tableMutationHistory";
|
||||
import { runBatchTableEmptyLayers, type BatchTableEmptyPlanItem } from "@/lib/sidebar/batchTableEmpty";
|
||||
import { buildDatabaseTableEmptyPlanLayers, buildMysqlTableMutationSql, DatabaseTableEmptyPlanError, type DatabaseEmptyTable } from "@/lib/sidebar/databaseTableEmpty";
|
||||
import { createSidebarActionTarget } from "@/lib/sidebar/sidebarActionTarget";
|
||||
import { uuid } from "@/lib/common/utils";
|
||||
import type { SidebarDangerDialogRequest } from "@/lib/sidebar/sidebarDangerDialog";
|
||||
import type { ConnectionConfig, TreeNode } from "@/types/database";
|
||||
|
||||
export function canEmptyDatabaseTables(node: TreeNode, connection?: ConnectionConfig): boolean {
|
||||
const profile = connection?.driver_profile?.toLowerCase();
|
||||
const unsupportedMysqlProfiles = ["doris", "selectdb", "starrocks", "manticoresearch"];
|
||||
return (
|
||||
node.type === "database" &&
|
||||
!!node.database &&
|
||||
!!node.connectionId &&
|
||||
connection?.db_type === "mysql" &&
|
||||
!unsupportedMysqlProfiles.includes(profile ?? "") &&
|
||||
!connectionIsEffectivelyReadOnly(connection) &&
|
||||
!["mysql", "sys", "information_schema", "performance_schema", "ndbinfo"].includes(node.database.toLowerCase())
|
||||
);
|
||||
}
|
||||
export const canDropDatabaseTables = canEmptyDatabaseTables;
|
||||
|
||||
export function useDatabaseTableEmpty(openDialog: (request: SidebarDangerDialogRequest) => void) {
|
||||
const { t } = useI18n();
|
||||
const { toast } = useToast();
|
||||
const connections = useConnectionStore();
|
||||
const queries = useQueryStore();
|
||||
async function requestDatabaseTables(node: TreeNode, operation: "empty" | "drop") {
|
||||
const target = createSidebarActionTarget(node);
|
||||
const connectionId = target.connectionId!;
|
||||
const database = target.database!;
|
||||
if (!canEmptyDatabaseTables(target, connections.getConfig(connectionId))) return;
|
||||
const typedName = ref("");
|
||||
const loading = ref(true);
|
||||
const executing = ref(false);
|
||||
const finished = ref(false);
|
||||
const cancelled = ref(false);
|
||||
const details = ref("");
|
||||
const completed = ref(0);
|
||||
const preparing = ref(0);
|
||||
const preparingTotal = ref(0);
|
||||
const plan = shallowRef<BatchTableEmptyPlanItem<DatabaseEmptyTable>[]>([]);
|
||||
const layers = shallowRef<{ items: BatchTableEmptyPlanItem<DatabaseEmptyTable>[]; dependencies?: Record<string, string[]> }[]>([]);
|
||||
const activeExecutionIds = new Set<string>();
|
||||
const preparationExecutionIds = new Set<string>();
|
||||
const connectionName = connections.getConfig(connectionId)?.name ?? connectionId;
|
||||
const fullSql = () => plan.value.map(({ sql }) => sql).join("\n");
|
||||
const previewSql = () => {
|
||||
const preview = plan.value
|
||||
.slice(0, 100)
|
||||
.map(({ sql }) => sql)
|
||||
.join("\n");
|
||||
return plan.value.length > 100 ? `${preview}\n-- ${plan.value.length - 100} more statements` : preview;
|
||||
};
|
||||
const request: SidebarDangerDialogRequest = {
|
||||
target,
|
||||
title: t(operation === "empty" ? "databaseEmpty.title" : "databaseDrop.title"),
|
||||
get message() {
|
||||
if (loading.value && plan.value.length === 0) return `${t(operation === "empty" ? "databaseEmpty.preparing" : "databaseDrop.preparing", { database })} ${preparingTotal.value ? `${preparing.value} / ${preparingTotal.value}` : ""}`;
|
||||
return t(operation === "empty" ? "databaseEmpty.message" : "databaseDrop.message", { connection: connectionName, database, count: plan.value.length });
|
||||
},
|
||||
get sql() {
|
||||
return previewSql();
|
||||
},
|
||||
copySql: fullSql,
|
||||
get detailsText() {
|
||||
return details.value;
|
||||
},
|
||||
get loading() {
|
||||
return loading.value;
|
||||
},
|
||||
get confirmDisabled() {
|
||||
return loading.value || finished.value || cancelled.value || !plan.value.length || typedName.value !== database;
|
||||
},
|
||||
confirmLabel: t(operation === "empty" ? "databaseEmpty.title" : "databaseDrop.title"),
|
||||
closeOnConfirm: false,
|
||||
get progress() {
|
||||
return executing.value && plan.value.length ? { completed: completed.value, total: plan.value.length, phase: "executing" as const } : loading.value && preparingTotal.value ? { completed: preparing.value, total: preparingTotal.value, phase: "preparing" as const } : undefined;
|
||||
},
|
||||
async cancelRunning() {
|
||||
cancelled.value = true;
|
||||
await Promise.all([...activeExecutionIds, ...preparationExecutionIds].map((id) => api.cancelQuery(id).catch(() => false)));
|
||||
},
|
||||
textInput: {
|
||||
value: "",
|
||||
label: t(operation === "empty" ? "databaseEmpty.typeName" : "databaseDrop.typeName", { database }),
|
||||
placeholder: database,
|
||||
onInput(value) {
|
||||
typedName.value = value;
|
||||
},
|
||||
},
|
||||
async confirm() {
|
||||
if (request.confirmDisabled) return false;
|
||||
loading.value = true;
|
||||
executing.value = true;
|
||||
const frozenPlan = plan.value;
|
||||
const reviewSql = previewSql();
|
||||
const start = Date.now();
|
||||
try {
|
||||
const result = await executeWithProductionSqlGuard({
|
||||
connection: connections.getConfig(connectionId),
|
||||
database,
|
||||
sql: reviewSql,
|
||||
source: t("production.sourceSidebar"),
|
||||
execute: () =>
|
||||
runBatchTableEmptyLayers(layers.value, {
|
||||
concurrency: 8,
|
||||
isCancelled: () => cancelled.value,
|
||||
keyOf: (table) => table.name,
|
||||
execute: async (item, executionId) => {
|
||||
activeExecutionIds.add(executionId);
|
||||
try {
|
||||
const response = await api.executeQuery(connectionId, database, item.sql, database, executionId);
|
||||
if (response.execution_error) throw new Error(String(response.rows[0]?.[0] ?? "Statement failed"));
|
||||
} finally {
|
||||
activeExecutionIds.delete(executionId);
|
||||
}
|
||||
},
|
||||
onProgress: (value) => {
|
||||
completed.value = value;
|
||||
},
|
||||
}),
|
||||
});
|
||||
if (!result) return false;
|
||||
finished.value = true;
|
||||
const failures = result.failed.map(({ target: item, error }) => `${item.name}: ${translateBackendError(t, error)}`);
|
||||
const cancelledCount = result.cancelled?.length ?? 0;
|
||||
const skippedCount = result.skipped?.length ?? 0;
|
||||
const skippedDetails = (result.skipped ?? []).slice(0, 100).map(({ target: item, reason, dependency }) => (dependency ? t(`${operation === "empty" ? "databaseEmpty" : "databaseDrop"}.blockedBy`, { table: item.name, dependency }) : `${item.name}: ${reason}`));
|
||||
const omittedFailures = failures.length > 100 ? [`... ${failures.length - 100} more failures`] : [];
|
||||
const omittedSkipped = skippedCount > 100 ? [`... ${skippedCount - 100} more skipped tables`] : [];
|
||||
details.value = [
|
||||
t(operation === "empty" ? "databaseEmpty.result" : "databaseDrop.result", { success: result.succeeded.length, failed: result.failed.length }),
|
||||
skippedCount ? t(operation === "empty" ? "databaseEmpty.skipped" : "databaseDrop.skipped", { count: skippedCount }) : "",
|
||||
...skippedDetails,
|
||||
...omittedSkipped,
|
||||
cancelledCount ? t(operation === "empty" ? "databaseEmpty.cancelled" : "databaseDrop.cancelled", { count: cancelledCount }) : "",
|
||||
...failures.slice(0, 100),
|
||||
...omittedFailures,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join("\n");
|
||||
toast(details.value, result.failed.length || cancelledCount || skippedCount ? 5000 : 3000);
|
||||
const historyTarget =
|
||||
frozenPlan.length > 100
|
||||
? `${frozenPlan
|
||||
.slice(0, 100)
|
||||
.map(({ target: table }) => table.name)
|
||||
.join(", ")}, +${frozenPlan.length - 100} more`
|
||||
: frozenPlan.map(({ target: table }) => table.name).join(", ");
|
||||
const historyError = failures.length > 100 ? `${failures.slice(0, 100).join("; ")}; +${failures.length - 100} more failures` : failures.join("; ");
|
||||
await recordTableMutationHistory(getTableMutationHistoryStoreOrNull(), {
|
||||
connectionId,
|
||||
connectionName,
|
||||
database,
|
||||
sql: reviewSql,
|
||||
elapsedMs: Date.now() - start,
|
||||
success: result.failed.length === 0 && cancelledCount === 0 && skippedCount === 0,
|
||||
error: historyError || undefined,
|
||||
target: historyTarget,
|
||||
}).catch((error) => console.warn("[DBX] failed to record database empty history", error));
|
||||
const complete = result.failed.length === 0 && cancelledCount === 0 && skippedCount === 0;
|
||||
if (result.succeeded.length) {
|
||||
const schema = connectionObjectTreeNodeSchema(connections.getConfig(connectionId), database, database);
|
||||
for (const table of result.succeeded) {
|
||||
if (operation === "drop") queries.closeDroppedTableObjectTabs({ connectionId, database, schema, schemaCandidates: [database, schema], name: table.name, objectType: "TABLE" });
|
||||
if (operation === "empty") await queries.refreshDataTabsForTable({ connectionId, database, schema, schemaCandidates: [database, schema], catalog: target.catalog, name: table.name }).catch((error) => console.warn("[DBX] failed to refresh emptied table", error));
|
||||
}
|
||||
await connections.refreshObjectListTreeNode(connectionId, database, undefined, target.catalog).catch((error) => {
|
||||
details.value += `\n${t("databaseEmpty.refreshFailed", { message: translateBackendError(t, error) })}`;
|
||||
});
|
||||
}
|
||||
return complete;
|
||||
} catch (error) {
|
||||
details.value = translateBackendError(t, error);
|
||||
toast(t("contextMenu.tableOperationFailed", { message: details.value }), 5000);
|
||||
return false;
|
||||
} finally {
|
||||
loading.value = false;
|
||||
executing.value = false;
|
||||
}
|
||||
},
|
||||
};
|
||||
openDialog(request);
|
||||
const ensurePreparationActive = () => {
|
||||
if (cancelled.value) throw new DatabaseTableEmptyPlanError("cancelled", []);
|
||||
};
|
||||
const runPreparationRequest = async <T>(request: (executionId: string) => Promise<T>): Promise<T> => {
|
||||
ensurePreparationActive();
|
||||
const executionId = uuid();
|
||||
preparationExecutionIds.add(executionId);
|
||||
try {
|
||||
const result = await request(executionId);
|
||||
ensurePreparationActive();
|
||||
return result;
|
||||
} catch (error) {
|
||||
if (cancelled.value) throw new DatabaseTableEmptyPlanError("cancelled", []);
|
||||
throw error;
|
||||
} finally {
|
||||
preparationExecutionIds.delete(executionId);
|
||||
}
|
||||
};
|
||||
try {
|
||||
await connections.ensureConnected(connectionId);
|
||||
const externalReferences = await runPreparationRequest((executionId) =>
|
||||
api.executeQuery(connectionId, database, "SELECT TABLE_SCHEMA, TABLE_NAME FROM information_schema.KEY_COLUMN_USAGE WHERE REFERENCED_TABLE_SCHEMA = DATABASE() AND TABLE_SCHEMA <> DATABASE() LIMIT 1", undefined, executionId),
|
||||
);
|
||||
if (externalReferences.execution_error) throw new Error(t("databaseEmpty.metadataFailed"));
|
||||
if (externalReferences.rows.length) throw new Error(t("databaseEmpty.externalReferences"));
|
||||
const foreignKeysByTable = await runPreparationRequest((executionId) => api.listForeignKeysForDatabase(connectionId, database, database, target.catalog, executionId));
|
||||
layers.value = await buildDatabaseTableEmptyPlanLayers({
|
||||
database,
|
||||
listTables: () => runPreparationRequest((executionId) => api.listObjects(connectionId, database, database, ["TABLE"], undefined, undefined, undefined, target.catalog, undefined, executionId)),
|
||||
foreignKeysByTable,
|
||||
isCancelled: () => cancelled.value,
|
||||
onProgress: (value, total) => {
|
||||
preparing.value = value;
|
||||
preparingTotal.value = total * 2;
|
||||
},
|
||||
onSqlProgress: (value, total) => {
|
||||
preparing.value = total + value;
|
||||
preparingTotal.value = total * 2;
|
||||
},
|
||||
buildSql: async (table) => buildMysqlTableMutationSql(operation, database, table.name),
|
||||
});
|
||||
plan.value = layers.value.flatMap((layer) => layer.items);
|
||||
if (!plan.value.length) details.value = t(operation === "empty" ? "databaseEmpty.noTables" : "databaseDrop.noTables");
|
||||
else if (plan.value.length > 2000) details.value = t(operation === "empty" ? "databaseEmpty.veryLargeWarning" : "databaseDrop.veryLargeWarning", { count: plan.value.length });
|
||||
else if (plan.value.length > 500) details.value = t(operation === "empty" ? "databaseEmpty.largeWarning" : "databaseDrop.largeWarning", { count: plan.value.length });
|
||||
} catch (error) {
|
||||
details.value =
|
||||
error instanceof DatabaseTableEmptyPlanError && error.reason === "cancelled"
|
||||
? t(`${operation === "empty" ? "databaseEmpty" : "databaseDrop"}.cancelledPreparation`)
|
||||
: error instanceof DatabaseTableEmptyPlanError
|
||||
? t(`${operation === "empty" ? "databaseEmpty" : "databaseDrop"}.${error.reason}`, { tables: error.tables.join(", ") })
|
||||
: translateBackendError(t, error);
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
return { requestEmptyDatabaseTables: (node: TreeNode) => requestDatabaseTables(node, "empty"), requestDropDatabaseTables: (node: TreeNode) => requestDatabaseTables(node, "drop") };
|
||||
}
|
||||
@@ -2025,6 +2025,44 @@ export default {
|
||||
defaultCharset: "Charset",
|
||||
defaultCollation: "Collation",
|
||||
},
|
||||
databaseEmpty: {
|
||||
menu: "Empty all table data",
|
||||
title: "Empty all table data",
|
||||
preparing: "Loading all tables in {database}...",
|
||||
cancelledPreparation: "Operation cancelled before execution.",
|
||||
message: "This will delete all rows from {count} tables in {database} on {connection}.",
|
||||
typeName: "Type {database} to confirm",
|
||||
result: "Completed: {success}; failed: {failed}",
|
||||
skipped: "Skipped: {count}",
|
||||
blockedBy: "Skipped {table}: dependency {dependency} did not complete.",
|
||||
cancelled: "Cancelled: {count}",
|
||||
largeWarning: "This operation affects {count} tables and may take a long time. Partial failures are possible.",
|
||||
veryLargeWarning: "This operation affects {count} tables. Expect a long run and review partial failures carefully.",
|
||||
noTables: "No tables were found in this database.",
|
||||
metadataFailed: "Could not read the database table metadata.",
|
||||
externalReferences: "The database has foreign-key references from another database; the operation was stopped.",
|
||||
scope: "The table list contains objects outside the selected database: {tables}",
|
||||
cycle: "Foreign-key cycle detected; the operation was stopped for: {tables}",
|
||||
refreshFailed: "Refresh failed: {message}",
|
||||
},
|
||||
databaseDrop: {
|
||||
menu: "Drop all tables",
|
||||
title: "Drop all tables",
|
||||
preparing: "Loading all tables in {database}...",
|
||||
cancelledPreparation: "Operation cancelled before execution.",
|
||||
message: "This will permanently drop {count} tables from {database} on {connection}.",
|
||||
typeName: "Type {database} to confirm",
|
||||
result: "Completed: {success}; failed: {failed}",
|
||||
skipped: "Skipped: {count}",
|
||||
blockedBy: "Skipped {table}: dependency {dependency} did not complete.",
|
||||
cancelled: "Cancelled: {count}",
|
||||
largeWarning: "This operation affects {count} tables and may take a long time. Partial failures are possible.",
|
||||
veryLargeWarning: "This operation affects {count} tables. Expect a long run and review partial failures carefully.",
|
||||
noTables: "No tables were found in this database.",
|
||||
scope: "The table list contains objects outside the selected database: {tables}",
|
||||
cycle: "Foreign-key cycle detected; the operation was stopped for: {tables}",
|
||||
refreshFailed: "Refresh failed: {message}",
|
||||
},
|
||||
gridfsBrowser: {
|
||||
bucketCount: "buckets",
|
||||
fileCount: "files",
|
||||
|
||||
@@ -9377,6 +9377,44 @@ export default withEnglishFallback({
|
||||
defaultCharset: "Juego de caracteres",
|
||||
defaultCollation: "Cotejamiento",
|
||||
},
|
||||
databaseEmpty: {
|
||||
menu: "Vaciar los datos de todas las tablas",
|
||||
title: "Vaciar los datos de todas las tablas",
|
||||
preparing: "Cargando todas las tablas de {database}...",
|
||||
cancelledPreparation: "Operación cancelada antes de ejecutarse.",
|
||||
message: "Se eliminarán todas las filas de {count} tablas de {database} en {connection}.",
|
||||
typeName: "Escribe {database} para confirmar",
|
||||
result: "Completadas: {success}; fallidas: {failed}",
|
||||
skipped: "Omitidas: {count}",
|
||||
blockedBy: "Se omitió {table}: la dependencia {dependency} no se completó.",
|
||||
cancelled: "Canceladas: {count}",
|
||||
largeWarning: "Esta operación afecta a {count} tablas y puede tardar mucho. Es posible que haya fallos parciales.",
|
||||
veryLargeWarning: "Esta operación afecta a {count} tablas. Espera una ejecución larga y revisa con atención los fallos parciales.",
|
||||
noTables: "No se encontraron tablas en esta base de datos.",
|
||||
metadataFailed: "No se pudieron leer los metadatos de las tablas de la base de datos.",
|
||||
externalReferences: "La base de datos recibe referencias de claves foráneas de otra base de datos; la operación se detuvo.",
|
||||
scope: "La lista de tablas incluye objetos fuera de la base de datos seleccionada: {tables}",
|
||||
cycle: "Se detectó un ciclo de claves foráneas; la operación se detuvo para: {tables}",
|
||||
refreshFailed: "Error al actualizar: {message}",
|
||||
},
|
||||
databaseDrop: {
|
||||
menu: "Eliminar todas las tablas",
|
||||
title: "Eliminar todas las tablas",
|
||||
preparing: "Cargando todas las tablas de {database}...",
|
||||
cancelledPreparation: "Operación cancelada antes de ejecutarse.",
|
||||
message: "Se eliminarán permanentemente {count} tablas de {database} en {connection}.",
|
||||
typeName: "Escribe {database} para confirmar",
|
||||
result: "Completadas: {success}; fallidas: {failed}",
|
||||
skipped: "Omitidas: {count}",
|
||||
blockedBy: "Se omitió {table}: la dependencia {dependency} no se completó.",
|
||||
cancelled: "Canceladas: {count}",
|
||||
largeWarning: "Esta operación afecta a {count} tablas y puede tardar mucho. Es posible que haya fallos parciales.",
|
||||
veryLargeWarning: "Esta operación afecta a {count} tablas. Espera una ejecución larga y revisa con atención los fallos parciales.",
|
||||
noTables: "No se encontraron tablas en esta base de datos.",
|
||||
scope: "La lista de tablas incluye objetos fuera de la base de datos seleccionada: {tables}",
|
||||
cycle: "Se detectó un ciclo de claves foráneas; la operación se detuvo para: {tables}",
|
||||
refreshFailed: "Error al actualizar: {message}",
|
||||
},
|
||||
gridfsBrowser: {
|
||||
bucketCount: "Cantidad de buckets",
|
||||
fileCount: "Archivos",
|
||||
|
||||
@@ -9122,6 +9122,44 @@ export default withEnglishFallback({
|
||||
defaultCharset: "Set di caratteri",
|
||||
defaultCollation: "Regole di confronto",
|
||||
},
|
||||
databaseEmpty: {
|
||||
menu: "Svuota i dati di tutte le tabelle",
|
||||
title: "Svuota i dati di tutte le tabelle",
|
||||
preparing: "Caricamento di tutte le tabelle in {database}...",
|
||||
cancelledPreparation: "Operazione annullata prima dell'esecuzione.",
|
||||
message: "Verranno eliminate tutte le righe di {count} tabelle in {database} su {connection}.",
|
||||
typeName: "Digita {database} per confermare",
|
||||
result: "Completate: {success}; non riuscite: {failed}",
|
||||
skipped: "Ignorate: {count}",
|
||||
blockedBy: "{table} ignorata: la dipendenza {dependency} non è stata completata.",
|
||||
cancelled: "Annullate: {count}",
|
||||
largeWarning: "Questa operazione coinvolge {count} tabelle e può richiedere molto tempo. Sono possibili errori parziali.",
|
||||
veryLargeWarning: "Questa operazione coinvolge {count} tabelle. Prevedi un'esecuzione lunga e controlla attentamente gli errori parziali.",
|
||||
noTables: "Nessuna tabella trovata in questo database.",
|
||||
metadataFailed: "Impossibile leggere i metadati delle tabelle del database.",
|
||||
externalReferences: "Il database riceve riferimenti di chiavi esterne da un altro database; operazione interrotta.",
|
||||
scope: "L'elenco delle tabelle contiene oggetti esterni al database selezionato: {tables}",
|
||||
cycle: "Rilevato un ciclo di chiavi esterne; operazione interrotta per: {tables}",
|
||||
refreshFailed: "Aggiornamento non riuscito: {message}",
|
||||
},
|
||||
databaseDrop: {
|
||||
menu: "Elimina tutte le tabelle",
|
||||
title: "Elimina tutte le tabelle",
|
||||
preparing: "Caricamento di tutte le tabelle in {database}...",
|
||||
cancelledPreparation: "Operazione annullata prima dell'esecuzione.",
|
||||
message: "Verranno eliminate definitivamente {count} tabelle da {database} su {connection}.",
|
||||
typeName: "Digita {database} per confermare",
|
||||
result: "Completate: {success}; non riuscite: {failed}",
|
||||
skipped: "Ignorate: {count}",
|
||||
blockedBy: "{table} ignorata: la dipendenza {dependency} non è stata completata.",
|
||||
cancelled: "Annullate: {count}",
|
||||
largeWarning: "Questa operazione coinvolge {count} tabelle e può richiedere molto tempo. Sono possibili errori parziali.",
|
||||
veryLargeWarning: "Questa operazione coinvolge {count} tabelle. Prevedi un'esecuzione lunga e controlla attentamente gli errori parziali.",
|
||||
noTables: "Nessuna tabella trovata in questo database.",
|
||||
scope: "L'elenco delle tabelle contiene oggetti esterni al database selezionato: {tables}",
|
||||
cycle: "Rilevato un ciclo di chiavi esterne; operazione interrotta per: {tables}",
|
||||
refreshFailed: "Aggiornamento non riuscito: {message}",
|
||||
},
|
||||
gridfsBrowser: {
|
||||
bucketCount: "Bucket",
|
||||
fileCount: "File",
|
||||
|
||||
@@ -9162,6 +9162,44 @@ export default withEnglishFallback({
|
||||
defaultCharset: "文字セット",
|
||||
defaultCollation: "照合順序",
|
||||
},
|
||||
databaseEmpty: {
|
||||
menu: "全テーブルのデータを空にする",
|
||||
title: "全テーブルのデータを空にする",
|
||||
preparing: "{database} 内のすべてのテーブルを読み込み中...",
|
||||
cancelledPreparation: "実行前に操作がキャンセルされました。",
|
||||
message: "接続 {connection} の {database} にある {count} 個のテーブルのすべての行を削除します。",
|
||||
typeName: "確認のため {database} を入力してください",
|
||||
result: "完了: {success}、失敗: {failed}",
|
||||
skipped: "スキップ: {count}",
|
||||
blockedBy: "{table} をスキップしました: 依存テーブル {dependency} が完了していません。",
|
||||
cancelled: "キャンセル: {count}",
|
||||
largeWarning: "この操作は {count} 個のテーブルを対象とするため時間がかかる可能性があり、一部が失敗する場合もあります。",
|
||||
veryLargeWarning: "この操作は {count} 個のテーブルを対象とします。実行に長い時間がかかるため、部分失敗の結果を慎重に確認してください。",
|
||||
noTables: "このデータベースにはテーブルが見つかりませんでした。",
|
||||
metadataFailed: "データベースのテーブルメタデータを読み取れませんでした。",
|
||||
externalReferences: "他のデータベースからこのデータベースへの外部キー参照があるため、操作を中止しました。",
|
||||
scope: "テーブル一覧に、選択したデータベースの外側にあるオブジェクトが含まれています: {tables}",
|
||||
cycle: "外部キーの循環参照が検出されたため、対象の操作を中止しました: {tables}",
|
||||
refreshFailed: "更新に失敗しました: {message}",
|
||||
},
|
||||
databaseDrop: {
|
||||
menu: "すべてのテーブルを削除",
|
||||
title: "すべてのテーブルを削除",
|
||||
preparing: "{database} 内のすべてのテーブルを読み込み中...",
|
||||
cancelledPreparation: "実行前に操作がキャンセルされました。",
|
||||
message: "接続 {connection} の {database} から {count} 個のテーブルを完全に削除します。",
|
||||
typeName: "確認のため {database} を入力してください",
|
||||
result: "完了: {success}、失敗: {failed}",
|
||||
skipped: "スキップ: {count}",
|
||||
blockedBy: "{table} をスキップしました: 依存テーブル {dependency} が完了していません。",
|
||||
cancelled: "キャンセル: {count}",
|
||||
largeWarning: "この操作は {count} 個のテーブルを対象とするため時間がかかる可能性があり、一部が失敗する場合があります。",
|
||||
veryLargeWarning: "この操作は {count} 個のテーブルを対象とします。実行に長い時間がかかるため、部分失敗の結果を慎重に確認してください。",
|
||||
noTables: "このデータベースにはテーブルが見つかりませんでした。",
|
||||
scope: "テーブル一覧に、選択したデータベースの外側にあるオブジェクトが含まれています: {tables}",
|
||||
cycle: "外部キーの循環参照が検出されたため、対象の操作を中止しました: {tables}",
|
||||
refreshFailed: "更新に失敗しました: {message}",
|
||||
},
|
||||
gridfsBrowser: {
|
||||
bucketCount: "バケット",
|
||||
fileCount: "ファイル",
|
||||
|
||||
@@ -1840,6 +1840,44 @@ export default withEnglishFallback({
|
||||
defaultCharset: "문자 집합",
|
||||
defaultCollation: "데이터 정렬",
|
||||
},
|
||||
databaseEmpty: {
|
||||
menu: "모든 테이블 데이터 비우기",
|
||||
title: "모든 테이블 데이터 비우기",
|
||||
preparing: "{database}의 모든 테이블을 불러오는 중...",
|
||||
cancelledPreparation: "실행 전에 작업이 취소되었습니다.",
|
||||
message: "{connection} 연결의 {database}에 있는 {count}개 테이블의 모든 행을 삭제합니다.",
|
||||
typeName: "확인하려면 {database}를 입력하세요",
|
||||
result: "완료: {success}, 실패: {failed}",
|
||||
skipped: "건너뜀: {count}",
|
||||
blockedBy: "{table}을(를) 건너뛰었습니다: 종속 테이블 {dependency}이(가) 완료되지 않았습니다.",
|
||||
cancelled: "취소됨: {count}",
|
||||
largeWarning: "이 작업은 {count}개 테이블에 영향을 주며 오랜 시간이 걸릴 수 있습니다. 일부가 실패할 수도 있습니다.",
|
||||
veryLargeWarning: "이 작업은 {count}개 테이블에 영향을 줍니다. 오래 걸릴 것으로 예상되며 부분 실패 결과를 꼼꼼히 확인하세요.",
|
||||
noTables: "이 데이터베이스에서 테이블을 찾지 못했습니다.",
|
||||
metadataFailed: "데이터베이스 테이블 메타데이터를 읽지 못했습니다.",
|
||||
externalReferences: "다른 데이터베이스가 외래 키로 이 데이터베이스를 참조하고 있어 작업을 중단했습니다.",
|
||||
scope: "테이블 목록에 선택한 데이터베이스 외부의 객체가 포함되어 있습니다: {tables}",
|
||||
cycle: "외래 키 순환 참조가 감지되어 해당 작업을 중단했습니다: {tables}",
|
||||
refreshFailed: "새로 고침 실패: {message}",
|
||||
},
|
||||
databaseDrop: {
|
||||
menu: "모든 테이블 삭제",
|
||||
title: "모든 테이블 삭제",
|
||||
preparing: "{database}의 모든 테이블을 불러오는 중...",
|
||||
cancelledPreparation: "실행 전에 작업이 취소되었습니다.",
|
||||
message: "{connection} 연결의 {database}에 있는 {count}개 테이블을 영구 삭제합니다.",
|
||||
typeName: "확인하려면 {database}를 입력하세요",
|
||||
result: "완료: {success}, 실패: {failed}",
|
||||
skipped: "건너뜀: {count}",
|
||||
blockedBy: "{table}을(를) 건너뛰었습니다: 종속 테이블 {dependency}이(가) 완료되지 않았습니다.",
|
||||
cancelled: "취소됨: {count}",
|
||||
largeWarning: "이 작업은 {count}개 테이블에 영향을 주며 오랜 시간이 걸릴 수 있습니다. 일부가 실패할 수도 있습니다.",
|
||||
veryLargeWarning: "이 작업은 {count}개 테이블에 영향을 줍니다. 오래 걸릴 것으로 예상되며 부분 실패 결과를 꼼꼼히 확인하세요.",
|
||||
noTables: "이 데이터베이스에서 테이블을 찾지 못했습니다.",
|
||||
scope: "테이블 목록에 선택한 데이터베이스 외부의 객체가 포함되어 있습니다: {tables}",
|
||||
cycle: "외래 키 순환 참조가 감지되어 해당 작업을 중단했습니다: {tables}",
|
||||
refreshFailed: "새로 고침 실패: {message}",
|
||||
},
|
||||
gridfsBrowser: {
|
||||
bucketCount: "버킷",
|
||||
fileCount: "파일",
|
||||
|
||||
@@ -9121,6 +9121,44 @@ export default withEnglishFallback({
|
||||
defaultCharset: "Conjunto de caracteres",
|
||||
defaultCollation: "Agrupamento",
|
||||
},
|
||||
databaseEmpty: {
|
||||
menu: "Esvaziar dados de todas as tabelas",
|
||||
title: "Esvaziar dados de todas as tabelas",
|
||||
preparing: "Carregando todas as tabelas em {database}...",
|
||||
cancelledPreparation: "Operação cancelada antes da execução.",
|
||||
message: "Isso excluirá todas as linhas de {count} tabelas em {database} na conexão {connection}.",
|
||||
typeName: "Digite {database} para confirmar",
|
||||
result: "Concluídas: {success}; com falha: {failed}",
|
||||
skipped: "Ignoradas: {count}",
|
||||
blockedBy: "{table} ignorada: a dependência {dependency} não foi concluída.",
|
||||
cancelled: "Canceladas: {count}",
|
||||
largeWarning: "Esta operação afeta {count} tabelas e pode demorar bastante. Falhas parciais são possíveis.",
|
||||
veryLargeWarning: "Esta operação afeta {count} tabelas. Espere uma execução longa e revise com atenção as falhas parciais.",
|
||||
noTables: "Nenhuma tabela foi encontrada neste banco de dados.",
|
||||
metadataFailed: "Não foi possível ler os metadados das tabelas do banco de dados.",
|
||||
externalReferences: "O banco de dados tem referências de chaves estrangeiras de outro banco de dados; a operação foi interrompida.",
|
||||
scope: "A lista de tabelas contém objetos fora do banco de dados selecionado: {tables}",
|
||||
cycle: "Ciclo de chaves estrangeiras detectado; a operação foi interrompida para: {tables}",
|
||||
refreshFailed: "Falha ao atualizar: {message}",
|
||||
},
|
||||
databaseDrop: {
|
||||
menu: "Remover todas as tabelas",
|
||||
title: "Remover todas as tabelas",
|
||||
preparing: "Carregando todas as tabelas em {database}...",
|
||||
cancelledPreparation: "Operação cancelada antes da execução.",
|
||||
message: "Isso removerá permanentemente {count} tabelas de {database} na conexão {connection}.",
|
||||
typeName: "Digite {database} para confirmar",
|
||||
result: "Concluídas: {success}; com falha: {failed}",
|
||||
skipped: "Ignoradas: {count}",
|
||||
blockedBy: "{table} ignorada: a dependência {dependency} não foi concluída.",
|
||||
cancelled: "Canceladas: {count}",
|
||||
largeWarning: "Esta operação afeta {count} tabelas e pode demorar bastante. Falhas parciais são possíveis.",
|
||||
veryLargeWarning: "Esta operação afeta {count} tabelas. Espere uma execução longa e revise com atenção as falhas parciais.",
|
||||
noTables: "Nenhuma tabela foi encontrada neste banco de dados.",
|
||||
scope: "A lista de tabelas contém objetos fora do banco de dados selecionado: {tables}",
|
||||
cycle: "Ciclo de chaves estrangeiras detectado; a operação foi interrompida para: {tables}",
|
||||
refreshFailed: "Falha ao atualizar: {message}",
|
||||
},
|
||||
gridfsBrowser: {
|
||||
bucketCount: "Buckets",
|
||||
fileCount: "Arquivos",
|
||||
|
||||
@@ -1933,6 +1933,44 @@ export default withEnglishFallback({
|
||||
defaultCharset: "Кодировка",
|
||||
defaultCollation: "Сортировка",
|
||||
},
|
||||
databaseEmpty: {
|
||||
menu: "Очистить данные всех таблиц",
|
||||
title: "Очистить данные всех таблиц",
|
||||
preparing: "Загрузка всех таблиц в {database}...",
|
||||
cancelledPreparation: "Операция отменена до выполнения.",
|
||||
message: "Будут удалены все строки из {count} таблиц в {database} на подключении {connection}.",
|
||||
typeName: "Введите {database} для подтверждения",
|
||||
result: "Завершено: {success}; с ошибками: {failed}",
|
||||
skipped: "Пропущено: {count}",
|
||||
blockedBy: "Пропущена {table}: зависимость {dependency} не была завершена.",
|
||||
cancelled: "Отменено: {count}",
|
||||
largeWarning: "Операция затрагивает {count} таблиц и может занять много времени. Возможны частичные сбои.",
|
||||
veryLargeWarning: "Операция затрагивает {count} таблиц. Ожидайте длительного выполнения и внимательно проверьте частичные сбои.",
|
||||
noTables: "В этой базе данных таблицы не найдены.",
|
||||
metadataFailed: "Не удалось прочитать метаданные таблиц базы данных.",
|
||||
externalReferences: "На базу данных есть ссылки по внешним ключам из другой базы данных; операция остановлена.",
|
||||
scope: "Список таблиц содержит объекты вне выбранной базы данных: {tables}",
|
||||
cycle: "Обнаружен цикл по внешним ключам; операция остановлена для: {tables}",
|
||||
refreshFailed: "Не удалось обновить: {message}",
|
||||
},
|
||||
databaseDrop: {
|
||||
menu: "Удалить все таблицы",
|
||||
title: "Удалить все таблицы",
|
||||
preparing: "Загрузка всех таблиц в {database}...",
|
||||
cancelledPreparation: "Операция отменена до выполнения.",
|
||||
message: "Будут безвозвратно удалены {count} таблиц из {database} на подключении {connection}.",
|
||||
typeName: "Введите {database} для подтверждения",
|
||||
result: "Завершено: {success}; с ошибками: {failed}",
|
||||
skipped: "Пропущено: {count}",
|
||||
blockedBy: "Пропущена {table}: зависимость {dependency} не была завершена.",
|
||||
cancelled: "Отменено: {count}",
|
||||
largeWarning: "Операция затрагивает {count} таблиц и может занять много времени. Возможны частичные сбои.",
|
||||
veryLargeWarning: "Операция затрагивает {count} таблиц. Ожидайте длительного выполнения и внимательно проверьте частичные сбои.",
|
||||
noTables: "В этой базе данных таблицы не найдены.",
|
||||
scope: "Список таблиц содержит объекты вне выбранной базы данных: {tables}",
|
||||
cycle: "Обнаружен цикл по внешним ключам; операция остановлена для: {tables}",
|
||||
refreshFailed: "Не удалось обновить: {message}",
|
||||
},
|
||||
gridfsBrowser: {
|
||||
bucketCount: "контейнеров",
|
||||
fileCount: "файлов",
|
||||
|
||||
@@ -1961,6 +1961,44 @@ export default withEnglishFallback({
|
||||
defaultCharset: "默认字符集",
|
||||
defaultCollation: "默认排序规则",
|
||||
},
|
||||
databaseEmpty: {
|
||||
menu: "清空所有表数据",
|
||||
title: "清空所有表数据",
|
||||
preparing: "正在加载数据库 {database} 的全部表...",
|
||||
cancelledPreparation: "操作已取消,尚未执行 SQL。",
|
||||
message: "将清空连接 {connection} 中数据库 {database} 的 {count} 张表数据。",
|
||||
typeName: "输入 {database} 以确认",
|
||||
result: "已完成:{success};失败:{failed}",
|
||||
skipped: "跳过:{count}",
|
||||
blockedBy: "已跳过 {table}:依赖表 {dependency} 未完成。",
|
||||
cancelled: "已取消:{count}",
|
||||
largeWarning: "本次操作涉及 {count} 张表,可能需要较长时间,并可能出现部分失败。",
|
||||
veryLargeWarning: "本次操作涉及 {count} 张表,执行时间可能很长,请重点关注部分失败结果。",
|
||||
noTables: "数据库中没有找到表。",
|
||||
metadataFailed: "读取数据库表元数据失败。",
|
||||
externalReferences: "检测到其他数据库对当前库存在外键引用,已停止操作。",
|
||||
scope: "表清单包含当前数据库之外的对象:{tables}",
|
||||
cycle: "检测到外键循环依赖,已停止操作:{tables}",
|
||||
refreshFailed: "刷新失败:{message}",
|
||||
},
|
||||
databaseDrop: {
|
||||
menu: "删除所有表",
|
||||
title: "删除所有表",
|
||||
preparing: "正在加载数据库 {database} 的全部表...",
|
||||
cancelledPreparation: "操作已取消,尚未执行 SQL。",
|
||||
message: "将永久删除连接 {connection} 中数据库 {database} 的 {count} 张表。",
|
||||
typeName: "输入 {database} 以确认",
|
||||
result: "已完成:{success};失败:{failed}",
|
||||
skipped: "跳过:{count}",
|
||||
blockedBy: "已跳过 {table}:依赖表 {dependency} 未完成。",
|
||||
cancelled: "已取消:{count}",
|
||||
largeWarning: "本次操作涉及 {count} 张表,可能需要较长时间,并可能出现部分失败。",
|
||||
veryLargeWarning: "本次操作涉及 {count} 张表,执行时间可能很长,请重点关注部分失败结果。",
|
||||
noTables: "数据库中没有找到表。",
|
||||
scope: "表清单包含当前数据库之外的对象:{tables}",
|
||||
cycle: "检测到外键循环依赖,已停止操作:{tables}",
|
||||
refreshFailed: "刷新失败:{message}",
|
||||
},
|
||||
gridfsBrowser: {
|
||||
bucketCount: "\u5b58\u50a8\u6876",
|
||||
fileCount: "\u6587\u4ef6",
|
||||
|
||||
@@ -9139,6 +9139,44 @@ export default withEnglishFallback({
|
||||
defaultCharset: "預設字元集",
|
||||
defaultCollation: "預設定序規則",
|
||||
},
|
||||
databaseEmpty: {
|
||||
menu: "清空所有資料表資料",
|
||||
title: "清空所有資料表資料",
|
||||
preparing: "正在載入資料庫 {database} 的全部資料表...",
|
||||
cancelledPreparation: "操作已取消,尚未執行 SQL。",
|
||||
message: "將清空連線 {connection} 中資料庫 {database} 的 {count} 張資料表資料。",
|
||||
typeName: "輸入 {database} 以確認",
|
||||
result: "已完成:{success};失敗:{failed}",
|
||||
skipped: "已略過:{count}",
|
||||
blockedBy: "已略過 {table}:相依資料表 {dependency} 未完成。",
|
||||
cancelled: "已取消:{count}",
|
||||
largeWarning: "本次操作涉及 {count} 張資料表,可能需要較長時間,並可能出現部分失敗。",
|
||||
veryLargeWarning: "本次操作涉及 {count} 張資料表,執行時間可能很長,請重點關注部分失敗結果。",
|
||||
noTables: "資料庫中沒有找到資料表。",
|
||||
metadataFailed: "讀取資料庫資料表中繼資料失敗。",
|
||||
externalReferences: "偵測到其他資料庫對目前資料庫存在外鍵引用,已停止操作。",
|
||||
scope: "資料表清單包含目前資料庫之外的物件:{tables}",
|
||||
cycle: "偵測到外鍵循環相依,已停止操作:{tables}",
|
||||
refreshFailed: "重新整理失敗:{message}",
|
||||
},
|
||||
databaseDrop: {
|
||||
menu: "刪除所有資料表",
|
||||
title: "刪除所有資料表",
|
||||
preparing: "正在載入資料庫 {database} 的全部資料表...",
|
||||
cancelledPreparation: "操作已取消,尚未執行 SQL。",
|
||||
message: "將永久刪除連線 {connection} 中資料庫 {database} 的 {count} 張資料表。",
|
||||
typeName: "輸入 {database} 以確認",
|
||||
result: "已完成:{success};失敗:{failed}",
|
||||
skipped: "已略過:{count}",
|
||||
blockedBy: "已略過 {table}:相依資料表 {dependency} 未完成。",
|
||||
cancelled: "已取消:{count}",
|
||||
largeWarning: "本次操作涉及 {count} 張資料表,可能需要較長時間,並可能出現部分失敗。",
|
||||
veryLargeWarning: "本次操作涉及 {count} 張資料表,執行時間可能很長,請重點關注部分失敗結果。",
|
||||
noTables: "資料庫中沒有找到資料表。",
|
||||
scope: "資料表清單包含目前資料庫之外的物件:{tables}",
|
||||
cycle: "偵測到外鍵循環相依,已停止操作:{tables}",
|
||||
refreshFailed: "重新整理失敗:{message}",
|
||||
},
|
||||
gridfsBrowser: {
|
||||
bucketCount: "儲存桶",
|
||||
fileCount: "檔案",
|
||||
|
||||
+100
-1
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { batchTableEmptyFeedback, buildBatchTableEmptyPlan, runBatchTableEmpty } from "@/lib/sidebar/batchTableEmpty";
|
||||
import { batchTableEmptyFeedback, buildBatchTableEmptyPlan, runBatchTableEmpty, runBatchTableEmptyLayers } from "@/lib/sidebar/batchTableEmpty";
|
||||
|
||||
describe("batch table empty", () => {
|
||||
it("executes the exact SQL captured for the confirmation preview", async () => {
|
||||
@@ -37,6 +37,8 @@ describe("batch table empty", () => {
|
||||
const succeeded = { succeeded: ["events"], failed: [] };
|
||||
const partial = { succeeded: ["events"], failed: [{ target: "logs", error: new Error("failed") }] };
|
||||
const failed = { succeeded: [], failed: [{ target: "logs", error: new Error("failed") }] };
|
||||
const skipped = { succeeded: ["events"], failed: [], skipped: [{ target: "logs", reason: "blocked" }] };
|
||||
const cancelled = { succeeded: ["events"], failed: [], cancelled: ["logs"] };
|
||||
|
||||
expect(batchTableEmptyFeedback(succeeded, true)).toBe("submitted");
|
||||
expect(batchTableEmptyFeedback(partial, true)).toBe("submitted-partial");
|
||||
@@ -44,5 +46,102 @@ describe("batch table empty", () => {
|
||||
expect(batchTableEmptyFeedback(succeeded, false)).toBe("success");
|
||||
expect(batchTableEmptyFeedback(partial, false)).toBe("partial");
|
||||
expect(batchTableEmptyFeedback(failed, false)).toBe("partial");
|
||||
expect(batchTableEmptyFeedback(skipped, false)).toBe("partial");
|
||||
expect(batchTableEmptyFeedback(cancelled, true)).toBe("submitted-partial");
|
||||
});
|
||||
|
||||
it("limits independent table execution concurrency", async () => {
|
||||
let active = 0;
|
||||
let peak = 0;
|
||||
const result = await runBatchTableEmptyLayers([{ items: Array.from({ length: 40 }, (_, i) => ({ target: i, sql: `DELETE ${i}` })) }], {
|
||||
concurrency: 8,
|
||||
execute: async () => {
|
||||
active += 1;
|
||||
peak = Math.max(peak, active);
|
||||
await new Promise((resolve) => setTimeout(resolve, 1));
|
||||
active -= 1;
|
||||
},
|
||||
});
|
||||
expect(peak).toBeLessThanOrEqual(8);
|
||||
expect(result.succeeded).toHaveLength(40);
|
||||
});
|
||||
|
||||
it("stops dispatching after cancellation", async () => {
|
||||
let dispatched = 0;
|
||||
let cancelled = false;
|
||||
const result = await runBatchTableEmptyLayers([{ items: Array.from({ length: 20 }, (_, i) => ({ target: i, sql: `DELETE ${i}` })) }], {
|
||||
concurrency: 4,
|
||||
isCancelled: () => cancelled,
|
||||
execute: async () => {
|
||||
dispatched += 1;
|
||||
cancelled = true;
|
||||
},
|
||||
});
|
||||
expect(dispatched).toBe(1);
|
||||
expect(result.cancelled?.length).toBe(19);
|
||||
});
|
||||
|
||||
it("classifies an in-flight cancellation separately from a failure", async () => {
|
||||
let cancelled = false;
|
||||
const result = await runBatchTableEmptyLayers([{ items: [{ target: "orders", sql: "DELETE FROM orders" }] }], {
|
||||
isCancelled: () => cancelled,
|
||||
execute: async () => {
|
||||
cancelled = true;
|
||||
throw new Error("request aborted");
|
||||
},
|
||||
});
|
||||
|
||||
expect(result.failed).toHaveLength(0);
|
||||
expect(result.cancelled).toEqual(["orders"]);
|
||||
});
|
||||
|
||||
it("skips a parent after a child in an earlier layer fails", async () => {
|
||||
const executed: string[] = [];
|
||||
const result = await runBatchTableEmptyLayers([{ items: [{ target: "child", sql: "DELETE FROM child" }] }, { items: [{ target: "parent", sql: "DELETE FROM parent" }], dependencies: { parent: ["child"] } }], {
|
||||
keyOf: (target) => target,
|
||||
execute: async ({ target }) => {
|
||||
executed.push(target);
|
||||
throw new Error("permission denied");
|
||||
},
|
||||
});
|
||||
|
||||
expect(executed).toEqual(["child"]);
|
||||
expect(result.failed.map(({ target }) => target)).toEqual(["child"]);
|
||||
expect(result.skipped?.map(({ target }) => target)).toEqual(["parent"]);
|
||||
});
|
||||
|
||||
it("builds SQL previews with bounded concurrency", async () => {
|
||||
let active = 0;
|
||||
let peak = 0;
|
||||
const plan = await buildBatchTableEmptyPlan(
|
||||
Array.from({ length: 40 }, (_, index) => index),
|
||||
async (target) => {
|
||||
active += 1;
|
||||
peak = Math.max(peak, active);
|
||||
await new Promise((resolve) => setTimeout(resolve, 1));
|
||||
active -= 1;
|
||||
return `DELETE FROM table_${target};`;
|
||||
},
|
||||
);
|
||||
|
||||
expect(plan).toHaveLength(40);
|
||||
expect(peak).toBeLessThanOrEqual(8);
|
||||
});
|
||||
|
||||
it("stops scheduling new SQL previews after the first build failure", async () => {
|
||||
let calls = 0;
|
||||
await expect(
|
||||
buildBatchTableEmptyPlan(
|
||||
Array.from({ length: 40 }, (_, index) => index),
|
||||
async (target) => {
|
||||
calls += 1;
|
||||
if (target === 0) throw new Error("preview failed");
|
||||
await new Promise((resolve) => setTimeout(resolve, 1));
|
||||
return `DELETE FROM table_${target};`;
|
||||
},
|
||||
),
|
||||
).rejects.toThrow("preview failed");
|
||||
|
||||
expect(calls).toBeLessThanOrEqual(8);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,125 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buildDatabaseTableEmptyPlan, buildDatabaseTableEmptyPlanLayers, buildMysqlTableMutationSql, DatabaseTableEmptyPlanError } from "@/lib/sidebar/databaseTableEmpty";
|
||||
|
||||
describe("database table empty plan", () => {
|
||||
it("renders MySQL mutation SQL locally and escapes backticks", () => {
|
||||
expect(buildMysqlTableMutationSql("empty", "app`db", "order`items")).toBe("DELETE FROM `app``db`.`order``items`;");
|
||||
expect(buildMysqlTableMutationSql("drop", "app", "orders")).toBe("DROP TABLE `app`.`orders`;");
|
||||
expect(buildMysqlTableMutationSql("empty", " app ", "orders")).toBe("DELETE FROM ` app `.`orders`;");
|
||||
});
|
||||
|
||||
it("uses a stable table-name order for independent tables", async () => {
|
||||
const plan = await buildDatabaseTableEmptyPlan({
|
||||
database: "app",
|
||||
listTables: async () => [
|
||||
{ name: "zebra", object_type: "TABLE", schema: "app" },
|
||||
{ name: "alpha", object_type: "TABLE", schema: "app" },
|
||||
],
|
||||
foreignKeysByTable: {},
|
||||
buildSql: async (table) => `DELETE FROM \`app\`.\`${table.name}\`;`,
|
||||
});
|
||||
|
||||
expect(plan.map(({ target }) => target.name)).toEqual(["alpha", "zebra"]);
|
||||
});
|
||||
|
||||
it("does not treat inherited object keys as foreign-key metadata", async () => {
|
||||
const foreignKeysByTable = Object.create({ toString: [{ name: "inherited", column: "id", ref_table: "parent", ref_column: "id" }] }) as Record<string, never>;
|
||||
const plan = await buildDatabaseTableEmptyPlan({
|
||||
database: "app",
|
||||
listTables: async () => [{ name: "toString", object_type: "TABLE", schema: "app" }],
|
||||
foreignKeysByTable,
|
||||
buildSql: async (table) => `DELETE FROM \`app\`.\`${table.name}\`;`,
|
||||
});
|
||||
|
||||
expect(plan.map(({ target }) => target.name)).toEqual(["toString"]);
|
||||
});
|
||||
|
||||
it("orders referencing tables before their parents", async () => {
|
||||
const options = {
|
||||
database: "app",
|
||||
listTables: async () => [
|
||||
{ name: "parent", object_type: "TABLE", schema: "app" },
|
||||
{ name: "child", object_type: "TABLE", schema: "app" },
|
||||
],
|
||||
listForeignKeys: async (table) => (table.name === "child" ? [{ name: "fk", column: "parent_id", ref_table: "parent", ref_column: "id" }] : []),
|
||||
buildSql: async (table) => `DELETE FROM \`${table.schema}\`.\`${table.name}\`;`,
|
||||
};
|
||||
const plan = await buildDatabaseTableEmptyPlan(options);
|
||||
const layers = await buildDatabaseTableEmptyPlanLayers(options);
|
||||
expect(plan.map(({ target }) => target.name)).toEqual(["child", "parent"]);
|
||||
expect(layers[1]?.dependencies).toEqual({ parent: ["child"] });
|
||||
});
|
||||
|
||||
it("stops on a foreign-key cycle instead of falling back to unsafe order", async () => {
|
||||
await expect(
|
||||
buildDatabaseTableEmptyPlan({
|
||||
database: "app",
|
||||
listTables: async () => [
|
||||
{ name: "a", object_type: "TABLE", schema: "app" },
|
||||
{ name: "b", object_type: "TABLE", schema: "app" },
|
||||
],
|
||||
listForeignKeys: async (table) => [{ name: "fk", column: "id", ref_table: table.name === "a" ? "b" : "a", ref_column: "id" }],
|
||||
buildSql: async () => "DELETE FROM t;",
|
||||
}),
|
||||
).rejects.toBeInstanceOf(DatabaseTableEmptyPlanError);
|
||||
});
|
||||
|
||||
it("treats a self-referencing foreign key as independent instead of a cycle", async () => {
|
||||
const plan = await buildDatabaseTableEmptyPlan({
|
||||
database: "app",
|
||||
listTables: async () => [
|
||||
{ name: "departments", object_type: "TABLE", schema: "app" },
|
||||
{ name: "employees", object_type: "TABLE", schema: "app" },
|
||||
],
|
||||
listForeignKeys: async (table) =>
|
||||
table.name === "employees"
|
||||
? [
|
||||
{ name: "fk_manager", column: "manager_id", ref_table: "employees", ref_column: "id" },
|
||||
{ name: "fk_department", column: "department_id", ref_table: "departments", ref_column: "id" },
|
||||
]
|
||||
: [],
|
||||
buildSql: async (table) => `DELETE FROM \`${table.schema}\`.\`${table.name}\`;`,
|
||||
});
|
||||
|
||||
expect(plan.map(({ target }) => target.name)).toEqual(["employees", "departments"]);
|
||||
});
|
||||
|
||||
it("builds a large no-dependency plan without per-table metadata calls", async () => {
|
||||
const tables = Array.from({ length: 1000 }, (_, index) => ({ name: `table_${index}`, object_type: "TABLE", schema: "app" }));
|
||||
let metadataCalls = 0;
|
||||
const sqlProgress: Array<[number, number]> = [];
|
||||
const layers = await buildDatabaseTableEmptyPlanLayers({
|
||||
database: "app",
|
||||
listTables: async () => tables,
|
||||
foreignKeysByTable: {},
|
||||
buildSql: async (table) => `DELETE FROM \`app\`.\`${table.name}\`;`,
|
||||
onProgress: () => {
|
||||
metadataCalls += 1;
|
||||
},
|
||||
onSqlProgress: (completed, total) => {
|
||||
sqlProgress.push([completed, total]);
|
||||
},
|
||||
});
|
||||
expect(layers).toHaveLength(1);
|
||||
expect(layers[0]!.items).toHaveLength(1000);
|
||||
expect(metadataCalls).toBe(1000);
|
||||
expect(sqlProgress.at(-1)).toEqual([1000, 1000]);
|
||||
});
|
||||
|
||||
it("does not start table metadata loading after cancellation", async () => {
|
||||
let listTablesCalls = 0;
|
||||
await expect(
|
||||
buildDatabaseTableEmptyPlan({
|
||||
database: "app",
|
||||
listTables: async () => {
|
||||
listTablesCalls += 1;
|
||||
return [];
|
||||
},
|
||||
foreignKeysByTable: {},
|
||||
buildSql: async () => "DELETE FROM app.table;",
|
||||
isCancelled: () => true,
|
||||
}),
|
||||
).rejects.toMatchObject({ reason: "cancelled" });
|
||||
expect(listTablesCalls).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -233,6 +233,7 @@ export const listIndexes = forward("listIndexes");
|
||||
export const listReferenceKeyColumns = forward("listReferenceKeyColumns");
|
||||
export const listReferenceKeys = forward("listReferenceKeys");
|
||||
export const listForeignKeys = forward("listForeignKeys");
|
||||
export const listForeignKeysForDatabase = forward("listForeignKeysForDatabase");
|
||||
export const listTriggers = forward("listTriggers");
|
||||
export const listConstraints = forward("listConstraints");
|
||||
export const listPartitions = forward("listPartitions");
|
||||
|
||||
@@ -1194,7 +1194,7 @@ export async function getMysqlTableAutoIncrement(connectionId: string, database:
|
||||
return get(`/api/schema/mysql/auto-increment?${qs({ connection_id: connectionId, database, table })}`);
|
||||
}
|
||||
|
||||
export async function listObjects(connectionId: string, database: string, schema: string, objectTypes?: (SidebarObjectKind | "EVENT")[], filter?: string, limit?: number, offset?: number, catalog?: string, tableNameFilter?: TableNameFilter): Promise<ObjectInfo[]> {
|
||||
export async function listObjects(connectionId: string, database: string, schema: string, objectTypes?: (SidebarObjectKind | "EVENT")[], filter?: string, limit?: number, offset?: number, catalog?: string, tableNameFilter?: TableNameFilter, executionId?: string): Promise<ObjectInfo[]> {
|
||||
return get(
|
||||
`/api/schema/objects?${qs({
|
||||
connection_id: connectionId,
|
||||
@@ -1206,6 +1206,7 @@ export async function listObjects(connectionId: string, database: string, schema
|
||||
offset,
|
||||
catalog,
|
||||
table_name_filter: tableNameFilter ? JSON.stringify(tableNameFilter) : undefined,
|
||||
execution_id: executionId,
|
||||
})}`,
|
||||
);
|
||||
}
|
||||
@@ -1276,6 +1277,10 @@ export async function listForeignKeys(connectionId: string, database: string, sc
|
||||
return get(`/api/schema/foreign-keys?${qs({ connection_id: connectionId, database, schema, table, catalog })}`);
|
||||
}
|
||||
|
||||
export async function listForeignKeysForDatabase(connectionId: string, database: string, schema: string, catalog?: string, executionId?: string): Promise<Record<string, ForeignKeyInfo[]>> {
|
||||
return get(`/api/schema/foreign-keys-for-database?${qs({ connection_id: connectionId, database, schema, catalog, execution_id: executionId })}`);
|
||||
}
|
||||
|
||||
export async function listTriggers(connectionId: string, database: string, schema: string, table: string, catalog?: string): Promise<TriggerInfo[]> {
|
||||
return get(`/api/schema/triggers?${qs({ connection_id: connectionId, database, schema, table, catalog })}`);
|
||||
}
|
||||
|
||||
@@ -1693,7 +1693,18 @@ export async function getMysqlTableAutoIncrement(connectionId: string, database:
|
||||
return invoke("get_mysql_table_auto_increment", { connectionId, database, table });
|
||||
}
|
||||
|
||||
export async function listObjects(connectionId: string, database: string, schema: string, objectTypes?: (SidebarObjectKind | "EVENT")[], filter?: string, limit?: number, offset?: number, catalog?: string, tableNameFilter?: import("@/types/database").TableNameFilter): Promise<ObjectInfo[]> {
|
||||
export async function listObjects(
|
||||
connectionId: string,
|
||||
database: string,
|
||||
schema: string,
|
||||
objectTypes?: (SidebarObjectKind | "EVENT")[],
|
||||
filter?: string,
|
||||
limit?: number,
|
||||
offset?: number,
|
||||
catalog?: string,
|
||||
tableNameFilter?: import("@/types/database").TableNameFilter,
|
||||
executionId?: string,
|
||||
): Promise<ObjectInfo[]> {
|
||||
return invoke("list_objects", {
|
||||
connectionId,
|
||||
database,
|
||||
@@ -1704,6 +1715,7 @@ export async function listObjects(connectionId: string, database: string, schema
|
||||
offset,
|
||||
catalog,
|
||||
tableNameFilter,
|
||||
executionId,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -2448,6 +2460,10 @@ export async function listForeignKeys(connectionId: string, database: string, sc
|
||||
});
|
||||
}
|
||||
|
||||
export async function listForeignKeysForDatabase(connectionId: string, database: string, schema: string, catalog?: string, executionId?: string): Promise<Record<string, ForeignKeyInfo[]>> {
|
||||
return invoke("list_foreign_keys_for_database", { connectionId, database, schema, catalog, executionId });
|
||||
}
|
||||
|
||||
export async function listTriggers(connectionId: string, database: string, schema: string, table: string, catalog?: string): Promise<TriggerInfo[]> {
|
||||
return invoke("list_triggers", {
|
||||
connectionId,
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
import { uuid } from "@/lib/common/utils";
|
||||
|
||||
export interface BatchTableEmptyResult<T> {
|
||||
succeeded: T[];
|
||||
failed: Array<{ target: T; error: unknown }>;
|
||||
skipped?: Array<{ target: T; reason: string; dependency?: string }>;
|
||||
cancelled?: T[];
|
||||
}
|
||||
|
||||
export interface BatchTableEmptyPlanItem<T> {
|
||||
@@ -10,14 +14,37 @@ export interface BatchTableEmptyPlanItem<T> {
|
||||
|
||||
export type BatchTableEmptyFeedback = "success" | "partial" | "submitted" | "submitted-partial";
|
||||
|
||||
export async function buildBatchTableEmptyPlan<T>(targets: readonly T[], buildSql: (target: T) => Promise<string>): Promise<BatchTableEmptyPlanItem<T>[]> {
|
||||
const plan: BatchTableEmptyPlanItem<T>[] = [];
|
||||
for (const target of targets) {
|
||||
const sql = await buildSql(target);
|
||||
if (!sql.trim()) throw new Error("Empty table SQL preview is unavailable");
|
||||
plan.push({ target, sql });
|
||||
}
|
||||
return plan;
|
||||
export async function buildBatchTableEmptyPlan<T>(targets: readonly T[], buildSql: (target: T) => Promise<string>, options: { concurrency?: number; isCancelled?: () => boolean; onProgress?: (completed: number, total: number) => void } = {}): Promise<BatchTableEmptyPlanItem<T>[]> {
|
||||
const plan: Array<BatchTableEmptyPlanItem<T> | undefined> = Array.from({ length: targets.length });
|
||||
const concurrency = Math.max(1, Math.min(options.concurrency ?? 8, 16));
|
||||
let cursor = 0;
|
||||
let completed = 0;
|
||||
let stopped = false;
|
||||
let firstError: unknown;
|
||||
const workers = Array.from({ length: Math.min(concurrency, targets.length) }, async () => {
|
||||
while (!stopped && cursor < targets.length) {
|
||||
if (options.isCancelled?.()) {
|
||||
stopped = true;
|
||||
firstError ??= new Error("Operation cancelled");
|
||||
return;
|
||||
}
|
||||
const index = cursor++;
|
||||
try {
|
||||
const sql = await buildSql(targets[index]!);
|
||||
if (!sql.trim()) throw new Error("Empty table SQL preview is unavailable");
|
||||
if (stopped) return;
|
||||
plan[index] = { target: targets[index]!, sql };
|
||||
options.onProgress?.(++completed, targets.length);
|
||||
} catch (error) {
|
||||
stopped = true;
|
||||
firstError ??= error;
|
||||
return;
|
||||
}
|
||||
}
|
||||
});
|
||||
await Promise.all(workers);
|
||||
if (firstError) throw firstError;
|
||||
return plan.filter((item): item is BatchTableEmptyPlanItem<T> => item !== undefined);
|
||||
}
|
||||
|
||||
export async function runBatchTableEmpty<T>(targets: readonly T[], execute: (target: T) => Promise<void>): Promise<BatchTableEmptyResult<T>> {
|
||||
@@ -33,7 +60,61 @@ export async function runBatchTableEmpty<T>(targets: readonly T[], execute: (tar
|
||||
return result;
|
||||
}
|
||||
|
||||
export async function runBatchTableEmptyLayers<T>(
|
||||
layers: readonly { items: readonly BatchTableEmptyPlanItem<T>[]; dependencies?: Record<string, string[]> }[],
|
||||
options: {
|
||||
concurrency?: number;
|
||||
execute: (item: BatchTableEmptyPlanItem<T>, executionId: string) => Promise<void>;
|
||||
isCancelled?: () => boolean;
|
||||
keyOf?: (target: T) => string;
|
||||
onProgress?: (completed: number, total: number) => void;
|
||||
},
|
||||
): Promise<BatchTableEmptyResult<T>> {
|
||||
const result: BatchTableEmptyResult<T> = { succeeded: [], failed: [], skipped: [], cancelled: [] };
|
||||
const concurrency = Math.max(1, Math.min(options.concurrency ?? 8, 16));
|
||||
let completed = 0;
|
||||
const total = layers.reduce((sum, layer) => sum + layer.items.length, 0);
|
||||
|
||||
for (const layer of layers) {
|
||||
const queue = [...layer.items];
|
||||
let cursor = 0;
|
||||
const workers = Array.from({ length: Math.min(concurrency, queue.length) }, async () => {
|
||||
while (cursor < queue.length) {
|
||||
const item = queue[cursor++];
|
||||
const key = options.keyOf?.(item.target);
|
||||
const blockedBy = key && layer.dependencies?.[key]?.find((dependency) => result.failed.some(({ target }) => options.keyOf?.(target) === dependency) || result.skipped?.some(({ target }) => options.keyOf?.(target) === dependency));
|
||||
if (blockedBy) {
|
||||
(result.skipped ??= []).push({ target: item.target, reason: `blocked by ${blockedBy}`, dependency: blockedBy });
|
||||
completed += 1;
|
||||
options.onProgress?.(completed, total);
|
||||
continue;
|
||||
}
|
||||
if (options.isCancelled?.()) {
|
||||
(result.cancelled ??= []).push(item.target);
|
||||
completed += 1;
|
||||
options.onProgress?.(completed, total);
|
||||
continue;
|
||||
}
|
||||
const executionId = uuid();
|
||||
try {
|
||||
await options.execute(item, executionId);
|
||||
result.succeeded.push(item.target);
|
||||
} catch (error) {
|
||||
if (options.isCancelled?.()) (result.cancelled ??= []).push(item.target);
|
||||
else result.failed.push({ target: item.target, error });
|
||||
} finally {
|
||||
completed += 1;
|
||||
options.onProgress?.(completed, total);
|
||||
}
|
||||
}
|
||||
});
|
||||
await Promise.all(workers);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export function batchTableEmptyFeedback(result: BatchTableEmptyResult<unknown>, asynchronousMutation: boolean): BatchTableEmptyFeedback {
|
||||
if (asynchronousMutation) return result.failed.length > 0 ? "submitted-partial" : "submitted";
|
||||
return result.failed.length > 0 ? "partial" : "success";
|
||||
const incomplete = result.failed.length > 0 || (result.skipped?.length ?? 0) > 0 || (result.cancelled?.length ?? 0) > 0;
|
||||
if (asynchronousMutation) return incomplete ? "submitted-partial" : "submitted";
|
||||
return incomplete ? "partial" : "success";
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
import type { ForeignKeyInfo, ObjectInfo } from "@/types/database";
|
||||
import { buildBatchTableEmptyPlan, type BatchTableEmptyPlanItem } from "@/lib/sidebar/batchTableEmpty";
|
||||
|
||||
export interface DatabaseEmptyTable {
|
||||
name: string;
|
||||
schema: string;
|
||||
}
|
||||
|
||||
export type DatabaseTableEmptyOperation = "empty" | "drop";
|
||||
|
||||
function quoteMysqlIdentifier(value: string): string {
|
||||
return `\`${value.replaceAll("`", "``")}\``;
|
||||
}
|
||||
|
||||
export function buildMysqlTableMutationSql(operation: DatabaseTableEmptyOperation, database: string, tableName: string): string {
|
||||
const table = database ? `${quoteMysqlIdentifier(database)}.${quoteMysqlIdentifier(tableName)}` : quoteMysqlIdentifier(tableName);
|
||||
return `${operation === "empty" ? "DELETE FROM" : "DROP TABLE"} ${table};`;
|
||||
}
|
||||
|
||||
export class DatabaseTableEmptyPlanError extends Error {
|
||||
constructor(
|
||||
public readonly reason: "cycle" | "scope" | "cancelled",
|
||||
public readonly tables: string[],
|
||||
) {
|
||||
super(`${reason}: ${tables.join(", ")}`);
|
||||
}
|
||||
}
|
||||
|
||||
export interface DatabaseEmptyTableLayer {
|
||||
items: BatchTableEmptyPlanItem<DatabaseEmptyTable>[];
|
||||
dependencies?: Record<string, string[]>;
|
||||
}
|
||||
|
||||
interface BuildOptions {
|
||||
database: string;
|
||||
listTables: () => Promise<ObjectInfo[]>;
|
||||
listForeignKeys?: (table: DatabaseEmptyTable) => Promise<ForeignKeyInfo[]>;
|
||||
foreignKeysByTable?: Record<string, ForeignKeyInfo[]>;
|
||||
buildSql: (table: DatabaseEmptyTable) => Promise<string>;
|
||||
isCancelled?: () => boolean;
|
||||
onProgress?: (completed: number, total: number) => void;
|
||||
onSqlProgress?: (completed: number, total: number) => void;
|
||||
}
|
||||
|
||||
/** Only fresh, unfiltered metadata belongs in a database-wide destructive plan. */
|
||||
async function buildLayers(options: BuildOptions): Promise<DatabaseEmptyTableLayer[]> {
|
||||
if (options.isCancelled?.()) throw new DatabaseTableEmptyPlanError("cancelled", []);
|
||||
const objects = await options.listTables();
|
||||
if (options.isCancelled?.()) throw new DatabaseTableEmptyPlanError("cancelled", []);
|
||||
const tables = new Map<string, DatabaseEmptyTable>();
|
||||
for (const object of objects) {
|
||||
if (object.object_type !== "TABLE") continue;
|
||||
if (object.schema && object.schema !== options.database) throw new DatabaseTableEmptyPlanError("scope", [object.name]);
|
||||
tables.set(object.name, { name: object.name, schema: options.database });
|
||||
}
|
||||
|
||||
const tableNames = [...tables.keys()].sort((left, right) => (left < right ? -1 : left > right ? 1 : 0));
|
||||
const dependencies = new Map<string, Set<string>>();
|
||||
const incoming = new Map(tableNames.map((name) => [name, 0]));
|
||||
let metadataCompleted = 0;
|
||||
for (const name of tableNames) {
|
||||
const table = tables.get(name)!;
|
||||
if (options.isCancelled?.()) throw new DatabaseTableEmptyPlanError("cancelled", []);
|
||||
const parents = new Set<string>();
|
||||
const hasBatchForeignKeys = options.foreignKeysByTable && Object.prototype.hasOwnProperty.call(options.foreignKeysByTable, table.name);
|
||||
const foreignKeys = hasBatchForeignKeys ? (options.foreignKeysByTable![table.name] ?? []) : options.listForeignKeys ? await options.listForeignKeys(table) : [];
|
||||
for (const fk of foreignKeys) {
|
||||
if (fk.ref_schema && fk.ref_schema !== options.database) continue;
|
||||
// A self-referencing foreign key is not a dependency edge: per-table DELETE/DROP are not
|
||||
// blocked by it and runtime constraints catch any leftover violations.
|
||||
if (fk.ref_table === table.name) continue;
|
||||
if (!tables.has(fk.ref_table)) throw new DatabaseTableEmptyPlanError("scope", [fk.ref_table]);
|
||||
parents.add(fk.ref_table);
|
||||
}
|
||||
dependencies.set(table.name, parents);
|
||||
for (const parent of parents) incoming.set(parent, incoming.get(parent)! + 1);
|
||||
options.onProgress?.(++metadataCompleted, tables.size);
|
||||
}
|
||||
|
||||
const layers: DatabaseEmptyTableLayer[] = [];
|
||||
let ready = tableNames.filter((name) => incoming.get(name) === 0);
|
||||
let processed = 0;
|
||||
let sqlCompleted = 0;
|
||||
while (ready.length) {
|
||||
if (options.isCancelled?.()) throw new DatabaseTableEmptyPlanError("cancelled", []);
|
||||
const names = ready;
|
||||
ready = [];
|
||||
const targets = names.map((name) => tables.get(name)!);
|
||||
let items: BatchTableEmptyPlanItem<DatabaseEmptyTable>[];
|
||||
try {
|
||||
items = await buildBatchTableEmptyPlan(targets, options.buildSql, {
|
||||
concurrency: 8,
|
||||
isCancelled: options.isCancelled,
|
||||
onProgress: (completed) => options.onSqlProgress?.(sqlCompleted + completed, tables.size),
|
||||
});
|
||||
} catch (error) {
|
||||
if (options.isCancelled?.()) throw new DatabaseTableEmptyPlanError("cancelled", []);
|
||||
throw error;
|
||||
}
|
||||
const reverseDependencies = new Map<string, string[]>();
|
||||
for (const [child, parents] of dependencies) {
|
||||
for (const parent of parents) {
|
||||
const children = reverseDependencies.get(parent) ?? [];
|
||||
children.push(child);
|
||||
reverseDependencies.set(parent, children);
|
||||
}
|
||||
}
|
||||
layers.push({
|
||||
items,
|
||||
dependencies: Object.fromEntries(names.map((name) => [name, reverseDependencies.get(name) ?? []])),
|
||||
});
|
||||
sqlCompleted += targets.length;
|
||||
processed += names.length;
|
||||
for (const name of names) {
|
||||
for (const parent of dependencies.get(name)!) {
|
||||
const remaining = incoming.get(parent)! - 1;
|
||||
incoming.set(parent, remaining);
|
||||
if (remaining === 0) ready.push(parent);
|
||||
}
|
||||
}
|
||||
ready.sort((left, right) => (left < right ? -1 : left > right ? 1 : 0));
|
||||
}
|
||||
// Unlike the legacy drop sorter, never silently fall back to an unsafe order.
|
||||
if (processed !== tables.size) {
|
||||
throw new DatabaseTableEmptyPlanError(
|
||||
"cycle",
|
||||
[...incoming].filter(([, count]) => count > 0).map(([name]) => name),
|
||||
);
|
||||
}
|
||||
return layers;
|
||||
}
|
||||
|
||||
export async function buildDatabaseTableEmptyPlanLayers(options: BuildOptions): Promise<DatabaseEmptyTableLayer[]> {
|
||||
return buildLayers(options);
|
||||
}
|
||||
|
||||
export async function buildDatabaseTableEmptyPlan(options: BuildOptions) {
|
||||
const layers = await buildLayers(options);
|
||||
return layers.flatMap((layer) => layer.items);
|
||||
}
|
||||
@@ -12,6 +12,7 @@ export interface SidebarDangerDialogOption {
|
||||
export interface SidebarDangerDialogProgress {
|
||||
completed: number;
|
||||
total: number;
|
||||
phase?: "preparing" | "executing";
|
||||
}
|
||||
|
||||
export interface SidebarDangerDialogTextInput {
|
||||
@@ -28,6 +29,7 @@ export interface SidebarDangerDialogRequest {
|
||||
message: string;
|
||||
confirmLabel: string;
|
||||
sql?: string;
|
||||
copySql?: string | (() => string);
|
||||
details?: string;
|
||||
detailsText?: string;
|
||||
loading?: boolean;
|
||||
|
||||
Reference in new issue
Block a user