github-advanced-security[bot] commented on code in PR #3037: URL: https://github.com/apache/drill/pull/3037#discussion_r2902135707
########## exec/java-exec/src/main/resources/webapp/src/components/results/ResultsGrid.tsx: ########## @@ -0,0 +1,641 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { useMemo, useCallback, useRef, useState } from 'react'; +import { AgGridReact } from 'ag-grid-react'; +import { Button, Space, Dropdown, Typography, Alert, Empty, Modal, Checkbox, Divider, Grid, message } from 'antd'; +import { + DownloadOutlined, + BarChartOutlined, + ExpandOutlined, + RobotOutlined, + UnorderedListOutlined, + SortAscendingOutlined, + ApiOutlined, + TableOutlined, +} from '@ant-design/icons'; +import type { ColDef, GridReadyEvent, GridApi, SortModelItem } from 'ag-grid-community'; +import type { MenuProps } from 'antd'; +import type { QueryResult, QueryError } from '../../types'; +import JsonCellRenderer from './JsonCellRenderer'; +import CustomHeader from './CustomHeader'; +import type { ColumnTransformation } from '../../utils/sqlTransformations'; +import { useTheme } from '../../hooks/useTheme'; + +import 'ag-grid-community/styles/ag-grid.css'; +import 'ag-grid-community/styles/ag-theme-alpine.css'; + +const { Text } = Typography; + +export interface ResultsSettings { + timestampDisplayFormat: 'locale' | 'iso' | 'utc' | 'epoch'; +} + +export const DEFAULT_RESULTS_SETTINGS: ResultsSettings = { + timestampDisplayFormat: 'locale', +}; + +interface ResultsGridProps { + results?: QueryResult; + error?: QueryError; + isLoading?: boolean; + onCreateVisualization?: () => void; + resultsSettings?: ResultsSettings; + onResultsSettingsChange?: (settings: ResultsSettings) => void; + onFixWithProspector?: () => void; + prospectorAvailable?: boolean; + onTransformColumn?: (columnName: string, transformation: ColumnTransformation) => void; + onShareApi?: () => void; +} + +export default function ResultsGrid({ + results, + error, + isLoading, + onCreateVisualization, + resultsSettings, + onFixWithProspector, + prospectorAvailable, + onTransformColumn, + onShareApi, +}: ResultsGridProps) { + const gridRef = useRef<AgGridReact>(null); + const gridApiRef = useRef<GridApi | null>(null); + const [columnManagerOpen, setColumnManagerOpen] = useState(false); + const [sortManagerOpen, setSortManagerOpen] = useState(false); + const [columnVisibility, setColumnVisibility] = useState<Record<string, boolean>>({}); + const screens = Grid.useBreakpoint(); + const isCompact = !screens.lg; + const { isDark } = useTheme(); + + const timestampFormat = resultsSettings?.timestampDisplayFormat ?? DEFAULT_RESULTS_SETTINGS.timestampDisplayFormat; + + // Generate column definitions from results with type-aware filters + const columnDefs = useMemo<ColDef[]>(() => { + if (!results?.columns) return []; + + return results.columns.map((col, index) => { + const metadataType = results.metadata?.[index]; + const config = getColumnConfig(metadataType); + const isDateColumn = metadataType && (metadataType.toUpperCase().includes('DATE') || metadataType.toUpperCase().includes('TIMESTAMP')); + + const colDef: ColDef = { + field: col, + headerName: col, + sortable: true, + resizable: true, + minWidth: Math.max(100, col.length * 9 + 60), + filter: config.filter, + filterParams: config.filterParams, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + headerComponent: CustomHeader as any, + headerComponentParams: { + onTransformColumn, + rowData: results.rows, + metadata: metadataType, + columnIndex: index, + }, + ...(config.filterValueGetter ? { filterValueGetter: config.filterValueGetter } : {}), + }; + + if (isDateColumn) { + colDef.valueGetter = (params) => { + const raw = params.data?.[col]; + if (raw == null) { + return null; + } + if (typeof raw === 'number') { + return new Date(raw).toISOString(); + } + return raw; + }; + colDef.valueFormatter = (params) => { + if (params.value == null) { + return ''; + } + return formatTimestamp(params.value, timestampFormat); + }; + } + + return colDef; + }); + }, [results, timestampFormat, onTransformColumn]); + + // Convert row data — stringify nested objects/arrays so AG Grid doesn't show [object Object] + const rowData = useMemo(() => { + if (!results?.rows) return []; + return results.rows.map((row) => { + const processed: Record<string, unknown> = {}; + for (const key of Object.keys(row)) { + const val = row[key]; + if (val !== null && typeof val === 'object') { + processed[key] = JSON.stringify(val); + } else { + processed[key] = val; + } + } + return processed; + }); + }, [results]); + + const saveColumnState = useCallback(() => { + const state = gridApiRef.current?.getColumnState(); + if (state) { + try { + localStorage.setItem('drill-grid-column-state', JSON.stringify(state)); + } catch { + // Ignore storage errors + } + } + }, []); + + const onGridReady = useCallback((params: GridReadyEvent) => { + gridApiRef.current = params.api; + + // Restore saved column state + try { + const savedState = localStorage.getItem('drill-grid-column-state'); + if (savedState) { + params.api.applyColumnState({ state: JSON.parse(savedState), applyOrder: true }); + } + } catch { + // Ignore storage errors + } + + params.api.sizeColumnsToFit(); + }, []); + + // Export functions + const exportToCsv = useCallback(() => { + gridApiRef.current?.exportDataAsCsv({ + fileName: `drill-query-${results?.queryId || 'results'}.csv`, + }); + }, [results?.queryId]); + + const exportToJson = useCallback(() => { + if (!results) return; + + const data = JSON.stringify(results.rows, null, 2); + const blob = new Blob([data], { type: 'application/json' }); + const url = URL.createObjectURL(blob); + const link = document.createElement('a'); + link.href = url; + link.download = `drill-query-${results.queryId || 'results'}.json`; + document.body.appendChild(link); + link.click(); + document.body.removeChild(link); + URL.revokeObjectURL(url); + }, [results]); + + const syncColumnVisibility = useCallback(() => { + if (gridApiRef.current && results?.columns) { + const vis: Record<string, boolean> = {}; + results.columns.forEach((col) => { + const column = gridApiRef.current!.getColumn(col); + vis[col] = column ? column.isVisible() : true; + }); + setColumnVisibility(vis); + } + }, [results?.columns]); + + const handleShowAllColumns = useCallback(() => { + if (gridApiRef.current && results?.columns) { + results.columns.forEach((col) => { + gridApiRef.current!.setColumnsVisible([col], true); + }); + syncColumnVisibility(); + saveColumnState(); + } + }, [results?.columns, saveColumnState, syncColumnVisibility]); + + // Sort manager state + const getSortModel = useCallback( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + () => (gridApiRef.current as any)?.getSortModel?.() || [], + [] + ); + + const handleClearSort = useCallback(() => { + if (gridApiRef.current) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (gridApiRef.current as any).setSortModel?.([]); + saveColumnState(); + } + }, [saveColumnState]); + + const copyAsTsv = useCallback(() => { + if (!results) return; + const cols = results.columns; + const header = cols.join('\t'); + const body = results.rows + .map((row) => cols.map((c) => String(row[c] ?? '')).join('\t')) + .join('\n'); + navigator.clipboard.writeText(`${header}\n${body}`).then(() => { + message.success('Copied as TSV', 1); + }).catch(() => {}); + }, [results]); + + const copyAsMarkdown = useCallback(() => { + if (!results) return; + const cols = results.columns; + const escape = (v: unknown) => String(v ?? '').replace(/\|/g, '\\|'); Review Comment: ## Incomplete string escaping or encoding This does not escape backslash characters in the input. [Show more details](https://github.com/apache/drill/security/code-scanning/61) -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
