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 <noreply@anthropic.com>

* feat: accept column filters, header row and separator on app s3 table routes

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat: show s3 csv and parquet results in the db table with filters

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat: apply db table header filters as you type and widen filterable columns

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: harden db table header filters, column widths and narrow s3 tables

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* chore: point ee ref at the unknown filter column fix

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: compare postgres arrays as text, ignore stale s3 table counts, clearable separator

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Ruben Fiszel <ruben@windmill.dev>
This commit is contained in:
Guilhem
2026-11-30 21:58:26 +01:00
committed by GitHub
co-authored by Claude Opus 5.5 Ruben Fiszel
parent f79e4b618d
commit 8064fa8fb6
11 changed files with 492 additions and 377 deletions
+9
View File
@@ -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:
+10 -5
View File
@@ -6378,6 +6378,9 @@ struct AppLoadCountQuery {
search_col: Option<String>,
search_term: Option<String>,
storage: Option<String>,
csv_separator: Option<String>,
csv_has_header: Option<bool>,
filters: Option<String>,
}
#[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<String>,
storage: Option<String>,
csv_separator: Option<String>,
csv_has_header: Option<bool>,
filters: Option<String>,
}
#[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,
},
)
}
+232 -34
View File
@@ -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<typeof setTimeout> | 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<HTMLElement>(
`[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<string, number> = $state({ ...storedLayout.widths })
let sizedColumns = new Set<string>(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}
<Popover
floatingConfig={{ strategy: 'fixed', placement: 'bottom-start' }}
closeFocus={() => 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()}
<Filter size={12} />
{/snippet}
{#snippet content()}
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div class="flex w-64 flex-col gap-2 p-3" onkeydown={escapeClosesOnly(closeHeaderFilter)}>
<span class="truncate text-xs font-semibold text-emphasis">Filter {col.field}</span>
{#if boolean}
<Select
items={[
{ label: 'true', value: 'true' },
{ label: 'false', value: 'false' }
]}
bind:value={
() => headerFilterDraft(key) || undefined,
(v) => {
if (headerFilter) headerFilter.draft = v ?? ''
setHeaderFilter(key, true, v ?? '')
}
}
placeholder="Value"
size="sm"
/>
{:else}
<TextInput
bind:value={() => headerFilterDraft(key), (v) => typeHeaderFilter(key, String(v ?? ''))}
size="sm"
inputProps={{
placeholder: number ? '10, >10, <=5' : 'Contains',
'aria-label': `Filter ${col.field}`,
onkeydown: (e: KeyboardEvent) => {
if (e.key === 'Enter') closeHeaderFilter()
}
}}
/>
<span class="text-2xs text-secondary">
{number
? 'A number, or a comparison: =, >, >=, <, <=, !='
: 'Rows whose value contains this text. Start with = for an exact match.'}
</span>
{/if}
{#if active}
<div class="flex justify-end">
<Button
variant="subtle"
unifiedSize="sm"
onClick={() => {
pendingHeaderFilter = undefined
clearTimeout(headerFilterTimer)
setHeaderFilter(key, boolean, '')
headerFilter = undefined
}}
>
Clear
</Button>
</div>
{/if}
</div>
{/snippet}
</Popover>
{/snippet}
{#snippet addColumnHeader()}
{#if canAddColumn}
<div
@@ -1041,18 +1224,23 @@
/>
<div class="h-full relative flex flex-col">
<div class="flex justify-between items-center bg-surface-input pr-2">
<FilterSearchbar
class="grow rounded-none !border-0"
size="lg"
searchIconPosition="left"
dropdownMaxWidth={480}
dropdownOffsetY={1}
schema={filterSchema.schema}
bind:value={filters}
placeholder="Search, or filter by column..."
/>
<div class="flex shrink-0 items-center gap-2 text-xs text-secondary">
<div class="flex flex-wrap justify-between items-center bg-surface-input pr-2">
<!-- The search bar stops its mousedown, which an open header filter would take as an
outside click; close that popover first so the bar gets the focus. -->
<div class="contents" onmousedowncapture={() => headerFilter && closeHeaderFilter()}>
<FilterSearchbar
class="grow min-w-48 rounded-none !border-0"
size="lg"
searchIconPosition="left"
dropdownMaxWidth={480}
dropdownOffsetY={1}
schema={filterSchema.schema}
bind:value={filters}
placeholder="Search, or filter by column..."
/>
</div>
<!-- Wraps under the search bar in a narrow panel rather than being cut off. -->
<div class="ml-auto flex shrink-0 items-center gap-2 pl-2 text-xs text-secondary">
{#if totalRows > 0 && endRow !== 0}
<span class="whitespace-nowrap">
{Math.min(firstVisible + 1, totalRows)}–{Math.min(lastVisible, totalRows)}
@@ -1061,14 +1249,16 @@
{/if}
</span>
{/if}
<Button
startIcon={{ icon: Download }}
variant="subtle"
unifiedSize="sm"
iconOnly
title="Download loaded rows as CSV"
onClick={downloadCsv}
/>
{#if !disableDownload}
<Button
startIcon={{ icon: Download }}
variant="subtle"
unifiedSize="sm"
iconOnly
title="Download loaded rows as CSV"
onClick={downloadCsv}
/>
{/if}
<div class="flex" bind:this={columnsAnchor}>
<Popover
floatingConfig={{ strategy: 'fixed', placement: 'bottom-end' }}
@@ -1088,7 +1278,12 @@
</Button>
{/snippet}
{#snippet content()}
<div class="flex w-60 flex-col py-1" data-testid="db-columns-picker">
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div
class="flex w-60 flex-col py-1"
data-testid="db-columns-picker"
onkeydown={escapeClosesOnly(() => (columnsPickerOpen = false))}
>
<label
class="flex cursor-pointer items-center gap-2 border-b px-3 py-1.5 text-xs font-medium text-emphasis hover:bg-surface-hover"
>
@@ -1220,7 +1415,7 @@
{/if}
<div
class={twMerge(
'relative shrink-0 flex items-center border-r',
'group/header relative shrink-0 flex items-center border-r',
// Above the other header cells, whose resize handles sit at z-10.
pin ? 'sticky z-20 bg-surface-tertiary dark:bg-surface-input' : '',
// The pinned block's edge against the scrolling columns is a pixel thicker.
@@ -1257,6 +1452,9 @@
<Icon size={12} class="shrink-0 text-secondary" />
{/if}
</button>
{#if filterSchema.keyOfColumn[col.field]}
{@render headerFilterButton(col, filterSchema.keyOfColumn[col.field])}
{/if}
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div
class="absolute -right-1 top-0 bottom-0 w-2 z-10 cursor-col-resize hover:bg-border-selected/50"
@@ -54,7 +54,8 @@
import Toggle from './Toggle.svelte'
import FileDownload from './common/fileDownload/FileDownload.svelte'
import ParqetTableRenderer from './ParqetCsvTableRenderer.svelte'
import S3ObjectTable from './common/fileDownload/S3ObjectTable.svelte'
import { serverTableFormat } from './s3TableOps'
import ToggleButtonGroup from './common/toggleButton-v2/ToggleButtonGroup.svelte'
import ToggleButton from './common/toggleButton-v2/ToggleButton.svelte'
import MapResult from './MapResult.svelte'
@@ -1309,16 +1310,9 @@
{/if}
</div>
{#if typeof s3object?.s3 === 'string'}
{#if s3object?.s3?.endsWith('.parquet') || s3object?.s3?.endsWith('.csv')}
{#if serverTableFormat(s3object.s3)}
{#key s3object.s3}
<ParqetTableRenderer
disable_download={s3object?.disable_download}
{workspaceId}
{appPath}
s3resource={s3object?.s3}
storage={s3object?.storage}
presigned={s3object?.presigned}
/>
<S3ObjectTable {s3object} {workspaceId} {appPath} />
{/key}
{:else if isS3ImageKey(s3object?.s3 ?? '')}
<div class="h-full mt-2">
@@ -1372,16 +1366,9 @@
{:else}
<div class="flex text-primary pt-2">{s3object?.s3} (download disabled)</div>
{/if}
{#if s3object?.s3?.endsWith('.parquet') || s3object?.s3?.endsWith('.csv')}
{#if typeof s3object?.s3 === 'string' && serverTableFormat(s3object.s3)}
{#if seeS3PreviewFileFromList == s3object?.s3}
<ParqetTableRenderer
disable_download={s3object?.disable_download}
{workspaceId}
{appPath}
s3resource={s3object?.s3}
storage={s3object?.storage}
presigned={s3object?.presigned}
/>{:else}
<S3ObjectTable {s3object} {workspaceId} {appPath} />{:else}
<button
class="text-primary whitespace-nowrap flex gap-2 items-center"
onclick={() => {
@@ -1,305 +0,0 @@
<script lang="ts">
import { run } from 'svelte/legacy'
import { type GridApi, createGrid, type IDatasource } from 'ag-grid-community'
import 'ag-grid-community/styles/ag-grid.css'
import 'ag-grid-community/styles/ag-theme-alpine.css'
import { twMerge } from 'tailwind-merge'
import DarkModeObserver from './DarkModeObserver.svelte'
import { AppService, HelpersService } from '$lib/gen'
import { downloadViaClient, shouldDownloadViaClient } from '$lib/utils/downloadFile'
import { enterpriseLicense } from '$lib/stores'
import { Download } from 'lucide-svelte'
import { Loader2 } from 'lucide-svelte'
import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte'
const operatingWorkspace = useOperatingWorkspace()
// import 'ag-grid-community/dist/styles/ag-theme-alpine-dark.css'
let selectedRowIndex = -1
interface Props {
s3resource: string
storage: string | undefined
workspaceId: string | undefined
disable_download?: boolean
// When set (deployed app view), read the file on-behalf of the app author
// through the app-scoped, provenance-gated `apps_u/*` endpoints instead of
// the viewer-scoped `job_helpers/*` API. Undefined in the editor/preview.
appPath?: string | undefined
// HMAC bearer (`exp=..&sig=..`) minted by `signS3Objects`. When present on a
// deployed-app read, it bypasses the provenance gate — matching the download
// and image routes. Forwarded to every app-scoped preview/count/export call.
presigned?: string | undefined
}
let {
s3resource,
storage,
workspaceId,
disable_download = false,
appPath = undefined,
presigned = undefined
}: Props = $props()
// Split the presigned bearer into typed query params for the generated client.
// Only meaningful in deployed-app (`appPath`) reads; empty otherwise.
function presignedParams(): { sig?: string; exp?: string } {
if (!appPath || !presigned) return {}
const p = new URLSearchParams(presigned)
return { sig: p.get('sig') ?? undefined, exp: p.get('exp') ?? undefined }
}
// Route the parquet/csv read through the app-scoped endpoints when `appPath`
// is set, else the viewer-scoped helpers. Same request/response shape either
// way — the only difference is which identity authorizes the S3 read.
function loadRowCount(searchCol: string | undefined, searchTerm: string | undefined) {
const workspace = workspaceId ?? $operatingWorkspace!
return appPath
? AppService.appLoadTableCount({
workspace,
path: appPath,
fileKey: s3resource,
searchCol,
searchTerm,
storage,
...presignedParams()
})
: HelpersService.loadTableRowCount({
workspace,
path: s3resource,
searchCol,
searchTerm,
storage
})
}
function loadChunk(args: {
offset?: number
limit?: number
sortCol?: string
sortDesc?: boolean
searchCol?: string
searchTerm?: string
csvSeparator?: string
}) {
const workspace = workspaceId ?? $operatingWorkspace!
const csv = s3resource.endsWith('.csv')
if (appPath) {
const data = {
workspace,
path: appPath,
fileKey: s3resource,
storage,
...args,
...presignedParams()
}
return csv ? AppService.appLoadCsvPreview(data) : AppService.appLoadParquetPreview(data)
}
const data = { workspace, path: s3resource, storage, ...args }
return csv ? HelpersService.loadCsvPreview(data) : HelpersService.loadParquetPreview(data)
}
let lastSearch: string | undefined = undefined
let nbRows: number | undefined = $state(undefined)
let csvSeparatorChar: string = $state(',')
let datasource: IDatasource = {
rowCount: 0,
getRows: async function (params) {
try {
const searchCol = params.filterModel ? Object.keys(params.filterModel)?.[0] : undefined
const searchTerm = searchCol ? params.filterModel?.[searchCol]?.filter : undefined
const csv = s3resource.endsWith('.csv')
const newSearch = searchCol ? searchCol + searchTerm : undefined
if (!nbRows || lastSearch != newSearch) {
nbRows = undefined
const res = await loadRowCount(searchCol, searchTerm)
nbRows = res.count
lastSearch = newSearch
}
const res = (await loadChunk({
offset: params.startRow,
limit: params.endRow - params.startRow,
sortCol: params.sortModel?.[0]?.colId,
sortDesc: params.sortModel?.[0]?.sort == 'desc',
searchCol,
searchTerm,
csvSeparator: csv ? csvSeparatorChar : undefined
})) as any
for (let i = 0; i < res.rows.length; i++) {
res.rows[i]['__index'] = i + params.startRow
if (!$enterpriseLicense) {
Object.keys(res.rows[i]).forEach((key) => {
if (key != '__index') {
res.rows[i][key] = 'Require EE'
}
})
}
}
params.successCallback(res.rows, nbRows)
} catch (e) {
console.error(e)
params.failCallback()
}
}
}
function toggleRow(row: any) {
if (row) {
let rowIndex = row.rowIndex
let data = { ...row.data }
delete data['__index']
if (selectedRowIndex !== rowIndex) {
selectedRowIndex = rowIndex
}
}
}
function toggleRows(rows: any[]) {
toggleRow(rows[0])
}
let eGui: HTMLDivElement | undefined = $state()
// A remount (a new separator) builds a new grid in the same element: the previous one is
// destroyed, or it stays on top showing the old columns.
let gridApi: GridApi | undefined
let mounts = 0
let error: string | undefined = $state(undefined)
async function mountGrid() {
if (eGui) {
const mount = ++mounts
try {
const csv = s3resource.endsWith('.csv')
const res = (await loadChunk({
limit: 0,
csvSeparator: csv ? csvSeparatorChar : undefined
})) as any
// The separator changed again while this one loaded: the later mount owns the grid.
if (mount !== mounts) return
gridApi?.destroy()
gridApi = createGrid(
eGui,
{
rowModelType: 'infinite',
datasource,
// @ts-ignore
columnDefs: res.columns.map((c) => {
return {
field: c,
sortable: true,
filter: true,
filterParams: {
filterOptions: ['contains'],
maxNumConditions: 1
}
}
}),
pagination: false,
// defaultColDef: {
// flex: 1
// },
suppressColumnMoveAnimation: true,
rowSelection: 'multiple',
rowMultiSelectWithClick: true,
suppressRowDeselection: true,
onSelectionChanged: (e) => {
onSelectionChanged(e.api)
},
getRowId: (data) => {
return (data as any).data['__index']
}
},
{}
)
error = undefined
} catch (e) {
if (mount !== mounts) return
error = e.body
console.error(e)
}
}
}
function onSelectionChanged(api: GridApi<any>) {
const rows = api.getSelectedNodes()
if (rows != undefined) {
toggleRows(rows)
}
}
let darkMode: boolean = $state(false)
run(() => {
eGui && mountGrid()
})
</script>
<DarkModeObserver bind:darkMode />
<div class={twMerge('mt-2 flex flex-col h-full min-h-[600px]')}>
{#if s3resource.endsWith('.csv')}
<div class="flex flex-row-reverse w-full">
<div class="flex items-baseline">
<label for="csvSeparatorChar" class="text-2xs text-secondary">Separator</label>
<div class="w-12 ml-2 mr-2">
<select class="h-8" bind:value={csvSeparatorChar} onchange={(e) => mountGrid()}>
<option value=",">,</option>
<option value=";">;</option>
<option value={'\t'}>\t</option>
<option value="|">|</option>
</select>
</div>
</div>
</div>
{/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()}
<button
class="text-secondary w-full text-right underline text-2xs whitespace-nowrap"
onclick={() => downloadViaClient(csvApiPath, csvName)}
><div class="flex flex-row-reverse gap-2 items-center"><Download size={12} /> CSV</div
></button
>
{:else}
<a
target="_blank"
href="/api{csvApiPath}"
class="text-secondary w-full text-right underline text-2xs whitespace-nowrap"
><div class="flex flex-row-reverse gap-2 items-center"><Download size={12} /> CSV</div></a
>
{/if}
{/if}
{#if nbRows != undefined}
<div class="text-secondary ml-0.5 text-2xs">{nbRows} rows</div>
{:else}
<Loader2 class="animate-spin ml-0.5" size={12} />
{/if}
<div
class="ag-theme-alpine shadow-sm h-full"
class:ag-theme-alpine-dark={darkMode}
style="height: 600px;"
>
{#if error}
<div class="text-red-500">{error}</div>
<div>Try changing separator to fix it</div>
{/if}
<div bind:this={eGui} style="height:100%; "></div>
</div>
</div>
<!-- <div class="flex gap-1 absolute bottom-1 right-2 text-sm text-secondary"
>{firstRow}{'->'}{lastRow + 1} of {datasource?.rowCount} rows</div
> -->
@@ -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
}
@@ -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) {
@@ -0,0 +1,178 @@
<script lang="ts">
import { ChevronDown, Download, Loader2 } from 'lucide-svelte'
import { Button } from '$lib/components/common'
import Select from '$lib/components/select/Select.svelte'
import Toggle from '$lib/components/Toggle.svelte'
import type { IDbTableOps } from '$lib/components/dbOps'
import { s3TableOps, serverTableFormat } from '$lib/components/s3TableOps'
import {
setOperatingWorkspace,
useOperatingWorkspace
} from '$lib/components/operatingWorkspace.svelte'
import { downloadViaClient, shouldDownloadViaClient } from '$lib/utils/downloadFile'
interface Props {
s3object: { s3: string; storage?: string; presigned?: string; disable_download?: boolean }
workspaceId?: string | undefined
/** Set in a deployed app: the file is read through the app-scoped `apps_u/*` routes. */
appPath?: string | undefined
}
let { s3object, workspaceId = undefined, appPath = undefined }: Props = $props()
const operatingWorkspace = useOperatingWorkspace()
// DBTable loads no rows without an operating workspace, and a public app sets none.
setOperatingWorkspace(() => workspaceId)
const CSV_SEPARATORS = [
{ value: ',', label: ',' },
{ value: ';', label: ';' },
{ value: '\t', label: 'Tab' },
{ value: '|', label: '|' }
]
// DBTable's search bar, header row and body rows, in px.
const TOOLBAR_HEIGHT = 40
// Below about this width the toolbar wraps the row count and buttons under the search bar.
const TOOLBAR_WRAP_WIDTH = 480
const HEADER_HEIGHT = 30
const ROW_HEIGHT = 34
const SCROLLBAR = 12
let separator: string | undefined = $state(undefined)
let hasHeader = $state(true)
/** The separator the server guessed while none is picked. */
let detectedSeparator: string | undefined = $state(undefined)
/** Rows in the whole file, kept while a search narrows them so the table keeps its height. */
let totalRows: number | undefined = $state(undefined)
let width = $state(0)
// JSON lines are read through the CSV route too, but have no separator or header row.
let isCsv = $derived(/\.(csv|tsv)$/i.test(s3object.s3))
let isParquet = $derived(serverTableFormat(s3object.s3) === 'parquet')
let workspace = $derived(workspaceId ?? $operatingWorkspace!)
// The server converts the whole file; the table's own export only has the rows it loaded.
let parquetCsvPath = $derived(
appPath
? `/w/${workspace}/apps_u/download_s3_parquet_file_as_csv/${appPath}?file_key=${encodeURIComponent(s3object.s3)}${s3object.storage ? `&storage=${s3object.storage}` : ''}${s3object.presigned ? `&${s3object.presigned}` : ''}`
: `/w/${workspace}/job_helpers/download_s3_parquet_file_as_csv?file_key=${encodeURIComponent(s3object.s3)}${s3object.storage ? `&storage=${s3object.storage}` : ''}`
)
let parquetCsvName = $derived((s3object.s3.split('/').pop() ?? 'download') + '.csv')
let height = $derived(
totalRows === undefined
? 240
: Math.min(
600,
Math.max(
180,
(width && width < TOOLBAR_WRAP_WIDTH ? 2 : 1) * TOOLBAR_HEIGHT +
HEADER_HEIGHT +
totalRows * ROW_HEIGHT +
SCROLLBAR
)
)
)
function recordingTotal(ops: IDbTableOps, source: Promise<unknown>): IDbTableOps {
return {
...ops,
getCount: async (params) => {
const n = await ops.getCount(params)
const filtered = !!params.quicksearch || Object.keys(params.columnFilters ?? {}).length > 0
// A count from a table the separator, header row or file replaced is not this one's.
if (!filtered && table === source) totalRows = n
return n
}
}
}
// Lazy: DBTable reaches Monaco, and every page that shows a job result imports this table.
const dbTable = import('$lib/components/DBTable.svelte')
let table = $derived.by(() => {
const pending = s3TableOps({
workspace,
fileKey: s3object.s3,
storage: s3object.storage,
csvSeparator: separator,
csvHasHeader: hasHeader,
app: appPath ? { path: appPath, presigned: s3object.presigned } : undefined
}).then((t) => {
// A table superseded while loading must not label the current one.
if (table !== pending) return t as never
detectedSeparator = t.csvSeparator
return dbTable.then((m) => ({
...t,
ops: recordingTotal(t.ops, pending),
DBTable: m.default
}))
})
return pending
})
</script>
<div class="flex flex-col gap-1 mt-2">
{#if isCsv || (isParquet && !s3object.disable_download)}
<div class="flex items-center justify-end gap-4 text-xs text-secondary">
{#if isCsv}
<div class="flex items-center gap-2">
<span>Separator</span>
<Select
size="sm"
class="w-20"
clearable
RightIcon={ChevronDown}
items={CSV_SEPARATORS}
bind:value={separator}
placeholder={CSV_SEPARATORS.find((s) => s.value === detectedSeparator)?.label ?? 'Auto'}
/>
</div>
<Toggle size="xs" bind:checked={hasHeader} options={{ right: 'Header row' }} />
{:else if shouldDownloadViaClient()}
<Button
variant="subtle"
unifiedSize="xs"
startIcon={{ icon: Download }}
onClick={() => downloadViaClient(parquetCsvPath, parquetCsvName)}
>
Download as CSV
</Button>
{:else}
<Button
variant="subtle"
unifiedSize="xs"
startIcon={{ icon: Download }}
href="/api{parquetCsvPath}"
download={parquetCsvName}
>
Download as CSV
</Button>
{/if}
</div>
{/if}
<div
class="overflow-hidden border rounded-md"
style="height: {height}px"
bind:clientWidth={width}
data-interactive
>
{#await table}
<div class="flex h-full items-center justify-center gap-1 text-2xs text-secondary">
<Loader2 size={12} class="animate-spin" /> Loading table
</div>
{:then t}
<t.DBTable dbTableOps={t.ops} disableDownload={s3object.disable_download || isParquet} />
{:catch e}
{@const message = String(e?.body ?? e?.message ?? e)}
<!-- The storage reports an empty file as a failed range read. -->
{#if /Range started at 0 and ended at 0/.test(message)}
<div class="p-3 text-xs text-secondary">This file is empty.</div>
{:else}
<div class="p-3 text-xs text-red-600 dark:text-red-400 break-words">
Could not read this file as a table: {message}
</div>
{/if}
{/await}
</div>
</div>
@@ -14,6 +14,8 @@ export type DbTableLayout = {
/** Columns left out of the grid. */
hidden?: string[]
formats?: Record<string, ColumnFormat>
/** `widths` leave room for the header's filter button. */
widthsFitFilterButton?: boolean
lastUsed?: number
}
@@ -14,6 +14,10 @@ describe('serverTableFormat', () => {
expect(serverTableFormat('a.json')).toBeUndefined()
expect(serverTableFormat('a.txt')).toBeUndefined()
})
it('leaves an upper-case parquet extension to the download card', () => {
expect(serverTableFormat('a.PARQUET')).toBeUndefined()
})
})
describe('datatypeOf', () => {
+38 -12
View File
@@ -1,13 +1,13 @@
import { HelpersService, OpenAPI } from '$lib/gen'
import { AppService, HelpersService, OpenAPI } from '$lib/gen'
import { getHeaders } from '$lib/gen/core/request'
import { ColumnIdentity, type ColumnDef } from './apps/components/display/dbtable/utils'
import type { IDbTableOps } from './dbOps'
/** Files the server can page through as a table, without reading them whole. */
export function serverTableFormat(fileKey: string): 'parquet' | 'csv' | undefined {
const key = fileKey.toLowerCase()
if (key.endsWith('.parquet')) return 'parquet'
if (/\.(csv|tsv|jsonl|ndjson)$/.test(key)) return 'csv'
// The parquet reader requires the lower-case extension; the CSV reader takes any case.
if (fileKey.endsWith('.parquet')) return 'parquet'
if (/\.(csv|tsv|jsonl|ndjson)$/i.test(fileKey)) return 'csv'
return undefined
}
@@ -18,6 +18,8 @@ export type S3TableSource = {
s3ResourcePath?: string
csvSeparator?: string
csvHasHeader?: boolean
/** Read through a deployed app's `apps_u/*` routes. */
app?: { path: string; presigned?: string }
}
type Chunk = {
@@ -47,14 +49,29 @@ export async function s3TableOps(
): Promise<{ ops: IDbTableOps; csvSeparator?: string }> {
const format = serverTableFormat(source.fileKey)
if (!format) throw new Error(`${source.fileKey} cannot be read as a table`)
const app = source.app
const common = {
workspace: source.workspace,
path: source.fileKey,
storage: source.storage,
s3ResourcePath: source.s3ResourcePath
}
const signed = new URLSearchParams(app?.presigned ?? '')
const appCommon = app && {
workspace: source.workspace,
path: app.path,
fileKey: source.fileKey,
storage: source.storage,
sig: signed.get('sig') ?? undefined,
exp: signed.get('exp') ?? undefined
}
const csvOptions: { csvSeparator?: string; csvHasHeader?: boolean } =
format === 'csv' ? { csvSeparator: source.csvSeparator, csvHasHeader: source.csvHasHeader } : {}
format === 'csv'
? {
csvSeparator: source.csvSeparator,
csvHasHeader: source.csvHasHeader
}
: {}
const filtersParam = (columnFilters: Record<string, unknown> | undefined) =>
columnFilters && Object.keys(columnFilters).length ? JSON.stringify(columnFilters) : undefined
const searchParam = (quicksearch: string) => quicksearch.trim() || undefined
@@ -67,8 +84,7 @@ export async function s3TableOps(
orderBy?: string
isDesc?: boolean
}): Promise<Chunk> {
const data = {
...common,
const args = {
...csvOptions,
offset: params.offset,
limit: params.limit,
@@ -77,6 +93,13 @@ export async function s3TableOps(
sortCol: params.orderBy,
sortDesc: params.isDesc
}
if (appCommon) {
const appData = { ...appCommon, ...args }
return (await (format === 'parquet'
? AppService.appLoadParquetPreview(appData)
: AppService.appLoadCsvPreview(appData))) as Chunk
}
const data = { ...common, ...args }
return (await (format === 'parquet'
? HelpersService.loadParquetPreview(data)
: HelpersService.loadCsvPreview(data))) as Chunk
@@ -89,7 +112,7 @@ export async function s3TableOps(
field,
datatype: datatypeOf(head.column_types?.[i]),
// The server cannot read a struct, map or union as text to filter it.
filterable: !/^(Struct|Map|Union)/.test(head.column_types?.[i] ?? ""),
filterable: !/^(Struct|Map|Union)/.test(head.column_types?.[i] ?? ''),
defaultvalue: '',
isprimarykey: false,
isidentity: ColumnIdentity.No,
@@ -99,15 +122,18 @@ export async function s3TableOps(
const ops: IDbTableOps = {
dbType: 'duckdb',
tableKey: source.fileKey.split('/').pop() ?? source.fileKey,
// Named after the file without its extension: the table's CSV export appends `.csv`.
tableKey: (source.fileKey.split('/').pop() ?? source.fileKey).replace(/\.[^.]+$/, ''),
colDefs,
getCount: async ({ quicksearch, columnFilters }) => {
const res = await HelpersService.loadTableRowCount({
...common,
const args = {
...csvOptions,
searchTerm: searchParam(quicksearch),
filters: filtersParam(columnFilters)
})
}
const res = appCommon
? await AppService.appLoadTableCount({ ...appCommon, ...args })
: await HelpersService.loadTableRowCount({ ...common, ...args })
return res.count ?? 0
},
getRows: async ({