Skip to content

armgit / dbx

Public Imported from GitHub
0

25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。

feat(postgres): add table vacuum action

amwps29011407b537f58
diff --git a/apps/desktop/src/components/objects/ObjectBrowser.vue b/apps/desktop/src/components/objects/ObjectBrowser.vue
index 26ae67c7a2..a03fbc9b08 100644
--- a/apps/desktop/src/components/objects/ObjectBrowser.vue
+++ b/apps/desktop/src/components/objects/ObjectBrowser.vue
@@ -3,6 +3,7 @@ import { computed, createApp, nextTick, onActivated, onBeforeUnmount, ref, watch
import { RecycleScroller } from "vue-virtual-scroller";
import { useSqlHighlighter } from "@/composables/useSqlHighlighter";
import {
+ Activity,
ArrowDown,
ArrowRightLeft,
ArrowUp,
@@ -61,7 +62,7 @@ import XlsxHeaderDialog from "@/components/export/XlsxHeaderDialog.vue";
import * as api from "@/lib/backend/api";
import type { ColumnInfo, ConnectionConfig, ForeignKeyInfo, IndexInfo, ObjectBrowserViewMode, ObjectBrowserViewport, ObjectInfo, ObjectSourceKind, ObjectStatistics, TableInfoTab, TreeNode, TriggerInfo } from "@/types/database";
import { sortTablesByFkDependency, type TableWithFk } from "@/lib/table/tableDependencySort";
-import { isSchemaAware, supportsTransfer } from "@/lib/database/databaseCapabilities";
+import { isSchemaAware, supportsTableVacuum, supportsTransfer } from "@/lib/database/databaseCapabilities";
import { supportsSchemaDiagram, supportsTableImport, supportsTableStructureEditing, supportsTableTruncate } from "@/lib/database/databaseFeatureSupport";
import { codeMirrorSqlDialect, connectionObjectTreeNodeSchema, connectionUsesDatabaseObjectTreeMode, effectiveDatabaseTypeForConnection, tableStructureDatabaseTypeForConnection } from "@/lib/database/jdbcDialect";
import { getTableMetadataCapabilities, type TableMetadataCapabilities } from "@/lib/table/tableMetadataCapabilities";
@@ -73,6 +74,7 @@ import {
buildCopyTableDataSql,
buildEmptyTableSql,
buildTruncateTableSql,
+ buildVacuumTableSql,
supportsDropTableCascade,
supportsTruncateTableCascade,
type TableAdminSqlOptions,
@@ -246,6 +248,12 @@ const showTruncateConfirm = ref(false);
const truncateTarget = ref<ObjectBrowserRow | null>(null);
const truncatePreviewSql = ref("");
const truncateTableCascade = ref(false);
+const showVacuumConfirm = ref(false);
+const vacuumTarget = ref<ObjectBrowserRow | null>(null);
+const vacuumPreviewSql = ref("");
+const vacuumTableFull = ref(false);
+const vacuumTableAnalyze = ref(false);
+const vacuumExecuting = ref(false);
const showEmptyConfirm = ref(false);
const emptyTarget = ref<ObjectBrowserRow | null>(null);
const emptyPreviewSql = ref("");
@@ -299,6 +307,8 @@ const canOpenStructureEditor = computed(() => supportsTableStructureEditing(tabl
const canOpenDiagram = computed(() => !!props.database && supportsSchemaDiagram(effectiveDatabaseType.value));
const canOpenTableImport = computed(() => !!props.database && supportsTableImport(effectiveDatabaseType.value));
const supportsTruncateTable = computed(() => supportsTableTruncate(effectiveDatabaseType.value));
+const supportsVacuumTable = computed(() => !props.connection.read_only && supportsTableVacuum(effectiveDatabaseType.value));
+const vacuumRiskMessage = computed(() => (vacuumExecuting.value ? t("contextMenu.vacuumTableRunningHint") : vacuumTableFull.value ? t("contextMenu.vacuumTableFullRisk") : vacuumTableAnalyze.value ? t("contextMenu.vacuumTableAnalyzeRisk") : t("contextMenu.vacuumTableDefaultRisk")));
const sourceDialect = computed(() => codeMirrorSqlDialect(effectiveDatabaseType.value));
const sourceFormatDialect = computed<SqlFormatDialect>(() => sqlFormatDialectForDbType(effectiveDatabaseType.value));
const objectFilters = computed<ObjectFilter[]>(() =>
@@ -2356,6 +2366,55 @@ async function confirmTruncateTable() {
truncateTarget.value = null;
}
+async function refreshVacuumPreviewSql() {
+ const row = vacuumTarget.value;
+ vacuumPreviewSql.value = "";
+ if (!row) return;
+ vacuumPreviewSql.value = await buildVacuumTableSql({
+ databaseType: effectiveDatabaseType.value,
+ schema: row.schema || selectedSchema.value,
+ tableName: row.name,
+ full: vacuumTableFull.value,
+ analyze: vacuumTableAnalyze.value,
+ }).catch(() => "");
+}
+
+function requestVacuumTable(row: ObjectBrowserRow) {
+ if (!supportsVacuumTable.value) return;
+ vacuumTarget.value = row;
+ vacuumTableFull.value = false;
+ vacuumTableAnalyze.value = false;
+ vacuumPreviewSql.value = "";
+ void refreshVacuumPreviewSql();
+ showVacuumConfirm.value = true;
+}
+
+async function confirmVacuumTable() {
+ const row = vacuumTarget.value;
+ if (!row || vacuumExecuting.value) return;
+ vacuumExecuting.value = true;
+ try {
+ const sql =
+ vacuumPreviewSql.value ||
+ (await buildVacuumTableSql({
+ databaseType: effectiveDatabaseType.value,
+ schema: row.schema || selectedSchema.value,
+ tableName: row.name,
+ full: vacuumTableFull.value,
+ analyze: vacuumTableAnalyze.value,
+ }));
+ const executed = await executeObjectBrowserSqlWithProductionGuard(sql, () => api.executeQuery(props.connection.id, props.database, sql, row.schema || selectedSchema.value));
+ if (!executed) return;
+ toast(t("contextMenu.vacuumTableSuccess", { name: row.name }));
+ showVacuumConfirm.value = false;
+ vacuumTarget.value = null;
+ } catch (e: any) {
+ toast(t("contextMenu.tableOperationFailed", { message: e?.message || String(e) }), 5000);
+ } finally {
+ vacuumExecuting.value = false;
+ }
+}
+
async function refreshEmptyPreviewSql(row: ObjectBrowserRow) {
emptyPreviewSql.value = "";
emptyPreviewSql.value = await buildEmptyTableSql(tableAdminSqlOptions(row)).catch(() => "");
@@ -2759,6 +2818,32 @@ function getTableMenuItems(item: ObjectBrowserRow): ContextMenuItem[] {
];
}
const useBatchActions = isSelectedBatchTableContext(item);
+ const moreActions: ContextMenuItem[] = [];
+ if (supportsVacuumTable.value) {
+ moreActions.push({ label: t("contextMenu.vacuumTable"), action: () => requestVacuumTable(item), icon: Activity, variant: "destructive" as const });
+ }
+ if (supportsTruncateTable.value) {
+ moreActions.push({
+ label: useBatchActions ? selectedBatchTableCountLabel("batchTruncate") : t("contextMenu.truncateTable"),
+ action: useBatchActions ? requestBatchTruncateTables : () => requestTruncateTable(item),
+ icon: Scissors,
+ variant: "destructive" as const,
+ });
+ }
+ moreActions.push(
+ {
+ label: useBatchActions ? selectedBatchTableCountLabel("batchEmpty") : t("contextMenu.emptyTable"),
+ action: useBatchActions ? requestBatchEmptyTables : () => requestEmptyTable(item),
+ icon: Eraser,
+ variant: "destructive" as const,
+ },
+ {
+ label: useBatchActions ? selectedBatchTableCountLabel("batchDrop") : t("contextMenu.dropTable"),
+ action: useBatchActions ? requestBatchDropTables : () => requestDrop(item),
+ icon: Trash2,
+ variant: "destructive" as const,
+ },
+ );
return [
{ label: t("contextMenu.viewData"), action: () => openViewData(item), icon: Table2 },
{
@@ -2780,28 +2865,7 @@ function getTableMenuItems(item: ObjectBrowserRow): ContextMenuItem[] {
{ label: t("contextMenu.duplicateStructure"), action: () => requestDuplicateStructure(item), icon: CopyPlus },
...tableClipboardMenuItems(item),
{ label: "", separator: true },
- ...(supportsTruncateTable.value
- ? [
- {
- label: useBatchActions ? selectedBatchTableCountLabel("batchTruncate") : t("contextMenu.truncateTable"),
- action: useBatchActions ? requestBatchTruncateTables : () => requestTruncateTable(item),
- icon: Scissors,
- variant: "destructive" as const,
- },
- ]
- : []),
- {
- label: useBatchActions ? selectedBatchTableCountLabel("batchEmpty") : t("contextMenu.emptyTable"),
- action: useBatchActions ? requestBatchEmptyTables : () => requestEmptyTable(item),
- icon: Eraser,
- variant: "destructive" as const,
- },
- {
- label: useBatchActions ? selectedBatchTableCountLabel("batchDrop") : t("contextMenu.dropTable"),
- action: useBatchActions ? requestBatchDropTables : () => requestDrop(item),
- icon: Trash2,
- variant: "destructive" as const,
- },
+ { label: t("common.more"), icon: ListTree, children: moreActions },
{ label: "", separator: true },
{ label: t("contextMenu.copyName"), action: () => copyName(item), icon: Copy },
];
@@ -3541,6 +3605,31 @@ function getObjectBrowserMenuItems(item: ObjectBrowserRow): ContextMenuItem[] {
</DialogContent>
</Dialog>
+ <DangerConfirmDialog
+ v-model:open="showVacuumConfirm"
+ :title="t('contextMenu.vacuumTableTitle')"
+ :message="t('contextMenu.vacuumTableMessage', { name: vacuumTarget?.name ?? '' })"
+ :details-text="vacuumRiskMessage"
+ :sql="vacuumPreviewSql"
+ :confirm-label="vacuumExecuting ? t('contextMenu.vacuumTableRunning') : vacuumTableFull ? t('contextMenu.vacuumTableFullConfirm') : t('contextMenu.vacuumTable')"
+ :loading="vacuumExecuting"
+ :close-on-confirm="false"
+ @confirm="confirmVacuumTable"
+ >
+ <template #options>
+ <div class="mb-3 flex gap-3 rounded-md border bg-muted/20 px-3 py-2 text-sm">
+ <label class="flex items-center gap-2" :title="t('contextMenu.vacuumTableAnalyzeHint')">
+ <input v-model="vacuumTableAnalyze" :disabled="vacuumExecuting" type="checkbox" class="h-3.5 w-3.5 shrink-0 accent-primary" @change="refreshVacuumPreviewSql" />
+ <span class="font-medium text-foreground">ANALYZE</span>
+ </label>
+ <label class="flex items-center gap-2" :title="t('contextMenu.vacuumTableFullHint')">
+ <input v-model="vacuumTableFull" :disabled="vacuumExecuting" type="checkbox" class="h-3.5 w-3.5 shrink-0 accent-destructive" @change="refreshVacuumPreviewSql" />
+ <span class="font-medium" :class="vacuumTableFull ? 'text-destructive' : 'text-foreground'">FULL</span>
+ </label>
+ </div>
+ </template>
+ </DangerConfirmDialog>
+
<DangerConfirmDialog
v-model:open="showTruncateConfirm"
:title="t('contextMenu.confirmTruncateTableTitle')"
diff --git a/apps/desktop/src/components/sidebar/ConnectionTree.vue b/apps/desktop/src/components/sidebar/ConnectionTree.vue
index 6a5dff66bb..6a2de7f653 100644
--- a/apps/desktop/src/components/sidebar/ConnectionTree.vue
+++ b/apps/desktop/src/components/sidebar/ConnectionTree.vue
@@ -61,7 +61,7 @@ import { codeMirrorSqlDialect } from "@/lib/database/jdbcDialect";
import { sqlFormatDialectForDbType } from "@/lib/sql/sqlFormatter";
import { createSidebarActionTarget, findSidebarActionTarget, matchesSidebarActionTarget, type SidebarActionTarget } from "@/lib/sidebar/sidebarActionTarget";
import { syncSidebarTreeNodeExpansion } from "@/lib/sidebar/sidebarTreeExpansion";
-import type { SidebarDangerDialogRequest } from "@/lib/sidebar/sidebarDangerDialog";
+import type { SidebarDangerDialogOption, SidebarDangerDialogRequest } from "@/lib/sidebar/sidebarDangerDialog";
import { resetSidebarTreeDialogState, sidebarDangerRunningExecutionId } from "./sidebarTreeDialogState";
import { SidebarDangerConfirmDialog, SidebarDdlViewDialog, SidebarObjectSourceDialog, SidebarProcedureExecutionDialog, SidebarVisibleDatabasesDialog, SidebarVisibleNacosNamespacesDialog, SidebarVisibleSchemasDialog } from "./sidebarAsyncDialogs";
import { sortConnectionListForDisplay } from "@/lib/sidebar/connectionListSort";
@@ -1609,8 +1609,9 @@ async function confirmSidebarDangerDialog() {
if (!request || sidebarDangerDialogConfirming.value) return;
if (request.closeOnConfirm !== false) sidebarDangerDialogOpen.value = false;
sidebarDangerDialogConfirming.value = true;
+ let completed: void | boolean = undefined;
try {
- await request.confirm();
+ completed = await request.confirm();
} finally {
// A danger operation that hit a client-observed timeout is kept alive
// (still cancellable) rather than settled outright — sidebarDangerRunningExecutionId
@@ -1620,7 +1621,7 @@ async function confirmSidebarDangerDialog() {
// execution actually settles.
if (!sidebarDangerRunningExecutionId.value) {
sidebarDangerDialogConfirming.value = false;
- sidebarDangerDialogOpen.value = false;
+ if (completed !== false) sidebarDangerDialogOpen.value = false;
}
}
}
@@ -1651,8 +1652,8 @@ async function cancelSidebarDangerDialogRunning() {
}
}
-function updateSidebarDangerDialogOption(event: Event) {
- const option = sidebarDangerDialogRequest.value?.option;
+function updateSidebarDangerDialogOption(event: Event, optionOverride?: SidebarDangerDialogOption) {
+ const option = optionOverride ?? sidebarDangerDialogRequest.value?.option;
if (!option) return;
option.checked = (event.target as HTMLInputElement).checked;
void option.onChange?.(option.checked);
@@ -2490,6 +2491,17 @@ defineExpose({ focusSearch, createNewGroup, collapseAllTreeNodes });
<div class="h-full bg-primary transition-[width] duration-200" :style="{ width: `${Math.round((sidebarDangerDialogRequest.progress.completed / sidebarDangerDialogRequest.progress.total) * 100)}%` }" />
</div>
</div>
+ <div v-if="sidebarDangerDialogRequest.options?.length" class="mb-3 flex flex-wrap gap-2">
+ <template v-for="(option, optionIndex) in sidebarDangerDialogRequest.options ?? []" :key="`danger-option-${optionIndex}`">
+ <label class="flex items-start gap-2 rounded-md border px-3 py-2 text-sm" :class="[option.compact ? 'min-w-32 flex-1' : 'w-full', option.danger && option.checked ? 'border-destructive/50 bg-destructive/10' : 'bg-muted/20']" :title="option.compact ? option.hint : undefined">
+ <input :checked="option.checked" :disabled="sidebarDangerDialogConfirming" type="checkbox" class="mt-0.5 h-3.5 w-3.5 shrink-0" :class="option.danger ? 'accent-destructive' : 'accent-primary'" @change="updateSidebarDangerDialogOption($event, option)" />
+ <span class="grid gap-0.5">
+ <span class="font-medium" :class="option.danger && option.checked ? 'text-destructive' : 'text-foreground'">{{ option.label }}</span>
+ <span v-if="!option.compact" class="text-xs leading-5 text-muted-foreground">{{ option.hint }}</span>
+ </span>
+ </label>
+ </template>
+ </div>
<label v-if="sidebarDangerDialogRequest.option" class="mb-3 flex items-start gap-2 rounded-md border bg-muted/20 px-3 py-2 text-sm">
<input :checked="sidebarDangerDialogRequest.option.checked" type="checkbox" class="mt-0.5 h-3.5 w-3.5 shrink-0 accent-primary" @change="updateSidebarDangerDialogOption" />
<span class="grid gap-0.5">
diff --git a/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue b/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue
index 69ecda600e..0c8d438d30 100644
--- a/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue
+++ b/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue
@@ -197,6 +197,7 @@ import {
isLoadingStructurePreview,
showEmptyTableConfirm,
showTruncateTableConfirm,
+ showVacuumTableConfirm,
showMysqlAutoIncrementConfirm,
showRenameObjectDialog,
renameObjectName,
@@ -208,6 +209,10 @@ import {
emptyTablePreviewSql,
truncateTablePreviewSql,
truncateTableCascade,
+ vacuumTableFull,
+ vacuumTableAnalyze,
+ vacuumTablePreviewSql,
+ vacuumTableExecuting,
mysqlAutoIncrementValue,
mysqlAutoIncrementPreviewSql,
dropObjectPreviewSql,
@@ -510,6 +515,7 @@ const {
const {
isTableNotView,
supportsTruncate,
+ supportsVacuum,
supportsMysqlAutoIncrement,
canDropTableCascade,
canTruncateTableCascade,
@@ -522,6 +528,9 @@ const {
confirmEmptyTable,
truncateTable,
confirmTruncateTable,
+ vacuumTable,
+ refreshVacuumPreviewForOptions,
+ confirmVacuumTable,
mysqlAutoIncrement,
refreshMysqlAutoIncrementPreviewSql,
confirmMysqlAutoIncrement,
@@ -3945,7 +3954,7 @@ function dangerRequest(request: Omit<SidebarDangerDialogRequest, "target">): Sid
const confirm = request.confirm;
routedRequest.confirm = async () => {
activateActionTarget(target);
- await confirm();
+ return confirm();
};
if (request.option?.onChange) {
const onChange = request.option.onChange;
@@ -3954,6 +3963,14 @@ function dangerRequest(request: Omit<SidebarDangerDialogRequest, "target">): Sid
await onChange(checked);
};
}
+ for (const option of request.options ?? []) {
+ if (!option.onChange) continue;
+ const onChange = option.onChange;
+ option.onChange = async (checked) => {
+ activateActionTarget(target);
+ await onChange(checked);
+ };
+ }
if (request.textInput?.onInput) {
const onInput = request.textInput.onInput;
request.textInput.onInput = async (value) => {
@@ -4062,6 +4079,49 @@ routeDangerDialog(showTruncateTableConfirm, () =>
}),
);
+routeDangerDialog(showVacuumTableConfirm, () =>
+ dangerRequest({
+ title: t("contextMenu.vacuumTableTitle"),
+ message: t("contextMenu.vacuumTableMessage", { name: activeNode.value.label }),
+ get detailsText() {
+ if (vacuumTableExecuting.value) return t("contextMenu.vacuumTableRunningHint");
+ return vacuumTableFull.value ? t("contextMenu.vacuumTableFullRisk") : vacuumTableAnalyze.value ? t("contextMenu.vacuumTableAnalyzeRisk") : t("contextMenu.vacuumTableDefaultRisk");
+ },
+ get sql() {
+ return vacuumTablePreviewSql.value;
+ },
+ get confirmLabel() {
+ return vacuumTableExecuting.value ? t("contextMenu.vacuumTableRunning") : vacuumTableFull.value ? t("contextMenu.vacuumTableFullConfirm") : t("contextMenu.vacuumTable");
+ },
+ loading: false,
+ closeOnConfirm: false,
+ options: [
+ {
+ checked: vacuumTableAnalyze.value,
+ label: t("contextMenu.vacuumTableAnalyze"),
+ hint: t("contextMenu.vacuumTableAnalyzeHint"),
+ compact: true,
+ async onChange(checked) {
+ vacuumTableAnalyze.value = checked;
+ await refreshVacuumPreviewForOptions();
+ },
+ },
+ {
+ checked: vacuumTableFull.value,
+ label: t("contextMenu.vacuumTableFull"),
+ hint: t("contextMenu.vacuumTableFullHint"),
+ compact: true,
+ danger: true,
+ async onChange(checked) {
+ vacuumTableFull.value = checked;
+ await refreshVacuumPreviewForOptions();
+ },
+ },
+ ],
+ confirm: confirmVacuumTable,
+ }),
+);
+
routeDangerDialog(showMysqlAutoIncrementConfirm, () =>
dangerRequest({
title: t("contextMenu.mysqlAutoIncrementTitle"),
@@ -5178,6 +5238,9 @@ function buildObjectSidebarMenu(context: SidebarMenuFactoryContext): boolean {
items.push({ label: t("contextMenu.duplicateStructure"), action: duplicateStructure, icon: CopyPlus });
// Keep menu copy aligned with keyboard copy so frozen multi-selection and single-row fallback stay compatible.
items.push(...treeTableClipboardMenuItems(node));
+ if (supportsVacuum.value) {
+ destructiveActions.push({ label: t("contextMenu.vacuumTable"), action: vacuumTable, icon: Activity, variant: "destructive" as const });
+ }
if (supportsMysqlAutoIncrement.value) {
items.push({ label: t("contextMenu.mysqlAutoIncrement"), action: mysqlAutoIncrement, icon: Gauge });
}
diff --git a/apps/desktop/src/components/sidebar/sidebarTreeDialogState.ts b/apps/desktop/src/components/sidebar/sidebarTreeDialogState.ts
index c4cd53f465..774a23c5d5 100644
--- a/apps/desktop/src/components/sidebar/sidebarTreeDialogState.ts
+++ b/apps/desktop/src/components/sidebar/sidebarTreeDialogState.ts
@@ -37,6 +37,7 @@ export const structureDocCopyTitle = ref("");
export const isLoadingStructurePreview = ref(false);
export const showEmptyTableConfirm = ref(false);
export const showTruncateTableConfirm = ref(false);
+export const showVacuumTableConfirm = ref(false);
export const showMysqlAutoIncrementConfirm = ref(false);
export const showRenameObjectDialog = ref(false);
export const renameObjectName = ref("");
@@ -48,6 +49,11 @@ export const batchDropCascade = ref(false);
export const emptyTablePreviewSql = ref("");
export const truncateTablePreviewSql = ref("");
export const truncateTableCascade = ref(false);
+export const vacuumTableFull = ref(false);
+export const vacuumTableAnalyze = ref(false);
+export const vacuumTablePreviewSql = ref("");
+export const vacuumTablePreviewKey = ref("");
+export const vacuumTableExecuting = ref(false);
export const mysqlAutoIncrementValue = ref("1");
export const mysqlAutoIncrementPreviewSql = ref("");
export const mysqlAutoIncrementPreviewKey = ref("");
@@ -187,6 +193,7 @@ const openFlags = [
showStructureDocCopyDialog,
showEmptyTableConfirm,
showTruncateTableConfirm,
+ showVacuumTableConfirm,
showMysqlAutoIncrementConfirm,
showDropObjectConfirm,
showRenameObjectDialog,
@@ -230,6 +237,7 @@ export function resetSidebarTreeDialogState() {
cloneMongoCollectionLoading.value = false;
resetMongoCreateIndexForm();
resetMongoIndexManager();
+ vacuumTableExecuting.value = false;
sidebarTreeDialogOwner.value = null;
sidebarDangerTarget.value = null;
sidebarFormTarget.value = null;
diff --git a/apps/desktop/src/composables/useSidebarTableMutationRuntime.ts b/apps/desktop/src/composables/useSidebarTableMutationRuntime.ts
index 1f68db45ad..01b25fd103 100644
--- a/apps/desktop/src/composables/useSidebarTableMutationRuntime.ts
+++ b/apps/desktop/src/composables/useSidebarTableMutationRuntime.ts
@@ -3,8 +3,20 @@ import { useI18n } from "vue-i18n";
import { useToast } from "@/composables/useToast";
import { useConnectionStore } from "@/stores/connectionStore";
import type { DatabaseType, TreeNode } from "@/types/database";
-import { supportsTableTruncate } from "@/lib/database/databaseCapabilities";
-import { buildDropTableSql, buildEmptyTableSql, buildMysqlAutoIncrementSql, buildTruncateTableSql, supportsDropTableCascade, supportsNativeMysqlAutoIncrement, supportsTruncateTableCascade, type MysqlAutoIncrementSqlOptions, type TableAdminSqlOptions } from "@/lib/database/dbAdminSql";
+import { supportsTableTruncate, supportsTableVacuum } from "@/lib/database/databaseCapabilities";
+import {
+ buildDropTableSql,
+ buildEmptyTableSql,
+ buildMysqlAutoIncrementSql,
+ buildTruncateTableSql,
+ buildVacuumTableSql,
+ supportsDropTableCascade,
+ supportsNativeMysqlAutoIncrement,
+ supportsTruncateTableCascade,
+ type MysqlAutoIncrementSqlOptions,
+ type TableAdminSqlOptions,
+ type VacuumTableSqlOptions,
+} from "@/lib/database/dbAdminSql";
import { isSqlServerLinkedNode } from "@/lib/database/sqlServerLinkedServers";
import { isQueryTimeoutErrorMessage } from "@/lib/sql/queryError";
import { uuid } from "@/lib/common/utils";
@@ -18,6 +30,7 @@ import {
showEmptyTableConfirm,
showMysqlAutoIncrementConfirm,
showTruncateTableConfirm,
+ showVacuumTableConfirm,
dropTablePreviewSql,
dropTableCascade,
emptyTablePreviewSql,
@@ -26,6 +39,11 @@ import {
mysqlAutoIncrementValue,
truncateTablePreviewSql,
truncateTableCascade,
+ vacuumTableFull,
+ vacuumTableAnalyze,
+ vacuumTablePreviewSql,
+ vacuumTablePreviewKey,
+ vacuumTableExecuting,
} from "@/components/sidebar/sidebarTreeDialogState";
interface SidebarTableMutationRuntimeOptions {
@@ -46,6 +64,10 @@ export function useSidebarTableMutationRuntime(options: SidebarTableMutationRunt
const isTableNotView = computed(() => activeNode.value.type === "table" && !isSqlServerLinkedNode(activeNode.value));
const supportsTruncate = computed(() => supportsTableTruncate(currentDatabaseType()));
+ const supportsVacuum = computed(() => {
+ const config = activeNode.value.connectionId ? connectionStore.getConfig(activeNode.value.connectionId) : undefined;
+ return activeNode.value.type === "table" && !config?.read_only && supportsTableVacuum(currentDatabaseType());
+ });
const canDropTableCascade = computed(() => activeNode.value.type === "table" && supportsDropTableCascade(currentDatabaseType()));
const canTruncateTableCascade = computed(() => activeNode.value.type === "table" && supportsTruncateTableCascade(currentDatabaseType()));
const supportsMysqlAutoIncrement = computed(() => activeNode.value.type === "table" && supportsNativeMysqlAutoIncrement(activeNode.value.connectionId ? connectionStore.getConfig(activeNode.value.connectionId) : undefined));
@@ -146,6 +168,69 @@ export function useSidebarTableMutationRuntime(options: SidebarTableMutationRunt
}
}
+ function vacuumTableSqlOptions(node: TreeNode, full = vacuumTableFull.value, analyze = vacuumTableAnalyze.value): VacuumTableSqlOptions {
+ return {
+ databaseType: databaseTypeForNode(node),
+ schema: node.schema,
+ tableName: node.label,
+ full,
+ analyze,
+ };
+ }
+
+ function vacuumTablePreviewKeyForNode(node: TreeNode, full = vacuumTableFull.value, analyze = vacuumTableAnalyze.value): string {
+ return JSON.stringify([node.id, databaseTypeForNode(node), node.schema || "", node.label, full, analyze]);
+ }
+
+ async function refreshVacuumTablePreviewSql() {
+ const node = sidebarDangerTarget.value ?? activeNode.value;
+ const full = vacuumTableFull.value;
+ const analyze = vacuumTableAnalyze.value;
+ const previewKey = vacuumTablePreviewKeyForNode(node, full, analyze);
+ vacuumTablePreviewSql.value = "";
+ vacuumTablePreviewKey.value = "";
+ const sql = await buildVacuumTableSql(vacuumTableSqlOptions(node, full, analyze)).catch(() => "");
+ const currentNode = sidebarDangerTarget.value ?? activeNode.value;
+ if (previewKey !== vacuumTablePreviewKeyForNode(currentNode)) return;
+ vacuumTablePreviewSql.value = sql;
+ vacuumTablePreviewKey.value = sql ? previewKey : "";
+ }
+
+ function vacuumTable() {
+ if (!supportsVacuum.value) return;
+ vacuumTableFull.value = false;
+ vacuumTableAnalyze.value = false;
+ vacuumTablePreviewSql.value = "";
+ vacuumTablePreviewKey.value = "";
+ void refreshVacuumTablePreviewSql();
+ showVacuumTableConfirm.value = true;
+ }
+
+ async function confirmVacuumTable(): Promise<boolean> {
+ const node = sidebarDangerTarget.value ?? activeNode.value;
+ if (!node.connectionId || node.database == null) return false;
+ vacuumTableExecuting.value = true;
+ try {
+ await connectionStore.ensureConnected(node.connectionId);
+ const optionsForNode = vacuumTableSqlOptions(node, vacuumTableFull.value, vacuumTableAnalyze.value);
+ const previewKey = vacuumTablePreviewKeyForNode(node);
+ const sql = vacuumTablePreviewKey.value === previewKey && vacuumTablePreviewSql.value ? vacuumTablePreviewSql.value : await buildVacuumTableSql(optionsForNode);
+ const executed = await options.executeWithProductionGuard(node, sql, { database: node.database, schema: node.schema });
+ if (executed === undefined) return false;
+ toast(t("contextMenu.vacuumTableSuccess", { name: node.label }), 3000);
+ return true;
+ } catch (error: any) {
+ toast(t("contextMenu.tableOperationFailed", { message: error?.message || String(error) }), 5000);
+ return false;
+ } finally {
+ vacuumTableExecuting.value = false;
+ }
+ }
+
+ async function refreshVacuumPreviewForOptions() {
+ await refreshVacuumTablePreviewSql();
+ }
+
function dropTable() {
dropTableCascade.value = false;
void refreshDropTablePreviewSql();
@@ -363,6 +448,7 @@ export function useSidebarTableMutationRuntime(options: SidebarTableMutationRunt
return {
isTableNotView,
supportsTruncate,
+ supportsVacuum,
canDropTableCascade,
canTruncateTableCascade,
supportsMysqlAutoIncrement,
@@ -375,6 +461,9 @@ export function useSidebarTableMutationRuntime(options: SidebarTableMutationRunt
confirmEmptyTable,
truncateTable,
confirmTruncateTable,
+ vacuumTable,
+ refreshVacuumPreviewForOptions,
+ confirmVacuumTable,
mysqlAutoIncrement,
refreshMysqlAutoIncrementPreviewSql,
confirmMysqlAutoIncrement,
diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.ts
index b7aeced89c..5d60cab396 100644
--- a/apps/desktop/src/i18n/locales/en.ts
+++ b/apps/desktop/src/i18n/locales/en.ts
@@ -2789,6 +2789,20 @@ export default {
dropTable: "Drop Table",
emptyTable: "Empty Table",
truncateTable: "Truncate Table",
+ vacuumTable: "Run VACUUM",
+ vacuumTableTitle: "Run VACUUM",
+ vacuumTableMessage: 'Run VACUUM on "{name}"?',
+ vacuumTableAnalyze: "ANALYZE",
+ vacuumTableAnalyzeHint: "Refresh optimizer statistics. This may change subsequent query plans and adds CPU and disk I/O overhead.",
+ vacuumTableFull: "FULL",
+ vacuumTableFullHint: "High risk: rewrites the entire table and takes an exclusive lock. Reads and writes may be blocked, and extra disk space may be required.",
+ vacuumTableDefaultRisk: "Routine maintenance: additional disk I/O may occur, and duration depends on table size.",
+ vacuumTableAnalyzeRisk: "Optimizer statistics will be refreshed, which may change subsequent query plans.",
+ vacuumTableFullRisk: "High risk: rewrites the entire table and takes an exclusive lock, which may block reads and writes and require extra disk space.",
+ vacuumTableFullConfirm: "Run VACUUM FULL",
+ vacuumTableRunning: "Running VACUUM...",
+ vacuumTableRunningHint: "VACUUM is running. Large tables may take a long time; keep this operation open.",
+ vacuumTableSuccess: 'VACUUM completed for "{name}"',
mysqlAutoIncrement: "Set AUTO_INCREMENT",
mysqlAutoIncrementTitle: "Set MySQL AUTO_INCREMENT",
mysqlAutoIncrementMessage: 'Set the next AUTO_INCREMENT value requested for "{name}"?',
diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.ts
index e4e06fb2c2..23d728ef9d 100644
--- a/apps/desktop/src/i18n/locales/zh-CN.ts
+++ b/apps/desktop/src/i18n/locales/zh-CN.ts
@@ -2713,6 +2713,20 @@ export default withEnglishFallback({
dropTable: "删除表",
emptyTable: "清空数据",
truncateTable: "截断表",
+ vacuumTable: "执行 VACUUM",
+ vacuumTableTitle: "执行 VACUUM",
+ vacuumTableMessage: "确定要对表「{name}」执行 VACUUM 吗?",
+ vacuumTableAnalyze: "ANALYZE",
+ vacuumTableAnalyzeHint: "重新收集统计信息,可能改变后续查询的执行计划,并产生额外的 CPU 和磁盘 I/O。",
+ vacuumTableFull: "FULL",
+ vacuumTableFullHint: "高风险:重写整张表并获取强排他锁,执行期间可能阻塞读写,并可能需要额外磁盘空间。",
+ vacuumTableDefaultRisk: "日常维护:可能产生额外磁盘 I/O,耗时取决于表大小。",
+ vacuumTableAnalyzeRisk: "将更新统计信息,后续查询的执行计划可能发生变化。",
+ vacuumTableFullRisk: "高风险:重写整表并获取强排他锁,可能阻塞读写并需要额外磁盘空间。",
+ vacuumTableFullConfirm: "执行 VACUUM FULL",
+ vacuumTableRunning: "正在执行 VACUUM...",
+ vacuumTableRunningHint: "正在执行 VACUUM,大型表可能需要较长时间,请勿关闭当前操作。",
+ vacuumTableSuccess: "已对表「{name}」执行 VACUUM",
mysqlAutoIncrement: "设置自增起始值",
mysqlAutoIncrementTitle: "设置 MySQL 自增起始值",
mysqlAutoIncrementMessage: "确定要设置表「{name}」请求的下一个自增值吗?",
diff --git a/apps/desktop/src/lib/__tests__/database/databaseFeatureSupport.spec.ts b/apps/desktop/src/lib/__tests__/database/databaseFeatureSupport.spec.ts
index 454fb499bd..75ecdd684a 100644
--- a/apps/desktop/src/lib/__tests__/database/databaseFeatureSupport.spec.ts
+++ b/apps/desktop/src/lib/__tests__/database/databaseFeatureSupport.spec.ts
@@ -12,6 +12,7 @@ import {
supportsQueryEditorBlockComments,
supportsSqlInListPaste,
supportsTableImport,
+ supportsTableVacuum,
supportsTransaction,
usesConnectionOnlyQueryTarget,
} from "@/lib/database/databaseFeatureSupport";
@@ -139,6 +140,20 @@ describe("supportsQueryEditorBlockComments", () => {
});
});
+describe("supportsTableVacuum", () => {
+ it("enables VACUUM for the supported PostgreSQL family", () => {
+ for (const databaseType of ["postgres", "gaussdb", "opengauss", "kingbase", "vastbase", "highgo", "uxdb", "kwdb"] as const) {
+ expect(supportsTableVacuum(databaseType)).toBe(true);
+ }
+ });
+
+ it("does not enable VACUUM for unrelated database types", () => {
+ for (const databaseType of ["mysql", "sqlite", "redshift", "oracle", "jdbc"] as const) {
+ expect(supportsTableVacuum(databaseType)).toBe(false);
+ }
+ });
+});
+
describe("supportsTableImport", () => {
it("enables OceanBase Oracle table import", () => {
expect(supportsTableImport("oceanbase-oracle")).toBe(true);
diff --git a/apps/desktop/src/lib/__tests__/database/dbAdminSql.spec.ts b/apps/desktop/src/lib/__tests__/database/dbAdminSql.spec.ts
index 01296dd008..eb69d034a7 100644
--- a/apps/desktop/src/lib/__tests__/database/dbAdminSql.spec.ts
+++ b/apps/desktop/src/lib/__tests__/database/dbAdminSql.spec.ts
@@ -9,12 +9,14 @@ const apiMock = vi.hoisted(() => ({
buildCreateTableSql: vi.fn(),
buildDuplicateTableStructureSql: vi.fn(),
buildMysqlAutoIncrementSql: vi.fn(),
+ buildVacuumTableSql: vi.fn(),
}));
vi.mock("@/lib/backend/api", () => apiMock);
import {
buildDuplicateTableStructurePlan,
+ buildVacuumTableSql,
buildMysqlAutoIncrementSql,
collectDuplicateTableColumnComments,
damengDropSchemaExecutionSchema,
@@ -66,6 +68,29 @@ describe("MySQL AUTO_INCREMENT administration", () => {
});
});
+describe("PostgreSQL-family VACUUM administration", () => {
+ it("forwards independent FULL and ANALYZE options", async () => {
+ apiMock.buildVacuumTableSql.mockResolvedValue('VACUUM FULL ANALYZE "public"."events";');
+
+ await expect(
+ buildVacuumTableSql({
+ databaseType: "postgres",
+ schema: "public",
+ tableName: "events",
+ full: true,
+ analyze: true,
+ }),
+ ).resolves.toBe('VACUUM FULL ANALYZE "public"."events";');
+ expect(apiMock.buildVacuumTableSql).toHaveBeenCalledWith({
+ databaseType: "postgres",
+ schema: "public",
+ tableName: "events",
+ full: true,
+ analyze: true,
+ });
+ });
+});
+
describe("collectDuplicateTableColumnComments", () => {
it("preserves meaningful whitespace and excludes whitespace-only comments", () => {
expect(
diff --git a/apps/desktop/src/lib/backend/api.ts b/apps/desktop/src/lib/backend/api.ts
index 32a134eed4..d4e755cbef 100644
--- a/apps/desktop/src/lib/backend/api.ts
+++ b/apps/desktop/src/lib/backend/api.ts
@@ -230,6 +230,7 @@ export const buildDropTableSql = forward("buildDropTableSql");
export const buildDropTableChildObjectSql = forward("buildDropTableChildObjectSql");
export const buildEmptyTableSql = forward("buildEmptyTableSql");
export const buildTruncateTableSql = forward("buildTruncateTableSql");
+export const buildVacuumTableSql = forward("buildVacuumTableSql");
export const buildMysqlAutoIncrementSql = forward("buildMysqlAutoIncrementSql");
export const buildDropDatabaseSql = forward("buildDropDatabaseSql");
export const buildCreateSchemaSql = forward("buildCreateSchemaSql");
diff --git a/apps/desktop/src/lib/backend/http.ts b/apps/desktop/src/lib/backend/http.ts
index fbe71efa6c..6ddee2eb6d 100644
--- a/apps/desktop/src/lib/backend/http.ts
+++ b/apps/desktop/src/lib/backend/http.ts
@@ -163,7 +163,18 @@ import type { BuildEditableObjectSourceSqlInput, BuildRoutineRenameObjectSourceI
import type { BuildViewDdlInput } from "@/lib/table/viewDdl";
import type { BuildRenameObjectSqlOptions } from "@/lib/table/objectRenameSql";
import type { CreateDatabaseSqlOptions } from "@/lib/database/createDatabaseSql";
-import type { DatabaseNameSqlOptions, DatabasePropertyEditSqlOptions, DropTableChildObjectSqlOptions, DropObjectSqlOptions, DuplicateTableStructureSqlOptions, CopyTableDataSqlOptions, MysqlAutoIncrementSqlOptions, SchemaNameSqlOptions, TableAdminSqlOptions } from "@/lib/database/dbAdminSql";
+import type {
+ DatabaseNameSqlOptions,
+ DatabasePropertyEditSqlOptions,
+ DropTableChildObjectSqlOptions,
+ DropObjectSqlOptions,
+ DuplicateTableStructureSqlOptions,
+ CopyTableDataSqlOptions,
+ MysqlAutoIncrementSqlOptions,
+ SchemaNameSqlOptions,
+ TableAdminSqlOptions,
+ VacuumTableSqlOptions,
+} from "@/lib/database/dbAdminSql";
import type { BuildDatabaseSqlExportOptions, BuildExportInsertStatementsOptions } from "@/lib/export/databaseExport";
import { loadBrowserAppState, saveBrowserAppState } from "@/lib/backend/browserAppStateStorage";
import type { DataCompareFromTablesOptions, DataCompareFromTablesPreparation, DataCompareSyncPlan, DataCompareSyncPlanOptions, DataComparePreparation, DataComparePreparationOptions } from "@/lib/dataGrid/dataCompare";
@@ -1289,6 +1300,10 @@ export async function buildTruncateTableSql(options: TableAdminSqlOptions): Prom
return post("/api/query/build-truncate-table-sql", { options });
}
+export async function buildVacuumTableSql(options: VacuumTableSqlOptions): Promise<string> {
+ return post("/api/query/build-vacuum-table-sql", { options });
+}
+
export async function buildMysqlAutoIncrementSql(options: MysqlAutoIncrementSqlOptions): Promise<string> {
return post("/api/query/build-mysql-auto-increment-sql", { options });
}
diff --git a/apps/desktop/src/lib/backend/tauri.ts b/apps/desktop/src/lib/backend/tauri.ts
index c07cf2f848..7e8248d96c 100644
--- a/apps/desktop/src/lib/backend/tauri.ts
+++ b/apps/desktop/src/lib/backend/tauri.ts
@@ -89,7 +89,18 @@ import type { BuildEditableObjectSourceSqlInput, BuildRoutineRenameObjectSourceI
import type { BuildViewDdlInput } from "@/lib/table/viewDdl";
import type { BuildRenameObjectSqlOptions } from "@/lib/table/objectRenameSql";
import type { CreateDatabaseSqlOptions } from "@/lib/database/createDatabaseSql";
-import type { DatabaseNameSqlOptions, DatabasePropertyEditSqlOptions, DropTableChildObjectSqlOptions, DropObjectSqlOptions, DuplicateTableStructureSqlOptions, CopyTableDataSqlOptions, MysqlAutoIncrementSqlOptions, SchemaNameSqlOptions, TableAdminSqlOptions } from "@/lib/database/dbAdminSql";
+import type {
+ DatabaseNameSqlOptions,
+ DatabasePropertyEditSqlOptions,
+ DropTableChildObjectSqlOptions,
+ DropObjectSqlOptions,
+ DuplicateTableStructureSqlOptions,
+ CopyTableDataSqlOptions,
+ MysqlAutoIncrementSqlOptions,
+ SchemaNameSqlOptions,
+ TableAdminSqlOptions,
+ VacuumTableSqlOptions,
+} from "@/lib/database/dbAdminSql";
import type { BuildDatabaseSqlExportOptions, BuildExportInsertStatementsOptions } from "@/lib/export/databaseExport";
export interface SshPromptResolution {
@@ -1443,6 +1454,10 @@ export async function buildTruncateTableSql(options: TableAdminSqlOptions): Prom
return invoke("build_truncate_table_sql", { options });
}
+export async function buildVacuumTableSql(options: VacuumTableSqlOptions): Promise<string> {
+ return invoke("build_vacuum_table_sql", { options });
+}
+
export async function buildMysqlAutoIncrementSql(options: MysqlAutoIncrementSqlOptions): Promise<string> {
return invoke("build_mysql_auto_increment_sql", { options });
}
diff --git a/apps/desktop/src/lib/database/__tests__/productionSafety.spec.ts b/apps/desktop/src/lib/database/__tests__/productionSafety.spec.ts
index afc8a5c8ad..b32b2e6990 100644
--- a/apps/desktop/src/lib/database/__tests__/productionSafety.spec.ts
+++ b/apps/desktop/src/lib/database/__tests__/productionSafety.spec.ts
@@ -91,6 +91,18 @@ describe("production SQL safety", () => {
}
});
+ it("detects VACUUM in a production PostgreSQL database", () => {
+ const pg = connection({ db_type: "postgres", production_databases: ["prod_app"] });
+ for (const sql of ['VACUUM "public"."orders"', 'VACUUM ANALYZE "public"."orders"', 'VACUUM FULL ANALYZE "public"."orders"']) {
+ expect(assessProductionSql(sql, pg, "prod_app")).toMatchObject({ active: true, isMutation: true, databases: ["prod_app"] });
+ }
+ });
+
+ it("detects qualified VACUUM targets for database-qualified dialects", () => {
+ const mysql = connection({ db_type: "mysql", production_databases: ["prod_app"] });
+ expect(assessProductionSql("VACUUM FULL prod_app.orders", mysql, "staging")).toMatchObject({ active: true, isMutation: true, databases: ["prod_app"] });
+ });
+
it("detects qualified procedure calls and privilege targets", () => {
for (const sql of ["CALL prod_app.purge_users()", "CALL `prod_app`.`purge_users`()", "GRANT ALL ON prod_app.* TO 'u'@'%'", "GRANT EXECUTE ON PROCEDURE prod_app.purge_users TO 'u'@'%'"]) {
expect(assessProductionSql(sql, connection(), "staging")).toMatchObject({ active: true, isMutation: true, databases: ["prod_app"] });
diff --git a/apps/desktop/src/lib/database/databaseCapabilitySets.ts b/apps/desktop/src/lib/database/databaseCapabilitySets.ts
index 3b5c496be7..18d3afacc5 100644
--- a/apps/desktop/src/lib/database/databaseCapabilitySets.ts
+++ b/apps/desktop/src/lib/database/databaseCapabilitySets.ts
@@ -88,6 +88,8 @@ export const TREE_SCHEMA_TYPES = new Set<DatabaseType>([
export const DATABASE_OBJECT_TREE_TYPES = new Set<DatabaseType>(["jdbc"]);
+export const PG_VACUUM_TYPES = new Set<DatabaseType>(["postgres", "gaussdb", "kwdb", "kingbase", "highgo", "uxdb", "vastbase", "opengauss"]);
+
export const PG_LIKE_STRUCTURE_TYPES = new Set<DatabaseType>(["postgres", "redshift", "gaussdb", "kwdb", "opengauss", "questdb"]);
export const DIAGRAM_SQL_TYPES = new Set<DatabaseType>(["mysql", "postgres", "sqlite", "rqlite", "turso", "cloudflare-d1", "sqlserver", "oracle", "redshift", "dameng", "gaussdb", "kwdb", "opengauss", "questdb", "oceanbase-oracle"]);
diff --git a/apps/desktop/src/lib/database/databaseFeatureSupport.ts b/apps/desktop/src/lib/database/databaseFeatureSupport.ts
index 0eb43f6ccb..12c2364df4 100644
--- a/apps/desktop/src/lib/database/databaseFeatureSupport.ts
+++ b/apps/desktop/src/lib/database/databaseFeatureSupport.ts
@@ -1,7 +1,7 @@
import type { ConnectionConfig, DatabaseType, TreeNodeType } from "@/types/database";
import { supportsDatabaseFeature } from "@/lib/database/databaseDriverManifest";
import { canEditTableStructure } from "@/lib/table/tableStructureCapabilities";
-import { CLEARABLE_QUERY_SCHEMA_TYPES, DATABASE_OBJECT_TREE_TYPES, DATABASE_SCHEMA_QUALIFIED_TYPES, FETCH_FIRST_TYPES, PG_LIKE_STRUCTURE_TYPES, SCHEMA_AWARE_TYPES, SINGLE_DATABASE_TYPES, TREE_SCHEMA_TYPES } from "@/lib/database/databaseCapabilitySets";
+import { CLEARABLE_QUERY_SCHEMA_TYPES, DATABASE_OBJECT_TREE_TYPES, DATABASE_SCHEMA_QUALIFIED_TYPES, FETCH_FIRST_TYPES, PG_LIKE_STRUCTURE_TYPES, PG_VACUUM_TYPES, SCHEMA_AWARE_TYPES, SINGLE_DATABASE_TYPES, TREE_SCHEMA_TYPES } from "@/lib/database/databaseCapabilitySets";
import { supportsRegisteredConnectionScopedQueryExecution, supportsRegisteredQueryTargetDatabaseListing, usesRegisteredConnectionOnlyQueryTarget } from "@/lib/database/sqlExecutionTargetRegistry";
export function isSchemaAware(dbType?: DatabaseType): boolean {
@@ -196,6 +196,10 @@ export function supportsTableTruncate(dbType?: DatabaseType): boolean {
return !!dbType && dbType !== "impala" && dbType !== "sqlite" && dbType !== "rqlite" && dbType !== "turso" && dbType !== "cloudflare-d1" && dbType !== "duckdb" && dbType !== "influxdb" && dbType !== "victoriametrics" && dbType !== "manticoresearch";
}
+export function supportsTableVacuum(dbType?: DatabaseType): boolean {
+ return !!dbType && PG_VACUUM_TYPES.has(dbType);
+}
+
export function usesPostgresLikeStructureCopy(dbType?: DatabaseType): boolean {
return !!dbType && PG_LIKE_STRUCTURE_TYPES.has(dbType);
}
diff --git a/apps/desktop/src/lib/database/dbAdminSql.ts b/apps/desktop/src/lib/database/dbAdminSql.ts
index 7328450351..d95a166246 100644
--- a/apps/desktop/src/lib/database/dbAdminSql.ts
+++ b/apps/desktop/src/lib/database/dbAdminSql.ts
@@ -18,6 +18,14 @@ export interface TableAdminSqlOptions {
cascade?: boolean;
}
+export interface VacuumTableSqlOptions {
+ databaseType?: DatabaseType;
+ schema?: string | null;
+ tableName: string;
+ full?: boolean;
+ analyze?: boolean;
+}
+
export interface MysqlAutoIncrementSqlOptions {
databaseType: DatabaseType;
driverProfile?: string | null;
@@ -286,6 +294,10 @@ export function buildTruncateTableSql(options: TableAdminSqlOptions): Promise<st
return api.buildTruncateTableSql(options);
}
+export function buildVacuumTableSql(options: VacuumTableSqlOptions): Promise<string> {
+ return api.buildVacuumTableSql(options);
+}
+
export function buildMysqlAutoIncrementSql(options: MysqlAutoIncrementSqlOptions): Promise<string> {
return api.buildMysqlAutoIncrementSql(options);
}
diff --git a/apps/desktop/src/lib/database/productionSafety.ts b/apps/desktop/src/lib/database/productionSafety.ts
index 0d277a1449..af6f18bad0 100644
--- a/apps/desktop/src/lib/database/productionSafety.ts
+++ b/apps/desktop/src/lib/database/productionSafety.ts
@@ -26,6 +26,7 @@ const COPY_TARGET_RE = new RegExp(String.raw`^\s*COPY\s+(${TARGET_NAME_PATTERN})
const TRUNCATE_TARGET_RE = new RegExp(String.raw`\bTRUNCATE\s+(?:TABLE\s+)?(${TARGET_NAME_PATTERN})`, "gi");
const RENAME_TABLE_TARGET_RE = new RegExp(String.raw`\bRENAME\s+TABLE\s+(${TARGET_NAME_PATTERN})\s+TO\s+(${TARGET_NAME_PATTERN})`, "gi");
const MAINTENANCE_TABLE_TARGET_RE = new RegExp(String.raw`\b(?:ANALYZE|OPTIMIZE|REPAIR|CHECK)\s+(?:NO_WRITE_TO_BINLOG\s+|LOCAL\s+)?TABLE\s+(${TARGET_NAME_PATTERN})`, "gi");
+const VACUUM_TABLE_TARGET_RE = new RegExp(String.raw`\bVACUUM(?:\s+FULL)?(?:\s+ANALYZE)?\s+(${TARGET_NAME_PATTERN})`, "gi");
const COMMENT_TARGET_RE = new RegExp(String.raw`\bCOMMENT\s+ON\s+(?:TABLE|VIEW|COLUMN|INDEX|SEQUENCE|FUNCTION|PROCEDURE|TYPE)\s+(${TARGET_NAME_PATTERN})`, "gi");
const ROUTINE_CALL_TARGET_RE = new RegExp(String.raw`\b(?:CALL|EXEC|EXECUTE)\s+(${QUALIFIED_NAME_PATTERN})`, "gi");
const PRIVILEGE_TARGET_RE = new RegExp(String.raw`\b(?:GRANT|REVOKE|DENY)\b[\s\S]*?\bON\s+(?:(?:TABLE|SEQUENCE|FUNCTION|PROCEDURE|ROUTINE|OBJECT)\s+|OBJECT\s*::\s*)?(${QUALIFIED_NAME_PATTERN})`, "gi");
@@ -159,7 +160,22 @@ function referencedDatabases(statements: string[], dbType: DatabaseType, activeD
if (!statementIsMutation) continue;
const currentDatabase = useDatabase || normalizedActiveDatabase;
- collectQualifiedTargetDatabases(statement, dbType, quotedIdentifiers, currentDatabase, statementDatabases, DML_TARGET_RE, DDL_OBJECT_TARGET_RE, INDEX_ON_TARGET_RE, TRUNCATE_TARGET_RE, MAINTENANCE_TABLE_TARGET_RE, COMMENT_TARGET_RE, ROUTINE_CALL_TARGET_RE, PRIVILEGE_TARGET_RE);
+ collectQualifiedTargetDatabases(
+ statement,
+ dbType,
+ quotedIdentifiers,
+ currentDatabase,
+ statementDatabases,
+ DML_TARGET_RE,
+ DDL_OBJECT_TARGET_RE,
+ INDEX_ON_TARGET_RE,
+ TRUNCATE_TARGET_RE,
+ MAINTENANCE_TABLE_TARGET_RE,
+ VACUUM_TABLE_TARGET_RE,
+ COMMENT_TARGET_RE,
+ ROUTINE_CALL_TARGET_RE,
+ PRIVILEGE_TARGET_RE,
+ );
collectQualifiedTargetDatabaseGroups(statement, dbType, quotedIdentifiers, currentDatabase, statementDatabases, RENAME_TABLE_TARGET_RE, [1, 2]);
for (const match of statement.matchAll(DATABASE_TARGET_RE)) {
const database = databaseTargetKindMeansDatabase(match[1], dbType) ? normalizeTargetDatabase(match[2], quotedIdentifiers) : "";
diff --git a/apps/desktop/src/lib/sidebar/sidebarDangerDialog.ts b/apps/desktop/src/lib/sidebar/sidebarDangerDialog.ts
index d2e076929e..6d05e664cc 100644
--- a/apps/desktop/src/lib/sidebar/sidebarDangerDialog.ts
+++ b/apps/desktop/src/lib/sidebar/sidebarDangerDialog.ts
@@ -4,6 +4,8 @@ export interface SidebarDangerDialogOption {
checked: boolean;
label: string;
hint: string;
+ compact?: boolean;
+ danger?: boolean;
onChange?: (checked: boolean) => void | Promise<void>;
}
@@ -32,7 +34,8 @@ export interface SidebarDangerDialogRequest {
closeOnConfirm?: boolean;
progress?: SidebarDangerDialogProgress;
option?: SidebarDangerDialogOption;
+ options?: SidebarDangerDialogOption[];
textInput?: SidebarDangerDialogTextInput;
cancelRunning?: () => void | Promise<void>;
- confirm: () => void | Promise<void>;
+ confirm: () => void | boolean | Promise<void | boolean>;
}
diff --git a/crates/dbx-core/src/db_admin_sql.rs b/crates/dbx-core/src/db_admin_sql.rs
index 3fb04d2172..6aebbb9bd8 100644
--- a/crates/dbx-core/src/db_admin_sql.rs
+++ b/crates/dbx-core/src/db_admin_sql.rs
@@ -101,6 +101,20 @@ pub struct TableAdminSqlOptions {
pub cascade: Option<bool>,
}
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct VacuumTableSqlOptions {
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub database_type: Option<DatabaseType>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub schema: Option<String>,
+ pub table_name: String,
+ #[serde(default)]
+ pub full: bool,
+ #[serde(default)]
+ pub analyze: bool,
+}
+
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MysqlAutoIncrementSqlOptions {
@@ -520,6 +534,32 @@ pub fn build_truncate_table_sql(options: TableAdminSqlOptions) -> String {
}
}
+pub fn build_vacuum_table_sql(options: VacuumTableSqlOptions) -> Result<String, String> {
+ if !supports_vacuum_table(options.database_type) {
+ return Err(format!("VACUUM is not supported for {}.", database_label(options.database_type)));
+ }
+ let table = qualified_name(options.database_type, options.schema.as_deref(), &options.table_name);
+ let full = if options.full { " FULL" } else { "" };
+ let analyze = if options.analyze { " ANALYZE" } else { "" };
+ Ok(format!("VACUUM{full}{analyze} {table};"))
+}
+
+fn supports_vacuum_table(database_type: Option<DatabaseType>) -> bool {
+ matches!(
+ database_type,
+ Some(
+ DatabaseType::Postgres
+ | DatabaseType::Gaussdb
+ | DatabaseType::Kwdb
+ | DatabaseType::Kingbase
+ | DatabaseType::Highgo
+ | DatabaseType::Uxdb
+ | DatabaseType::Vastbase
+ | DatabaseType::OpenGauss
+ )
+ )
+}
+
pub fn build_mysql_auto_increment_sql(options: MysqlAutoIncrementSqlOptions) -> Result<String, String> {
let profile = options.driver_profile.as_deref().map(str::trim).unwrap_or_default();
if options.database_type != Some(DatabaseType::Mysql)
@@ -1303,6 +1343,58 @@ mod tests {
);
}
+ #[test]
+ fn builds_vacuum_table_sql_for_all_options() {
+ let base = VacuumTableSqlOptions {
+ database_type: Some(DatabaseType::Postgres),
+ schema: Some("public".to_string()),
+ table_name: "events".to_string(),
+ full: false,
+ analyze: false,
+ };
+ assert_eq!(build_vacuum_table_sql(base.clone()).unwrap(), "VACUUM \"public\".\"events\";");
+ assert_eq!(
+ build_vacuum_table_sql(VacuumTableSqlOptions { analyze: true, ..base.clone() }).unwrap(),
+ "VACUUM ANALYZE \"public\".\"events\";"
+ );
+ assert_eq!(
+ build_vacuum_table_sql(VacuumTableSqlOptions { full: true, ..base.clone() }).unwrap(),
+ "VACUUM FULL \"public\".\"events\";"
+ );
+ assert_eq!(
+ build_vacuum_table_sql(VacuumTableSqlOptions { full: true, analyze: true, ..base }).unwrap(),
+ "VACUUM FULL ANALYZE \"public\".\"events\";"
+ );
+ }
+
+ #[test]
+ fn vacuum_is_restricted_to_supported_postgres_family_types() {
+ for database_type in [
+ DatabaseType::Postgres,
+ DatabaseType::Gaussdb,
+ DatabaseType::OpenGauss,
+ DatabaseType::Kingbase,
+ DatabaseType::Vastbase,
+ ] {
+ assert!(build_vacuum_table_sql(VacuumTableSqlOptions {
+ database_type: Some(database_type),
+ schema: None,
+ table_name: "events".to_string(),
+ full: false,
+ analyze: false,
+ })
+ .is_ok());
+ }
+ assert!(build_vacuum_table_sql(VacuumTableSqlOptions {
+ database_type: Some(DatabaseType::Mysql),
+ schema: None,
+ table_name: "events".to_string(),
+ full: false,
+ analyze: false,
+ })
+ .is_err());
+ }
+
#[test]
fn builds_drop_and_clear_table_sql() {
let options = TableAdminSqlOptions {
diff --git a/crates/dbx-web/src/main.rs b/crates/dbx-web/src/main.rs
index 5b3197a68a..8136546806 100644
--- a/crates/dbx-web/src/main.rs
+++ b/crates/dbx-web/src/main.rs
@@ -481,6 +481,7 @@ async fn main() {
.route("/query/build-drop-table-child-object-sql", post(routes::query::build_drop_table_child_object_sql))
.route("/query/build-empty-table-sql", post(routes::query::build_empty_table_sql))
.route("/query/build-truncate-table-sql", post(routes::query::build_truncate_table_sql))
+ .route("/query/build-vacuum-table-sql", post(routes::query::build_vacuum_table_sql))
.route("/query/build-mysql-auto-increment-sql", post(routes::query::build_mysql_auto_increment_sql))
.route("/query/build-drop-database-sql", post(routes::query::build_drop_database_sql))
.route("/query/build-create-schema-sql", post(routes::query::build_create_schema_sql))
diff --git a/crates/dbx-web/src/routes/query.rs b/crates/dbx-web/src/routes/query.rs
index 2d81a06713..ce07cc263e 100644
--- a/crates/dbx-web/src/routes/query.rs
+++ b/crates/dbx-web/src/routes/query.rs
@@ -173,6 +173,12 @@ pub struct BuildTableAdminSqlRequest {
pub options: dbx_core::db_admin_sql::TableAdminSqlOptions,
}
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct BuildVacuumTableSqlRequest {
+ pub options: dbx_core::db_admin_sql::VacuumTableSqlOptions,
+}
+
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BuildMysqlAutoIncrementSqlRequest {
@@ -729,6 +735,10 @@ pub async fn build_truncate_table_sql(Json(req): Json<BuildTableAdminSqlRequest>
Json(dbx_core::db_admin_sql::build_truncate_table_sql(req.options))
}
+pub async fn build_vacuum_table_sql(Json(req): Json<BuildVacuumTableSqlRequest>) -> Result<Json<String>, AppError> {
+ dbx_core::db_admin_sql::build_vacuum_table_sql(req.options).map(Json).map_err(AppError::from)
+}
+
pub async fn build_mysql_auto_increment_sql(
Json(req): Json<BuildMysqlAutoIncrementSqlRequest>,
) -> Result<Json<String>, AppError> {
diff --git a/src-tauri/src/commands/query.rs b/src-tauri/src/commands/query.rs
index 0786b54401..f89260e614 100644
--- a/src-tauri/src/commands/query.rs
+++ b/src-tauri/src/commands/query.rs
@@ -513,6 +513,11 @@ pub fn build_truncate_table_sql(options: dbx_core::db_admin_sql::TableAdminSqlOp
Ok(dbx_core::db_admin_sql::build_truncate_table_sql(options))
}
+#[tauri::command]
+pub fn build_vacuum_table_sql(options: dbx_core::db_admin_sql::VacuumTableSqlOptions) -> Result<String, String> {
+ dbx_core::db_admin_sql::build_vacuum_table_sql(options)
+}
+
#[tauri::command]
pub fn build_mysql_auto_increment_sql(
options: dbx_core::db_admin_sql::MysqlAutoIncrementSqlOptions,
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index 54791fe682..859ce80a8a 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -1727,6 +1727,7 @@ pub fn run() {
commands::query::build_drop_table_child_object_sql,
commands::query::build_empty_table_sql,
commands::query::build_truncate_table_sql,
+ commands::query::build_vacuum_table_sql,
commands::query::build_mysql_auto_increment_sql,
commands::query::build_drop_database_sql,
commands::query::build_create_schema_sql,