From 8064fa8fb62fc30ce88777395bf69ca828374e23 Mon Sep 17 00:00:00 2001 From: Guilhem Date: Mon, 30 Nov 2026 21:58:26 +0100 Subject: [PATCH] feat: show s3 csv and parquet results in the db table with filters (#12712) * feat: filter a db table from its column headers Co-Authored-By: Claude Opus 5.5 * feat: accept column filters, header row and separator on app s3 table routes Co-Authored-By: Claude Opus 5.5 * feat: show s3 csv and parquet results in the db table with filters Co-Authored-By: Claude Opus 5.5 * feat: apply db table header filters as you type and widen filterable columns Co-Authored-By: Claude Opus 5.5 * fix: harden db table header filters, column widths and narrow s3 tables Co-Authored-By: Claude Opus 5.5 * chore: point ee ref at the unknown filter column fix Co-Authored-By: Claude Opus 5.5 * fix: compare postgres arrays as text, ignore stale s3 table counts, clearable separator Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 Co-authored-by: Ruben Fiszel --- backend/windmill-api/openapi.yaml | 9 + backend/windmill-api/src/apps.rs | 15 +- frontend/src/lib/components/DBTable.svelte | 266 +++++++++++++-- .../src/lib/components/DisplayResult.svelte | 25 +- .../components/ParqetCsvTableRenderer.svelte | 305 ------------------ .../src/lib/components/TaggedTextInput.svelte | 13 +- .../lib/components/apps/editor/appUtilsS3.ts | 2 +- .../common/fileDownload/S3ObjectTable.svelte | 178 ++++++++++ .../lib/components/dbTableLayoutStorage.ts | 2 + .../src/lib/components/s3TableOps.test.ts | 4 + frontend/src/lib/components/s3TableOps.ts | 50 ++- 11 files changed, 492 insertions(+), 377 deletions(-) delete mode 100644 frontend/src/lib/components/ParqetCsvTableRenderer.svelte create mode 100644 frontend/src/lib/components/common/fileDownload/S3ObjectTable.svelte diff --git a/backend/windmill-api/openapi.yaml b/backend/windmill-api/openapi.yaml index 6dcbfa5f63..44dff55639 100644 --- a/backend/windmill-api/openapi.yaml +++ b/backend/windmill-api/openapi.yaml @@ -17824,6 +17824,7 @@ paths: in: query schema: type: string + - $ref: "#/components/parameters/TablePreviewFilters" - $ref: "#/components/parameters/S3Sig" - $ref: "#/components/parameters/S3Exp" responses: @@ -17878,6 +17879,8 @@ paths: in: query schema: type: string + - $ref: "#/components/parameters/TablePreviewCsvHasHeader" + - $ref: "#/components/parameters/TablePreviewFilters" - $ref: "#/components/parameters/S3Sig" - $ref: "#/components/parameters/S3Exp" responses: @@ -17912,6 +17915,12 @@ paths: in: query schema: type: string + - name: csv_separator + in: query + schema: + type: string + - $ref: "#/components/parameters/TablePreviewCsvHasHeader" + - $ref: "#/components/parameters/TablePreviewFilters" - $ref: "#/components/parameters/S3Sig" - $ref: "#/components/parameters/S3Exp" responses: diff --git a/backend/windmill-api/src/apps.rs b/backend/windmill-api/src/apps.rs index 84197fe8a3..5cc92edd60 100644 --- a/backend/windmill-api/src/apps.rs +++ b/backend/windmill-api/src/apps.rs @@ -6378,6 +6378,9 @@ struct AppLoadCountQuery { search_col: Option, search_term: Option, storage: Option, + csv_separator: Option, + csv_has_header: Option, + filters: Option, } #[cfg(feature = "parquet")] @@ -6390,9 +6393,9 @@ impl AppLoadCountQuery { search_term: self.search_term, storage: self.storage, s3_resource_path: None, - csv_separator: None, - csv_has_header: None, - filters: None, + csv_separator: self.csv_separator, + csv_has_header: self.csv_has_header, + filters: self.filters, }, ) } @@ -6410,6 +6413,8 @@ struct AppLoadPreviewQuery { search_term: Option, storage: Option, csv_separator: Option, + csv_has_header: Option, + filters: Option, } #[cfg(feature = "parquet")] @@ -6427,8 +6432,8 @@ impl AppLoadPreviewQuery { storage: self.storage, csv_separator: self.csv_separator, s3_resource_path: None, - csv_has_header: None, - filters: None, + csv_has_header: self.csv_has_header, + filters: self.filters, }, ) } diff --git a/frontend/src/lib/components/DBTable.svelte b/frontend/src/lib/components/DBTable.svelte index 0309bb39cc..8c6bba513c 100644 --- a/frontend/src/lib/components/DBTable.svelte +++ b/frontend/src/lib/components/DBTable.svelte @@ -15,10 +15,16 @@ const MIN_COL_WIDTH = 60 const DEFAULT_COL_WIDTH = 150 const MAX_AUTO_COL_WIDTH = 400 - // Header padding, its key and sort icons with their gaps, and the cell's right border. - const HEADER_CHROME = 49 + // Header padding, the sort arrow with its gap (kept free so sorting never truncates the + // label), and the border. + const HEADER_CHROME = 34 + // A key, link or join icon with its gap. + const HEADER_ICON_WIDTH = 16 // A pinned header's pin icon with its gap, and the thicker border at the pinned block's edge. const PIN_CHROME = 17 + // The filter button in a filterable column's header, with its margin. + const HEADER_FILTER_WIDTH = 24 + const HEADER_FILTER_DEBOUNCE = 300 const CELL_PADDING = 18 // A double click starts with a click: following a foreign key waits this long // so the double click can edit the cell instead. @@ -45,6 +51,7 @@ Columns3, EyeOff, Download, + Filter, KeyRound, Link, Merge, @@ -107,6 +114,8 @@ joinTargets?: DbJoinTarget[] /** Offered from the add-column button: adding a column to the table itself. */ onNewColumn?: () => void + /** Hides the button that downloads the loaded rows, for a file whose owner disabled downloads. */ + disableDownload?: boolean } let { dbTableOps, @@ -116,7 +125,8 @@ onRowFilterApplied, layoutStorageKey, joinTargets, - onNewColumn + onNewColumn, + disableDownload = false }: Props = $props() const storedLayout = untrack(() => @@ -164,6 +174,65 @@ ) let columnFilters = $derived(columnFiltersOf(filters, filterSchema)) let hasFilters = $derived(!!quicksearch || !!filterWhere) + /** The column whose header filter is open, and the value typed there. A header filter + * writes the same entry the search bar does, so each shows the other's filter. */ + let headerFilter: { column: string; key: string; draft: string } | undefined = $state(undefined) + /** The typed value not yet written to `filters`. Written when typing pauses, and at once + * when the popover closes or another column is typed in, so no keystroke is lost. */ + let pendingHeaderFilter: { key: string; draft: string } | undefined + let headerFilterTimer: ReturnType | undefined + function setHeaderFilter(key: string, boolean: boolean, draft: string) { + const { [key]: current, ...rest } = filters + const trimmed = draft.trim() + const value = trimmed ? (boolean ? trimmed === 'true' : trimmed) : undefined + if (value === current) return + filters = value === undefined ? rest : { ...rest, [key]: value } + } + function flushHeaderFilter() { + clearTimeout(headerFilterTimer) + const pending = pendingHeaderFilter + pendingHeaderFilter = undefined + if (pending) setHeaderFilter(pending.key, false, pending.draft) + } + /** Filters as the reader types; a half-typed comparison such as `>` matches no row. */ + function typeHeaderFilter(key: string, draft: string) { + if (pendingHeaderFilter && pendingHeaderFilter.key !== key) flushHeaderFilter() + if (headerFilter?.key === key) headerFilter.draft = draft + pendingHeaderFilter = { key, draft } + clearTimeout(headerFilterTimer) + headerFilterTimer = setTimeout(flushHeaderFilter, HEADER_FILTER_DEBOUNCE) + } + /** For a popover's content: Escape closes that popover only. Left to the window, it + * would also close a drawer the table sits in. */ + function escapeClosesOnly(close: () => void) { + return (e: KeyboardEvent) => { + if (e.key !== 'Escape') return + e.stopPropagation() + close() + } + } + /** Where focus goes when a header filter closes: back to its button, unless the click + * that closed it put focus somewhere else (the search bar). */ + function headerFilterCloseFocus(column: string): HTMLElement | null { + const active = document.activeElement + if (active && active !== document.body) return null + return ( + scrollEl?.querySelector( + `[data-header-column="${CSS.escape(column)}"] [data-popover]` + ) ?? null + ) + } + function closeHeaderFilter() { + flushHeaderFilter() + headerFilter = undefined + } + /** The open popover's text: what was typed, unless the filter was changed from elsewhere + * (the search bar, a chip removed) since. */ + function headerFilterDraft(key: string): string { + const applied = filters[key] === undefined ? '' : String(filters[key]) + const draft = headerFilter?.key === key ? headerFilter.draft : applied + return pendingHeaderFilter?.key === key || draft.trim() === applied ? draft : applied + } $effect(() => { const f = rowFilter @@ -235,6 +304,9 @@ colDefs: dbTableOps.colDefs, quicksearch, filterWhere, + // Sources that filter rows themselves read the values: `>` and `abc` on a number + // column render the same SQL but are different requests. + columnFilters, sort, joins, workspace: $operatingWorkspace, @@ -245,18 +317,22 @@ // A refresh keeps the scroll position; a new query starts from the top. const onlyRefreshed = prevQuery && deepEqual({ ...query, refreshCount: 0 }, { ...prevQuery, refreshCount: 0 }) + const onlySorted = + prevQuery && deepEqual({ ...query, sort: undefined }, { ...prevQuery, sort: undefined }) prevQuery = query if (!onlyRefreshed && scrollEl) scrollEl.scrollTop = 0 - reload() + reload(onlySorted) }) }) - function reload() { + /** `keepCount`: the rows are the same, only their order changed. */ + function reload(keepCount = false) { generation += 1 blocks = {} endRow = undefined - rowCount = undefined editing = undefined + if (keepCount && rowCount !== undefined) return + rowCount = undefined if (!$operatingWorkspace) return const gen = generation dbTableOps @@ -372,7 +448,10 @@ const sizedWidths = Object.fromEntries( [...sizedColumns].filter((f) => widths[f] !== undefined).map((f) => [f, widths[f]]) ) - if (Object.keys(sizedWidths).length) layout.widths = sizedWidths + if (Object.keys(sizedWidths).length) { + layout.widths = sizedWidths + layout.widthsFitFilterButton = true + } if (Object.keys(pinned).length) layout.pinned = $state.snapshot(pinned) if (joins.length) layout.joins = $state.snapshot(joins) if (hidden.length) layout.hidden = $state.snapshot(hidden) @@ -383,6 +462,8 @@ // ── Column widths ──────────────────────────────────────────────────────── let widths: Record = $state({ ...storedLayout.widths }) let sizedColumns = new Set(Object.keys(storedLayout.widths ?? {})) + // Widths saved before headers had a filter button can be too narrow for their label. + let widenStoredWidths = !storedLayout.widthsFitFilterButton let autoSizedFor: ColumnDef[] | undefined let measureCtx: CanvasRenderingContext2D | null | undefined @@ -398,12 +479,23 @@ const family = getComputedStyle(scrollEl).fontFamily const rows = loadedRows().slice(0, 300) const next = { ...widths } + const headerWidth = (col: ColumnDef) => + textWidth(col.field, `600 12px ${family}`) + + HEADER_CHROME + + (col.isprimarykey || fkByColumn[col.field] || joinedAliases.has(col.field) + ? HEADER_ICON_WIDTH + : 0) + + (pinned[col.field] ? PIN_CHROME : 0) + + (filterSchema.keyOfColumn[col.field] ? HEADER_FILTER_WIDTH : 0) for (const col of columns) { - if (only ? !only.includes(col.field) : sizedColumns.has(col.field)) continue - let w = - textWidth(col.field, `600 12px ${family}`) + - HEADER_CHROME + - (pinned[col.field] ? PIN_CHROME : 0) + if (only ? !only.includes(col.field) : sizedColumns.has(col.field)) { + if (!only && widenStoredWidths && next[col.field] !== undefined) + next[col.field] = Math.ceil( + Math.max(next[col.field], Math.min(MAX_AUTO_COL_WIDTH, headerWidth(col))) + ) + continue + } + let w = headerWidth(col) for (const row of rows) { const text = formatCell(row[col.field]).slice(0, 200) || 'NULL' w = Math.max(w, textWidth(text, `400 12px ${family}`) + CELL_PADDING) @@ -412,6 +504,7 @@ next[col.field] = Math.ceil(Math.min(MAX_AUTO_COL_WIDTH, Math.max(MIN_COL_WIDTH, w))) sizedColumns.add(col.field) } + if (!only) widenStoredWidths = false widths = next saveLayout() } @@ -928,6 +1021,96 @@ {/if} {/snippet} +{#snippet headerFilterButton(col: ColumnDef, key: string)} + {@const boolean = dbColumnKind(col.datatype) === 'boolean'} + {@const number = dbColumnKind(col.datatype) === 'number'} + {@const active = filters[key] !== undefined && filters[key] !== ''} + {@const open = headerFilter?.column === col.field} + headerFilterCloseFocus(col.field)} + bind:isOpen={ + () => open, + (isOpen) => { + if (isOpen) { + flushHeaderFilter() + headerFilter = { column: col.field, key, draft: active ? String(filters[key]) : '' } + } else if (open) closeHeaderFilter() + } + } + class={twMerge( + 'mr-1 flex h-5 w-5 shrink-0 items-center justify-center rounded hover:bg-surface-hover', + active || open + ? 'text-accent' + : 'text-secondary opacity-0 group-hover/header:opacity-100 focus-visible:opacity-100' + )} + triggerAttrs={{ + 'aria-label': `Filter ${col.field}`, + title: active ? `Filtered: ${filters[key]}` : `Filter ${col.field}` + }} + > + {#snippet trigger()} + + {/snippet} + {#snippet content()} + +
+ Filter {col.field} + {#if boolean} + mountGrid()}> - - - - - -
- - - {/if} - {#if !disable_download && !s3resource.endsWith('.csv')} - {@const csvApiPath = appPath - ? `/w/${workspaceId}/apps_u/download_s3_parquet_file_as_csv/${appPath}?file_key=${encodeURIComponent(s3resource)}${storage ? `&storage=${storage}` : ''}${presigned ? `&${presigned}` : ''}` - : `/w/${workspaceId}/job_helpers/download_s3_parquet_file_as_csv?file_key=${encodeURIComponent(s3resource)}${storage ? `&storage=${storage}` : ''}`} - {@const csvName = (s3resource.split('/').pop() ?? 'download') + '.csv'} - {#if shouldDownloadViaClient()} - - {:else} -
CSV
- {/if} - {/if} - - {#if nbRows != undefined} -
{nbRows} rows
- {:else} - - {/if} -
- {#if error} -
{error}
-
Try changing separator to fix it
- {/if} -
-
- - - diff --git a/frontend/src/lib/components/TaggedTextInput.svelte b/frontend/src/lib/components/TaggedTextInput.svelte index 66f968f097..be4b7c8e97 100644 --- a/frontend/src/lib/components/TaggedTextInput.svelte +++ b/frontend/src/lib/components/TaggedTextInput.svelte @@ -44,7 +44,9 @@ const currentText = getTextContent() if (currentText !== value) { updateDisplay(value) - if (!_preventCursorMoveOnNextSync) { + // Placing the caret focuses this input: never take focus from another field + // that wrote the value, such as a table's column filter. + if (!_preventCursorMoveOnNextSync && !typingElsewhere()) { restoreCursor(value.length) const cursorPos = getCursorPosition() updateCurrentTag(cursorPos) @@ -54,6 +56,15 @@ _preventCursorMoveOnNextSync = false }) + function typingElsewhere(): boolean { + const active = document.activeElement + return ( + active instanceof HTMLElement && + !contentEditableDiv.contains(active) && + active.matches('input, textarea, select, [contenteditable]:not([contenteditable="false"])') + ) + } + export function preventCursorMoveOnNextSync() { _preventCursorMoveOnNextSync = true } diff --git a/frontend/src/lib/components/apps/editor/appUtilsS3.ts b/frontend/src/lib/components/apps/editor/appUtilsS3.ts index 15353382cc..9e9228dd59 100644 --- a/frontend/src/lib/components/apps/editor/appUtilsS3.ts +++ b/frontend/src/lib/components/apps/editor/appUtilsS3.ts @@ -117,7 +117,7 @@ export async function getS3File({ // Editor/preview runs execute as the *caller* (Viewer mode), so read their // results back as the caller through the viewer-scoped `job_helpers` endpoint — - // never author-mode — consistent with DisplayResult/ParqetCsvTableRenderer. Only + // never author-mode — consistent with DisplayResult. Only // a deployed app view reads on-behalf of the author via the provenance-gated // `apps_u` endpoint. if (isEditor) { diff --git a/frontend/src/lib/components/common/fileDownload/S3ObjectTable.svelte b/frontend/src/lib/components/common/fileDownload/S3ObjectTable.svelte new file mode 100644 index 0000000000..122f618a0d --- /dev/null +++ b/frontend/src/lib/components/common/fileDownload/S3ObjectTable.svelte @@ -0,0 +1,178 @@ + + +
+ {#if isCsv || (isParquet && !s3object.disable_download)} +
+ {#if isCsv} +
+ Separator +