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(grid): filter query results by cell value from the context menu

弈秋ce4362c4f5aa
diff --git a/apps/desktop/src/components/grid/DataGrid.vue b/apps/desktop/src/components/grid/DataGrid.vue
index 957813652b..dc048ffd29 100644
--- a/apps/desktop/src/components/grid/DataGrid.vue
+++ b/apps/desktop/src/components/grid/DataGrid.vue
@@ -168,6 +168,7 @@ import {
type TransposeScrollAlignment,
} from "@/lib/dataGrid/dataGridTranspose";
import { canApplyGridSelectionValue, canDeleteGridRowItem, canEditGridCellDetail, matchesRowStatusFilter, shouldShowQuickEntryDraftRow, type RowStatus, type RowStatusFilter } from "@/lib/dataGrid/gridRowStatus";
+import { matchesResultClientFilter, type ResultClientFilter, type ResultClientFilterMode } from "@/lib/dataGrid/gridClientFilter";
import { displayCellValue, firstLineCellDisplayValue, gridCellDisplayValue, limitDataGridCellDisplay, SQLSERVER_DATA_GRID_CELL_DISPLAY_MAX_LENGTH, type CellValue } from "@/lib/dataGrid/cellValue";
import { cellExternalUrl } from "@/lib/dataGrid/cellExternalUrl";
import { getApplicablePreviewActions, type PreviewAction } from "@/lib/dataGrid/resultPreviewRegistry";
@@ -1283,6 +1284,24 @@ type FilterMode = DataGridContextFilterMode;
type StructuredFilterRule = DataGridStructuredFilterRule;
const localColumnFilters = ref<Record<number, Set<string>>>(restoreDataGridLocalColumnFilters(props.result.local_column_filters, props.result.columns.length, props.result.columns, props.localColumnFilterColumns));
+// #13237: query-result grids cannot re-query the server, so their「筛选此值」
+// menu filters the loaded rows in memory. Only active outside table-data mode
+// (which keeps its server-side WHERE filtering). Keyed by column index so a
+// filter on a second column AND-composes with the first instead of replacing it.
+const resultClientFilters = ref<Record<number, ResultClientFilter>>({});
+const canClientFilterResult = computed(() => !canUseWhereSearch.value);
+/** True while at least one in-memory cell filter actually narrows the rows. */
+const hasResultClientFilters = computed(() => canClientFilterResult.value && Object.keys(resultClientFilters.value).length > 0);
+function clearResultClientFilters(columnIndex?: number) {
+ if (columnIndex === undefined) {
+ resultClientFilters.value = {};
+ return;
+ }
+ if (!resultClientFilters.value[columnIndex]) return;
+ const next = { ...resultClientFilters.value };
+ delete next[columnIndex];
+ resultClientFilters.value = next;
+}
const localFilterOpenColumn = ref<number | null>(null);
const headerActionMenuOpenColumn = ref<number | null>(null);
const headerSortMenuOpenColumn = ref<number | null>(null);
@@ -1567,6 +1586,11 @@ const localColumnFilterRuntime = useDataGridColumnFilters({
getConnectionConfig: () => (props.connectionId ? connectionStore.getConfig(props.connectionId) : undefined),
getIdentifierQuote: () => connectionStore.connectionIdentifierQuote?.(props.connectionId),
getGlobalQueryTimeoutSecs: () => settingsStore.editorSettings.globalQueryTimeoutSecs,
+ // Let the shared local-filter chip, funnel and clear path cover the
+ // in-memory result-cell filters too (#13419).
+ getClientColumnFilterActive: (columnIndex) => canClientFilterResult.value && !!resultClientFilters.value[columnIndex],
+ getClientFilterCount: () => (canClientFilterResult.value ? Object.keys(resultClientFilters.value).length : 0),
+ clearClientFilters: clearResultClientFilters,
getDistinctWhereInput: (columnIndex) => {
const current = serverColumnFilters.value[columnIndex]?.condition;
const manualWhere = current ? removeColumnValueFilterCondition(whereFilterInput.value, current) : whereFilterInput.value;
@@ -2344,6 +2368,7 @@ async function clearStructuredSortRules() {
watch(filterEditorView, () => sortBuilder.setOpen(false));
const rowStatusFilter = ref<RowStatusFilter>("all");
+
const gridRef = ref<HTMLDivElement>();
const dataGridTopbarRef = ref<HTMLDivElement>();
const headerRef = ref<HTMLDivElement>();
@@ -4864,6 +4889,15 @@ function closeSqlPreview() {
}
}
+// #13237: the in-memory cell filter belongs to the logical result, not to the
+// result object. Load-more appends publish a new object with the same
+// generation, so keying the reset on the object dropped the filter (#13419).
+watch(
+ () => props.viewGeneration,
+ () => {
+ resultClientFilters.value = {};
+ },
+);
// Watch for edits — auto-refresh preview when panel is open
watch([pendingChangeCount, pendingChangesVersion], () => {
schedulePreviewRefresh();
@@ -5523,8 +5557,21 @@ const rollbackToolbarCapability = computed<DataGridToolbarActionCapability>(() =
onTrigger: useTransaction.value ? onToolbarRollback : discardChanges,
}));
+// #13237: run the in-memory result-cell filters inside the existing client
+// filter pipeline, so empty states, the funnel, the local-filter chip and the
+// Ctrl+F row filter all observe the same narrowed row set (#13419).
+const clientFilteredRows = computed(() => {
+ if (!hasResultClientFilters.value) return localFilteredRows.value;
+ const filters = Object.values(resultClientFilters.value);
+ const rows = props.result.rows;
+ return localFilteredRows.value.filter((sourceIndex) => {
+ const row = rows[sourceIndex];
+ return filters.every((filter) => matchesResultClientFilter(row ?? [], filter, allColumnTypes.value[filter.colIndex]));
+ });
+});
+
const sortedRows = computed(() => {
- let indices = localFilteredRows.value;
+ let indices = clientFilteredRows.value;
const q = deferredClientSearchText.value;
if (q && dataGridSearchMode.value === "filter" && !replaceOpen.value) {
// Preserve the legacy Ctrl+F behavior when the user chooses row filtering.
@@ -5567,7 +5614,8 @@ const displayRowRefs = computed<DisplayRowRef[]>(() => {
const isDeleted = deletedRows.value.has(sourceIndex);
const status: RowStatus = isDeleted ? "deleted" : dirty?.size ? "edited" : "clean";
const isActiveEditingRow = quickEntryEnabled.value && editingCell.value?.rowId === sourceIndex;
- if (matchesRowStatusFilter(status, rowStatusFilter.value) || isActiveEditingRow) {
+ const statusVisible = matchesRowStatusFilter(status, rowStatusFilter.value) || isActiveEditingRow;
+ if (statusVisible) {
refs.push({
id: sourceIndex,
displayIndex: refs.length,
@@ -7718,7 +7766,30 @@ async function contextFilterCondition(target: ContextFilterTarget, mode: FilterM
}
async function applyContextFilter(mode: FilterMode) {
- if (!canUseWhereSearch.value) return;
+ if (!canUseWhereSearch.value) {
+ if (!canClientFilterResult.value) return;
+ // The client filter mirrors the server submenu minus "custom", which is a
+ // SQL condition with no in-memory semantics.
+ const clientMode: Partial<Record<FilterMode, ResultClientFilterMode>> = {
+ equals: "equals",
+ "not-equals": "not-equals",
+ like: "like",
+ "not-like": "not-like",
+ "less-than": "less-than",
+ "greater-than": "greater-than",
+ "is-null": "is-null",
+ "is-not-null": "is-not-null",
+ };
+ const mapped = clientMode[mode];
+ if (!mapped) return;
+ const target = contextFilterTarget.value;
+ if (!target) return;
+ // Keep the raw value so NULL stays NULL and text is never stringified
+ // into a numeric comparison (#13419). Per-column keying AND-composes.
+ resultClientFilters.value = { ...resultClientFilters.value, [target.col]: { colIndex: target.col, mode: mapped, value: target.sourceValue ?? null } };
+ contextFilterTarget.value = null;
+ return;
+ }
const target = contextFilterTarget.value;
if (!target) return;
activeContextFilterActions.add(target.id);
@@ -7753,6 +7824,10 @@ async function openContextCustomFilter() {
}
async function clearContextFilter() {
+ if (canClientFilterResult.value) {
+ clearResultClientFilters();
+ return;
+ }
await clearAllFilters();
}
@@ -14112,6 +14187,7 @@ function filterSubmenu(): ContextMenuItem {
apply: applyContextFilter,
applyCustom: openContextCustomFilter,
clear: clearContextFilter,
+ hideCustom: canClientFilterResult.value,
});
}
@@ -14468,7 +14544,7 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
canCopyAlterSql: canCopyAlterColumnSql.value,
canCopyMetadata: true,
canCopyComment: contextCopyableColumnComments.value.length > 0,
- canFilter: canUseWhereSearch.value,
+ canFilter: canUseWhereSearch.value || canClientFilterResult.value,
hasSort: !!sortCol.value,
sortMode: localSortMode.value,
databaseSortEnabled: props.databaseSortEnabled !== false && databaseSortSupportedForDatabase(resolvedDatabaseType.value),
diff --git a/apps/desktop/src/components/grid/__tests__/DataGridResultCellFilter.spec.ts b/apps/desktop/src/components/grid/__tests__/DataGridResultCellFilter.spec.ts
new file mode 100644
index 0000000000..13b98658d2
--- /dev/null
+++ b/apps/desktop/src/components/grid/__tests__/DataGridResultCellFilter.spec.ts
@@ -0,0 +1,234 @@
+// @vitest-environment happy-dom
+
+import { createApp, defineComponent, h, markRaw, nextTick, shallowRef, type App, type PropType } from "vue";
+import { createPinia, setActivePinia } from "pinia";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import i18n from "@/i18n";
+import type { QueryResult } from "@/types/database";
+import type { CellValue } from "@/lib/dataGrid/cellValue";
+import { TooltipProvider } from "@/components/ui/tooltip";
+
+vi.mock("@/composables/useDataGridColumnResize", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("@/composables/useDataGridColumnResize")>();
+ const { ref } = await import("vue");
+ return {
+ ...actual,
+ useDataGridColumnResize: () => ({
+ initColumnWidths: vi.fn(),
+ onResizeStart: vi.fn(),
+ autoFitColumn: vi.fn(),
+ hasUserSizedColumns: ref(false),
+ renderedColumnWidths: ref([160, 160]),
+ totalWidth: ref(320),
+ columnVars: ref({ "--total-w": "320px" }),
+ getIsResizing: () => false,
+ }),
+ };
+});
+
+import DataGrid from "../DataGrid.vue";
+import { useSettingsStore } from "@/stores/settingsStore";
+
+const RecycleScroller = defineComponent({
+ props: {
+ items: {
+ type: Array as PropType<unknown[]>,
+ default: () => [],
+ },
+ },
+ setup(props, { attrs, slots }) {
+ return () =>
+ h(
+ "div",
+ attrs,
+ props.items.map((item) => slots.default?.({ item })),
+ );
+ },
+});
+
+interface DataGridApi {
+ displayItems: Array<{ sourceIndex?: number }>;
+}
+
+const mountedApps: Array<{ app: App; host: HTMLElement }> = [];
+
+function resultOf(rows: CellValue[][]): QueryResult {
+ return markRaw<QueryResult>({
+ columns: ["code", "status"],
+ column_types: ["varchar", "varchar"],
+ rows,
+ affected_rows: rows.length,
+ execution_time_ms: 0,
+ });
+}
+
+function mountGrid(initialResult: QueryResult, viewGeneration = "generation-1") {
+ const pinia = createPinia();
+ setActivePinia(pinia);
+ useSettingsStore().updateEditorSettings({ dataGridRenderMode: "dom" });
+ const result = shallowRef(initialResult);
+ const generation = shallowRef(viewGeneration);
+ const gridRef = shallowRef<DataGridApi | null>(null);
+ const host = document.createElement("div");
+ document.body.append(host);
+ const Root = defineComponent({
+ setup() {
+ return () =>
+ h(
+ TooltipProvider,
+ { delayDuration: 0 },
+ {
+ default: () =>
+ h(DataGrid, {
+ ref: gridRef,
+ result: result.value,
+ viewGeneration: generation.value,
+ databaseType: "mysql",
+ context: "results",
+ onExecuteSql: vi.fn(),
+ }),
+ },
+ );
+ },
+ });
+ const app = createApp(Root);
+ app.use(pinia);
+ app.use(i18n);
+ app.component("RecycleScroller", RecycleScroller);
+ app.mount(host);
+ mountedApps.push({ app, host });
+ return {
+ host,
+ gridRef,
+ replaceResult: (nextResult: QueryResult, nextGeneration = generation.value) => {
+ result.value = nextResult;
+ generation.value = nextGeneration;
+ },
+ };
+}
+
+async function settle() {
+ for (let i = 0; i < 6; i++) {
+ await nextTick();
+ await Promise.resolve();
+ }
+}
+
+function displayedSourceIndexes(gridRef: { value: DataGridApi | null }): number[] {
+ return (gridRef.value?.displayItems ?? []).map((item) => item.sourceIndex ?? -1);
+}
+
+function contextMenuButton(label: string): HTMLButtonElement {
+ const button = [...document.querySelectorAll<HTMLButtonElement>("[data-dbx-context-menu] button")].find((candidate) => candidate.textContent?.trim() === label);
+ if (!button) throw new Error(`Context menu item not found: ${label}`);
+ return button;
+}
+
+/** Right-click a visible cell and run an in-memory filter action from the submenu. */
+async function applyCellFilterMenu(host: HTMLElement, displayRow: number, visibleCol: number, itemKey: string) {
+ const cell = host.querySelector<HTMLElement>(`[data-row-index="${displayRow}"] [data-visible-col-index="${visibleCol}"]`);
+ if (!cell) throw new Error(`Cell not found: ${displayRow}/${visibleCol}`);
+ cell.dispatchEvent(new MouseEvent("contextmenu", { bubbles: true, cancelable: true, clientX: 12, clientY: 12 }));
+ await settle();
+ contextMenuButton(i18n.global.t("grid.filter")).dispatchEvent(new MouseEvent("mouseenter", { bubbles: true }));
+ await settle();
+ contextMenuButton(i18n.global.t(itemKey)).click();
+ await settle();
+}
+
+function filterByCellValue(host: HTMLElement, displayRow: number, visibleCol: number) {
+ return applyCellFilterMenu(host, displayRow, visibleCol, "grid.filterByValue");
+}
+
+function excludeCellValue(host: HTMLElement, displayRow: number, visibleCol: number) {
+ return applyCellFilterMenu(host, displayRow, visibleCol, "grid.filterExcludeValue");
+}
+
+afterEach(() => {
+ for (const { app, host } of mountedApps.splice(0)) {
+ app.unmount();
+ host.remove();
+ }
+ document.querySelectorAll("[data-dbx-context-menu]").forEach((menu) => menu.remove());
+ vi.restoreAllMocks();
+});
+
+describe("DataGrid in-memory result cell filter (#13237)", () => {
+ it("AND-composes columns and clears through the local-filter chip", async () => {
+ const { host, gridRef } = mountGrid(
+ resultOf([
+ ["007", "a"],
+ ["7", "a"],
+ ["007", "b"],
+ [null, "a"],
+ ["", "b"],
+ ]),
+ );
+ await settle();
+ expect(displayedSourceIndexes(gridRef)).toEqual([0, 1, 2, 3, 4]);
+
+ await filterByCellValue(host, 0, 0);
+ expect(displayedSourceIndexes(gridRef)).toEqual([0, 2]);
+
+ // A second column must narrow the first filter, not replace it.
+ await filterByCellValue(host, 0, 1);
+ expect(displayedSourceIndexes(gridRef)).toEqual([0]);
+
+ const chip = host.querySelector<HTMLButtonElement>(`button[title="${i18n.global.t("grid.clearLocalFilters")}"]`);
+ expect(chip).toBeTruthy();
+ expect(chip?.textContent).toContain("2");
+ chip!.click();
+ await settle();
+ expect(displayedSourceIndexes(gridRef)).toEqual([0, 1, 2, 3, 4]);
+ });
+
+ it("compares text by value and shows the filtered empty state", async () => {
+ const { host, gridRef } = mountGrid(
+ resultOf([
+ ["007", "a"],
+ ["7", "a"],
+ ["007", "b"],
+ ]),
+ );
+ await settle();
+
+ // "7" must not match the "007" rows the way Number() coercion did.
+ await filterByCellValue(host, 1, 0);
+ expect(displayedSourceIndexes(gridRef)).toEqual([1]);
+
+ // Excluding the only remaining row's status hides every row, which is a
+ // filter result rather than an empty dataset.
+ await excludeCellValue(host, 0, 1);
+ expect(displayedSourceIndexes(gridRef)).toEqual([]);
+ expect(host.textContent).toContain(i18n.global.t("grid.noFilteredRows"));
+ expect(host.textContent).not.toContain(i18n.global.t("grid.noRows"));
+ });
+
+ it("keeps the filter on appended rows and resets it on a new generation", async () => {
+ const { host, gridRef, replaceResult } = mountGrid(
+ resultOf([
+ ["007", "a"],
+ ["7", "b"],
+ ]),
+ );
+ await settle();
+ await filterByCellValue(host, 0, 0);
+ expect(displayedSourceIndexes(gridRef)).toEqual([0]);
+
+ // Load-more appends publish a new result object with the same generation.
+ replaceResult(
+ resultOf([
+ ["007", "a"],
+ ["7", "b"],
+ ["007", "c"],
+ ]),
+ );
+ await settle();
+ expect(displayedSourceIndexes(gridRef)).toEqual([0, 2]);
+
+ // A replaced logical result (new generation) drops the stale filter.
+ replaceResult(resultOf([["7", "b"]]), "generation-2");
+ await settle();
+ expect(displayedSourceIndexes(gridRef)).toEqual([0]);
+ });
+});
diff --git a/apps/desktop/src/composables/useDataGridColumnFilters.ts b/apps/desktop/src/composables/useDataGridColumnFilters.ts
index 7651a52fc2..72a7c9ff9c 100644
--- a/apps/desktop/src/composables/useDataGridColumnFilters.ts
+++ b/apps/desktop/src/composables/useDataGridColumnFilters.ts
@@ -58,6 +58,14 @@ export interface UseDataGridColumnFiltersOptions {
getConnectionConfig: () => Pick<ConnectionConfig, "driver_profile" | "query_timeout_secs" | "query_timeout_inherit"> | undefined;
getIdentifierQuote: () => string | undefined;
getGlobalQueryTimeoutSecs: () => number | undefined;
+ /**
+ * #13237: in-memory value filters for grids that cannot re-query (query
+ * results). They share this local-filter surface so the funnel and the
+ * chip/clear path also cover them.
+ */
+ getClientColumnFilterActive?: (columnIndex: number) => boolean;
+ getClientFilterCount?: () => number;
+ clearClientFilters?: (columnIndex?: number) => void;
getDistinctWhereInput?: (columnIndex: number) => string | undefined;
getNewRows: () => readonly (readonly CellValue[])[];
getRowData: (row: CellValue[], sourceIndex: number) => readonly CellValue[];
@@ -140,8 +148,8 @@ export function useDataGridColumnFilters(options: UseDataGridColumnFiltersOption
return [...filteredOptions, ...selectedOptions.map((option) => ({ ...option, count: 0 }))].sort((a, b) => a.label.localeCompare(b.label, undefined, { numeric: true, sensitivity: "base" }));
}
- const localFilterActive = (columnIndex: number) => !!state.localColumnFilters.value[columnIndex]?.size || !!state.serverColumnFilters.value[columnIndex];
- const localFilterCount = computed(() => Object.values(state.localColumnFilters.value).filter((values) => values.size).length);
+ const localFilterActive = (columnIndex: number) => !!state.localColumnFilters.value[columnIndex]?.size || !!state.serverColumnFilters.value[columnIndex] || !!options.getClientColumnFilterActive?.(columnIndex);
+ const localFilterCount = computed(() => Object.values(state.localColumnFilters.value).filter((values) => values.size).length + (options.getClientFilterCount?.() ?? 0));
const serverColumnFilterCount = computed(() => Object.keys(state.serverColumnFilters.value).length);
const hasLocalColumnFilters = computed(() => localFilterCount.value > 0);
const hasServerColumnFilters = computed(() => serverColumnFilterCount.value > 0);
@@ -415,6 +423,7 @@ export function useDataGridColumnFilters(options: UseDataGridColumnFiltersOption
}
}
closeLocalFilter();
+ options.clearClientFilters?.(columnIndex);
options.resetGridVerticalScroll();
if (removedServerFilter && applyServerWhereFilter && options.canUseWhereSearch.value) void options.applyWhereFilter();
}
diff --git a/apps/desktop/src/lib/__tests__/dataGrid/gridClientFilter.spec.ts b/apps/desktop/src/lib/__tests__/dataGrid/gridClientFilter.spec.ts
new file mode 100644
index 0000000000..a03051da21
--- /dev/null
+++ b/apps/desktop/src/lib/__tests__/dataGrid/gridClientFilter.spec.ts
@@ -0,0 +1,83 @@
+import { describe, expect, it } from "vitest";
+import { matchesResultClientFilter, type ResultClientFilter } from "@/lib/dataGrid/gridClientFilter";
+import type { CellValue } from "@/lib/dataGrid/cellValue";
+
+const row: CellValue[] = ["orders-001", 42, null, "Pending", 3.5];
+
+describe("matchesResultClientFilter (#13237)", () => {
+ function f(mode: ResultClientFilter["mode"], value: CellValue = "", colIndex = 0): ResultClientFilter {
+ return { colIndex, mode, value };
+ }
+
+ it("equals matches text exactly and numbers only against numbers", () => {
+ expect(matchesResultClientFilter(row, f("equals", "orders-001"))).toBe(true);
+ expect(matchesResultClientFilter(row, f("equals", 42, 1))).toBe(true);
+ // Typed comparison: a number cell is not the text "42" and vice versa.
+ expect(matchesResultClientFilter([42], f("equals", "42"))).toBe(false);
+ expect(matchesResultClientFilter(["42"], f("equals", 42))).toBe(false);
+ expect(matchesResultClientFilter(row, f("equals", "orders-002"))).toBe(false);
+ });
+
+ it("not-equals inverts equals for non-null rows and excludes NULL", () => {
+ expect(matchesResultClientFilter(row, f("not-equals", "orders-001"))).toBe(false);
+ expect(matchesResultClientFilter(row, f("not-equals", "other"))).toBe(true);
+ // `col <> value` is unknown for NULL in SQL, so NULL rows stay out.
+ expect(matchesResultClientFilter([null], f("not-equals", "other"))).toBe(false);
+ expect(matchesResultClientFilter([""], f("not-equals", ""))).toBe(false);
+ expect(matchesResultClientFilter(["x"], f("not-equals", ""))).toBe(true);
+ });
+
+ it("like / not-like are case-insensitive substrings and skip NULL", () => {
+ expect(matchesResultClientFilter(row, f("like", "PENDING", 3))).toBe(true);
+ expect(matchesResultClientFilter(row, f("not-like", "pending", 3))).toBe(false);
+ expect(matchesResultClientFilter([null], f("like", ""))).toBe(false);
+ expect(matchesResultClientFilter([null], f("not-like", "pending"))).toBe(false);
+ });
+
+ it("less-than / greater-than compare numbers numerically and text by collation", () => {
+ expect(matchesResultClientFilter(row, f("less-than", 100, 1))).toBe(true);
+ expect(matchesResultClientFilter(row, f("greater-than", 100, 1))).toBe(false);
+ expect(matchesResultClientFilter(row, f("less-than", "1", 0))).toBe(false);
+ expect(matchesResultClientFilter(row, f("greater-than", 3, 4))).toBe(true);
+ // Text is never parsed as a number: "9" < "10" numerically, but not as text.
+ expect(matchesResultClientFilter(["9"], f("less-than", "10"))).toBe(false);
+ expect(matchesResultClientFilter(["9"], f("less-than", "10"), "varchar")).toBe(false);
+ // A numeric column type opts into numeric ordering for string-encoded cells.
+ expect(matchesResultClientFilter(["9"], f("less-than", "10"), "int")).toBe(true);
+ expect(matchesResultClientFilter([null], f("less-than", 10))).toBe(false);
+ });
+
+ it("is-null / is-not-null are strictly null and undefined", () => {
+ expect(matchesResultClientFilter(row, f("is-null", null, 2))).toBe(true);
+ expect(matchesResultClientFilter(row, f("is-not-null", null, 2))).toBe(false);
+ expect(matchesResultClientFilter([undefined as unknown as CellValue], f("is-null", null))).toBe(true);
+ expect(matchesResultClientFilter(row, f("is-not-null", null, 3))).toBe(true);
+ // Empty text is a value, not NULL.
+ expect(matchesResultClientFilter([""], f("is-null", null))).toBe(false);
+ expect(matchesResultClientFilter([""], f("is-not-null", null))).toBe(true);
+ });
+
+ it("equals / not-equals on a NULL value behave like is-null / is-not-null", () => {
+ expect(matchesResultClientFilter([null], f("equals", null))).toBe(true);
+ expect(matchesResultClientFilter([null], f("equals", ""))).toBe(false);
+ expect(matchesResultClientFilter([""], f("equals", null))).toBe(false);
+ expect(matchesResultClientFilter([""], f("equals", ""))).toBe(true);
+ expect(matchesResultClientFilter(["x"], f("not-equals", null))).toBe(true);
+ expect(matchesResultClientFilter(["x"], f("not-equals", ""))).toBe(true);
+ expect(matchesResultClientFilter([null], f("not-equals", null))).toBe(false);
+ });
+
+ it("does not coerce numeric-looking text on a text column (#13419)", () => {
+ expect(matchesResultClientFilter(["007"], f("equals", "007"))).toBe(true);
+ expect(matchesResultClientFilter(["007"], f("equals", "7"))).toBe(false);
+ expect(matchesResultClientFilter(["7"], f("equals", "007"))).toBe(false);
+ expect(matchesResultClientFilter(["1.0"], f("equals", "1"))).toBe(false);
+ expect(matchesResultClientFilter(["1e3"], f("equals", "1000"))).toBe(false);
+ // The row that `col = '007'` keeps must survive "not equals 7".
+ expect(matchesResultClientFilter(["007"], f("not-equals", "7"))).toBe(true);
+ // Numeric column types keep numeric semantics.
+ expect(matchesResultClientFilter(["007"], f("equals", "7"), "int")).toBe(true);
+ expect(matchesResultClientFilter(["1.0"], f("equals", "1"), "numeric(10,2)")).toBe(true);
+ expect(matchesResultClientFilter(["1e3"], f("equals", "1000"), "float8")).toBe(true);
+ });
+});
diff --git a/apps/desktop/src/lib/dataGrid/dataGridContextMenu.ts b/apps/desktop/src/lib/dataGrid/dataGridContextMenu.ts
index aa574ad2c2..7e93459bbd 100644
--- a/apps/desktop/src/lib/dataGrid/dataGridContextMenu.ts
+++ b/apps/desktop/src/lib/dataGrid/dataGridContextMenu.ts
@@ -50,6 +50,8 @@ export function createDataGridFilterSubmenu(options: {
apply: (mode: "equals" | "not-equals" | "like" | "not-like" | "less-than" | "greater-than" | "is-null" | "is-not-null") => void;
applyCustom: () => void;
clear: () => void;
+ /** Result grids filter in memory and have no SQL condition builder (#13237). */
+ hideCustom?: boolean;
}): DataGridContextMenuItem {
const { labels } = options;
return {
@@ -62,7 +64,7 @@ export function createDataGridFilterSubmenu(options: {
{ label: labels.notLike, action: () => options.apply("not-like") },
{ label: labels.lessThan, action: () => options.apply("less-than") },
{ label: labels.greaterThan, action: () => options.apply("greater-than") },
- { label: labels.custom, action: () => options.applyCustom() },
+ ...(options.hideCustom ? [] : [{ label: labels.custom, action: () => options.applyCustom() }]),
{ label: "", separator: true },
{ label: labels.isNull, action: () => options.apply("is-null") },
{ label: labels.isNotNull, action: () => options.apply("is-not-null") },
diff --git a/apps/desktop/src/lib/dataGrid/gridClientFilter.ts b/apps/desktop/src/lib/dataGrid/gridClientFilter.ts
new file mode 100644
index 0000000000..018b0133b0
--- /dev/null
+++ b/apps/desktop/src/lib/dataGrid/gridClientFilter.ts
@@ -0,0 +1,109 @@
+/**
+ * Client-side value filtering for query-result grids (#13237).
+ *
+ * Table-data grids filter on the server through a WHERE clause; a query
+ * result has no table to re-query, so its「筛选此值」menu filters the loaded
+ * rows in memory instead. Modes mirror the server-side submenu minus the
+ * numeric comparisons and the SQL condition builder.
+ *
+ * Comparison follows the server-side semantics instead of stringifying cells:
+ * NULL stays distinct from empty text, equals/not-equals on a NULL value
+ * become IS NULL / IS NOT NULL, and text is never coerced to a number
+ * (numeric comparison needs a numeric column type or two numeric cells).
+ */
+
+import type { CellValue } from "./cellValue";
+import { isNumericColumnType } from "./dataGridColumnType";
+
+export type ResultClientFilterMode = "equals" | "not-equals" | "like" | "not-like" | "less-than" | "greater-than" | "is-null" | "is-not-null";
+
+export interface ResultClientFilter {
+ /** Actual (source) column index the filter applies to. */
+ colIndex: number;
+ mode: ResultClientFilterMode;
+ /** Raw cell value for the value modes; null for is-null / is-not-null. */
+ value: CellValue;
+}
+
+function isNullish(value: unknown): value is null | undefined {
+ return value === null || value === undefined;
+}
+
+/** Text used by LIKE; callers keep NULL out so it never reads as empty text. */
+function filterText(value: unknown): string {
+ if (typeof value === "string") return value;
+ if (typeof value === "boolean") return value ? "true" : "false";
+ return String(value);
+}
+
+/** Numeric view of a cell, only for numeric columns or numeric cells. */
+function numericValue(value: unknown): number | null {
+ if (typeof value === "number") return Number.isNaN(value) ? null : value;
+ if (typeof value === "string" && value.trim() !== "") {
+ const parsed = Number(value);
+ return Number.isNaN(parsed) ? null : parsed;
+ }
+ return null;
+}
+
+function valuesEqual(cell: unknown, needle: unknown, columnType: string | undefined): boolean {
+ if (isNumericColumnType(columnType)) {
+ const a = numericValue(cell);
+ const b = numericValue(needle);
+ return a !== null && b !== null && a === b;
+ }
+ // Typed comparison: on a text column "007" is not 7 and "1.0" is not 1.
+ return cell === needle;
+}
+
+/** Ordering for less-than / greater-than; null means incomparable. */
+function compareValues(cell: unknown, needle: unknown, columnType: string | undefined): number | null {
+ if (isNumericColumnType(columnType)) {
+ const a = numericValue(cell);
+ const b = numericValue(needle);
+ return a === null || b === null ? null : Math.sign(a - b);
+ }
+ if (typeof cell === "number" && typeof needle === "number") return Math.sign(cell - needle);
+ // Text keeps its collation order; it is never parsed as a number (#13419).
+ if (typeof cell === "string" && typeof needle === "string") return Math.sign(cell.localeCompare(needle));
+ return null;
+}
+
+export function matchesResultClientFilter(row: readonly CellValue[], filter: ResultClientFilter, columnType?: string): boolean {
+ const cell = row[filter.colIndex];
+ const cellIsNull = isNullish(cell);
+ switch (filter.mode) {
+ case "is-null":
+ return cellIsNull;
+ case "is-not-null":
+ return !cellIsNull;
+ }
+
+ const needle = filter.value;
+ const needleIsNull = isNullish(needle);
+ switch (filter.mode) {
+ case "equals":
+ // A NULL cell filters to IS NULL, so empty-text rows stay out (#13419).
+ if (needleIsNull) return cellIsNull;
+ return !cellIsNull && valuesEqual(cell, needle, columnType);
+ case "not-equals":
+ if (needleIsNull) return !cellIsNull;
+ // SQL three-valued logic: `col <> value` never matches a NULL row.
+ return !cellIsNull && !valuesEqual(cell, needle, columnType);
+ case "like":
+ case "not-like": {
+ // LIKE against NULL is unknown in SQL, so neither side matches.
+ if (cellIsNull || needleIsNull) return false;
+ const text = filterText(cell).toLowerCase();
+ const pattern = filterText(needle).toLowerCase();
+ return filter.mode === "like" ? text.includes(pattern) : !text.includes(pattern);
+ }
+ case "less-than":
+ case "greater-than": {
+ if (cellIsNull || needleIsNull) return false;
+ const compared = compareValues(cell, needle, columnType);
+ if (compared === null) return false;
+ return filter.mode === "less-than" ? compared < 0 : compared > 0;
+ }
+ }
+}
diff --git a/apps/desktop/src/lib/table/tableVGroup.ts b/apps/desktop/src/lib/table/tableVGroup.ts
index a1839bf4a0..5166f39950 100644
--- a/apps/desktop/src/lib/table/tableVGroup.ts
+++ b/apps/desktop/src/lib/table/tableVGroup.ts
@@ -140,6 +140,10 @@ export function tableVGroupKindOfContainerNode(node: Pick<TreeNode, "type" | "ta
case "group-jobs":
return "jobs";
case "group-packages":
+ // Bodies live in their own sidebar group but share the packages virtual
+ // group: a v-group key must be unique per package name, and bodies pair
+ // with their spec by name.
+ case "group-package-bodies":
return "packages";
case "group-types":
return "types";
diff --git a/apps/desktop/src/types/database.ts b/apps/desktop/src/types/database.ts
index 24cf888e16..8de1ef0070 100644
--- a/apps/desktop/src/types/database.ts
+++ b/apps/desktop/src/types/database.ts
@@ -2121,6 +2121,7 @@ export type TreeNodeType =
| "oracle-db-link"
| "group-jobs"
| "group-packages"
+ | "group-package-bodies"
| "group-partitions"
| "group-extensions"
| "group-event-triggers"