fix(table): refresh data tabs after clearing tables

This commit is contained in:
zipg authored and GitHub committed 2026-07-11 17:48:51 +08:00
1 parent 085d7661af
commit 3747f08baa
6 files changed
+309 -13

No files matched your search

@@ -0,0 +1,124 @@
import { createPinia, setActivePinia } from "pinia";
import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
buildTableSelectSql: vi.fn(),
closeClientConnectionSession: vi.fn(),
closeQuerySession: vi.fn(),
executeMulti: vi.fn(),
getConnectionConfig: vi.fn(),
saveOpenTabsState: vi.fn(),
}));
vi.mock("@/lib/backend/api", () => ({
buildTableSelectSql: mocks.buildTableSelectSql,
closeClientConnectionSession: mocks.closeClientConnectionSession,
closeQuerySession: mocks.closeQuerySession,
executeMulti: mocks.executeMulti,
saveOpenTabsState: mocks.saveOpenTabsState,
}));
vi.mock("@/stores/connectionStore", () => ({
useConnectionStore: () => ({
ensureConnected: vi.fn().mockResolvedValue(undefined),
getConfig: mocks.getConnectionConfig,
recordConnectionLostError: vi.fn(),
}),
}));
vi.mock("@/stores/settingsStore", () => ({
useSettingsStore: () => ({
editorSettings: { pageSize: 100 },
}),
}));
function installLocalStorage() {
const data = new Map<string, string>();
vi.stubGlobal("localStorage", {
getItem: vi.fn((key: string) => data.get(key) ?? null),
setItem: vi.fn((key: string, value: string) => data.set(key, value)),
removeItem: vi.fn((key: string) => data.delete(key)),
});
}
describe("queryStore table data refresh", () => {
beforeEach(() => {
vi.clearAllMocks();
vi.unstubAllGlobals();
installLocalStorage();
setActivePinia(createPinia());
mocks.getConnectionConfig.mockReturnValue({
id: "pg-1",
name: "Postgres",
db_type: "postgres",
database: "app",
query_timeout_secs: 30,
});
mocks.buildTableSelectSql.mockResolvedValue("SELECT id, status FROM public.users WHERE status = 'ACTIVE' ORDER BY created_at DESC LIMIT 25 OFFSET 50");
mocks.executeMulti.mockResolvedValue([
{
columns: ["id", "status"],
rows: [],
affected_rows: 0,
execution_time_ms: 1,
},
]);
});
it("refreshes only matching data tabs after a table mutation", async () => {
const { useQueryStore } = await import("@/stores/queryStore");
const store = useQueryStore();
const publicTabId = store.createTab("pg-1", "app", "users", "data", "public");
store.setTableMeta(publicTabId, {
schema: "public",
tableName: "users",
tableType: "TABLE",
columns: [
{ name: "id", data_type: "integer", is_nullable: false, column_default: null, is_primary_key: true, extra: null },
{ name: "status", data_type: "text", is_nullable: true, column_default: null, is_primary_key: false, extra: null },
],
primaryKeys: ["id"],
});
const publicTab = store.tabs.find((tab) => tab.id === publicTabId)!;
publicTab.whereInput = "status = 'ACTIVE'";
publicTab.orderByInput = "created_at DESC";
publicTab.resultPageLimit = 25;
publicTab.resultPageOffset = 50;
const archiveTabId = store.createTab("pg-1", "app", "users", "data", "archive");
store.setTableMeta(archiveTabId, {
schema: "archive",
tableName: "users",
tableType: "TABLE",
columns: [{ name: "id", data_type: "integer", is_nullable: false, column_default: null, is_primary_key: true, extra: null }],
primaryKeys: ["id"],
});
const refreshed = await store.refreshDataTabsForTable({
connectionId: "pg-1",
database: "app",
schema: "public",
name: "users",
});
expect(refreshed).toBe(1);
expect(mocks.buildTableSelectSql).toHaveBeenCalledWith({
databaseType: "postgres",
schema: "public",
tableName: "users",
tableType: "TABLE",
catalog: undefined,
columns: ["id", "status"],
primaryKeys: ["id"],
includeRowId: false,
whereInput: "status = 'ACTIVE'",
orderBy: "created_at DESC",
limit: 25,
offset: 50,
});
expect(mocks.executeMulti).toHaveBeenCalledTimes(1);
expect(store.tabs.find((tab) => tab.id === publicTabId)?.result?.rows).toEqual([]);
expect(store.tabs.find((tab) => tab.id === archiveTabId)?.result).toBeUndefined();
});
});
+63 -2
View File
@@ -28,13 +28,13 @@ import { redisCommandResultToQueryResult } from "@/lib/redis/redisQueryResult";
import { nextRedisCommandDb } from "@/lib/redis/redisCommandSession";
import { isRedisMutatingCommand } from "@/lib/redis/redisCommandTable";
import { usesAgentCursorForQuery } from "@/lib/database/databaseDriverManifest";
import { canUseKeylessRowPredicate } from "@/lib/table/tableEditing";
import { canUseKeylessRowPredicate, usesSyntheticRowIdKey } from "@/lib/table/tableEditing";
import { TABLE_DATA_EXPORT_PAGE_SIZE } from "@/lib/table/tableDataExport";
import { tableMetaForDataTab } from "@/lib/table/tableDataTabMeta";
import { dataTabExecutionDatabase } from "@/lib/table/dataTabExecutionDatabase";
import { tableOpenPageLimit } from "@/lib/table/tableOpenPageLimit";
import { loadTableMetadata } from "@/lib/metadata/tableMetadataCache";
import { quoteTableIdentifier } from "@/lib/table/tableSelectSql";
import { buildTableSelectSql, quoteTableIdentifier } from "@/lib/table/tableSelectSql";
import { connectionQueryExecutionSchema, effectiveDatabaseTypeForConnection, metadataSchemaForConnection } from "@/lib/database/jdbcDialect";
import { frontendQueryTimeoutSecsForSql, queryTimeoutSecsForConnection } from "@/lib/sql/queryTimeout";
import { queryResultSourceLabel } from "@/lib/sql/queryResultSource";
@@ -83,6 +83,15 @@ interface DroppedTableObjectTarget {
objectType?: DroppedTableObjectType;
}
interface TableDataRefreshTarget {
connectionId: string;
database: string;
schema?: string;
schemaCandidates?: Array<string | undefined>;
catalog?: string;
name: string;
}
function tabClientSessionId(tab: Pick<QueryTab, "id">, suffix?: (typeof BACKGROUND_CLIENT_SESSION_SUFFIXES)[number]): string {
return suffix ? `${tab.id}:${suffix}` : tab.id;
}
@@ -1528,12 +1537,63 @@ export const useQueryStore = defineStore("query", () => {
return false;
}
function tabMatchesTableDataRefreshTarget(tab: QueryTab, target: TableDataRefreshTarget): boolean {
if (tab.mode !== "data" || tab.connectionId !== target.connectionId || tab.database !== target.database) return false;
const tableMeta = tableMetaForDataTab(tab);
if (!tableMeta || tableMeta.tableName !== target.name) return false;
if ((tableMeta.catalog || "") !== (target.catalog || "")) return false;
const targetSchemas = droppedTableObjectSchemaCandidates(target);
return targetSchemas.has(normalizeOptionalSchema(tableMeta.schema ?? tab.schema));
}
function closeDroppedTableObjectTabs(target: DroppedTableObjectTarget) {
// A dropped table-like object makes existing data/structure tabs stale; close
// them immediately instead of letting the next refresh fail against a missing object.
closeTabsWhere((tab) => tabMatchesDroppedTableObject(tab, target));
}
async function refreshDataTabsForTable(target: TableDataRefreshTarget): Promise<number> {
const matchingTabs = tabs.value.filter((tab) => tabMatchesTableDataRefreshTarget(tab, target));
if (matchingTabs.length === 0) return 0;
const settingsStore = useSettingsStore();
let refreshed = 0;
for (const tab of matchingTabs) {
const tableMeta = tableMetaForDataTab(tab);
if (!tableMeta?.tableName) continue;
const conn = useConnectionStore().getConfig(tab.connectionId);
const effectiveDbType = effectiveDatabaseTypeForConnection(conn);
const primaryKeys = tab.tableMeta ? tab.tableMeta.primaryKeys : tableMeta.primaryKeys;
const sortOrder = tab.resultSortColumn && tab.resultSortDirection ? `${quoteTableIdentifier(effectiveDbType, tab.resultSortColumn)} ${tab.resultSortDirection.toUpperCase()}` : undefined;
const orderBy = tab.orderByInput?.trim() || sortOrder;
const limit = tab.resultPageLimit ?? settingsStore.editorSettings.pageSize ?? tableOpenPageLimit();
const offset = tab.resultPageOffset ?? 0;
const sql = await buildTableSelectSql({
databaseType: effectiveDbType,
schema: tableMeta.schema,
tableName: tableMeta.tableName,
tableType: tableMeta.tableType,
catalog: tableMeta.catalog,
columns: tableMeta.columns.map((column) => column.name),
primaryKeys,
includeRowId: usesSyntheticRowIdKey(effectiveDbType, primaryKeys, tableMeta.tableType),
whereInput: tab.whereInput,
orderBy,
limit,
offset,
});
updateSql(tab.id, sql);
await executeTabSql(tab.id, sql, {
pagination: { limit, offset },
preserveResultDuringExecution: true,
});
refreshed += 1;
}
return refreshed;
}
function releaseTabsWhere(predicate: (tab: QueryTab) => boolean) {
closeTabsWhere((tab) => predicate(tab) && tab.mode !== "query");
tabs.value
@@ -3501,6 +3561,7 @@ export const useQueryStore = defineStore("query", () => {
closeConnectionTabs,
closeDatabaseTabs,
closeDroppedTableObjectTabs,
refreshDataTabsForTable,
releaseConnectionTabs,
releaseDatabaseTabs,
isDatabaseOpen,