feat(objects): open database objects in side panel

This commit is contained in:
gggaiitx authored and GitHub committed 2026-07-11 12:48:57 +08:00
1 parent ce7739fcda
commit 5bcd24df1c
5 files changed
+886 -30

No files matched your search

@@ -1,5 +1,5 @@
<script setup lang="ts"> <script setup lang="ts">
import { computed, nextTick, onActivated, onBeforeUnmount, ref, watch } from "vue"; import { computed, nextTick, onActivated, onBeforeUnmount, ref, watch, type Component } from "vue";
import { RecycleScroller } from "vue-virtual-scroller"; import { RecycleScroller } from "vue-virtual-scroller";
import { useSqlHighlighter } from "@/composables/useSqlHighlighter"; import { useSqlHighlighter } from "@/composables/useSqlHighlighter";
import { import {
@@ -14,12 +14,15 @@ import {
CopyPlus, CopyPlus,
ChevronDown, ChevronDown,
ChevronRight, ChevronRight,
Columns3Cog,
Download, Download,
Eraser, Eraser,
Eye, Eye,
FileCode, FileCode,
GripVertical, GripVertical,
KeyRound,
LayoutGrid, LayoutGrid,
Link2,
List, List,
ListTree, ListTree,
Upload, Upload,
@@ -31,13 +34,16 @@ import {
Play, Play,
Package, Package,
RefreshCw, RefreshCw,
RotateCcw,
Scissors, Scissors,
Search, Search,
ScrollText, ScrollText,
Square, Square,
Table2, Table2,
TableProperties,
TerminalSquare, TerminalSquare,
Trash2, Trash2,
WrapText,
X, X,
} from "@lucide/vue"; } from "@lucide/vue";
import { useI18n } from "vue-i18n"; import { useI18n } from "vue-i18n";
@@ -48,11 +54,12 @@ import CustomContextMenu, { type ContextMenuItem } from "@/components/ui/CustomC
import DangerConfirmDialog from "@/components/editor/DangerConfirmDialog.vue"; import DangerConfirmDialog from "@/components/editor/DangerConfirmDialog.vue";
import ProcedureExecutionDialog from "@/components/objects/ProcedureExecutionDialog.vue"; import ProcedureExecutionDialog from "@/components/objects/ProcedureExecutionDialog.vue";
import * as api from "@/lib/backend/api"; import * as api from "@/lib/backend/api";
import type { ConnectionConfig, ForeignKeyInfo, ObjectBrowserViewMode, ObjectBrowserViewport, ObjectInfo, ObjectSourceKind, ObjectStatistics } from "@/types/database"; import type { ColumnInfo, ConnectionConfig, ForeignKeyInfo, IndexInfo, ObjectBrowserViewMode, ObjectBrowserViewport, ObjectInfo, ObjectSourceKind, ObjectStatistics, TableInfoTab, TriggerInfo } from "@/types/database";
import { sortTablesByFkDependency, type TableWithFk } from "@/lib/table/tableDependencySort"; import { sortTablesByFkDependency, type TableWithFk } from "@/lib/table/tableDependencySort";
import { isSchemaAware } from "@/lib/database/databaseCapabilities"; import { isSchemaAware } from "@/lib/database/databaseCapabilities";
import { supportsSchemaDiagram, supportsTableImport, supportsTableStructureEditing, supportsTableTruncate } from "@/lib/database/databaseFeatureSupport"; import { supportsSchemaDiagram, supportsTableImport, supportsTableStructureEditing, supportsTableTruncate } from "@/lib/database/databaseFeatureSupport";
import { codeMirrorSqlDialect, connectionUsesDatabaseObjectTreeMode, effectiveDatabaseTypeForConnection, tableStructureDatabaseTypeForConnection } from "@/lib/database/jdbcDialect"; import { codeMirrorSqlDialect, connectionUsesDatabaseObjectTreeMode, effectiveDatabaseTypeForConnection, tableStructureDatabaseTypeForConnection } from "@/lib/database/jdbcDialect";
import { getTableMetadataCapabilities, type TableMetadataCapabilities } from "@/lib/table/tableMetadataCapabilities";
import { buildTableSelectSql } from "@/lib/table/tableSelectSql"; import { buildTableSelectSql } from "@/lib/table/tableSelectSql";
import { buildDropObjectSql, buildDropTableSql, buildDuplicateTableStructureSql, buildCopyTableDataSql, buildEmptyTableSql, buildTruncateTableSql, supportsDropTableCascade, supportsTruncateTableCascade, type TableAdminSqlOptions } from "@/lib/database/dbAdminSql"; import { buildDropObjectSql, buildDropTableSql, buildDuplicateTableStructureSql, buildCopyTableDataSql, buildEmptyTableSql, buildTruncateTableSql, supportsDropTableCascade, supportsTruncateTableCascade, type TableAdminSqlOptions } from "@/lib/database/dbAdminSql";
import { useToast } from "@/composables/useToast"; import { useToast } from "@/composables/useToast";
@@ -86,6 +93,8 @@ import {
type ObjectBrowserSortDirection, type ObjectBrowserSortDirection,
type ObjectBrowserSortKey, type ObjectBrowserSortKey,
} from "@/lib/table/objectBrowserRows"; } from "@/lib/table/objectBrowserRows";
import { resolveRowClickAction, shouldDeferSingleClick, type ObjectBrowserRowAction } from "@/lib/table/objectBrowserRowAction";
import { createSidePanelRequestGuard } from "@/lib/table/sidePanelRequestGuard";
type ObjectFilter = "all" | "tables" | "views" | "materializedViews" | "procedures" | "functions" | "sequences" | "packages"; type ObjectFilter = "all" | "tables" | "views" | "materializedViews" | "procedures" | "functions" | "sequences" | "packages";
type ObjectBrowserColumnKey = "select" | "name" | "type" | "estimatedRows" | "totalBytes" | "created_at" | "updated_at" | "comment"; type ObjectBrowserColumnKey = "select" | "name" | "type" | "estimatedRows" | "totalBytes" | "created_at" | "updated_at" | "comment";
@@ -127,6 +136,33 @@ const sourceError = ref("");
const sourceRow = ref<ObjectBrowserRow | null>(null); const sourceRow = ref<ObjectBrowserRow | null>(null);
const sourceEditing = ref(false); const sourceEditing = ref(false);
const sourceCanEdit = ref(true); const sourceCanEdit = ref(true);
// --- Right-side panel state ---
// Unified panel: either "table-info" (for tables) or "source" (for views/procedures/etc.)
const sidePanelRow = ref<ObjectBrowserRow | null>(null);
const sidePanelMode = ref<"table-info" | "source">("source");
// Table info panel state
const tableInfoTab = ref<TableInfoTab>("ddl");
const tableColumns = ref<ColumnInfo[]>([]);
const tableColumnsLoading = ref(false);
const tableDdlContent = ref("");
const tableDdlLoading = ref(false);
const tableIndexes = ref<IndexInfo[]>([]);
const tableIndexesLoading = ref(false);
const tableForeignKeys = ref<ForeignKeyInfo[]>([]);
const tableForeignKeysLoading = ref(false);
const tableTriggers = ref<TriggerInfo[]>([]);
const tableTriggersLoading = ref(false);
const tableInfoSearchQuery = ref("");
const tableInfoWrap = ref(true);
const tableInfoDdlPreRef = ref<HTMLPreElement | null>(null);
const SIDE_PANEL_MIN_WIDTH = 280;
const SIDE_PANEL_MAX_WIDTH = 900;
const sidePanelWidth = ref(settingsStore.editorSettings.tableInfoDrawerWidth || 420);
let sidePanelResizeStartX = 0;
let sidePanelResizeStartWidth = 0;
const isResizingSidePanel = ref(false);
const sidePanelGuard = createSidePanelRequestGuard();
const tableMetadataCapabilities = computed<TableMetadataCapabilities>(() => getTableMetadataCapabilities(effectiveDatabaseType.value));
const effectiveDatabaseType = computed(() => effectiveDatabaseTypeForConnection(props.connection) ?? props.connection.db_type); const effectiveDatabaseType = computed(() => effectiveDatabaseTypeForConnection(props.connection) ?? props.connection.db_type);
const tableStructureDatabaseType = computed(() => tableStructureDatabaseTypeForConnection(props.connection) ?? props.connection.db_type); const tableStructureDatabaseType = computed(() => tableStructureDatabaseTypeForConnection(props.connection) ?? props.connection.db_type);
const sourceEditableText = ref(""); const sourceEditableText = ref("");
@@ -454,6 +490,12 @@ onBeforeUnmount(() => {
gridResizeObserver = null; gridResizeObserver = null;
if (viewportFrame) window.cancelAnimationFrame(viewportFrame); if (viewportFrame) window.cancelAnimationFrame(viewportFrame);
if (restoreViewportFrame) window.cancelAnimationFrame(restoreViewportFrame); if (restoreViewportFrame) window.cancelAnimationFrame(restoreViewportFrame);
window.removeEventListener("mousemove", onSidePanelResizeMove);
window.removeEventListener("mouseup", onSidePanelResizeEnd);
if (singleClickTimer) {
clearTimeout(singleClickTimer);
singleClickTimer = null;
}
}); });
const gridRows = computed(() => { const gridRows = computed(() => {
@@ -652,10 +694,6 @@ function togglePartitionParent(row: ObjectBrowserRow) {
expandedPartitionParentIds.value = next; expandedPartitionParentIds.value = next;
} }
function canOpenSource(row: ObjectBrowserRow) {
return row.type === "VIEW" || row.type === "MATERIALIZED_VIEW" || row.type === "PROCEDURE" || row.type === "FUNCTION" || row.type === "SEQUENCE" || row.type === "PACKAGE" || row.type === "PACKAGE_BODY";
}
function canRename(row: ObjectBrowserRow) { function canRename(row: ObjectBrowserRow) {
return supportsObjectRename(effectiveDatabaseType.value, row.type) || supportsSourceBackedRoutineRename(effectiveDatabaseType.value, row.type as ObjectSourceKind); return supportsObjectRename(effectiveDatabaseType.value, row.type) || supportsSourceBackedRoutineRename(effectiveDatabaseType.value, row.type as ObjectSourceKind);
} }
@@ -665,26 +703,300 @@ function sourceTitle(row: ObjectBrowserRow | null) {
return `${row.name} ${t("objects.source")}`; return `${row.name} ${t("objects.source")}`;
} }
function onRowClick(row: ObjectBrowserRow, event: MouseEvent) { const SINGLE_CLICK_DELAY = 250;
if (settingsStore.editorSettings.sidebarActivation === "double") { let singleClickTimer: ReturnType<typeof setTimeout> | null = null;
if (event.detail === 2) openRow(row);
return; function executeRowAction(row: ObjectBrowserRow, action: ObjectBrowserRowAction) {
switch (action) {
case "table-info":
void openTableInfo(row);
break;
case "open-table":
emit("openTable", { tableName: row.name, schema: row.schema });
break;
case "open-source":
void openSource(row);
break;
} }
if (event.detail > 1) return;
openRow(row);
} }
function openRow(row: ObjectBrowserRow) { function onRowClick(row: ObjectBrowserRow, event: MouseEvent) {
if (row.type === "TABLE") { const activation = settingsStore.editorSettings.sidebarActivation;
emit("openTable", { tableName: row.name, schema: row.schema }); const { action, isDouble } = resolveRowClickAction(row, event.detail, activation);
// Double click: cancel any pending single-click and fire immediately
if (isDouble) {
if (singleClickTimer) {
clearTimeout(singleClickTimer);
singleClickTimer = null;
}
executeRowAction(row, action);
return; return;
} }
if (canOpenSource(row)) { // Single click: defer when the row has a distinct double-click action so a
void openSource(row); // following second click can cancel it (e.g. TABLE single→table-info, double→open-table).
if (shouldDeferSingleClick(row, action, activation)) {
if (singleClickTimer) clearTimeout(singleClickTimer);
singleClickTimer = setTimeout(() => {
singleClickTimer = null;
executeRowAction(row, action);
}, SINGLE_CLICK_DELAY);
return;
} }
executeRowAction(row, action);
}
// --- Table info panel (replicates DataGrid table-info-drawer) ---
type TableInfoTabItem = { id: TableInfoTab; label: string; icon: Component; count?: number };
const tableInfoTabs = computed<TableInfoTabItem[]>(() => {
const tabs: TableInfoTabItem[] = [];
if (tableMetadataCapabilities.value.ddl) {
tabs.push({ id: "ddl", label: "DDL", icon: Code2 });
}
if (tableMetadataCapabilities.value.columns) {
tabs.push({ id: "columns", label: t("grid.tableInfoColumns"), icon: ListTree, count: tableColumns.value.length });
}
if (tableMetadataCapabilities.value.indexes) {
tabs.push({ id: "indexes", label: t("grid.tableInfoIndexes"), icon: KeyRound, count: tableIndexes.value.length });
}
if (tableMetadataCapabilities.value.foreignKeys) {
tabs.push({ id: "foreignKeys", label: t("grid.tableInfoForeignKeys"), icon: Link2, count: tableForeignKeys.value.length });
}
if (tableMetadataCapabilities.value.triggers) {
tabs.push({ id: "triggers", label: t("grid.tableInfoTriggers"), icon: RotateCcw, count: tableTriggers.value.length });
}
return tabs;
});
const tableInfoTabListStyle = computed(() => ({
gridTemplateColumns: `repeat(${tableInfoTabs.value.length}, minmax(0, 1fr))`,
}));
const filteredTableColumns = computed(() => {
if (!tableInfoSearchQuery.value) return tableColumns.value;
const q = tableInfoSearchQuery.value.toLowerCase();
return tableColumns.value.filter((c) => c.name.toLowerCase().includes(q) || c.data_type.toLowerCase().includes(q));
});
const filteredTableIndexes = computed(() => {
if (!tableInfoSearchQuery.value) return tableIndexes.value;
const q = tableInfoSearchQuery.value.toLowerCase();
return tableIndexes.value.filter((i) => i.name.toLowerCase().includes(q) || i.columns.some((c) => c.toLowerCase().includes(q)));
});
const filteredTableForeignKeys = computed(() => {
if (!tableInfoSearchQuery.value) return tableForeignKeys.value;
const q = tableInfoSearchQuery.value.toLowerCase();
return tableForeignKeys.value.filter((fk) => fk.name.toLowerCase().includes(q) || fk.column.toLowerCase().includes(q) || fk.ref_table.toLowerCase().includes(q) || fk.ref_column.toLowerCase().includes(q));
});
const filteredTableTriggers = computed(() => {
if (!tableInfoSearchQuery.value) return tableTriggers.value;
const q = tableInfoSearchQuery.value.toLowerCase();
return tableTriggers.value.filter((tr) => tr.name.toLowerCase().includes(q));
});
const filteredTableDdlContent = computed(() => {
if (!tableDdlContent.value) return "";
const html = highlight(tableDdlContent.value);
if (!tableInfoSearchQuery.value) return html;
const escaped = tableInfoSearchQuery.value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const regex = new RegExp(`(${escaped})`, "gi");
return html.replace(/>([^<]*)</g, (_, text) => {
return `>${text.replace(regex, "<mark>$1</mark>")}<`;
});
});
async function openTableInfo(row: ObjectBrowserRow) {
// Toggle off if clicking the same table
if (sidePanelRow.value?.id === row.id && sidePanelMode.value === "table-info") {
closeSidePanel();
return;
}
sidePanelRow.value = row;
sidePanelMode.value = "table-info";
sidePanelGuard.bump();
// Reset state
tableColumns.value = [];
tableDdlContent.value = "";
tableIndexes.value = [];
tableForeignKeys.value = [];
tableTriggers.value = [];
tableInfoSearchQuery.value = "";
// Determine first available tab
const firstTab = tableInfoTabs.value[0]?.id ?? "ddl";
await selectTableInfoTab(firstTab);
}
async function selectTableInfoTab(tab: TableInfoTab) {
const nextTab = tableInfoTabs.value.some((item) => item.id === tab) ? tab : tableInfoTabs.value[0]?.id;
if (!nextTab) return;
tableInfoTab.value = nextTab;
tableInfoSearchQuery.value = "";
if (nextTab === "ddl") await fetchTableDdl();
else if (nextTab === "columns") await fetchTableColumns();
else if (nextTab === "indexes") await fetchTableIndexes();
else if (nextTab === "foreignKeys") await fetchTableForeignKeys();
else if (nextTab === "triggers") await fetchTableTriggers();
}
async function fetchTableDdl() {
const row = sidePanelRow.value;
if (!row) return;
const epoch = sidePanelGuard.capture();
tableDdlLoading.value = true;
try {
const schema = row.schema || selectedSchema.value || props.database;
const ddl = await api.getTableDdl(props.connection.id, props.database || "", schema, row.name);
if (sidePanelGuard.isStale(epoch)) return;
tableDdlContent.value = ddl;
} catch (e: any) {
if (sidePanelGuard.isStale(epoch)) return;
tableDdlContent.value = `-- Error: ${e?.message || e}`;
} finally {
if (sidePanelGuard.isFresh(epoch)) tableDdlLoading.value = false;
}
}
async function fetchTableColumns() {
const row = sidePanelRow.value;
if (!row || tableColumns.value.length > 0) return;
const epoch = sidePanelGuard.capture();
tableColumnsLoading.value = true;
try {
const schema = row.schema || selectedSchema.value || props.database;
const columns = await api.getColumns(props.connection.id, props.database || "", schema, row.name);
if (sidePanelGuard.isStale(epoch)) return;
tableColumns.value = columns;
} catch {
if (sidePanelGuard.isStale(epoch)) return;
tableColumns.value = [];
} finally {
if (sidePanelGuard.isFresh(epoch)) tableColumnsLoading.value = false;
}
}
async function fetchTableIndexes() {
const row = sidePanelRow.value;
if (!row || tableIndexes.value.length > 0) return;
const epoch = sidePanelGuard.capture();
tableIndexesLoading.value = true;
try {
const schema = row.schema || selectedSchema.value || props.database;
const indexes = await api.listIndexes(props.connection.id, props.database || "", schema, row.name);
if (sidePanelGuard.isStale(epoch)) return;
tableIndexes.value = indexes;
} catch {
if (sidePanelGuard.isStale(epoch)) return;
tableIndexes.value = [];
} finally {
if (sidePanelGuard.isFresh(epoch)) tableIndexesLoading.value = false;
}
}
async function fetchTableForeignKeys() {
const row = sidePanelRow.value;
if (!row || tableForeignKeys.value.length > 0) return;
const epoch = sidePanelGuard.capture();
tableForeignKeysLoading.value = true;
try {
const schema = row.schema || selectedSchema.value || props.database;
const fks = await api.listForeignKeys(props.connection.id, props.database || "", schema, row.name);
if (sidePanelGuard.isStale(epoch)) return;
tableForeignKeys.value = fks;
} catch {
if (sidePanelGuard.isStale(epoch)) return;
tableForeignKeys.value = [];
} finally {
if (sidePanelGuard.isFresh(epoch)) tableForeignKeysLoading.value = false;
}
}
async function fetchTableTriggers() {
const row = sidePanelRow.value;
if (!row || tableTriggers.value.length > 0) return;
const epoch = sidePanelGuard.capture();
tableTriggersLoading.value = true;
try {
const schema = row.schema || selectedSchema.value || props.database;
const triggers = await api.listTriggers(props.connection.id, props.database || "", schema, row.name);
if (sidePanelGuard.isStale(epoch)) return;
tableTriggers.value = triggers;
} catch {
if (sidePanelGuard.isStale(epoch)) return;
tableTriggers.value = [];
} finally {
if (sidePanelGuard.isFresh(epoch)) tableTriggersLoading.value = false;
}
}
function copyTableDdl() {
void copyToClipboard(tableDdlContent.value);
toast(t("grid.copyDdl"), 2000);
}
function onTableInfoDdlKeydown(e: KeyboardEvent) {
if ((e.ctrlKey || e.metaKey) && e.key === "a") {
e.preventDefault();
const el = tableInfoDdlPreRef.value;
if (!el) return;
const range = document.createRange();
range.selectNodeContents(el);
const sel = window.getSelection();
sel?.removeAllRanges();
sel?.addRange(range);
}
}
// --- Side panel resize ---
function onSidePanelResizeStart(event: MouseEvent) {
isResizingSidePanel.value = true;
sidePanelResizeStartX = event.clientX;
sidePanelResizeStartWidth = sidePanelWidth.value;
window.addEventListener("mousemove", onSidePanelResizeMove);
window.addEventListener("mouseup", onSidePanelResizeEnd);
}
function onSidePanelResizeMove(event: MouseEvent) {
if (!isResizingSidePanel.value) return;
const delta = sidePanelResizeStartX - event.clientX;
const next = Math.min(SIDE_PANEL_MAX_WIDTH, Math.max(SIDE_PANEL_MIN_WIDTH, sidePanelResizeStartWidth + delta));
sidePanelWidth.value = next;
}
function onSidePanelResizeEnd() {
isResizingSidePanel.value = false;
window.removeEventListener("mousemove", onSidePanelResizeMove);
window.removeEventListener("mouseup", onSidePanelResizeEnd);
settingsStore.updateEditorSettings({ tableInfoDrawerWidth: sidePanelWidth.value });
}
function closeSidePanel() {
sidePanelRow.value = null;
sidePanelMode.value = "source";
sidePanelGuard.bump();
}
const canOpenTableStructureEditor = computed(() => sidePanelRow.value?.type === "TABLE" && canOpenStructureEditor.value);
function openTableStructureEditor() {
const row = sidePanelRow.value;
if (!row || row.type !== "TABLE" || !canOpenTableStructureEditor.value) return;
queryStore.openTableStructure(props.connection.id, props.database, row.schema || selectedSchema.value, row.name, tableInfoTab.value);
} }
async function openSource(row: ObjectBrowserRow) { async function openSource(row: ObjectBrowserRow) {
// Toggle off if clicking the same source row
if (sidePanelRow.value?.id === row.id && sidePanelMode.value === "source") {
closeSidePanel();
return;
}
// Starting a different object must invalidate slower source requests before
// any state is reset, otherwise an old response can populate the new row.
const epoch = sidePanelGuard.start();
sidePanelRow.value = row;
sidePanelMode.value = "source";
sourceRow.value = row; sourceRow.value = row;
sourceContent.value = ""; sourceContent.value = "";
sourceError.value = ""; sourceError.value = "";
@@ -694,27 +1006,35 @@ async function openSource(row: ObjectBrowserRow) {
sourceDraft.value = ""; sourceDraft.value = "";
sourceSaveError.value = ""; sourceSaveError.value = "";
sourceLoading.value = true; sourceLoading.value = true;
const connectionId = props.connection.id;
const database = props.database;
const schema = row.schema || selectedSchema.value || database;
try { try {
const result = await api.getObjectSource(props.connection.id, props.database, row.schema || selectedSchema.value || props.database, row.name, row.type as ObjectSourceKind); const result = await api.getObjectSource(connectionId, database, schema, row.name, row.type as ObjectSourceKind);
if (sidePanelGuard.isStale(epoch)) return;
sourceCanEdit.value = result.editable !== false && row.type !== "SEQUENCE"; sourceCanEdit.value = result.editable !== false && row.type !== "SEQUENCE";
const editable = await api.buildEditableObjectSource({ const editable = await api.buildEditableObjectSource({
databaseType: effectiveDatabaseType.value, databaseType: effectiveDatabaseType.value,
objectType: row.type as ObjectSourceKind, objectType: row.type as ObjectSourceKind,
schema: row.schema || selectedSchema.value || props.database, schema,
name: row.name, name: row.name,
source: result.source, source: result.source,
}); });
if (sidePanelGuard.isStale(epoch)) return;
const formatted = await formatSqlForDisplay(editable, sourceFormatDialect.value, settingsStore.editorSettings.sqlFormatter);
if (sidePanelGuard.isStale(epoch)) return;
sourceEditableText.value = editable; sourceEditableText.value = editable;
sourceContent.value = await formatSqlForDisplay(editable, sourceFormatDialect.value, settingsStore.editorSettings.sqlFormatter); sourceContent.value = formatted;
sourceDraft.value = editable; sourceDraft.value = editable;
sourceEditing.value = sourceCanEdit.value; sourceEditing.value = sourceCanEdit.value;
if (!sourceCanEdit.value && row.type !== "SEQUENCE") { if (!sourceCanEdit.value && row.type !== "SEQUENCE") {
toast(t("objects.sourceReadOnly"), 3000); toast(t("objects.sourceReadOnly"), 3000);
} }
} catch (e: any) { } catch (e: any) {
if (sidePanelGuard.isStale(epoch)) return;
sourceError.value = e?.message || String(e); sourceError.value = e?.message || String(e);
} finally { } finally {
sourceLoading.value = false; if (sidePanelGuard.isFresh(epoch)) sourceLoading.value = false;
} }
} }
@@ -908,6 +1228,7 @@ function dropConfirmMessage(): string {
function closeSource() { function closeSource() {
sourceRow.value = null; sourceRow.value = null;
sidePanelRow.value = null;
sourceContent.value = ""; sourceContent.value = "";
sourceError.value = ""; sourceError.value = "";
sourceEditing.value = false; sourceEditing.value = false;
@@ -1529,7 +1850,10 @@ async function saveSource() {
} }
if (!sourceRow.value || !sourceDraft.value.trim()) return; if (!sourceRow.value || !sourceDraft.value.trim()) return;
const row = sourceRow.value; const row = sourceRow.value;
const schema = row.schema || selectedSchema.value || props.database; const epoch = sidePanelGuard.capture();
const connectionId = props.connection.id;
const database = props.database;
const schema = row.schema || selectedSchema.value || database;
sourceSaving.value = true; sourceSaving.value = true;
sourceSaveError.value = ""; sourceSaveError.value = "";
try { try {
@@ -1540,15 +1864,17 @@ async function saveSource() {
name: row.name, name: row.name,
source: sourceDraft.value, source: sourceDraft.value,
}); });
await executeObjectSourceSave(props.connection.id, props.database, effectiveDatabaseType.value, statements, schema); await executeObjectSourceSave(connectionId, database, effectiveDatabaseType.value, statements, schema);
if (sidePanelGuard.isStale(epoch)) return;
toast(t("objects.sourceSaved")); toast(t("objects.sourceSaved"));
sourceEditing.value = false; sourceEditing.value = false;
sourceDraft.value = ""; sourceDraft.value = "";
await openSource(row); await openSource(row);
} catch (e: any) { } catch (e: any) {
if (sidePanelGuard.isStale(epoch)) return;
sourceSaveError.value = e?.message || String(e); sourceSaveError.value = e?.message || String(e);
} finally { } finally {
sourceSaving.value = false; if (sidePanelGuard.isFresh(epoch)) sourceSaving.value = false;
} }
} }
@@ -1714,6 +2040,15 @@ watch(
userHasSelectedFilter.value = false; userHasSelectedFilter.value = false;
objectFilter.value = "all"; objectFilter.value = "all";
clearTableSelection(); clearTableSelection();
// Close side panel and invalidate any pending source/table-info requests
// so stale results from the old context don't overwrite new state.
closeSidePanel();
sourceRow.value = null;
sourceContent.value = "";
sourceError.value = "";
sourceLoading.value = false;
sourceEditing.value = false;
sourceSaving.value = false;
try { try {
await connectionStore.ensureConnected(props.connection.id); await connectionStore.ensureConnected(props.connection.id);
} catch (e) { } catch (e) {
@@ -1741,7 +2076,7 @@ function exportDataSubmenu(item: ObjectBrowserRow): ContextMenuItem {
function getTableMenuItems(item: ObjectBrowserRow): ContextMenuItem[] { function getTableMenuItems(item: ObjectBrowserRow): ContextMenuItem[] {
return [ return [
{ label: t("contextMenu.viewData"), action: () => openRow(item), icon: Table2 }, { label: t("contextMenu.viewData"), action: () => openViewData(item), icon: Table2 },
{ {
label: t("contextMenu.viewDdl"), label: t("contextMenu.viewDdl"),
action: () => { action: () => {
@@ -1977,7 +2312,8 @@ function getObjectBrowserMenuItems(item: ObjectBrowserRow): ContextMenuItem[] {
<div v-else-if="filteredRows.length === 0" class="flex flex-1 items-center justify-center text-sm text-muted-foreground"> <div v-else-if="filteredRows.length === 0" class="flex flex-1 items-center justify-center text-sm text-muted-foreground">
{{ t("objects.empty") }} {{ t("objects.empty") }}
</div> </div>
<div v-else class="flex min-h-0 min-w-0 flex-1 flex-col"> <div v-else class="flex min-h-0 min-w-0 flex-1">
<div class="flex min-h-0 min-w-0 flex-1 flex-col">
<div v-if="isListView" class="object-browser-table flex min-h-0 min-w-0 flex-1 flex-col overflow-x-auto overflow-y-hidden"> <div v-if="isListView" class="object-browser-table flex min-h-0 min-w-0 flex-1 flex-col overflow-x-auto overflow-y-hidden">
<div class="grid h-7 shrink-0 items-center gap-3 border-b bg-muted/40 px-3 text-xs font-medium text-muted-foreground" :style="{ gridTemplateColumns, minWidth: `${objectGridMinWidth}px` }"> <div class="grid h-7 shrink-0 items-center gap-3 border-b bg-muted/40 px-3 text-xs font-medium text-muted-foreground" :style="{ gridTemplateColumns, minWidth: `${objectGridMinWidth}px` }">
<div v-if="showCheckboxColumn" class="relative flex min-w-0 items-center"> <div v-if="showCheckboxColumn" class="relative flex min-w-0 items-center">
@@ -2064,7 +2400,11 @@ function getObjectBrowserMenuItems(item: ObjectBrowserRow): ContextMenuItem[] {
<span class="truncate">{{ t("objects.comment") }}</span> <span class="truncate">{{ t("objects.comment") }}</span>
<component :is="sortIconFor('comment')" v-if="sortIconFor('comment')" class="h-3 w-3 shrink-0" /> <component :is="sortIconFor('comment')" v-if="sortIconFor('comment')" class="h-3 w-3 shrink-0" />
</button> </button>
<div class="absolute -right-2 top-0 bottom-0 z-10 flex w-3 cursor-col-resize items-center justify-center text-muted-foreground/70 hover:bg-primary/30 hover:text-primary" @mousedown="onObjectColumnResizeStart('comment', $event)" @dblclick="resetObjectColumnWidth('comment', 260, $event)"> <div
class="absolute -right-2 top-0 bottom-0 z-10 flex w-3 cursor-col-resize items-center justify-center text-muted-foreground/70 hover:bg-primary/30 hover:text-primary"
@mousedown="onObjectColumnResizeStart('comment', $event)"
@dblclick="resetObjectColumnWidth('comment', 260, $event)"
>
<GripVertical class="h-3 w-3" /> <GripVertical class="h-3 w-3" />
</div> </div>
</div> </div>
@@ -2167,7 +2507,166 @@ function getObjectBrowserMenuItems(item: ObjectBrowserRow): ContextMenuItem[] {
</template> </template>
</RecycleScroller> </RecycleScroller>
</div> </div>
<div v-if="sourceRow" class="flex h-[42%] min-h-44 shrink-0 flex-col border-t bg-background"> </div>
<!-- Right-side panel: table info or source -->
<div v-if="sidePanelRow" class="object-browser-side-panel relative flex min-h-0 shrink-0 flex-col border-l bg-background" :class="{ 'side-panel-resizing': isResizingSidePanel }" :style="{ width: `${sidePanelWidth}px` }">
<div class="absolute left-0 top-0 bottom-0 z-20 w-1.5 -translate-x-1/2 cursor-col-resize hover:bg-primary/30" @mousedown.prevent="onSidePanelResizeStart" />
<!-- Table info mode -->
<template v-if="sidePanelMode === 'table-info'">
<div class="flex items-center gap-2 px-3 py-1.5 border-b shrink-0 bg-muted/20 h-9">
<TableProperties class="w-3.5 h-3.5 text-muted-foreground" />
<span class="text-xs font-medium flex-1 min-w-0 truncate">{{ sidePanelRow?.name }}</span>
<div v-if="tableInfoTab === 'ddl'" class="table-info-actions flex min-w-0 shrink-0 items-center gap-1">
<Button variant="ghost" size="sm" class="table-info-action-button h-6 px-2 text-xs" :title="t('grid.copyDdl')" :aria-label="t('grid.copyDdl')" @click="copyTableDdl">
<Copy class="w-3 h-3" />
<span class="table-info-action-label">{{ t("grid.copyDdl") }}</span>
</Button>
<Button variant="ghost" size="icon" class="h-6 w-6" :class="{ 'bg-accent': tableInfoWrap }" @click="tableInfoWrap = !tableInfoWrap">
<WrapText class="w-3 h-3" />
</Button>
</div>
<Button v-if="canOpenTableStructureEditor" variant="ghost" size="sm" class="table-info-action-button h-6 px-2 text-xs" :title="t('contextMenu.editStructure')" :aria-label="t('contextMenu.editStructure')" @click="openTableStructureEditor">
<Columns3Cog class="w-3 h-3" />
<span class="table-info-action-label">{{ t("contextMenu.editStructure") }}</span>
</Button>
<Button variant="ghost" size="icon" class="h-5 w-5" @click="closeSidePanel">
<X class="w-3 h-3" />
</Button>
</div>
<div class="grid border-b bg-background shrink-0" :style="tableInfoTabListStyle">
<button
v-for="tab in tableInfoTabs"
:key="tab.id"
class="h-9 min-w-0 px-1.5 text-[11px] border-b-2 transition-colors"
:class="tableInfoTab === tab.id ? 'border-primary bg-gray-300/80 text-foreground dark:bg-gray-700/80' : 'border-transparent text-muted-foreground hover:bg-gray-200 hover:text-foreground dark:hover:bg-gray-800/50'"
:title="tab.label"
@click="selectTableInfoTab(tab.id)"
>
<component :is="tab.icon" class="mx-auto h-3.5 w-3.5" />
<span class="block truncate">{{ tab.label }}</span>
</button>
</div>
<div class="px-2 py-1.5 border-b shrink-0 bg-background">
<div class="relative">
<Search class="absolute left-2 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-muted-foreground" />
<input v-model="tableInfoSearchQuery" :placeholder="t('grid.tableInfoSearch')" class="w-full h-7 pl-7 pr-6 text-xs bg-muted/50 rounded border border-border focus:outline-none focus:border-primary/50" @keydown.escape="tableInfoSearchQuery = ''" />
<button v-if="tableInfoSearchQuery" class="absolute right-1.5 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground" @click="tableInfoSearchQuery = ''">
<X class="w-3 h-3" />
</button>
</div>
</div>
<div v-if="tableInfoTab === 'columns'" class="flex-1 min-h-0 overflow-auto">
<div v-if="tableColumnsLoading" class="h-full flex items-center justify-center">
<Loader2 class="w-4 h-4 animate-spin text-muted-foreground" />
</div>
<div v-else-if="tableInfoSearchQuery && filteredTableColumns.length === 0" class="p-6 text-center text-xs text-muted-foreground">
{{ t("grid.tableInfoNoResults") }}
</div>
<table v-else class="w-full text-xs">
<thead class="sticky top-0 bg-muted text-muted-foreground">
<tr class="border-b">
<th class="text-left text-nowrap font-medium px-3 py-2 w-8">#</th>
<th class="text-left text-nowrap font-medium px-3 py-2">{{ t("grid.columnName") }}</th>
<th class="text-left text-nowrap font-medium px-3 py-2">{{ t("grid.columnType") }}</th>
<th class="text-left text-nowrap font-medium px-3 py-2">{{ t("grid.tableInfoNullable") }}</th>
</tr>
</thead>
<tbody>
<tr v-for="(column, index) in filteredTableColumns" :key="column.name" class="border-b hover:bg-gray-200 dark:hover:bg-gray-800/30" :title="column.name">
<td class="px-3 py-2 text-muted-foreground w-8">{{ index + 1 }}</td>
<td class="px-3 py-2 font-medium">
<span class="inline-flex items-center gap-1.5">
<KeyRound v-if="column.is_primary_key" class="h-3 w-3 text-amber-500" />
{{ column.name }}
</span>
<div v-if="column.comment" class="mt-0.5 text-[11px] text-muted-foreground truncate">
{{ column.comment }}
</div>
</td>
<td class="px-3 py-2 font-mono text-[11px] text-muted-foreground">{{ column.data_type }}</td>
<td class="px-3 py-2">{{ column.is_nullable ? "YES" : "NO" }}</td>
</tr>
</tbody>
</table>
</div>
<div v-else-if="tableInfoTab === 'indexes'" class="flex-1 min-h-0 overflow-auto">
<div v-if="tableIndexesLoading" class="h-full flex items-center justify-center">
<Loader2 class="w-4 h-4 animate-spin text-muted-foreground" />
</div>
<div v-else-if="tableInfoSearchQuery && filteredTableIndexes.length === 0" class="p-6 text-center text-xs text-muted-foreground">
{{ t("grid.tableInfoNoResults") }}
</div>
<div v-else-if="tableIndexes.length === 0" class="p-6 text-center text-xs text-muted-foreground">
{{ t("grid.tableInfoEmpty") }}
</div>
<div v-else class="divide-y">
<div v-for="index in filteredTableIndexes" :key="index.name" class="p-3 text-xs">
<div class="flex items-start gap-2">
<div class="min-w-0 flex-1">
<div class="font-medium truncate">{{ index.name }}</div>
<div class="mt-1 flex flex-wrap gap-1">
<span v-if="index.is_primary" class="rounded bg-amber-500/10 px-1.5 py-0.5 text-amber-600">PK</span>
<span v-if="index.is_unique" class="rounded bg-emerald-500/10 px-1.5 py-0.5 text-emerald-600">UNIQUE</span>
<span v-if="index.index_type" class="rounded bg-muted px-1.5 py-0.5 text-muted-foreground">{{ index.index_type }}</span>
</div>
<div class="mt-2 font-mono text-[11px] text-muted-foreground break-all">
{{ index.columns.join(", ") }}
</div>
</div>
</div>
</div>
</div>
</div>
<div v-else-if="tableInfoTab === 'foreignKeys'" class="flex-1 min-h-0 overflow-auto">
<div v-if="tableForeignKeysLoading" class="h-full flex items-center justify-center">
<Loader2 class="w-4 h-4 animate-spin text-muted-foreground" />
</div>
<div v-else-if="tableInfoSearchQuery && filteredTableForeignKeys.length === 0" class="p-6 text-center text-xs text-muted-foreground">
{{ t("grid.tableInfoNoResults") }}
</div>
<div v-else-if="tableForeignKeys.length === 0" class="p-6 text-center text-xs text-muted-foreground">
{{ t("grid.tableInfoEmpty") }}
</div>
<div v-else class="divide-y">
<div v-for="fk in filteredTableForeignKeys" :key="`${fk.name}:${fk.column}`" class="p-3 text-xs">
<div class="font-medium truncate">{{ fk.name }}</div>
<div class="mt-1 font-mono text-[11px] text-muted-foreground break-all">{{ fk.column }} -> {{ fk.ref_table }}.{{ fk.ref_column }}</div>
</div>
</div>
</div>
<div v-else-if="tableInfoTab === 'triggers'" class="flex-1 min-h-0 overflow-auto">
<div v-if="tableTriggersLoading" class="h-full flex items-center justify-center">
<Loader2 class="w-4 h-4 animate-spin text-muted-foreground" />
</div>
<div v-else-if="tableInfoSearchQuery && filteredTableTriggers.length === 0" class="p-6 text-center text-xs text-muted-foreground">
{{ t("grid.tableInfoNoResults") }}
</div>
<div v-else-if="tableTriggers.length === 0" class="p-6 text-center text-xs text-muted-foreground">
{{ t("grid.tableInfoEmpty") }}
</div>
<div v-else class="divide-y">
<div v-for="trigger in filteredTableTriggers" :key="trigger.name" class="p-3 text-xs">
<div class="font-medium truncate">{{ trigger.name }}</div>
<div class="mt-1 text-[11px] text-muted-foreground">{{ trigger.timing }} {{ trigger.event }}</div>
</div>
</div>
</div>
<pre
v-else-if="tableInfoTab === 'ddl' && !tableDdlLoading"
ref="tableInfoDdlPreRef"
data-native-clipboard
tabindex="0"
class="flex-1 min-w-0 text-xs font-mono p-3 overflow-auto ddl-code leading-5 select-text outline-none"
:class="tableInfoWrap ? 'whitespace-pre-wrap break-words' : 'whitespace-pre'"
v-html="filteredTableDdlContent"
@keydown="onTableInfoDdlKeydown"
></pre>
<div v-else class="flex-1 flex items-center justify-center">
<Loader2 class="w-4 h-4 animate-spin text-muted-foreground" />
</div>
</template>
<!-- Source mode (views, procedures, functions, sequences) -->
<template v-else>
<div class="flex h-8 shrink-0 items-center gap-2 border-b bg-muted/20 px-3"> <div class="flex h-8 shrink-0 items-center gap-2 border-b bg-muted/20 px-3">
<Code2 class="h-3.5 w-3.5 text-muted-foreground" /> <Code2 class="h-3.5 w-3.5 text-muted-foreground" />
<span class="min-w-0 flex-1 truncate text-xs font-medium">{{ sourceTitle(sourceRow) }}</span> <span class="min-w-0 flex-1 truncate text-xs font-medium">{{ sourceTitle(sourceRow) }}</span>
@@ -2195,14 +2694,25 @@ function getObjectBrowserMenuItems(item: ObjectBrowserRow): ContextMenuItem[] {
{{ sourceError }} {{ sourceError }}
</div> </div>
<div v-else-if="sourceEditing" class="flex min-h-0 flex-1 flex-col" data-object-source-editor> <div v-else-if="sourceEditing" class="flex min-h-0 flex-1 flex-col" data-object-source-editor>
<QueryEditor v-model="sourceDraft" class="min-h-0 flex-1" :connection-id="props.connection.id" :database="props.database" :schema="selectedSchema" :database-type="props.connection.db_type" :dialect="sourceDialect" :format-dialect="sourceFormatDialect" force-word-wrap @save="saveSource" /> <QueryEditor
v-model="sourceDraft"
class="min-h-0 flex-1"
:connection-id="props.connection.id"
:database="props.database"
:schema="selectedSchema"
:database-type="props.connection.db_type"
:dialect="sourceDialect"
:format-dialect="sourceFormatDialect"
force-word-wrap
@save="saveSource"
/>
<div v-if="sourceSaveError" class="shrink-0 border-t px-3 py-2 text-xs text-destructive"> <div v-if="sourceSaveError" class="shrink-0 border-t px-3 py-2 text-xs text-destructive">
{{ sourceSaveError }} {{ sourceSaveError }}
</div> </div>
</div> </div>
<QueryEditor <QueryEditor
v-else v-else
:key="`source-preview-${sourceRow.id}`" :key="`source-preview-${sourceRow?.id}`"
:model-value="sourceContent" :model-value="sourceContent"
class="min-h-0 flex-1" class="min-h-0 flex-1"
:connection-id="props.connection.id" :connection-id="props.connection.id"
@@ -2215,6 +2725,7 @@ function getObjectBrowserMenuItems(item: ObjectBrowserRow): ContextMenuItem[] {
read-only read-only
data-object-source-preview data-object-source-preview
/> />
</template>
</div> </div>
</div> </div>
</div> </div>
@@ -2410,4 +2921,50 @@ function getObjectBrowserMenuItems(item: ObjectBrowserRow): ContextMenuItem[] {
column-gap: 12px; column-gap: 12px;
align-items: start; align-items: start;
} }
.side-panel-resizing {
user-select: none;
pointer-events: none;
}
.ddl-code {
container-type: inline-size;
}
.object-browser-side-panel {
container-type: inline-size;
}
.table-info-action-button {
gap: 0.25rem;
max-width: 8rem;
overflow: hidden;
transition:
max-width 180ms ease,
padding-inline 180ms ease;
}
.table-info-action-label {
min-width: 0;
max-width: 6rem;
overflow: hidden;
white-space: nowrap;
opacity: 1;
transition:
max-width 180ms ease,
opacity 120ms ease;
}
@container (max-width: 360px) {
.table-info-action-button {
width: 1.5rem;
max-width: 1.5rem;
padding-inline: 0;
}
.table-info-action-label {
max-width: 0;
opacity: 0;
}
}
</style> </style>
@@ -0,0 +1,145 @@
import { describe, expect, it } from "vitest";
import { doubleClickRowAction, resolveRowClickAction, shouldDeferSingleClick, singleClickRowAction, type ObjectBrowserRowAction } from "@/lib/table/objectBrowserRowAction";
import type { ObjectBrowserRow } from "@/lib/table/objectBrowserRows";
function row(type: ObjectBrowserRow["type"], name = "test"): ObjectBrowserRow {
return { id: `${type}-${name}`, name, displayName: name, type };
}
describe("singleClickRowAction", () => {
it("returns table-info for TABLE", () => {
expect(singleClickRowAction(row("TABLE", "users"))).toBe("table-info");
});
it("returns open-source for VIEW", () => {
expect(singleClickRowAction(row("VIEW", "v_users"))).toBe("open-source");
});
it("returns open-source for PROCEDURE", () => {
expect(singleClickRowAction(row("PROCEDURE", "sp_test"))).toBe("open-source");
});
it("returns open-source for FUNCTION", () => {
expect(singleClickRowAction(row("FUNCTION", "fn_test"))).toBe("open-source");
});
it("returns open-source for SEQUENCE", () => {
expect(singleClickRowAction(row("SEQUENCE", "seq_test"))).toBe("open-source");
});
it("returns open-source for MATERIALIZED_VIEW", () => {
expect(singleClickRowAction(row("MATERIALIZED_VIEW", "mv_test"))).toBe("open-source");
});
it("returns open-source for PACKAGE", () => {
expect(singleClickRowAction(row("PACKAGE", "pkg_test"))).toBe("open-source");
});
it("returns open-source for PACKAGE_BODY", () => {
expect(singleClickRowAction(row("PACKAGE_BODY", "pkg_body_test"))).toBe("open-source");
});
it("returns none for null/undefined", () => {
expect(singleClickRowAction(null)).toBe("none");
expect(singleClickRowAction(undefined)).toBe("none");
});
});
describe("doubleClickRowAction", () => {
it("returns open-table for TABLE", () => {
expect(doubleClickRowAction(row("TABLE", "orders"))).toBe("open-table");
});
it("returns open-source for VIEW", () => {
expect(doubleClickRowAction(row("VIEW", "v_orders"))).toBe("open-source");
});
it("returns open-source for PROCEDURE", () => {
expect(doubleClickRowAction(row("PROCEDURE", "sp_run"))).toBe("open-source");
});
it("returns none for null/undefined", () => {
expect(doubleClickRowAction(null)).toBe("none");
});
});
describe("resolveRowClickAction", () => {
const tableRow = row("TABLE", "users");
const viewRow = row("VIEW", "v_users");
describe("single-click activation mode", () => {
it("single click on TABLE returns table-info", () => {
const result = resolveRowClickAction(tableRow, 1, "single");
expect(result.action).toBe("table-info");
expect(result.isDouble).toBe(false);
});
it("double click on TABLE returns open-table", () => {
const result = resolveRowClickAction(tableRow, 2, "single");
expect(result.action).toBe("open-table");
expect(result.isDouble).toBe(true);
});
it("single click on VIEW returns open-source", () => {
const result = resolveRowClickAction(viewRow, 1, "single");
expect(result.action).toBe("open-source");
expect(result.isDouble).toBe(false);
});
it("double click on VIEW returns open-source", () => {
const result = resolveRowClickAction(viewRow, 2, "single");
expect(result.action).toBe("open-source");
expect(result.isDouble).toBe(true);
});
});
describe("double-click activation mode", () => {
it("single click (detail=1) returns none", () => {
const result = resolveRowClickAction(tableRow, 1, "double");
expect(result.action).toBe("none");
expect(result.isDouble).toBe(false);
});
it("double click on TABLE returns open-table", () => {
const result = resolveRowClickAction(tableRow, 2, "double");
expect(result.action).toBe("open-table");
expect(result.isDouble).toBe(true);
});
it("double click on VIEW returns open-source", () => {
const result = resolveRowClickAction(viewRow, 2, "double");
expect(result.action).toBe("open-source");
expect(result.isDouble).toBe(true);
});
});
});
describe("shouldDeferSingleClick", () => {
const tableRow = row("TABLE", "users");
const viewRow = row("VIEW", "v_users");
it("defers TABLE table-info in single mode (distinct single/double actions)", () => {
expect(shouldDeferSingleClick(tableRow, "table-info", "single")).toBe(true);
});
it("does not defer VIEW open-source in single mode (same single/double action)", () => {
expect(shouldDeferSingleClick(viewRow, "open-source", "single")).toBe(false);
});
it("does not defer in double activation mode", () => {
expect(shouldDeferSingleClick(tableRow, "table-info", "double")).toBe(false);
});
it("does not defer none action", () => {
expect(shouldDeferSingleClick(tableRow, "none", "single")).toBe(false);
});
it("does not defer when action is not the single-click action", () => {
expect(shouldDeferSingleClick(tableRow, "open-table", "single")).toBe(false);
});
it("handles null/undefined row", () => {
expect(shouldDeferSingleClick(null, "table-info", "single")).toBe(false);
expect(shouldDeferSingleClick(undefined, "open-source", "single")).toBe(false);
});
});
@@ -0,0 +1,59 @@
import { describe, expect, it } from "vitest";
import { createSidePanelRequestGuard } from "@/lib/table/sidePanelRequestGuard";
describe("SidePanelRequestGuard", () => {
it("fresh capture is not stale", () => {
const guard = createSidePanelRequestGuard();
const epoch = guard.capture();
expect(guard.isStale(epoch)).toBe(false);
expect(guard.isFresh(epoch)).toBe(true);
});
it("bump invalidates previously captured epoch", () => {
const guard = createSidePanelRequestGuard();
const epoch = guard.capture();
guard.bump();
expect(guard.isStale(epoch)).toBe(true);
expect(guard.isFresh(epoch)).toBe(false);
});
it("multiple bumps invalidate all previous epochs", () => {
const guard = createSidePanelRequestGuard();
const e1 = guard.capture();
guard.bump();
const e2 = guard.capture();
guard.bump();
const e3 = guard.capture();
expect(guard.isStale(e1)).toBe(true);
expect(guard.isStale(e2)).toBe(true);
expect(guard.isStale(e3)).toBe(false);
expect(guard.isFresh(e3)).toBe(true);
});
it("starting B invalidates an in-flight request for A", () => {
const guard = createSidePanelRequestGuard();
const epochA = guard.start();
const epochB = guard.start();
expect(guard.isStale(epochA)).toBe(true);
expect(guard.isFresh(epochB)).toBe(true);
});
it("simulates database context change: old results are stale", () => {
const guard = createSidePanelRequestGuard();
const epochDb1 = guard.capture();
// Database switch → close panel + bump epoch
guard.bump();
// Old request from DB1 arrives — must be discarded
expect(guard.isStale(epochDb1)).toBe(true);
});
it("guards are independent", () => {
const guard1 = createSidePanelRequestGuard();
const guard2 = createSidePanelRequestGuard();
const e1 = guard1.capture();
guard2.bump();
expect(guard1.isStale(e1)).toBe(false);
expect(guard2.isStale(e1)).toBe(true);
});
});
@@ -0,0 +1,62 @@
import type { ObjectBrowserRow } from "@/lib/table/objectBrowserRows";
export type ObjectBrowserRowAction = "table-info" | "open-table" | "open-source" | "none";
/**
* Determine the action for a single click on an object browser row.
* - TABLE → table-info (show table properties panel)
* - VIEW/MATERIALIZED_VIEW/PROCEDURE/FUNCTION/SEQUENCE/PACKAGE/PACKAGE_BODY → open-source
* - otherwise → none
*/
export function singleClickRowAction(row: ObjectBrowserRow | null | undefined): ObjectBrowserRowAction {
if (!row) return "none";
if (row.type === "TABLE") return "table-info";
if (canOpenSource(row)) return "open-source";
return "none";
}
/**
* Determine the action for a double click on an object browser row.
* - TABLE → open-table (open table data tab)
* - VIEW/MATERIALIZED_VIEW/PROCEDURE/FUNCTION/SEQUENCE/PACKAGE/PACKAGE_BODY → open-source
* - otherwise → none
*/
export function doubleClickRowAction(row: ObjectBrowserRow | null | undefined): ObjectBrowserRowAction {
if (!row) return "none";
if (row.type === "TABLE") return "open-table";
if (canOpenSource(row)) return "open-source";
return "none";
}
/**
* Resolve a row click event into a single or double action based on click detail
* and the sidebar activation setting.
*/
export function resolveRowClickAction(row: ObjectBrowserRow | null | undefined, detail: number, activation: "single" | "double"): { action: ObjectBrowserRowAction; isDouble: boolean } {
if (activation === "double") {
if (detail === 2) return { action: doubleClickRowAction(row), isDouble: true };
return { action: "none", isDouble: false };
}
// single-click activation
if (detail > 1) return { action: doubleClickRowAction(row), isDouble: true };
return { action: singleClickRowAction(row), isDouble: false };
}
/**
* Whether a single-click action should be deferred to distinguish it from a
* possible upcoming double-click. Only applies in single-click activation mode
* and when the row's single-click and double-click actions differ (e.g. TABLE:
* single → table-info, double → open-table). For rows whose single and double
* actions are identical (e.g. VIEW → open-source both), no deferral is needed.
*/
export function shouldDeferSingleClick(row: ObjectBrowserRow | null | undefined, action: ObjectBrowserRowAction, activation: "single" | "double"): boolean {
if (activation !== "single") return false;
if (action === "none") return false;
const single = singleClickRowAction(row);
const double = doubleClickRowAction(row);
return single !== double && action === single;
}
function canOpenSource(row: ObjectBrowserRow): boolean {
return row.type === "VIEW" || row.type === "MATERIALIZED_VIEW" || row.type === "PROCEDURE" || row.type === "FUNCTION" || row.type === "SEQUENCE" || row.type === "PACKAGE" || row.type === "PACKAGE_BODY";
}
@@ -0,0 +1,33 @@
/**
* Side panel async request guard.
*
* Prevents stale async results (from a previous object or database context)
* from overwriting the current panel state. Each context change bumps the
* epoch; in-flight requests capture the epoch at start and compare before
* writing results.
*/
export interface SidePanelRequestGuard {
/** Bump the epoch, invalidating all previously captured epochs. */
bump: () => void;
/** Start a new request context and return its epoch. */
start: () => number;
/** Capture the current epoch for later staleness comparison. */
capture: () => number;
/** Returns true if the captured epoch is no longer current (request is stale). */
isStale: (capturedEpoch: number) => boolean;
/** Returns true if the captured epoch is still current (request is fresh). */
isFresh: (capturedEpoch: number) => boolean;
}
export function createSidePanelRequestGuard(): SidePanelRequestGuard {
let epoch = 0;
return {
bump: () => {
epoch++;
},
start: () => ++epoch,
capture: () => epoch,
isStale: (capturedEpoch: number) => capturedEpoch !== epoch,
isFresh: (capturedEpoch: number) => capturedEpoch === epoch,
};
}