Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
restore data explorer + lint
x032205c5c31faf7e0e
diff --git a/frontend/src/pages/pam/PamDataExplorerPage/PamDataExplorerPage.tsx b/frontend/src/pages/pam/PamDataExplorerPage/PamDataExplorerPage.tsxnew file mode 100644index 0000000000..9c44bef4bb--- /dev/null+++ b/frontend/src/pages/pam/PamDataExplorerPage/PamDataExplorerPage.tsx@@ -0,0 +1,555 @@+import { useCallback, useEffect, useRef, useState } from "react";+import { useParams } from "@tanstack/react-router";+import {+ AlertTriangleIcon,+ DatabaseIcon,+ PlusIcon,+ ShieldCheckIcon,+ TableIcon,+ TerminalSquareIcon,+ UnplugIcon,+ XIcon+} from "lucide-react";++import { Spinner } from "@app/components/v2";+import { Button } from "@app/components/v3/generic/Button";+import { cn } from "@app/components/v3/utils";+import { useGetPamAccountById } from "@app/hooks/api/pam";++import { DataExplorerGrid } from "./components/DataExplorerGrid";+import { DataExplorerSidebar } from "./components/DataExplorerSidebar";+import { QueryPanel } from "./components/QueryPanel";+import type { SchemaInfo, TableInfo } from "./data-explorer-types";+import { useDataExplorerSession } from "./use-data-explorer-session";+import { useQueryTabs } from "./use-query-tabs";++type Props = {+ reason?: string;+};++export const PamDataExplorerPage = ({ reason }: Props = {}) => {+ const { accountId, orgId } = useParams({+ strict: false+ }) as {+ accountId: string;+ orgId: string;+ accountType: string;+ };++ const { data: account } = useGetPamAccountById(accountId);++ // Sidebar-only view state. Switching schemas in the sidebar does not alter+ // open tabs — tabs are bound to their own (schema, table) at open time.+ const [schemas, setSchemas] = useState<SchemaInfo[]>([]);+ const [selectedSchema, setSelectedSchema] = useState("public");+ const [tables, setTables] = useState<TableInfo[]>([]);+ const [isLoadingSchemas, setIsLoadingSchemas] = useState(false);+ const [isLoadingTables, setIsLoadingTables] = useState(false);+ const [hasDisconnected, setHasDisconnected] = useState(false);+ const [disconnectReason, setDisconnectReason] = useState<string | null>(null);+ const latestSchemaRequestRef = useRef(0);+ const tabElRefs = useRef<Map<string, HTMLDivElement | null>>(new Map());++ const [approvalJustification, setApprovalJustification] = useState("");++ // Forward refs for tab-state handlers that useDataExplorerSession calls+ // before useQueryTabs has been called. Assigned after useQueryTabs below.+ const markConnectionDeadRef = useRef<((connId: string) => void) | null>(null);+ const resetTabsRef = useRef<(() => void) | null>(null);+ const openFirstQueryTabRef = useRef<(() => Promise<string | null>) | null>(null);+ // Shared guard so the first-connect effect and onReconnected don't both+ // end up opening a default tab.+ const defaultTabOpenedRef = useRef(false);++ const {+ isConnected,+ isConnecting,+ errorMessage,+ mfaState,+ approvalState,+ connect,+ disconnect,+ reconnect,+ handleMfaVerification,+ submitApprovalRequest,+ approvalRequestUrl,+ openConnection,+ closeConnection,+ fetchSchemas,+ fetchTables,+ fetchTableDetail,+ executeQuery,+ cancelQuery+ } = useDataExplorerSession({+ accountId,+ orgId,+ accountName: account?.name ?? "",+ reason,+ onSessionEnd: (endReason?: string) => {+ setHasDisconnected(true);+ setDisconnectReason(endReason ?? null);+ },+ onConnectionClosed: (connId: string) => {+ markConnectionDeadRef.current?.(connId);+ },+ onReconnected: () => {+ // Drop all tabs on reconnect — all connectionIds are invalid.+ resetTabsRef.current?.();+ // Claim the default-tab slot so the first-connect effect skips it.+ defaultTabOpenedRef.current = true;+ const opener = openFirstQueryTabRef.current;+ if (opener) opener().catch(() => {});+ }+ });++ const {+ tabs,+ activeTabId,+ atTabLimit,+ isOpeningTab,+ openQueryTab,+ openBrowseTab,+ closeTab,+ setActiveTab,+ updateTabSql,+ setTabTransactionOpen,+ markConnectionDead,+ resetTabs,+ refreshBrowseTab,+ MAX_TABS+ } = useQueryTabs({+ openConnection,+ closeConnection,+ fetchTableDetail+ });++ markConnectionDeadRef.current = markConnectionDead;+ resetTabsRef.current = resetTabs;+ openFirstQueryTabRef.current = openQueryTab;++ // Drive connection from the page, not the hook.+ // Use a ref callback as the gate (same approach as useWebAccessSession's containerEl).+ // The ref callback fires once after the real DOM mount — StrictMode's simulated+ // unmount/remount does NOT re-fire ref callbacks, so we get exactly one connect.+ const connectedOnceRef = useRef(false);+ const mountRef = useCallback(+ (node: HTMLDivElement | null) => {+ if (node && !connectedOnceRef.current) {+ connectedOnceRef.current = true;+ connect();+ }+ },+ [connect]+ );++ // Cleanup on real unmount+ useEffect(() => {+ return () => {+ disconnect();+ };+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, []);++ const loadTables = useCallback(+ async (schema: string) => {+ // Guard against stale responses when the user switches schemas quickly.+ // Only apply results if this is still the latest request.+ latestSchemaRequestRef.current += 1;+ const requestId = latestSchemaRequestRef.current;+ setIsLoadingTables(true);+ try {+ const result = await fetchTables(schema);+ if (latestSchemaRequestRef.current !== requestId) return;+ setTables(result);+ } catch {+ // Error handled by the hook+ } finally {+ if (latestSchemaRequestRef.current === requestId) {+ setIsLoadingTables(false);+ }+ }+ },+ [fetchTables]+ );++ const loadSchemas = useCallback(+ async (keepSelected = false) => {+ setIsLoadingSchemas(true);+ try {+ const result = await fetchSchemas();+ setSchemas(result);+ const hasSelected = result.find((s) => s.name === selectedSchema);+ const activeSchema = hasSelected ? selectedSchema : (result[0]?.name ?? "public");+ if (!hasSelected && result.length > 0 && !keepSelected) {+ setSelectedSchema(activeSchema);+ }+ if (result.length > 0) {+ await loadTables(activeSchema);+ }+ } catch {+ // Error handled by the hook+ } finally {+ setIsLoadingSchemas(false);+ }+ },+ [fetchSchemas, loadTables, selectedSchema]+ );++ // Keep the active tab visible in the tab bar whenever activation changes+ // (tab switch, new tab opened, sidebar table opened, etc.). Only scrolls the+ // tab bar itself — not ancestor containers — so the rest of the page layout+ // stays put.+ useEffect(() => {+ if (!activeTabId) return;+ const el = tabElRefs.current.get(activeTabId);+ const container = el?.parentElement;+ if (!el || !container) return;+ const elRect = el.getBoundingClientRect();+ const cRect = container.getBoundingClientRect();+ if (elRect.left < cRect.left) {+ container.scrollBy({ left: elRect.left - cRect.left, behavior: "smooth" });+ } else if (elRect.right > cRect.right) {+ container.scrollBy({ left: elRect.right - cRect.right, behavior: "smooth" });+ }+ }, [activeTabId, tabs.length]);++ // Auto-load schemas when we transition to connected+ const wasConnectedRef = useRef(false);+ useEffect(() => {+ if (isConnected && !wasConnectedRef.current) {+ wasConnectedRef.current = true;+ setHasDisconnected(false);+ (async () => {+ await loadSchemas();+ // Open a default query tab once — onReconnected handles subsequent+ // reconnects via defaultTabOpenedRef, so we don't double-open.+ if (!defaultTabOpenedRef.current) {+ defaultTabOpenedRef.current = true;+ await openQueryTab();+ }+ })().catch(() => {});+ }+ if (!isConnected) {+ wasConnectedRef.current = false;+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [isConnected]);++ const handleSchemaChange = useCallback(+ (schema: string) => {+ setSelectedSchema(schema);+ loadTables(schema);+ },+ [loadTables]+ );++ const handleTableOpen = useCallback(+ (tableName: string, opts: { forceNew: boolean }) => {+ openBrowseTab(selectedSchema, tableName, opts).catch(() => {});+ },+ [selectedSchema, openBrowseTab]+ );++ const handleReconnect = useCallback(() => {+ setHasDisconnected(false);+ setDisconnectReason(null);+ setSchemas([]);+ setTables([]);+ resetTabs();+ reconnect();+ }, [reconnect, resetTabs]);++ // Tab-scoped refresh: re-fetches tableDetail + schemas + sidebar tables.+ // The grid also re-runs its own SELECT after this completes.+ const handleTabRefresh = useCallback(+ async (tabId: string) => {+ await Promise.all([refreshBrowseTab(tabId), loadSchemas(true), loadTables(selectedSchema)]);+ },+ [refreshBrowseTab, loadSchemas, loadTables, selectedSchema]+ );++ const activeBrowseTarget = (() => {+ const active = tabs.find((t) => t.id === activeTabId);+ if (active?.kind === "browse") return { schema: active.schema, table: active.table };+ return null;+ })();++ // --- Overlay states (shown instead of the main layout) ---++ if (isConnecting && !isConnected) {+ return (+ <div className="flex h-screen w-screen flex-col items-center justify-center gap-4 bg-bunker-800">+ <Spinner className="h-8 w-8" />+ <p className="text-sm text-mineshaft-300">Connecting to database...</p>+ </div>+ );+ }++ if (mfaState?.required) {+ return (+ <div className="flex h-screen w-screen flex-col items-center justify-center gap-3 bg-bunker-800">+ <ShieldCheckIcon className="size-8 text-mineshaft-400" />+ <h2 className="text-sm font-medium text-mineshaft-100">MFA Verification Required</h2>+ <p className="max-w-sm text-center text-xs text-mineshaft-400">+ Multi-factor authentication is required to access this database account.+ </p>+ {mfaState.verifying ? (+ <div className="flex items-center gap-2 text-xs text-mineshaft-400">+ <Spinner className="h-4 w-4" />+ Waiting for verification...+ </div>+ ) : (+ <Button variant="outline" size="xs" onClick={handleMfaVerification}>+ Verify MFA+ </Button>+ )}+ </div>+ );+ }++ if (approvalState?.required) {+ return (+ <div className="flex h-screen w-screen flex-col items-center justify-center gap-3 bg-bunker-800">+ <AlertTriangleIcon className="size-8 text-mineshaft-400" />+ <h2 className="text-sm font-medium text-mineshaft-100">Approval Required</h2>+ <p className="max-w-sm text-center text-xs text-mineshaft-400">+ This account is protected by policy: {approvalState.policyName ?? "Unknown"}+ </p>+ {approvalState.submitted ? (+ <div className="flex flex-col items-center gap-2">+ <p className="text-xs text-mineshaft-300">Approval request created successfully.</p>+ {approvalRequestUrl && (+ <a+ href={approvalRequestUrl}+ target="_blank"+ rel="noopener noreferrer"+ className="text-xs text-primary-500 underline hover:text-primary-400"+ >+ View approval request+ </a>+ )}+ <Button variant="outline" size="xs" onClick={handleReconnect}>+ Reconnect+ </Button>+ </div>+ ) : (+ <div className="flex w-full max-w-sm flex-col gap-2">+ <textarea+ className="w-full rounded border border-mineshaft-600 bg-bunker-700 px-3 py-2 text-xs text-mineshaft-200 placeholder:text-mineshaft-500 focus:border-mineshaft-400 focus:outline-none"+ placeholder="Justification (optional)"+ rows={2}+ value={approvalJustification}+ onChange={(e) => setApprovalJustification(e.target.value)}+ />+ {approvalState.errorMessage && (+ <p className="text-xs text-red-400">{approvalState.errorMessage}</p>+ )}+ <div className="flex justify-center gap-2">+ <Button+ variant="outline"+ size="xs"+ isPending={approvalState.creating}+ onClick={() => submitApprovalRequest(approvalJustification)}+ >+ Create Approval Request+ </Button>+ </div>+ </div>+ )}+ </div>+ );+ }++ if (errorMessage && !isConnected) {+ return (+ <div className="flex h-screen w-screen flex-col items-center justify-center gap-3 bg-bunker-800">+ <AlertTriangleIcon className="size-8 text-mineshaft-400" />+ <h2 className="text-sm font-medium text-mineshaft-100">Connection Error</h2>+ <p className="max-w-sm text-center text-xs text-mineshaft-400">{errorMessage}</p>+ <Button variant="outline" size="xs" onClick={handleReconnect}>+ Try Again+ </Button>+ </div>+ );+ }++ if (hasDisconnected && !isConnected && !isConnecting) {+ return (+ <div className="flex h-screen w-screen flex-col items-center justify-center gap-3 bg-bunker-800">+ <UnplugIcon className="size-8 text-mineshaft-400" />+ <h2 className="text-sm font-medium text-mineshaft-100">Disconnected</h2>+ <p className="text-xs text-mineshaft-400">+ {disconnectReason ?? "The database connection was closed."}+ </p>+ <Button variant="outline" size="xs" onClick={handleReconnect}>+ Reconnect+ </Button>+ </div>+ );+ }++ // --- Main layout ---++ const tabOpeningDisabled = isOpeningTab || atTabLimit;++ return (+ <div ref={mountRef} className="flex h-screen w-screen flex-col bg-bunker-800">+ <div className="flex flex-1 overflow-hidden">+ <DataExplorerSidebar+ schemas={schemas}+ selectedSchema={selectedSchema}+ onSchemaChange={handleSchemaChange}+ tables={tables}+ activeBrowseTarget={activeBrowseTarget}+ onTableOpen={handleTableOpen}+ isLoadingSchemas={isLoadingSchemas}+ isLoadingTables={isLoadingTables}+ disabled={isOpeningTab}+ />++ <div className="flex flex-1 flex-col overflow-hidden">+ <div className="flex min-h-[34px] shrink-0 items-center overflow-x-auto border-b border-mineshaft-600 bg-mineshaft-800 px-2 [scrollbar-color:transparent_transparent] [scrollbar-width:thin] hover:[scrollbar-color:#4a4b4e_transparent] [&::-webkit-scrollbar]:h-1 [&::-webkit-scrollbar-thumb]:rounded-full [&::-webkit-scrollbar-thumb]:bg-transparent hover:[&::-webkit-scrollbar-thumb]:bg-mineshaft-600 [&::-webkit-scrollbar-track]:bg-transparent">+ {tabs.map((tab) => {+ const isActive = activeTabId === tab.id;+ const Icon = tab.kind === "browse" ? TableIcon : TerminalSquareIcon;+ return (+ <div+ key={tab.id}+ ref={(el) => {+ if (el) tabElRefs.current.set(tab.id, el);+ else tabElRefs.current.delete(tab.id);+ }}+ role="button"+ tabIndex={0}+ onClick={() => setActiveTab(tab.id)}+ onKeyDown={(e) => (e.key === "Enter" || e.key === " ") && setActiveTab(tab.id)}+ className={cn(+ "group flex shrink-0 cursor-pointer items-center gap-1 border-b-2 px-3 py-2 text-xs font-medium transition-colors",+ isActive+ ? "border-info text-mineshaft-100"+ : "border-transparent text-mineshaft-400 hover:text-mineshaft-200",+ tab.isDead && "text-red-400"+ )}+ >+ <span className="flex items-center gap-1.5">+ <Icon className="size-3.5" />+ {tab.title}+ </span>+ <button+ type="button"+ onClick={(e) => {+ e.stopPropagation();+ closeTab(tab.id);+ }}+ className="ml-1 rounded p-0.5 text-mineshaft-300 transition-colors hover:text-mineshaft-100"+ aria-label={`Close ${tab.title}`}+ >+ <XIcon className="size-3" />+ </button>+ </div>+ );+ })}++ <button+ type="button"+ onClick={() => {+ openQueryTab().catch(() => {});+ }}+ disabled={tabOpeningDisabled}+ className="ml-1 flex shrink-0 items-center gap-1.5 rounded border border-mineshaft-600 px-2 py-1 text-xs text-mineshaft-300 transition-colors first:ml-0 hover:border-mineshaft-500 hover:text-mineshaft-100 disabled:cursor-not-allowed disabled:opacity-40 disabled:hover:border-mineshaft-600 disabled:hover:text-mineshaft-300"+ aria-label="New query tab"+ title={atTabLimit ? `Tab limit (${MAX_TABS}) reached` : "New query tab"}+ >+ <PlusIcon className="size-3" />+ New query+ </button>+ </div>++ {/* All tabs are mounted; inactive tabs are CSS-hidden so their+ component instance state (filters, pagination, SQL, results)+ survives tab switches. */}+ {tabs.map((tab) => {+ const deadTabView = (+ <div className="flex flex-1 flex-col items-center justify-center gap-3 text-center">+ <AlertTriangleIcon className="size-8 text-red-400" />+ <p className="text-sm text-mineshaft-300">+ This connection was closed and cannot be reused.+ </p>+ <Button variant="outline" size="xs" onClick={() => closeTab(tab.id)}>+ Close tab+ </Button>+ </div>+ );+ let content;+ if (tab.isDead) {+ content = deadTabView;+ } else if (tab.kind === "browse") {+ content = (+ <DataExplorerGrid+ key={tab.id}+ tableDetail={tab.tableDetail}+ tableType={tables.find((t) => t.name === tab.table)?.tableType}+ schema={tab.schema}+ table={tab.table}+ connectionId={tab.connectionId}+ executeQuery={executeQuery}+ isLoading={tab.isLoadingDetail}+ onRefresh={() => handleTabRefresh(tab.id)}+ />+ );+ } else {+ content = (+ <QueryPanel+ key={tab.id}+ tab={tab}+ executeQuery={executeQuery}+ cancelQuery={cancelQuery}+ onSqlChange={(sql) => updateTabSql(tab.id, sql)}+ onTransactionStateChange={(open) => setTabTransactionOpen(tab.id, open)}+ />+ );+ }+ return (+ <div+ key={tab.id}+ className={cn("flex flex-1 overflow-hidden", activeTabId !== tab.id && "hidden")}+ >+ {content}+ </div>+ );+ })}++ {tabs.length === 0 && (+ <div className="flex flex-1 flex-col items-center justify-center gap-3 text-center">+ <DatabaseIcon className="size-12 text-mineshaft-600" />+ <p className="text-sm text-mineshaft-400">No tabs open</p>+ <Button+ variant="outline"+ size="xs"+ onClick={() => {+ openQueryTab().catch(() => {});+ }}+ isPending={isOpeningTab}+ >+ New query tab+ </Button>+ </div>+ )}+ </div>+ </div>++ {/* Status bar */}+ <div className="flex items-center justify-between border-t border-mineshaft-600 bg-mineshaft-800 px-3 py-1.5 text-xs">+ <span className="text-mineshaft-400">+ {tables.length} table{tables.length !== 1 ? "s" : ""}+ </span>+ <div className="flex items-center gap-4">+ <span>+ <span className="text-mineshaft-400">Account:</span>{" "}+ <span className="text-mineshaft-300">{account?.name ?? "Account"}</span>+ </span>+ </div>+ </div>+ </div>+ );+};diff --git a/frontend/src/pages/pam/PamDataExplorerPage/components/DataExplorerGrid.tsx b/frontend/src/pages/pam/PamDataExplorerPage/components/DataExplorerGrid.tsxnew file mode 100644index 0000000000..d58af64525--- /dev/null+++ b/frontend/src/pages/pam/PamDataExplorerPage/components/DataExplorerGrid.tsx@@ -0,0 +1,763 @@+import { useCallback, useMemo, useRef, useState } from "react";+import type { CellContext, ColumnDef, HeaderContext } from "@tanstack/react-table";+import { EyeIcon } from "lucide-react";++import { createNotification } from "@app/components/notifications";+import { ContentLoader } from "@app/components/v2";+import { Alert, AlertDescription } from "@app/components/v3/generic/Alert";+import { Checkbox } from "@app/components/v3/generic/Checkbox";+import type { CellOpts } from "@app/components/v3/generic/DataGrid";+import { DataGrid, useDataGrid } from "@app/components/v3/generic/DataGrid";+import { Skeleton } from "@app/components/v3/generic/Skeleton";++import type { ColumnInfo, FieldInfo, ForeignKeyInfo, TableDetail } from "../data-explorer-types";+import { getColumnIndicator } from "../data-explorer-utils";+import { copyData, exportData } from "../data-export";+import type { FilterCondition, SortCondition } from "../sql-generation";+import {+ buildCountQuery,+ buildDeleteQuery,+ buildInsertQuery,+ buildSelectQuery,+ buildUpdateQuery,+ wrapInTransaction+} from "../sql-generation";+import { DataExplorerToolbar } from "./DataExplorerToolbar";++type DataExplorerGridProps = {+ tableDetail: TableDetail | null;+ tableType?: string;+ schema: string;+ table: string;+ connectionId: string;+ executeQuery: (+ connectionId: string,+ sql: string+ ) => Promise<{+ rows: Record<string, unknown>[];+ fields: FieldInfo[];+ rowCount: number | null;+ command: string;+ executionTimeMs: number;+ }>;+ isLoading: boolean;+ onRefresh?: () => Promise<void>;+};++const ROW_KEY_PREFIX = "__new_";++function cellValuesEqual(a: unknown, b: unknown): boolean {+ if (a === null && b === null) return true;+ if (a === null || b === null) return false;+ if (a === undefined && b === undefined) return true;+ if (a === undefined || b === undefined) return false;+ return String(a) === String(b);+}++function pgTypeToCellOpts(): CellOpts {+ return { variant: "short-text" };+}++function getColumnSize(col: ColumnInfo, hasIndicator: boolean): number {+ // Extra width for PK/FK icon + badge + type label in header+ const indicatorExtra = hasIndicator ? 40 : 0;+ const t = col.type.toLowerCase();+ if (t === "boolean" || t === "bool" || t === "smallint" || t === "int2")+ return 100 + indicatorExtra;+ if (t === "integer" || t === "int4" || t === "serial") return 120 + indicatorExtra;+ if (t === "uuid") return 280 + indicatorExtra;+ if (t === "json" || t === "jsonb") return 250 + indicatorExtra;+ if (t === "text" || t === "xml") return 220 + indicatorExtra;+ // Scale with column name length as a rough heuristic+ return Math.max(180, Math.min(350, col.name.length * 10 + 120)) + indicatorExtra;+}++type RowData = Record<string, unknown>;++type SelectionMeta = {+ onRowSelect?: (rowIndex: number, checked: boolean, shiftKey: boolean) => void;+};++function SelectHeader({ table: t }: HeaderContext<RowData, unknown>) {+ const isAllSelected = t.getIsAllRowsSelected();+ const isSomeSelected = t.getIsSomeRowsSelected();+ return (+ <Checkbox+ isChecked={isAllSelected || isSomeSelected}+ isIndeterminate={isSomeSelected && !isAllSelected}+ onCheckedChange={() => {+ t.toggleAllRowsSelected(!isAllSelected);+ }}+ />+ );+}++function SelectCell({ row, table: t }: CellContext<RowData, unknown>) {+ const meta = t.options.meta as SelectionMeta | undefined;+ const isSelected = row.getIsSelected();+ return (+ <Checkbox+ isChecked={isSelected}+ onCheckedChange={(checked) => {+ if (meta?.onRowSelect) {+ meta.onRowSelect(row.index, Boolean(checked), false);+ } else {+ row.toggleSelected(Boolean(checked));+ }+ }}+ />+ );+}++const SELECT_COLUMN: ColumnDef<RowData> = {+ id: "select",+ header: SelectHeader,+ cell: SelectCell,+ size: 40,+ minSize: 40,+ maxSize: 40,+ enableSorting: false,+ enableHiding: false,+ enablePinning: false,+ enableResizing: false+};++function buildColumnDefs(+ cols: ColumnInfo[],+ primaryKeys: string[],+ foreignKeys: ForeignKeyInfo[]+): ColumnDef<Record<string, unknown>>[] {+ // Build a map from column name → FK info for O(1) lookup+ const fkMap = new Map<string, ForeignKeyInfo>();+ foreignKeys.forEach((fk) => {+ fk.columns.forEach((c) => {+ if (!fkMap.has(c)) fkMap.set(c, fk);+ });+ });++ return cols.map((col) => {+ const columnIndicator = getColumnIndicator(col.name, primaryKeys, fkMap);+ return {+ id: col.name,+ accessorKey: col.name,+ header: col.name,+ meta: {+ label: col.name,+ typeLabel: col.type,+ cell: pgTypeToCellOpts(),+ columnIndicator+ },+ size: getColumnSize(col, Boolean(columnIndicator)),+ minSize: 80,+ maxSize: 600,+ enableSorting: true,+ enablePinning: true,+ enableHiding: true+ };+ });+}++function getRowKey(row: Record<string, unknown>, primaryKeys: string[]): string {+ if (primaryKeys.length === 0) return "";+ const keyObj: Record<string, unknown> = {};+ primaryKeys.forEach((pk) => {+ keyObj[pk] = row[pk];+ });+ return JSON.stringify(keyObj);+}++function getPkMatch(row: Record<string, unknown>, primaryKeys: string[]): Record<string, unknown> {+ const match: Record<string, unknown> = {};+ primaryKeys.forEach((pk) => {+ match[pk] = row[pk];+ });+ return match;+}++export const DataExplorerGrid = ({+ tableDetail,+ tableType,+ schema,+ table,+ connectionId,+ executeQuery,+ isLoading,+ onRefresh+}: DataExplorerGridProps) => {+ const [originalData, setOriginalData] = useState<Record<string, unknown>[]>([]);+ const [currentData, setCurrentData] = useState<Record<string, unknown>[]>([]);+ const [totalCount, setTotalCount] = useState(0);+ const [offset, setOffset] = useState(0);+ const [pageSize, setPageSize] = useState(50);+ const [filters, setFilters] = useState<FilterCondition[]>([]);+ const [sorts, setSorts] = useState<SortCondition[]>([]);+ const [executionTimeMs, setExecutionTimeMs] = useState<number | null>(null);+ const [isSaving, setIsSaving] = useState(false);+ const [isDataLoading, setIsDataLoading] = useState(true);+ const [newRowTempIds, setNewRowTempIds] = useState<Set<string>>(new Set());+ const newRowCounterRef = useRef(0);+ const [hasLoaded, setHasLoaded] = useState(false);+ const isFetchingRef = useRef(false);++ const primaryKeys = tableDetail?.primaryKeys ?? [];+ const foreignKeys = tableDetail?.foreignKeys ?? [];+ const tableColumns = tableDetail?.columns ?? [];+ const hasPrimaryKey = primaryKeys.length > 0;+ const primaryKeysRef = useRef(primaryKeys);+ primaryKeysRef.current = primaryKeys;++ const [selectedRowCount, setSelectedRowCount] = useState(0);+ const gridRef = useRef<ReturnType<typeof useDataGrid<Record<string, unknown>>>["table"] | null>(+ null+ );+ const selectedRowsRef = useRef<Record<string, unknown>[]>([]);++ // Build TanStack Table column definitions from PG metadata+ const columnDefs = useMemo(+ () =>+ hasPrimaryKey+ ? [SELECT_COLUMN, ...buildColumnDefs(tableColumns, primaryKeys, foreignKeys)]+ : buildColumnDefs(tableColumns, primaryKeys, foreignKeys),+ [hasPrimaryKey, tableColumns, primaryKeys, foreignKeys]+ );++ const fetchData = useCallback(+ async (o: number, ps: number, f: FilterCondition[], s: SortCondition[]): Promise<number> => {+ if (!tableDetail) return 0;+ isFetchingRef.current = true;+ setIsDataLoading(true);+ try {+ const selectSql = buildSelectQuery({+ schema,+ table,+ filters: f,+ sorts: s,+ limit: ps,+ offset: o,+ primaryKeys+ });+ const countSql = buildCountQuery({ schema, table, filters: f });++ // These two queries don't share a database snapshot (the backend processes them+ // sequentially, not in a single transaction), so the count could be off by 1 if+ // another session modifies data between them. Acceptable for a data explorer.+ const [dataResult, countResult] = await Promise.all([+ executeQuery(connectionId, selectSql),+ executeQuery(connectionId, countSql)+ ]);++ const taggedRows = dataResult.rows.map((row: Record<string, unknown>) => ({+ ...row,+ originalPkKey: getRowKey(row, primaryKeys)+ }));+ setOriginalData(taggedRows);+ setCurrentData(taggedRows);+ setExecutionTimeMs(dataResult.executionTimeMs);+ setTotalCount(Number(countResult.rows[0]?.count ?? 0));+ setNewRowTempIds(new Set());+ setSelectedRowCount(0);+ selectedRowsRef.current = [];+ setHasLoaded(true);+ return dataResult.rows.length;+ } catch (err) {+ createNotification({+ title: "Failed to load data",+ text: err instanceof Error ? err.message : "Unknown error",+ type: "error"+ });+ return -1;+ } finally {+ isFetchingRef.current = false;+ setIsDataLoading(false);+ }+ },+ [tableDetail, schema, table, primaryKeys, executeQuery, connectionId]+ );++ // Fetch data when filters/sorts/pagination change.+ // Table switches are handled by the parent via key={schema.table} which+ // remounts this component with fresh state — no manual reset needed.+ const prevFetchKeyRef = useRef("");+ const fetchKey = `${schema}.${table}.${offset}.${pageSize}.${JSON.stringify(filters)}.${JSON.stringify(sorts)}`;+ if (fetchKey !== prevFetchKeyRef.current && tableDetail && !isLoading) {+ prevFetchKeyRef.current = fetchKey;+ fetchData(offset, pageSize, filters, sorts);+ } else if (isDataLoading && hasLoaded && !isFetchingRef.current) {+ // Handlers eagerly set isDataLoading so the overlay appears immediately.+ // If the fetchKey didn't actually change (e.g. applying empty filters when+ // none were active), no fetch runs — reset loading to avoid getting stuck.+ setIsDataLoading(false);+ }++ const pageSizeRef = useRef(pageSize);+ pageSizeRef.current = pageSize;+ const sortsRef = useRef(sorts);+ sortsRef.current = sorts;++ const handleFiltersChange = useCallback(+ async (newFilters: FilterCondition[]): Promise<boolean> => {+ setFilters(newFilters);+ setOffset(0);+ // Update prevFetchKeyRef so the render-time pattern doesn't double-fire+ prevFetchKeyRef.current = `${schema}.${table}.${0}.${pageSizeRef.current}.${JSON.stringify(newFilters)}.${JSON.stringify(sortsRef.current)}`;+ const result = await fetchData(0, pageSizeRef.current, newFilters, sortsRef.current);+ return result >= 0;+ },+ [schema, table, fetchData]+ );++ const handleSortsChange = useCallback((newSorts: SortCondition[]) => {+ setIsDataLoading(true);+ setSorts(newSorts);+ setOffset(0);+ }, []);++ const handleOffsetChange = useCallback((newOffset: number) => {+ setIsDataLoading(true);+ setOffset(Math.max(0, newOffset));+ }, []);++ const handlePageSizeChange = useCallback((newSize: number) => {+ setIsDataLoading(true);+ setPageSize(newSize);+ setOffset(0);+ }, []);++ // PK-based lookup map for O(1) original row matching (avoids index misalignment after prepend)+ const originalDataByPk = useMemo(() => {+ if (primaryKeys.length === 0) return null;+ const map = new Map<string, Record<string, unknown>>();+ originalData.forEach((row) => {+ map.set(getRowKey(row, primaryKeys), row);+ });+ return map;+ }, [originalData, primaryKeys]);++ const originalDataByPkRef = useRef(originalDataByPk);+ originalDataByPkRef.current = originalDataByPk;++ // Change tracking — use PK-based lookup so new row prepends don't misalign indices+ const changeCount = useMemo(() => {+ let count = newRowTempIds.size;+ if (!originalDataByPk) return count;+ currentData.forEach((row) => {+ if (row.tempRowId && newRowTempIds.has(String(row.tempRowId))) return;+ const key = row.originalPkKey as string;+ if (!key) return;+ const original = originalDataByPk.get(key);+ if (!original) return;+ const hasChanges = tableColumns.some(+ (col) => !cellValuesEqual(row[col.name], original[col.name])+ );+ if (hasChanges) count += 1;+ });+ return count;+ }, [currentData, originalDataByPk, primaryKeys, newRowTempIds, tableColumns]);++ const handleAddRecord = useCallback(() => {+ newRowCounterRef.current += 1;+ const tempId = `${ROW_KEY_PREFIX}${newRowCounterRef.current}`;+ const newRow: Record<string, unknown> = { tempRowId: tempId };+ tableColumns.forEach((col) => {+ newRow[col.name] = null;+ });+ setCurrentData((prev) => [newRow, ...prev]);+ setNewRowTempIds((prev) => new Set(prev).add(tempId));+ return null;+ }, [tableColumns]);++ const handleRowsDelete = useCallback(+ async (_rows: Record<string, unknown>[], rowIndices: number[]) => {+ const tempIdsToRemove: string[] = [];+ const deleteStatements: string[] = [];++ rowIndices.forEach((idx) => {+ const row = currentData[idx];+ if (!row) return;+ const tempId = row.tempRowId ? String(row.tempRowId) : null;+ if (tempId) {+ tempIdsToRemove.push(tempId);+ } else {+ deleteStatements.push(+ buildDeleteQuery({ schema, table, primaryKeyMatch: getPkMatch(row, primaryKeys) })+ );+ }+ });++ // Remove unsaved new rows from local state immediately+ if (tempIdsToRemove.length > 0) {+ const tempIdSet = new Set(tempIdsToRemove);+ setCurrentData((prev) =>+ prev.filter((r) => !r.tempRowId || !tempIdSet.has(String(r.tempRowId)))+ );+ setNewRowTempIds((prev) => {+ const next = new Set(prev);+ tempIdsToRemove.forEach((id) => next.delete(id));+ return next;+ });+ }++ // Execute DELETE SQL for persisted rows immediately+ if (deleteStatements.length > 0) {+ try {+ const sql = wrapInTransaction(deleteStatements);+ await executeQuery(connectionId, sql);+ createNotification({+ text: `Deleted ${deleteStatements.length} row${deleteStatements.length !== 1 ? "s" : ""}`,+ type: "success"+ });+ const rowCount = await fetchData(offset, pageSize, filters, sorts);+ if (rowCount === 0 && offset > 0) {+ setOffset(Math.max(0, offset - pageSize));+ }+ } catch (err) {+ createNotification({+ title: "Delete failed",+ text: err instanceof Error ? err.message : "Unknown error",+ type: "error"+ });+ }+ }+ },+ [+ currentData,+ primaryKeys,+ schema,+ table,+ connectionId,+ executeQuery,+ fetchData,+ offset,+ pageSize,+ filters,+ sorts+ ]+ );++ const handleDiscard = useCallback(() => {+ setCurrentData(originalData);+ setNewRowTempIds(new Set());+ }, [originalData]);++ const handleSave = useCallback(async () => {+ setIsSaving(true);+ try {+ const statements: string[] = [];++ // Inserts (new rows)+ currentData.forEach((row) => {+ const tempId = row.tempRowId ? String(row.tempRowId) : null;+ if (!tempId || !newRowTempIds.has(tempId)) return;+ const values: Record<string, unknown> = {};+ tableColumns.forEach((col) => {+ if (+ row[col.name] !== null &&+ row[col.name] !== undefined &&+ String(row[col.name]) !== ""+ ) {+ values[col.name] = row[col.name];+ }+ });+ statements.push(buildInsertQuery({ schema, table, row: values }));+ });++ // Updates (changed rows) — use PK-based lookup so prepends don't misalign+ const pkMap = originalDataByPk;+ currentData.forEach((row) => {+ if (row.tempRowId) return;+ const key = row.originalPkKey as string;+ const original = key && pkMap ? pkMap.get(key) : undefined;+ if (!original) return;+ const changes: Record<string, unknown> = {};+ tableColumns.forEach((col) => {+ if (!cellValuesEqual(row[col.name], original[col.name])) {+ changes[col.name] = row[col.name];+ }+ });+ if (Object.keys(changes).length > 0) {+ statements.push(+ buildUpdateQuery({+ schema,+ table,+ changes,+ primaryKeyMatch: getPkMatch(original, primaryKeys)+ })+ );+ }+ });++ if (statements.length === 0) {+ createNotification({ text: "No changes to save", type: "info" });+ setIsSaving(false);+ return;+ }++ const sql = wrapInTransaction(statements);++ // The WebSocket maxPayload is 64 KB. Guard against sending a query+ // that would exceed the limit and silently kill the connection.+ const MAX_QUERY_SIZE = 50 * 1024;+ if (sql.length > MAX_QUERY_SIZE) {+ createNotification({+ title: "Save failed",+ text: "Changes are too large to save at once. Try saving fewer or smaller changes.",+ type: "error"+ });+ setIsSaving(false);+ return;+ }++ await executeQuery(connectionId, sql);+ createNotification({+ text: `Saved ${statements.length} change${statements.length !== 1 ? "s" : ""}`,+ type: "success"+ });++ await fetchData(offset, pageSize, filters, sorts);+ } catch (err) {+ createNotification({+ title: "Save failed",+ text: err instanceof Error ? err.message : "Unknown error",+ type: "error"+ });+ } finally {+ setIsSaving(false);+ }+ }, [+ currentData,+ originalDataByPk,+ newRowTempIds,+ tableColumns,+ primaryKeys,+ schema,+ table,+ connectionId,+ executeQuery,+ fetchData,+ offset,+ pageSize,+ filters,+ sorts+ ]);++ const handleDataChange = useCallback((newData: Record<string, unknown>[]) => {+ setCurrentData(newData);+ }, []);++ // Use refs so the callback identity is stable (survives tableMeta useMemo)+ // while always reading the latest data.+ const currentDataRef = useRef(currentData);+ currentDataRef.current = currentData;+ const newRowTempIdsRef = useRef(newRowTempIds);+ newRowTempIdsRef.current = newRowTempIds;++ const getIsCellDirty = useCallback((rowIndex: number, columnId: string) => {+ const row = currentDataRef.current[rowIndex];+ if (!row) return false;+ if (row.tempRowId && newRowTempIdsRef.current.has(String(row.tempRowId))) return true;+ const pkMap = originalDataByPkRef.current;+ if (!pkMap) return false;+ const key = row.originalPkKey as string;+ if (!key) return false;+ const original = pkMap.get(key);+ if (!original) return false;+ return !cellValuesEqual(row[columnId], original[columnId]);+ }, []);++ const getIsRowNew = useCallback((rowIndex: number) => {+ const row = currentDataRef.current[rowIndex];+ if (!row) return false;+ return Boolean(row.tempRowId && newRowTempIdsRef.current.has(String(row.tempRowId)));+ }, []);++ // Stable row identity for TanStack Table+ const getRowId = useCallback(+ (row: Record<string, unknown>, index: number) => {+ if (row.tempRowId) return String(row.tempRowId);+ if (row.originalPkKey) return row.originalPkKey as string;+ if (primaryKeys.length > 0) return getRowKey(row, primaryKeys);+ return String(index);+ },+ [primaryKeys]+ );++ // Dice UI DataGrid+ const gridProps = useDataGrid<Record<string, unknown>>({+ data: currentData,+ columns: columnDefs,+ onDataChange: handleDataChange,+ getRowId,+ readOnly: !hasPrimaryKey,+ rowHeight: "short",+ enableSearch: true,+ enablePaste: hasPrimaryKey,+ onRowsDelete: hasPrimaryKey ? handleRowsDelete : undefined,+ onRowSelectionChange: (rowSelection) => {+ const selectedIds = new Set(Object.keys(rowSelection).filter((k) => rowSelection[k]));+ setSelectedRowCount(selectedIds.size);+ if (selectedIds.size > 0) {+ selectedRowsRef.current = currentData.filter((_row, idx) =>+ selectedIds.has(getRowId(_row, idx))+ );+ } else {+ selectedRowsRef.current = [];+ }+ },+ meta: { getIsCellDirty, getIsRowNew } as Record<string, unknown>+ });+ gridRef.current = gridProps.table;++ const handleDeleteSelected = useCallback(async () => {+ // Use the snapshot captured at selection time — by the time this click handler+ // fires, the DataGrid's outside-click listener has already cleared rowSelection.+ const rows = selectedRowsRef.current;+ if (rows.length === 0) return;++ const tempIdsToRemove: string[] = [];+ const deleteStatements: string[] = [];++ rows.forEach((row) => {+ const tempId = row.tempRowId ? String(row.tempRowId) : null;+ if (tempId) {+ tempIdsToRemove.push(tempId);+ } else {+ deleteStatements.push(+ buildDeleteQuery({ schema, table, primaryKeyMatch: getPkMatch(row, primaryKeys) })+ );+ }+ });++ // Remove unsaved new rows from local state immediately+ if (tempIdsToRemove.length > 0) {+ const tempIdSet = new Set(tempIdsToRemove);+ setCurrentData((prev) =>+ prev.filter((r) => !r.tempRowId || !tempIdSet.has(String(r.tempRowId)))+ );+ setNewRowTempIds((prev) => {+ const next = new Set(prev);+ tempIdsToRemove.forEach((id) => next.delete(id));+ return next;+ });+ }++ // Execute DELETE SQL for persisted rows+ if (deleteStatements.length > 0) {+ try {+ const sql = wrapInTransaction(deleteStatements);+ await executeQuery(connectionId, sql);+ createNotification({+ text: `Deleted ${deleteStatements.length} row${deleteStatements.length !== 1 ? "s" : ""}`,+ type: "success"+ });+ const rowCount = await fetchData(offset, pageSize, filters, sorts);+ if (rowCount === 0 && offset > 0) {+ setOffset(Math.max(0, offset - pageSize));+ }+ } catch (err) {+ createNotification({+ title: "Delete failed",+ text: err instanceof Error ? err.message : "Unknown error",+ type: "error"+ });+ }+ }++ gridRef.current?.resetRowSelection();+ selectedRowsRef.current = [];+ setSelectedRowCount(0);+ }, [+ schema,+ table,+ primaryKeys,+ connectionId,+ executeQuery,+ fetchData,+ offset,+ pageSize,+ filters,+ sorts+ ]);++ if (!tableDetail) {+ return (+ <div className="flex flex-1 items-center justify-center">+ <Skeleton className="h-64 w-96" />+ </div>+ );+ }++ return (+ <div className="flex flex-1 flex-col overflow-hidden">+ <DataExplorerToolbar+ columns={tableColumns}+ filters={filters}+ onFiltersChange={handleFiltersChange}+ sorts={sorts}+ onSortsChange={handleSortsChange}+ changeCount={changeCount}+ onSave={handleSave}+ onDiscard={handleDiscard}+ isSaving={isSaving}+ onAddRecord={handleAddRecord}+ selectedRowCount={selectedRowCount}+ onDeleteSelected={handleDeleteSelected}+ totalCount={totalCount}+ offset={offset}+ pageSize={pageSize}+ onOffsetChange={handleOffsetChange}+ onPageSizeChange={handlePageSizeChange}+ executionTimeMs={executionTimeMs}+ hasPrimaryKey={hasPrimaryKey}+ isDataLoading={isDataLoading}+ onRefresh={async () => {+ if (onRefresh) await onRefresh();+ await fetchData(offset, pageSize, filters, sorts);+ }}+ isRefreshing={isDataLoading && hasLoaded}+ onExport={(fmt) =>+ exportData(+ currentData,+ tableColumns.map((c) => c.name),+ fmt+ )+ }+ onCopy={(fmt) =>+ copyData(+ currentData,+ tableColumns.map((c) => c.name),+ fmt+ )+ }+ hasData={currentData.length > 0}+ />++ {!hasPrimaryKey && (+ <div className="shrink-0 px-3 py-3">+ <Alert variant="info" className="py-2">+ <EyeIcon />+ <AlertDescription>+ {tableType === "view" || tableType === "materialized_view"+ ? "This view is read-only."+ : "This table has no primary key. Browsing is read-only — editing requires a primary key."}+ </AlertDescription>+ </Alert>+ </div>+ )}++ {/* Dice UI DataGrid */}+ <div className="data-explorer-grid relative flex min-h-0 flex-1 flex-col overflow-hidden font-mono text-foreground [--color-gray-200:var(--color-border)] [&_[data-slot=grid-footer]]:hidden [&_[data-slot=grid-header]]:bg-container [&_[data-slot=grid]]:thin-scrollbar [&_[data-slot=grid]]:rounded-none [&_[data-slot=grid]]:border-0 [&_[data-slot=grid]]:bg-bunker-800">+ {isDataLoading && !hasLoaded && <ContentLoader className="h-full" />}+ <DataGrid+ {...gridProps}+ className={`min-h-0 flex-1 ${isDataLoading && !hasLoaded ? "hidden" : ""}`}+ stretchColumns+ />+ {isDataLoading && hasLoaded && (+ <div className="absolute inset-0 z-20 flex items-center justify-center bg-bunker-800/60">+ <ContentLoader className="h-auto" lottieClassName="h-24 w-24" />+ </div>+ )}+ </div>+ </div>+ );+};diff --git a/frontend/src/pages/pam/PamDataExplorerPage/components/DataExplorerRowEditor.tsx b/frontend/src/pages/pam/PamDataExplorerPage/components/DataExplorerRowEditor.tsxnew file mode 100644index 0000000000..1144f5e9bd--- /dev/null+++ b/frontend/src/pages/pam/PamDataExplorerPage/components/DataExplorerRowEditor.tsx@@ -0,0 +1,143 @@+// NOTE: This component is not currently wired up but is kept for future use+// as a side-sheet row editor for the data explorer grid.+import { useEffect, useState } from "react";++import { Badge } from "@app/components/v3/generic/Badge";+import { Button } from "@app/components/v3/generic/Button";+import { Input } from "@app/components/v3/generic/Input";+import {+ Sheet,+ SheetContent,+ SheetFooter,+ SheetHeader,+ SheetTitle+} from "@app/components/v3/generic/Sheet";+import { TextArea } from "@app/components/v3/generic/TextArea";++import type { ColumnInfo } from "../data-explorer-types";++type DataExplorerRowEditorProps = {+ isOpen: boolean;+ onOpenChange: (open: boolean) => void;+ row: Record<string, unknown> | null;+ columns: ColumnInfo[];+ primaryKeys: string[];+ onApply: (updates: Record<string, unknown>) => void;+};++const JSON_TYPES = new Set(["json", "jsonb", "xml"]);++export const DataExplorerRowEditor = ({+ isOpen,+ onOpenChange,+ row,+ columns,+ primaryKeys,+ onApply+}: DataExplorerRowEditorProps) => {+ const [formValues, setFormValues] = useState<Record<string, string>>({});++ useEffect(() => {+ if (row) {+ const values: Record<string, string> = {};+ columns.forEach((col) => {+ const val = row[col.name];+ values[col.name] = val === null || val === undefined ? "" : String(val);+ });+ setFormValues(values);+ }+ }, [row, columns]);++ const handleApply = () => {+ const updates: Record<string, unknown> = {};+ columns.forEach((col) => {+ const newVal = formValues[col.name] ?? "";+ const oldVal = row?.[col.name];+ const oldStr = oldVal === null || oldVal === undefined ? "" : String(oldVal);+ if (newVal !== oldStr) {+ // If field is empty and column is nullable, set to null+ updates[col.name] = newVal === "" && col.nullable ? null : newVal;+ }+ });+ onApply(updates);+ onOpenChange(false);+ };++ const isPk = (colName: string) => primaryKeys.includes(colName);+ const isReadOnly = (col: ColumnInfo) => isPk(col.name) || col.identityGeneration === "ALWAYS";++ return (+ <Sheet open={isOpen} onOpenChange={onOpenChange}>+ <SheetContent className="overflow-y-auto sm:max-w-lg">+ <SheetHeader>+ <SheetTitle>Edit Row</SheetTitle>+ </SheetHeader>+ <div className="space-y-3 py-4">+ {columns.map((col) => {+ const readOnly = isReadOnly(col);+ const value = formValues[col.name] ?? "";+ const isNull = row?.[col.name] === null;+ const isJsonType = JSON_TYPES.has(col.type.replace("[]", ""));++ return (+ <div key={col.name}>+ <div className="mb-1 flex items-center gap-2">+ {/* eslint-disable-next-line jsx-a11y/label-has-associated-control */}+ <label+ htmlFor={`row-editor-${col.name}`}+ className="text-xs font-medium text-mineshaft-200"+ >+ {col.name}+ </label>+ <Badge variant="outline" className="text-[10px]">+ {col.type}+ </Badge>+ {isPk(col.name) && <Badge className="text-[10px]">PK</Badge>}+ {col.nullable && (+ <Badge variant="outline" className="text-[10px]">+ nullable+ </Badge>+ )}+ {isNull && (+ <Badge variant="outline" className="text-[10px] text-yellow-500">+ NULL+ </Badge>+ )}+ </div>+ {isJsonType ? (+ <TextArea+ value={value}+ onChange={(e) =>+ setFormValues((prev) => ({ ...prev, [col.name]: e.target.value }))+ }+ disabled={readOnly}+ className="font-mono text-xs"+ rows={4}+ />+ ) : (+ <Input+ value={value}+ onChange={(e) =>+ setFormValues((prev) => ({ ...prev, [col.name]: e.target.value }))+ }+ disabled={readOnly}+ className="text-xs"+ placeholder={isNull ? "NULL" : undefined}+ />+ )}+ </div>+ );+ })}+ </div>+ <SheetFooter className="gap-2">+ <Button variant="outline" onClick={() => onOpenChange(false)}>+ Cancel+ </Button>+ <Button variant="info" onClick={handleApply}>+ Apply+ </Button>+ </SheetFooter>+ </SheetContent>+ </Sheet>+ );+};diff --git a/frontend/src/pages/pam/PamDataExplorerPage/components/DataExplorerSidebar.tsx b/frontend/src/pages/pam/PamDataExplorerPage/components/DataExplorerSidebar.tsxnew file mode 100644index 0000000000..66920b1b05--- /dev/null+++ b/frontend/src/pages/pam/PamDataExplorerPage/components/DataExplorerSidebar.tsx@@ -0,0 +1,198 @@+import { useCallback, useEffect, useRef, useState } from "react";+import { DatabaseIcon, SearchIcon, TableIcon, ViewIcon } from "lucide-react";++import { Input } from "@app/components/v3/generic/Input";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue+} from "@app/components/v3/generic/Select/Select";+import { Skeleton } from "@app/components/v3/generic/Skeleton";+import { cn } from "@app/components/v3/utils";++import type { SchemaInfo, TableInfo } from "../data-explorer-types";++type SelectedTab = { schema: string; table: string };++type DataExplorerSidebarProps = {+ schemas: SchemaInfo[];+ selectedSchema: string;+ onSchemaChange: (schema: string) => void;+ tables: TableInfo[];+ activeBrowseTarget: SelectedTab | null;+ onTableOpen: (table: string, opts: { forceNew: boolean }) => void;+ isLoadingSchemas: boolean;+ isLoadingTables: boolean;+ disabled?: boolean;+};++type ContextMenuState = {+ tableName: string;+ x: number;+ y: number;+};++export const DataExplorerSidebar = ({+ schemas,+ selectedSchema,+ onSchemaChange,+ tables,+ activeBrowseTarget,+ onTableOpen,+ isLoadingSchemas,+ isLoadingTables,+ disabled = false+}: DataExplorerSidebarProps) => {+ const [search, setSearch] = useState("");+ const [contextMenu, setContextMenu] = useState<ContextMenuState | null>(null);+ const menuRef = useRef<HTMLDivElement>(null);++ // Reset search when schema changes+ useEffect(() => {+ setSearch("");+ }, [selectedSchema]);++ // Close context menu on outside click / Escape+ useEffect(() => {+ if (!contextMenu) return undefined;+ const handleDown = (e: MouseEvent) => {+ if (menuRef.current && !menuRef.current.contains(e.target as Node)) {+ setContextMenu(null);+ }+ };+ const handleKey = (e: KeyboardEvent) => {+ if (e.key === "Escape") setContextMenu(null);+ };+ window.addEventListener("mousedown", handleDown);+ window.addEventListener("keydown", handleKey);+ return () => {+ window.removeEventListener("mousedown", handleDown);+ window.removeEventListener("keydown", handleKey);+ };+ }, [contextMenu]);++ const filteredTables = tables.filter((t) => t.name.toLowerCase().includes(search.toLowerCase()));++ const getTableIcon = useCallback((tableType: string) => {+ if (tableType === "view" || tableType === "materialized_view") {+ return <ViewIcon className="size-3.5 shrink-0 text-accent" />;+ }+ return <TableIcon className="size-3.5 shrink-0 text-accent" />;+ }, []);++ const handleClick = (name: string, e: React.MouseEvent) => {+ if (disabled) return;+ const forceNew = e.metaKey || e.ctrlKey;+ onTableOpen(name, { forceNew });+ };++ const handleContextMenu = (name: string, e: React.MouseEvent) => {+ if (disabled) return;+ e.preventDefault();+ setContextMenu({ tableName: name, x: e.clientX, y: e.clientY });+ };++ const handleOpenInNewTab = () => {+ if (!contextMenu) return;+ onTableOpen(contextMenu.tableName, { forceNew: true });+ setContextMenu(null);+ };++ return (+ <div className="flex h-full w-64 shrink-0 flex-col border-r border-border bg-container">+ {/* Schema selector + Search */}+ <div className="space-y-2 border-b border-border p-3">+ {isLoadingSchemas ? (+ <Skeleton className="h-8 w-full" />+ ) : (+ <Select value={selectedSchema} onValueChange={onSchemaChange} disabled={disabled}>+ <SelectTrigger className="h-9 w-full text-xs text-foreground">+ <span className="flex items-center gap-1.5">+ <DatabaseIcon className="size-3.5 text-accent" />+ <SelectValue />+ </span>+ </SelectTrigger>+ <SelectContent position="popper">+ {schemas.map((s) => (+ <SelectItem key={s.name} value={s.name}>+ {s.name}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ )}+ <div className="relative">+ <SearchIcon className="absolute top-1/2 left-2 size-3.5 -translate-y-1/2 text-accent" />+ <Input+ value={search}+ onChange={(e) => setSearch(e.target.value)}+ placeholder="Search tables..."+ className="pl-7 text-xs text-foreground"+ />+ </div>+ </div>++ {/* Table list */}+ <div className="thin-scrollbar flex-1 overflow-y-auto">+ {isLoadingTables && tables.length === 0 && (+ <div className="space-y-1 p-2">+ {Array.from({ length: 8 }).map((_, i) => (+ // eslint-disable-next-line react/no-array-index-key+ <Skeleton key={i} className="h-7 w-full" />+ ))}+ </div>+ )}+ {!isLoadingTables && filteredTables.length === 0 && (+ <div className="p-4 text-center text-xs text-accent">+ {search ? "No matching tables" : "No tables in this schema"}+ </div>+ )}+ {!isLoadingTables && filteredTables.length > 0 && (+ <div className="p-1">+ {filteredTables.map((t) => {+ const isActive =+ activeBrowseTarget?.schema === selectedSchema &&+ activeBrowseTarget.table === t.name;+ return (+ <button+ key={t.name}+ type="button"+ disabled={disabled}+ onClick={(e) => handleClick(t.name, e)}+ onContextMenu={(e) => handleContextMenu(t.name, e)}+ className={cn(+ "flex w-full items-center gap-2 rounded-md px-2.5 py-1.5 text-left text-xs text-muted transition-colors hover:bg-container-hover disabled:cursor-not-allowed disabled:opacity-50",+ isActive && "bg-container-hover text-foreground"+ )}+ >+ {getTableIcon(t.tableType)}+ <span className="truncate" title={t.name}>+ {t.name}+ </span>+ </button>+ );+ })}+ </div>+ )}+ </div>++ {contextMenu && (+ <div+ ref={menuRef}+ style={{ position: "fixed", top: contextMenu.y, left: contextMenu.x, zIndex: 50 }}+ className="min-w-[160px] rounded-md border border-border bg-popover p-1 text-xs text-foreground shadow-md"+ >+ <button+ type="button"+ onClick={handleOpenInNewTab}+ className="flex w-full items-center gap-2 rounded-sm px-2 py-1.5 text-left hover:bg-container-hover"+ >+ Open in new tab+ </button>+ </div>+ )}+ </div>+ );+};diff --git a/frontend/src/pages/pam/PamDataExplorerPage/components/DataExplorerToolbar.tsx b/frontend/src/pages/pam/PamDataExplorerPage/components/DataExplorerToolbar.tsxnew file mode 100644index 0000000000..54d225036b--- /dev/null+++ b/frontend/src/pages/pam/PamDataExplorerPage/components/DataExplorerToolbar.tsx@@ -0,0 +1,307 @@+import { useState } from "react";+import {+ ChevronLeftIcon,+ ChevronRightIcon,+ ClockIcon,+ PlusIcon,+ RefreshCwIcon,+ SaveIcon,+ Trash2Icon,+ UndoIcon+} from "lucide-react";++import { Button } from "@app/components/v3/generic/Button";+import { Popover, PopoverContent, PopoverTrigger } from "@app/components/v3/generic/Popover";++import type { ColumnInfo } from "../data-explorer-types";+import type { ExportFormat } from "../data-export";+import type { FilterCondition, SortCondition } from "../sql-generation";+import { ExportDropdown } from "./ExportDropdown";+import { FilterPopover } from "./FilterPopover";+import { SortPopover } from "./SortPopover";++type DataExplorerToolbarProps = {+ columns: ColumnInfo[];+ filters: FilterCondition[];+ onFiltersChange: (filters: FilterCondition[]) => Promise<boolean>;+ sorts: SortCondition[];+ onSortsChange: (sorts: SortCondition[]) => void;+ changeCount: number;+ onSave: () => void;+ onDiscard: () => void;+ isSaving: boolean;+ onAddRecord: () => void;+ selectedRowCount: number;+ onDeleteSelected: () => void;+ totalCount: number;+ offset: number;+ pageSize: number;+ onOffsetChange: (offset: number) => void;+ onPageSizeChange: (size: number) => void;+ executionTimeMs: number | null;+ hasPrimaryKey: boolean;+ isDataLoading?: boolean;+ onRefresh: () => void;+ isRefreshing?: boolean;+ onExport: (format: ExportFormat) => void;+ onCopy: (format: ExportFormat) => void;+ hasData: boolean;+};++export const DataExplorerToolbar = ({+ columns,+ filters,+ onFiltersChange,+ sorts,+ onSortsChange,+ changeCount,+ onSave,+ onDiscard,+ isSaving,+ onAddRecord,+ selectedRowCount,+ onDeleteSelected,+ totalCount,+ offset,+ pageSize,+ onOffsetChange,+ onPageSizeChange,+ executionTimeMs,+ hasPrimaryKey,+ isDataLoading = false,+ onRefresh,+ isRefreshing = false,+ onExport,+ onCopy,+ hasData+}: DataExplorerToolbarProps) => {+ const rangeStart = totalCount === 0 ? 0 : offset + 1;+ const rangeEnd = Math.min(offset + pageSize, totalCount);++ return (+ <div+ role="toolbar"+ data-grid-popover=""+ className="flex items-center justify-between border-b border-border px-3 py-1.5"+ onMouseDown={(e) => e.stopPropagation()}+ >+ <div className="flex items-center gap-2">+ <FilterPopover columns={columns} filters={filters} onFiltersChange={onFiltersChange} />+ <SortPopover+ columns={columns}+ sorts={sorts}+ onSortsChange={onSortsChange}+ disabled={isDataLoading}+ />++ {hasPrimaryKey && (+ <>+ <div className="h-4 w-px bg-border" />+ <Button variant="outline" size="xs" onClick={onAddRecord} className="gap-1">+ <PlusIcon className="size-3" />+ Add record+ </Button>+ </>+ )}++ {selectedRowCount > 0 && hasPrimaryKey && (+ <Button variant="danger" size="xs" onClick={onDeleteSelected} className="gap-1">+ <Trash2Icon className="size-3" />+ Delete {selectedRowCount} record{selectedRowCount !== 1 ? "s" : ""}+ </Button>+ )}++ {changeCount > 0 && (+ <>+ <div className="h-4 w-px bg-border" />+ <Button+ variant="success"+ size="xs"+ onClick={onSave}+ isPending={isSaving}+ className="gap-1"+ >+ <SaveIcon className="size-3" />+ Save {changeCount} change{changeCount !== 1 ? "s" : ""}+ </Button>+ <Button variant="ghost" size="xs" onClick={onDiscard} className="gap-1 underline">+ <UndoIcon className="size-3" />+ Discard changes+ </Button>+ </>+ )}+ </div>++ <div className="flex items-center gap-2">+ {executionTimeMs !== null && (+ <span className="flex items-center gap-1 text-xs text-accent">+ <ClockIcon className="size-3" />+ {executionTimeMs}ms+ </span>+ )}++ {/* Pagination */}+ <Button+ variant="ghost"+ size="xs"+ disabled={offset <= 0}+ onClick={() => onOffsetChange(Math.max(0, offset - pageSize))}+ className="size-7 p-0"+ >+ <ChevronLeftIcon className="size-3.5" />+ </Button>+ {/* eslint-disable-next-line @typescript-eslint/no-use-before-define */}+ <LimitOffsetPopover+ totalCount={totalCount}+ rangeStart={rangeStart}+ rangeEnd={rangeEnd}+ pageSize={pageSize}+ offset={offset}+ onPageSizeChange={onPageSizeChange}+ onOffsetChange={onOffsetChange}+ />+ <Button+ variant="ghost"+ size="xs"+ disabled={offset + pageSize >= totalCount}+ onClick={() => onOffsetChange(offset + pageSize)}+ className="size-7 p-0"+ >+ <ChevronRightIcon className="size-3.5" />+ </Button>++ {/* Export */}+ <ExportDropdown onExport={onExport} onCopy={onCopy} disabled={!hasData} />++ {/* Refresh */}+ <Button+ variant="ghost"+ size="xs"+ onClick={onRefresh}+ disabled={isRefreshing}+ className="size-7 p-0"+ >+ <RefreshCwIcon className={`size-3.5 ${isRefreshing ? "animate-spin" : ""}`} />+ </Button>+ </div>+ </div>+ );+};++// --- Limit / Offset popover ---++type LimitOffsetPopoverProps = {+ totalCount: number;+ rangeStart: number;+ rangeEnd: number;+ pageSize: number;+ offset: number;+ onPageSizeChange: (size: number) => void;+ onOffsetChange: (offset: number) => void;+};++const LimitOffsetPopover = ({+ totalCount,+ rangeStart,+ rangeEnd,+ pageSize,+ offset,+ onPageSizeChange,+ onOffsetChange+}: LimitOffsetPopoverProps) => {+ const [open, setOpen] = useState(false);+ const [limitInput, setLimitInput] = useState(String(pageSize));+ const [offsetInput, setOffsetInput] = useState(String(offset));++ const handleOpen = (isOpen: boolean) => {+ if (isOpen) {+ setLimitInput(String(pageSize));+ setOffsetInput(String(offset));+ }+ setOpen(isOpen);+ };++ const limitNum = Number(limitInput);+ const getLimitError = (): string | null => {+ if (limitInput === "" || Number.isNaN(limitNum)) return "Must be a number";+ if (limitNum < 1) return "Minimum is 1";+ if (limitNum > 1000) return "Maximum is 1000";+ return null;+ };+ const limitError = getLimitError();++ const offsetNum = Number(offsetInput);+ const getOffsetError = (): string | null => {+ if (offsetInput === "" || Number.isNaN(offsetNum)) return "Must be a number";+ if (offsetNum < 0) return "Must be 0 or greater";+ return null;+ };+ const offsetError = getOffsetError();++ const applyChanges = () => {+ if (limitError || offsetError) return;+ const newLimit = Math.max(1, Math.min(1000, limitNum || 50));+ const newOffset = Math.max(0, offsetNum || 0);+ onPageSizeChange(newLimit);+ onOffsetChange(newOffset);+ setOpen(false);+ };++ return (+ <Popover open={open} onOpenChange={handleOpen}>+ <PopoverTrigger asChild>+ <Button variant="ghost" size="xs" className="text-muted">+ {rangeStart} - {rangeEnd} of {totalCount}+ </Button>+ </PopoverTrigger>+ <PopoverContent className="w-auto p-3" align="center">+ <div className="flex flex-col gap-2">+ <div className="flex items-center gap-3">+ <div className="flex flex-col items-center gap-1">+ <span className="text-[10px] font-medium text-accent">Limit</span>+ <input+ type="number"+ value={limitInput}+ onChange={(e) => setLimitInput(e.target.value)}+ onKeyDown={(e) => e.key === "Enter" && applyChanges()}+ className={`h-8 w-16 rounded border bg-transparent text-center text-sm text-mineshaft-200 outline-none ${+ limitError+ ? "border-red-500 focus:border-red-500"+ : "border-border focus:border-ring"+ }`}+ min={1}+ />+ </div>+ <div className="flex flex-col items-center gap-1">+ <span className="text-[10px] font-medium text-accent">Offset</span>+ <input+ type="number"+ value={offsetInput}+ onChange={(e) => setOffsetInput(e.target.value)}+ onKeyDown={(e) => e.key === "Enter" && applyChanges()}+ className={`h-8 w-16 rounded border bg-transparent text-center text-sm text-mineshaft-200 outline-none ${+ offsetError+ ? "border-red-500 focus:border-red-500"+ : "border-border focus:border-ring"+ }`}+ min={0}+ />+ </div>+ </div>+ {(limitError || offsetError) && (+ <p className="text-center text-[10px] text-red-400">{limitError || offsetError}</p>+ )}+ <Button+ variant="outline"+ size="xs"+ onClick={applyChanges}+ disabled={Boolean(limitError || offsetError)}+ className="w-full"+ >+ Apply+ </Button>+ </div>+ </PopoverContent>+ </Popover>+ );+};diff --git a/frontend/src/pages/pam/PamDataExplorerPage/components/ExportDropdown.tsx b/frontend/src/pages/pam/PamDataExplorerPage/components/ExportDropdown.tsxnew file mode 100644index 0000000000..e1d55aec01--- /dev/null+++ b/frontend/src/pages/pam/PamDataExplorerPage/components/ExportDropdown.tsx@@ -0,0 +1,50 @@+import { ClipboardCopyIcon, DownloadIcon } from "lucide-react";++import { Button } from "@app/components/v3/generic/Button";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger+} from "@app/components/v3/generic/Dropdown";++import type { ExportFormat } from "../data-export";++type Props = {+ onExport: (format: ExportFormat) => void;+ onCopy: (format: ExportFormat) => void;+ disabled?: boolean;+};++export function ExportDropdown({ onExport, onCopy, disabled }: Props) {+ return (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button variant="ghost" size="xs" disabled={disabled} title="Export">+ <DownloadIcon />+ Export+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end">+ <DropdownMenuItem onClick={() => onExport("csv")}>+ <DownloadIcon className="size-3.5" />+ Download as CSV+ </DropdownMenuItem>+ <DropdownMenuItem onClick={() => onExport("json")}>+ <DownloadIcon className="size-3.5" />+ Download as JSON+ </DropdownMenuItem>+ <DropdownMenuSeparator />+ <DropdownMenuItem onClick={() => onCopy("csv")}>+ <ClipboardCopyIcon className="size-3.5" />+ Copy as CSV+ </DropdownMenuItem>+ <DropdownMenuItem onClick={() => onCopy("json")}>+ <ClipboardCopyIcon className="size-3.5" />+ Copy as JSON+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ );+}diff --git a/frontend/src/pages/pam/PamDataExplorerPage/components/FilterPopover.tsx b/frontend/src/pages/pam/PamDataExplorerPage/components/FilterPopover.tsxnew file mode 100644index 0000000000..f1dd4c18b6--- /dev/null+++ b/frontend/src/pages/pam/PamDataExplorerPage/components/FilterPopover.tsx@@ -0,0 +1,264 @@+import { useEffect, useState } from "react";+import { CheckIcon, FilterIcon, PlusIcon, XIcon } from "lucide-react";++import { Button } from "@app/components/v3/generic/Button";+import { Input } from "@app/components/v3/generic/Input";+import { Popover, PopoverContent, PopoverTrigger } from "@app/components/v3/generic/Popover";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue+} from "@app/components/v3/generic/Select";++import type { ColumnInfo } from "../data-explorer-types";+import type { FilterCondition, FilterOperator } from "../sql-generation";++function getFilterPlaceholder(columnType: string, operator: FilterOperator): string {+ switch (operator) {+ case "LIKE":+ return "%pattern%";+ case "ILIKE":+ return "%pattern% (case-insensitive)";+ case "IN":+ return "a, b, c";+ case "IS NULL":+ case "IS NOT NULL":+ return "";+ default:+ break;+ }++ const t = columnType.toLowerCase().replace("[]", "");+ switch (t) {+ case "int2":+ case "int4":+ case "int8":+ case "serial":+ case "bigserial":+ case "smallserial":+ case "integer":+ case "bigint":+ case "smallint":+ return "42";+ case "float4":+ case "float8":+ case "numeric":+ case "decimal":+ case "real":+ case "double precision":+ case "money":+ return "3.14";+ case "bool":+ case "boolean":+ return "true";+ case "uuid":+ return "550e8400-e29b-41d4-a716-...";+ case "date":+ return "2024-01-15";+ case "timestamp":+ case "timestamptz":+ return "2024-01-15 09:30:00";+ case "time":+ case "timetz":+ return "09:30:00";+ case "json":+ case "jsonb":+ return '{"key": "value"}';+ case "inet":+ case "cidr":+ return "192.168.1.0/24";+ case "text":+ case "varchar":+ case "char":+ case "bpchar":+ case "name":+ case "citext":+ return "some text";+ default:+ return "Value";+ }+}++const OPERATORS: { value: FilterOperator; label: string; needsValue: boolean }[] = [+ { value: "=", label: "equals", needsValue: true },+ { value: "<>", label: "not equals", needsValue: true },+ { value: ">", label: "greater than", needsValue: true },+ { value: "<", label: "less than", needsValue: true },+ { value: ">=", label: "greater or equal", needsValue: true },+ { value: "<=", label: "less or equal", needsValue: true },+ { value: "LIKE", label: "like", needsValue: true },+ { value: "ILIKE", label: "ilike", needsValue: true },+ { value: "IS NULL", label: "is null", needsValue: false },+ { value: "IS NOT NULL", label: "is not null", needsValue: false },+ { value: "IN", label: "in", needsValue: true }+];++type FilterPopoverProps = {+ columns: ColumnInfo[];+ filters: FilterCondition[];+ onFiltersChange: (filters: FilterCondition[]) => Promise<boolean>;+};++export const FilterPopover = ({ columns, filters, onFiltersChange }: FilterPopoverProps) => {+ const [open, setOpen] = useState(false);+ const [draft, setDraft] = useState<FilterCondition[]>(filters);+ const [isApplying, setIsApplying] = useState(false);++ // Sync draft when external filters change (e.g. cleared from outside)+ useEffect(() => {+ if (!open) {+ setDraft(filters);+ }+ }, [filters, open]);++ // Reset draft when popover opens; prevent close while applying+ const handleOpenChange = (isOpen: boolean) => {+ if (!isOpen && isApplying) return;+ if (isOpen) {+ setDraft(filters);+ }+ setOpen(isOpen);+ };++ const addFilter = () => {+ if (columns.length === 0) return;+ setDraft((prev) => [...prev, { column: columns[0].name, operator: "=", value: "" }]);+ };++ const removeFilter = (index: number) => {+ setDraft((prev) => prev.filter((_, i) => i !== index));+ };++ const updateFilter = (index: number, update: Partial<FilterCondition>) => {+ setDraft((prev) => prev.map((f, i) => (i === index ? { ...f, ...update } : f)));+ };++ const clearAll = async () => {+ setIsApplying(true);+ await onFiltersChange([]);+ setIsApplying(false);+ setOpen(false);+ };++ const applyFilters = async () => {+ setIsApplying(true);+ const success = await onFiltersChange(draft);+ setIsApplying(false);+ if (success) setOpen(false);+ };++ return (+ <Popover open={open} onOpenChange={handleOpenChange}>+ <PopoverTrigger asChild>+ <Button variant="outline" size="xs" className="gap-1.5">+ <FilterIcon className="size-3" />+ Filter+ {filters.length > 0 && (+ <span className="rounded-full bg-primary/20 px-1.5 text-[10px] font-medium text-primary">+ {filters.length}+ </span>+ )}+ </Button>+ </PopoverTrigger>+ <PopoverContent className="w-[580px] p-3" align="start">+ <div className="mb-2 flex items-center justify-between">+ <span className="text-sm font-medium text-mineshaft-200">Filters</span>+ {draft.length > 0 && (+ <Button variant="ghost" size="xs" onClick={clearAll} className="h-auto p-0 text-xs">+ Clear all+ </Button>+ )}+ </div>++ {draft.length === 0 ? (+ <p className="py-3 text-center text-xs text-mineshaft-400">No filters applied</p>+ ) : (+ <div className="space-y-2">+ {draft.map((filter, index) => {+ const opConfig = OPERATORS.find((o) => o.value === filter.operator);+ const colInfo = columns.find((c) => c.name === filter.column);+ return (+ // eslint-disable-next-line react/no-array-index-key+ <div key={index} className="flex items-center gap-1.5">+ <Select+ value={filter.column}+ onValueChange={(val) => updateFilter(index, { column: val })}+ >+ <SelectTrigger+ size="sm"+ className="w-40 text-xs text-mineshaft-200"+ title={filter.column}+ >+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {columns.map((col) => (+ <SelectItem key={col.name} value={col.name}>+ {col.name}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>++ <Select+ value={filter.operator}+ onValueChange={(val) =>+ updateFilter(index, { operator: val as FilterOperator })+ }+ >+ <SelectTrigger size="sm" className="w-28 text-xs text-mineshaft-200">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {OPERATORS.map((op) => (+ <SelectItem key={op.value} value={op.value}>+ {op.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>++ {opConfig?.needsValue !== false && (+ <Input+ value={filter.value}+ onChange={(e) => updateFilter(index, { value: e.target.value })}+ placeholder={getFilterPlaceholder(colInfo?.type ?? "", filter.operator)}+ className="h-7 flex-1 text-xs text-mineshaft-200"+ />+ )}++ <button+ type="button"+ onClick={() => removeFilter(index)}+ className="rounded p-1 text-mineshaft-400 hover:bg-mineshaft-700 hover:text-mineshaft-200"+ >+ <XIcon className="size-3" />+ </button>+ </div>+ );+ })}+ </div>+ )}++ <div className="mt-3 flex items-center justify-between">+ <Button variant="outline" size="xs" onClick={addFilter} className="gap-1">+ <PlusIcon className="size-3" />+ Add filter+ </Button>+ <Button+ variant="info"+ size="xs"+ onClick={applyFilters}+ isPending={isApplying}+ className="gap-1"+ >+ <CheckIcon className="size-3" />+ Apply+ </Button>+ </div>+ </PopoverContent>+ </Popover>+ );+};diff --git a/frontend/src/pages/pam/PamDataExplorerPage/components/QueryPanel.tsx b/frontend/src/pages/pam/PamDataExplorerPage/components/QueryPanel.tsxnew file mode 100644index 0000000000..b546e14af0--- /dev/null+++ b/frontend/src/pages/pam/PamDataExplorerPage/components/QueryPanel.tsx@@ -0,0 +1,209 @@+import { useEffect, useRef, useState } from "react";+import { GripHorizontalIcon } from "lucide-react";++import { cn } from "@app/components/v3/utils";++import type { FieldInfo } from "../data-explorer-types";+import { copyData, exportData } from "../data-export";+import type { QueryTab } from "../use-query-tabs";+import { ExportDropdown } from "./ExportDropdown";+import { QueryResultsTable } from "./QueryResultsTable";+import { QueryToolbar } from "./QueryToolbar";+import { SqlEditor } from "./SqlEditor";++function getRowLabel(rowCount: number, isTruncated: boolean): string {+ if (isTruncated) return `Showing 1,000 of ${rowCount.toLocaleString()} rows`;+ return `${rowCount} row${rowCount !== 1 ? "s" : ""}`;+}++type QueryResult = {+ rows: Record<string, unknown>[];+ fields: FieldInfo[];+ rowCount: number | null;+ isTruncated: boolean;+ transactionOpen: boolean;+ command: string;+ executionTimeMs: number;+};++type Props = {+ tab: QueryTab;+ executeQuery: (connectionId: string, sql: string) => Promise<QueryResult>;+ cancelQuery: (connectionId: string) => void;+ onSqlChange: (sql: string) => void;+ onTransactionStateChange: (open: boolean) => void;+};++export function QueryPanel({+ tab,+ executeQuery,+ cancelQuery,+ onSqlChange,+ onTransactionStateChange+}: Props) {+ const [isRunning, setIsRunning] = useState(false);+ const [result, setResult] = useState<QueryResult | null>(null);+ const [error, setError] = useState<string | null>(null);+ const [isDragging, setIsDragging] = useState(false);+ const [hasSelection, setHasSelection] = useState(false);+ const sqlToRunRef = useRef<string>(tab.sql);++ const containerRef = useRef<HTMLDivElement>(null);+ const editorPaneRef = useRef<HTMLDivElement>(null);+ const splitPctRef = useRef(40);++ useEffect(() => {+ if (editorPaneRef.current) {+ editorPaneRef.current.style.height = `${splitPctRef.current}%`;+ }+ }, []);++ const runSql = async (sqlToRun: string) => {+ setIsRunning(true);+ setError(null);+ try {+ const res = await executeQuery(tab.connectionId, sqlToRun);+ onTransactionStateChange(res.transactionOpen);+ setResult(res);+ } catch (err) {+ // BE is the source of truth via transactionOpen on error responses, but+ // when the pending promise rejects without a transactionOpen (e.g. WS+ // drop, timeout) we fall back to assuming the txn is gone.+ onTransactionStateChange(false);+ setError(err instanceof Error ? err.message : String(err));+ setResult(null);+ } finally {+ setIsRunning(false);+ }+ };++ const handleRun = async (sqlToRun?: string) => {+ const query = sqlToRun ?? sqlToRunRef.current;+ if (!query.trim() || isRunning) return;+ await runSql(query);+ };++ const handleCommit = async () => {+ await runSql("COMMIT");+ };++ const handleRollback = async () => {+ await runSql("ROLLBACK");+ };++ useEffect(() => {+ if (!isDragging) return undefined;++ const onMouseMove = (e: MouseEvent) => {+ const container = containerRef.current;+ const editorPane = editorPaneRef.current;+ if (!container || !editorPane) return;+ const rect = container.getBoundingClientRect();+ const pct = Math.min(85, Math.max(10, ((e.clientY - rect.top) / rect.height) * 100));+ splitPctRef.current = pct;+ editorPane.style.height = `${pct}%`;+ };++ const onMouseUp = () => setIsDragging(false);++ window.addEventListener("mousemove", onMouseMove);+ window.addEventListener("mouseup", onMouseUp);+ return () => {+ window.removeEventListener("mousemove", onMouseMove);+ window.removeEventListener("mouseup", onMouseUp);+ };+ }, [isDragging]);++ return (+ <div className="flex h-full w-full flex-col overflow-hidden">+ <QueryToolbar+ isRunning={isRunning}+ isInTransaction={tab.isInTransaction}+ hasSelection={hasSelection}+ onRun={handleRun}+ onCommit={handleCommit}+ onRollback={handleRollback}+ onCancel={() => cancelQuery(tab.connectionId)}+ />+ <div+ ref={containerRef}+ className={cn("flex flex-1 flex-col overflow-hidden", isDragging && "select-none")}+ >+ <div+ ref={editorPaneRef}+ className="min-h-0 overflow-hidden"+ style={{ backgroundColor: "#16181a" }}+ >+ <SqlEditor+ value={tab.sql}+ onChange={onSqlChange}+ onExecute={(s) => handleRun(s)}+ onSelectionChange={setHasSelection}+ onSqlToRunChange={(s) => {+ sqlToRunRef.current = s;+ }}+ />+ </div>++ {/* eslint-disable-next-line jsx-a11y/no-static-element-interactions */}+ <div+ className="group relative z-10 h-0 shrink-0 cursor-row-resize"+ onMouseDown={(e) => {+ e.preventDefault();+ setIsDragging(true);+ }}+ >+ <div+ className={cn(+ "absolute inset-x-0 top-0 h-px bg-mineshaft-600 transition-colors group-hover:bg-mineshaft-400",+ isDragging && "bg-mineshaft-400"+ )}+ />+ <div+ className={cn(+ "absolute top-0 left-1/2 -translate-x-1/2 -translate-y-1/2 rounded-sm bg-mineshaft-600 px-2 text-mineshaft-300 transition-colors group-hover:bg-mineshaft-500 group-hover:text-mineshaft-100",+ isDragging && "bg-mineshaft-500 text-mineshaft-100"+ )}+ >+ <GripHorizontalIcon className="size-3" />+ </div>+ </div>++ <div className="relative z-0 flex min-h-0 flex-1 flex-col overflow-hidden bg-bunker-800">+ <div className="min-h-0 flex-1 overflow-hidden">+ <QueryResultsTable result={result} error={error} isRunning={isRunning} />+ </div>+ {!isRunning && result && !error && (+ <div className="flex shrink-0 items-center justify-between border-t border-mineshaft-600 px-3 py-1">+ <span className="text-xs text-mineshaft-400">+ {result.rowCount != null+ ? getRowLabel(result.rowCount, result.isTruncated)+ : result.command}+ {" · "}+ {result.executionTimeMs}ms+ </span>+ {result.rows.length > 0 && (+ <ExportDropdown+ onExport={(fmt) =>+ exportData(+ result.rows,+ result.fields.map((f) => f.name),+ fmt+ )+ }+ onCopy={(fmt) =>+ copyData(+ result.rows,+ result.fields.map((f) => f.name),+ fmt+ )+ }+ />+ )}+ </div>+ )}+ </div>+ </div>+ </div>+ );+}diff --git a/frontend/src/pages/pam/PamDataExplorerPage/components/QueryResultsTable.tsx b/frontend/src/pages/pam/PamDataExplorerPage/components/QueryResultsTable.tsxnew file mode 100644index 0000000000..6b7c29e063--- /dev/null+++ b/frontend/src/pages/pam/PamDataExplorerPage/components/QueryResultsTable.tsx@@ -0,0 +1,134 @@+import { useCallback, useMemo } from "react";+import type { ColumnDef } from "@tanstack/react-table";++import { Spinner } from "@app/components/v2";+import { DataGrid, useDataGrid } from "@app/components/v3/generic/DataGrid";++import type { FieldInfo } from "../data-explorer-types";++type QueryResult = {+ rows: Record<string, unknown>[];+ fields: FieldInfo[];+ rowCount: number | null;+ isTruncated: boolean;+ command: string;+ executionTimeMs: number;+};++type Props = {+ result: QueryResult | null;+ error: string | null;+ isRunning: boolean;+};++type RowData = Record<string, unknown>;++function buildColumns(fields: FieldInfo[]): ColumnDef<RowData>[] {+ return fields.map((f) => ({+ id: f.name,+ accessorKey: f.name,+ header: f.name,+ meta: {+ label: f.name,+ cell: { variant: "short-text" as const }+ },+ enableSorting: true,+ enablePinning: true,+ enableHiding: true+ }));+}++function ResultsGrid({ result }: { result: QueryResult }) {+ const { isTruncated } = result;++ const columns = useMemo(() => buildColumns(result.fields), [result.fields]);++ const getRowId = useCallback((_row: RowData, index: number) => String(index), []);++ const gridProps = useDataGrid<RowData>({+ data: result.rows,+ columns,+ getRowId,+ readOnly: true,+ rowHeight: "short",+ enableSearch: true+ });++ return (+ <div className="flex h-full flex-col overflow-hidden">+ <div className="data-explorer-grid relative flex min-h-0 flex-1 flex-col overflow-hidden font-mono text-foreground [--color-gray-200:var(--color-border)] [&_[data-slot=grid-footer]]:hidden [&_[data-slot=grid-header]]:bg-container [&_[data-slot=grid]]:thin-scrollbar [&_[data-slot=grid]]:rounded-none [&_[data-slot=grid]]:border-0 [&_[data-slot=grid]]:bg-bunker-800">+ <DataGrid {...gridProps} className="min-h-0 flex-1" stretchColumns />+ </div>+ {isTruncated && (+ <div className="shrink-0 border-t border-mineshaft-600 bg-mineshaft-800 px-3 py-1.5 text-xs text-yellow-500/80">+ Showing first {result.rows.length.toLocaleString()} rows (results truncated)+ </div>+ )}+ </div>+ );+}++export function QueryResultsTable({ result, error, isRunning }: Props) {+ if (isRunning) {+ return (+ <div className="flex h-full items-center justify-center">+ <Spinner className="size-5" />+ </div>+ );+ }++ if (error) {+ return (+ <div className="p-4">+ <div className="rounded-md border border-red-500/30 bg-red-500/10 px-4 py-3 font-mono text-xs whitespace-pre-wrap text-red-400">+ {error}+ </div>+ </div>+ );+ }++ if (!result) {+ return (+ <div className="flex h-full items-center justify-center">+ <p className="text-sm text-mineshaft-300">Run a query to see results</p>+ </div>+ );+ }++ if (result.rows.length === 0) {+ const cmdUpper = result.command.toUpperCase();+ const count = result.rowCount ?? 0;+ const verb: Record<string, string> = {+ INSERT: "inserted",+ UPDATE: "updated",+ DELETE: "deleted"+ };+ const staticMessage: Record<string, string> = {+ BEGIN: "Transaction started",+ COMMIT: "Transaction committed",+ ROLLBACK: "Transaction rolled back"+ };++ const isMutation = verb[cmdUpper] !== undefined && result.fields.length === 0;++ let message: string;+ if (staticMessage[cmdUpper]) {+ message = staticMessage[cmdUpper];+ } else if (isMutation) {+ message = `${count} row${count !== 1 ? "s" : ""} ${verb[cmdUpper]}`;+ } else {+ message = "No rows returned";+ }++ return (+ <div className="flex h-full flex-col items-center justify-center gap-2">+ <span className="rounded border-2 border-mineshaft-500 bg-mineshaft-700 px-3 py-1.5 font-mono text-sm text-mineshaft-200">+ {message}+ {isMutation && <span className="ml-2 text-mineshaft-400">· No rows returned</span>}+ </span>+ </div>+ );+ }++ return <ResultsGrid result={result} />;+}diff --git a/frontend/src/pages/pam/PamDataExplorerPage/components/QueryToolbar.tsx b/frontend/src/pages/pam/PamDataExplorerPage/components/QueryToolbar.tsxnew file mode 100644index 0000000000..edb5ae893e--- /dev/null+++ b/frontend/src/pages/pam/PamDataExplorerPage/components/QueryToolbar.tsx@@ -0,0 +1,73 @@+import { CheckIcon, PlayIcon, RotateCcwIcon, SquareIcon } from "lucide-react";++import { Button } from "@app/components/v3/generic/Button";++const isMac = typeof navigator !== "undefined" && navigator.userAgent.includes("Mac");++type Props = {+ isRunning: boolean;+ isInTransaction: boolean;+ hasSelection: boolean;+ onRun: () => void;+ onCommit: () => void;+ onRollback: () => void;+ onCancel: () => void;+};++export function QueryToolbar({+ isRunning,+ isInTransaction,+ hasSelection,+ onRun,+ onCommit,+ onRollback,+ onCancel+}: Props) {+ return (+ <div className="flex shrink-0 items-center justify-between border-b border-mineshaft-600 bg-bunker-800 px-3 py-1.5">+ <div className="flex items-center gap-3">+ {isRunning ? (+ <Button size="xs" variant="outline" onClick={onCancel} className="gap-1.5">+ <SquareIcon className="size-3 text-red-400" />+ Cancel+ </Button>+ ) : (+ <Button size="xs" onClick={() => onRun()} className="gap-1.5">+ <PlayIcon className="size-3" />+ {hasSelection ? "Run Selection" : "Run"}+ <span className="opacity-60">{isMac ? "⌘" : "Ctrl"} ↵</span>+ </Button>+ )}+ {isInTransaction && (+ <>+ <Button+ size="xs"+ variant="success"+ onClick={onCommit}+ isDisabled={isRunning}+ className="gap-1.5"+ >+ <CheckIcon className="size-3" />+ Commit+ </Button>+ <Button+ size="xs"+ variant="danger"+ onClick={onRollback}+ isDisabled={isRunning}+ className="gap-1.5"+ >+ <RotateCcwIcon className="size-3" />+ Rollback+ </Button>+ </>+ )}+ </div>+ {isInTransaction && (+ <span className="rounded bg-yellow-500/15 px-2 py-0.5 text-xs font-medium text-yellow-400">+ Transaction open+ </span>+ )}+ </div>+ );+}diff --git a/frontend/src/pages/pam/PamDataExplorerPage/components/SortPopover.tsx b/frontend/src/pages/pam/PamDataExplorerPage/components/SortPopover.tsxnew file mode 100644index 0000000000..aa912071e9--- /dev/null+++ b/frontend/src/pages/pam/PamDataExplorerPage/components/SortPopover.tsx@@ -0,0 +1,102 @@+import { ArrowUpDownIcon, CheckIcon } from "lucide-react";++import { Button } from "@app/components/v3/generic/Button";+import {+ Command,+ CommandEmpty,+ CommandGroup,+ CommandInput,+ CommandItem,+ CommandList+} from "@app/components/v3/generic/Command";+import { Popover, PopoverContent, PopoverTrigger } from "@app/components/v3/generic/Popover";+import { cn } from "@app/components/v3/utils";++import type { ColumnInfo } from "../data-explorer-types";+import type { SortCondition } from "../sql-generation";++type SortPopoverProps = {+ columns: ColumnInfo[];+ sorts: SortCondition[];+ onSortsChange: (sorts: SortCondition[]) => void;+ disabled?: boolean;+};++export const SortPopover = ({+ columns,+ sorts,+ onSortsChange,+ disabled = false+}: SortPopoverProps) => {+ const activeSort = sorts[0] ?? null;+ const isAscending = activeSort?.direction !== "DESC";++ const handleColumnSelect = (colName: string) => {+ if (activeSort?.column === colName) {+ onSortsChange([]);+ } else {+ onSortsChange([{ column: colName, direction: isAscending ? "ASC" : "DESC" }]);+ }+ };++ const handleDirectionToggle = () => {+ if (!activeSort) return;+ onSortsChange([+ { column: activeSort.column, direction: activeSort.direction === "ASC" ? "DESC" : "ASC" }+ ]);+ };++ return (+ <Popover>+ <PopoverTrigger asChild>+ <Button variant="outline" size="xs" className="gap-1.5" disabled={disabled}>+ <ArrowUpDownIcon className="size-3" />+ Sort+ {activeSort && (+ <span className="rounded-full bg-primary/20 px-1.5 text-[10px] font-medium text-primary">+ {activeSort.column}+ </span>+ )}+ </Button>+ </PopoverTrigger>+ <PopoverContent className="w-[300px] p-0" align="start">+ <div className="flex items-center justify-between border-b border-border px-3 py-2">+ <span className="text-sm font-medium text-foreground">Sort by</span>+ <button+ type="button"+ onClick={handleDirectionToggle}+ disabled={!activeSort || disabled}+ className="flex items-center gap-1.5 rounded px-2 py-0.5 text-xs text-muted transition-colors hover:bg-foreground/5 disabled:opacity-40"+ >+ {isAscending ? "Ascending" : "Descending"}+ <ArrowUpDownIcon className="size-3" />+ </button>+ </div>+ <Command>+ <CommandInput placeholder="Search columns..." />+ <CommandList>+ <CommandEmpty>No matching columns</CommandEmpty>+ <CommandGroup>+ {columns.map((col) => (+ <CommandItem+ key={col.name}+ value={col.name}+ onSelect={() => handleColumnSelect(col.name)}+ disabled={disabled}+ >+ <CheckIcon+ className={cn(+ "size-3.5",+ activeSort?.column === col.name ? "opacity-100" : "opacity-0"+ )}+ />+ <span className="truncate">{col.name}</span>+ </CommandItem>+ ))}+ </CommandGroup>+ </CommandList>+ </Command>+ </PopoverContent>+ </Popover>+ );+};diff --git a/frontend/src/pages/pam/PamDataExplorerPage/components/SqlEditor.tsx b/frontend/src/pages/pam/PamDataExplorerPage/components/SqlEditor.tsxnew file mode 100644index 0000000000..87b36729cd--- /dev/null+++ b/frontend/src/pages/pam/PamDataExplorerPage/components/SqlEditor.tsx@@ -0,0 +1,155 @@+import { useEffect, useRef } from "react";+import { defaultKeymap, history, historyKeymap } from "@codemirror/commands";+import { PostgreSQL, sql } from "@codemirror/lang-sql";+import { HighlightStyle, syntaxHighlighting } from "@codemirror/language";+import { EditorState, type Transaction } from "@codemirror/state";+import { EditorView, keymap, placeholder, type ViewUpdate } from "@codemirror/view";+import { tags } from "@lezer/highlight";++const infisicalTheme = EditorView.theme({+ "&": { height: "100%", fontSize: "13px", backgroundColor: "#16181a" },+ "&.cm-editor": { backgroundColor: "#16181a" },+ ".cm-scroller": {+ overflow: "auto",+ fontFamily: "ui-monospace, 'Cascadia Code', 'Source Code Pro', Menlo, monospace",+ backgroundColor: "#16181a",+ scrollbarWidth: "thin",+ scrollbarColor: "#39393d transparent"+ },+ ".cm-scroller::-webkit-scrollbar": { width: "4px", height: "4px" },+ ".cm-scroller::-webkit-scrollbar-track": { background: "transparent" },+ ".cm-scroller::-webkit-scrollbar-thumb": { background: "#39393d", borderRadius: "2px" },+ ".cm-content": { padding: "8px 0", caretColor: "#e0ed34", backgroundColor: "#16181a" },+ ".cm-line": { backgroundColor: "transparent" },+ ".cm-gutters": {+ backgroundColor: "#16181a",+ borderRight: "1px solid #2b2c30",+ color: "#707174"+ },+ ".cm-lineNumbers .cm-gutterElement": { padding: "0 12px 0 8px" },+ ".cm-activeLine": { backgroundColor: "rgba(45, 47, 51, 0.5)" },+ ".cm-activeLineGutter": { backgroundColor: "rgba(45, 47, 51, 0.5)" },+ ".cm-cursor": { borderLeftColor: "#e0ed34" },+ ".cm-selectionBackground": { backgroundColor: "#2d2f33 !important" },+ "&.cm-focused .cm-selectionBackground": { backgroundColor: "#2d2f33 !important" },+ ".cm-matchingBracket": { backgroundColor: "#323439", color: "#e0ed34 !important" }+});++const infisicalHighlight = HighlightStyle.define(+ [+ { tag: tags.keyword, color: "#63b0bd", fontWeight: "600" },+ { tag: tags.string, color: "#29b866" },+ { tag: tags.number, color: "#f39c12" },+ { tag: tags.comment, color: "#707174", fontStyle: "italic" },+ { tag: tags.operator, color: "#adaeb0" },+ { tag: tags.punctuation, color: "#adaeb0" },+ { tag: tags.separator, color: "#adaeb0" },+ { tag: tags.bracket, color: "#adaeb0" },+ { tag: tags.name, color: "#ebebeb" },+ { tag: tags.function(tags.name), color: "#63b0bd" },+ { tag: tags.typeName, color: "#f39c12" },+ { tag: tags.bool, color: "#63b0bd" },+ { tag: tags.null, color: "#707174" },+ { tag: tags.special(tags.string), color: "#29b866" },+ { tag: tags.invalid, color: "#e74c3c" }+ ],+ { all: { color: "#ebebeb" } }+);++const MAX_SQL_BYTES = 50 * 1024; // 50KB — matches backend Zod limit++const maxSqlLength = EditorState.transactionFilter.of((tr: Transaction) => {+ if (tr.docChanged && tr.newDoc.length > MAX_SQL_BYTES) return [];+ return tr;+});++type Props = {+ value: string;+ onChange: (value: string) => void;+ onExecute: (sql: string) => void;+ onSelectionChange: (hasSelection: boolean) => void;+ onSqlToRunChange: (sql: string) => void;+};++export function SqlEditor({+ value,+ onChange,+ onExecute,+ onSelectionChange,+ onSqlToRunChange+}: Props) {+ const containerRef = useRef<HTMLDivElement>(null);+ const viewRef = useRef<EditorView | null>(null);+ const onExecuteRef = useRef(onExecute);+ const onChangeRef = useRef(onChange);+ const onSelectionChangeRef = useRef(onSelectionChange);+ const onSqlToRunChangeRef = useRef(onSqlToRunChange);+ onExecuteRef.current = onExecute;+ onChangeRef.current = onChange;+ onSelectionChangeRef.current = onSelectionChange;+ onSqlToRunChangeRef.current = onSqlToRunChange;++ useEffect(() => {+ if (!containerRef.current) return undefined;++ const view = new EditorView({+ state: EditorState.create({+ doc: value,+ extensions: [+ history(),+ keymap.of([+ {+ key: "Mod-Enter",+ run: (v) => {+ const selection = v.state.selection.main;+ const selectedText = selection.empty+ ? v.state.doc.toString()+ : v.state.sliceDoc(selection.from, selection.to);+ onExecuteRef.current(selectedText);+ return true;+ }+ },+ ...historyKeymap,+ ...defaultKeymap+ ]),+ maxSqlLength,+ placeholder("Start writing SQL..."),+ sql({ dialect: PostgreSQL }),+ infisicalTheme,+ syntaxHighlighting(infisicalHighlight),+ EditorView.updateListener.of((update: ViewUpdate) => {+ if (update.docChanged) {+ const doc = update.state.doc.toString();+ onChangeRef.current(doc);+ if (update.state.selection.main.empty) {+ onSqlToRunChangeRef.current(doc);+ }+ }+ if (update.selectionSet) {+ const selection = update.state.selection.main;+ if (selection.empty) {+ onSqlToRunChangeRef.current(update.state.doc.toString());+ onSelectionChangeRef.current(false);+ } else {+ onSqlToRunChangeRef.current(update.state.sliceDoc(selection.from, selection.to));+ onSelectionChangeRef.current(true);+ }+ }+ })+ ]+ }),+ parent: containerRef.current+ });++ viewRef.current = view;+ onSqlToRunChangeRef.current(value);++ return () => {+ view.destroy();+ viewRef.current = null;+ };+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, []);++ return <div ref={containerRef} className="h-full w-full" />;+}diff --git a/frontend/src/pages/pam/PamDataExplorerPage/data-explorer-types.ts b/frontend/src/pages/pam/PamDataExplorerPage/data-explorer-types.tsnew file mode 100644index 0000000000..0c423f56a5--- /dev/null+++ b/frontend/src/pages/pam/PamDataExplorerPage/data-explorer-types.ts@@ -0,0 +1,87 @@+// WebSocket message types for the Postgres Data Explorer++export type DataExplorerClientMessage =+ // Metadata (no connectionId) — served by short-lived BE pg.Clients+ | { type: "get-schemas"; id: string }+ | { type: "get-tables"; id: string; schema: string }+ // Tab-scoped — routed to a specific BE controller+ | { type: "get-table-detail"; id: string; connectionId: string; schema: string; table: string }+ | { type: "query"; id: string; connectionId: string; sql: string }+ // Cancel is fire-and-forget; gains connectionId for routing but not id+ | { type: "cancel"; connectionId: string }+ // Lifecycle+ | { type: "open-connection"; id: string }+ | { type: "close-connection"; connectionId: string }+ // Keepalive sent while the browser tab is visible; resets the BE idle timer+ | { type: "activity" };++export type DataExplorerServerMessage =+ | { type: "schemas"; id: string; data: SchemaInfo[] }+ | { type: "tables"; id: string; data: TableInfo[] }+ | {+ type: "table-detail";+ id: string;+ connectionId: string;+ transactionOpen: boolean;+ data: TableDetail;+ }+ | {+ type: "query-result";+ id: string;+ connectionId: string;+ rows: Record<string, unknown>[];+ fields: FieldInfo[];+ rowCount: number | null;+ isTruncated: boolean;+ transactionOpen: boolean;+ command: string;+ executionTimeMs: number;+ }+ | {+ type: "error";+ id: string;+ connectionId?: string;+ transactionOpen?: boolean;+ error: string;+ detail?: string;+ hint?: string;+ }+ | { type: "connection-opened"; id: string; connectionId: string; backendPid: number | null }+ | { type: "connection-open-failed"; id: string; error: string }+ | { type: "connection-closed"; connectionId: string; reason: string }+ | { type: "ready" }+ | { type: "session_end"; reason: string };++export type SchemaInfo = {+ name: string;+};++export type TableInfo = {+ name: string;+ tableType: string;+};++export type ColumnInfo = {+ name: string;+ type: string;+ nullable: boolean;+ identityGeneration: string | null;+};++export type ForeignKeyInfo = {+ constraintName: string;+ columns: string[];+ targetSchema: string;+ targetTable: string;+ targetColumns: string[];+};++export type TableDetail = {+ columns: ColumnInfo[];+ primaryKeys: string[];+ foreignKeys: ForeignKeyInfo[];+};++export type FieldInfo = {+ name: string;+};diff --git a/frontend/src/pages/pam/PamDataExplorerPage/data-explorer-utils.ts b/frontend/src/pages/pam/PamDataExplorerPage/data-explorer-utils.tsnew file mode 100644index 0000000000..a00fc9540a--- /dev/null+++ b/frontend/src/pages/pam/PamDataExplorerPage/data-explorer-utils.ts@@ -0,0 +1,15 @@+import type { ForeignKeyInfo } from "./data-explorer-types";++export function getColumnIndicator(+ colName: string,+ primaryKeys: string[],+ fkMap: Map<string, ForeignKeyInfo>+): { type: "pk" | "fk"; tooltip?: string } | undefined {+ if (primaryKeys.includes(colName)) return { type: "pk" };+ const fk = fkMap.get(colName);+ if (fk) {+ const targetCol = fk.targetColumns[fk.columns.indexOf(colName)] ?? fk.targetColumns[0];+ return { type: "fk", tooltip: `\u2192 ${fk.targetSchema}.${fk.targetTable}(${targetCol})` };+ }+ return undefined;+}diff --git a/frontend/src/pages/pam/PamDataExplorerPage/data-export.ts b/frontend/src/pages/pam/PamDataExplorerPage/data-export.tsnew file mode 100644index 0000000000..4e52a457a8--- /dev/null+++ b/frontend/src/pages/pam/PamDataExplorerPage/data-export.ts@@ -0,0 +1,75 @@+export type ExportFormat = "csv" | "json";++const FORMULA_PREFIXES = new Set(["=", "+", "-", "@"]);++function escapeCsvField(value: unknown): string {+ if (value === null || value === undefined) return "";+ let str = typeof value === "object" ? JSON.stringify(value) : String(value);+ if (FORMULA_PREFIXES.has(str.charAt(0))) {+ str = `'${str}`;+ }+ if (str.includes(",") || str.includes('"') || str.includes("\n") || str.includes("\r")) {+ return `"${str.replace(/"/g, '""')}"`;+ }+ return str;+}++function buildTimestamp(): string {+ return new Date()+ .toISOString()+ .replace(/[:]/g, "-")+ .replace(/\.\d+Z$/, "Z");+}++function buildCsv(rows: Record<string, unknown>[], columns: string[]): string {+ const header = columns.map(escapeCsvField).join(",");+ const body = rows+ .map((row) => columns.map((col) => escapeCsvField(row[col])).join(","))+ .join("\n");+ return `${header}\n${body}`;+}++function buildJson(rows: Record<string, unknown>[], columns: string[]): string {+ const filtered = rows.map((row) => {+ const obj: Record<string, unknown> = {};+ columns.forEach((col) => {+ obj[col] = row[col] ?? null;+ });+ return obj;+ });+ return JSON.stringify(filtered, null, 2);+}++function serialize(+ rows: Record<string, unknown>[],+ columns: string[],+ format: ExportFormat+): string {+ return format === "json" ? buildJson(rows, columns) : buildCsv(rows, columns);+}++export function exportData(+ rows: Record<string, unknown>[],+ columns: string[],+ format: ExportFormat+): void {+ if (rows.length === 0) return;+ const content = serialize(rows, columns, format);+ const mime = format === "json" ? "application/json;charset=utf-8;" : "text/csv;charset=utf-8;";+ const blob = new Blob([content], { type: mime });+ const url = URL.createObjectURL(blob);+ const a = document.createElement("a");+ a.href = url;+ a.download = `infisical_data_${buildTimestamp()}.${format}`;+ a.click();+ URL.revokeObjectURL(url);+}++export async function copyData(+ rows: Record<string, unknown>[],+ columns: string[],+ format: ExportFormat+): Promise<void> {+ if (rows.length === 0) return;+ await navigator.clipboard.writeText(serialize(rows, columns, format));+}diff --git a/frontend/src/pages/pam/PamDataExplorerPage/sql-generation.ts b/frontend/src/pages/pam/PamDataExplorerPage/sql-generation.tsnew file mode 100644index 0000000000..8790880a93--- /dev/null+++ b/frontend/src/pages/pam/PamDataExplorerPage/sql-generation.ts@@ -0,0 +1,175 @@+// Client-side SQL generation for the Postgres Data Explorer.+// All identifiers are properly quoted to prevent SQL injection.++export function quoteIdent(name: string): string {+ return `"${name.replace(/"/g, '""')}"`;+}++export function quoteLiteral(value: unknown): string {+ if (value === null || value === undefined) return "NULL";+ if (typeof value === "number") {+ if (!Number.isFinite(value)) return "NULL";+ return String(value);+ }+ if (typeof value === "boolean") return value ? "TRUE" : "FALSE";+ const str = String(value);+ // Use dollar-quoting if the string contains single quotes and no dollar signs+ if (str.includes("'") && !str.includes("$")) {+ return `$$${str}$$`;+ }+ return `'${str.replace(/'/g, "''")}'`;+}++export type FilterCondition = {+ column: string;+ operator: FilterOperator;+ value: string;+};++export type FilterOperator =+ | "="+ | "<>"+ | ">"+ | "<"+ | ">="+ | "<="+ | "LIKE"+ | "ILIKE"+ | "IS NULL"+ | "IS NOT NULL"+ | "IN";++export type SortCondition = {+ column: string;+ direction: "ASC" | "DESC";+};++function buildWhereClause(filters: FilterCondition[]): string {+ if (filters.length === 0) return "";+ const conditions = filters.map((f) => {+ const col = quoteIdent(f.column);+ switch (f.operator) {+ case "IS NULL":+ return `${col} IS NULL`;+ case "IS NOT NULL":+ return `${col} IS NOT NULL`;+ case "IN": {+ const values = f.value+ .split(",")+ .map((v) => quoteLiteral(v.trim()))+ .join(", ");+ return `${col} IN (${values})`;+ }+ case "LIKE":+ case "ILIKE":+ return `${col} ${f.operator} ${quoteLiteral(f.value)}`;+ default:+ return `${col} ${f.operator} ${quoteLiteral(f.value)}`;+ }+ });+ return ` WHERE ${conditions.join(" AND ")}`;+}++function buildOrderByClause(sorts: SortCondition[]): string {+ if (sorts.length === 0) return "";+ const parts = sorts.map((s) => `${quoteIdent(s.column)} ${s.direction}`);+ return ` ORDER BY ${parts.join(", ")}`;+}++export function buildSelectQuery(params: {+ schema: string;+ table: string;+ filters: FilterCondition[];+ sorts: SortCondition[];+ limit: number;+ offset: number;+ primaryKeys?: string[];+}): string {+ const { schema, table, filters, sorts, limit, offset, primaryKeys } = params;+ const tableName = `${quoteIdent(schema)}.${quoteIdent(table)}`;+ const where = buildWhereClause(filters);++ // Default sort by PK for stable pagination+ let orderBy: string;+ if (sorts.length > 0) {+ orderBy = buildOrderByClause(sorts);+ } else if (primaryKeys && primaryKeys.length > 0) {+ orderBy = buildOrderByClause(+ primaryKeys.map((pk) => ({ column: pk, direction: "ASC" as const }))+ );+ } else {+ orderBy = "";+ }++ return `SELECT * FROM ${tableName}${where}${orderBy} LIMIT ${limit} OFFSET ${offset}`;+}++export function buildCountQuery(params: {+ schema: string;+ table: string;+ filters: FilterCondition[];+}): string {+ const { schema, table, filters } = params;+ const tableName = `${quoteIdent(schema)}.${quoteIdent(table)}`;+ const where = buildWhereClause(filters);+ return `SELECT COUNT(*) AS count FROM ${tableName}${where}`;+}++export function buildInsertQuery(params: {+ schema: string;+ table: string;+ row: Record<string, unknown>;+}): string {+ const { schema, table, row } = params;+ const tableName = `${quoteIdent(schema)}.${quoteIdent(table)}`;+ const entries = Object.entries(row).filter(([, v]) => v !== undefined && v !== "");+ if (entries.length === 0) {+ return `INSERT INTO ${tableName} DEFAULT VALUES RETURNING *`;+ }+ const columns = entries.map(([k]) => quoteIdent(k)).join(", ");+ const values = entries.map(([, v]) => quoteLiteral(v)).join(", ");+ return `INSERT INTO ${tableName} (${columns}) VALUES (${values}) RETURNING *`;+}++export function buildUpdateQuery(params: {+ schema: string;+ table: string;+ changes: Record<string, unknown>;+ primaryKeyMatch: Record<string, unknown>;+}): string {+ const { schema, table, changes, primaryKeyMatch } = params;+ if (Object.keys(primaryKeyMatch).length === 0) {+ throw new Error("UPDATE requires at least one primary key condition");+ }+ const tableName = `${quoteIdent(schema)}.${quoteIdent(table)}`;+ const setClauses = Object.entries(changes)+ .map(([col, val]) => `${quoteIdent(col)} = ${quoteLiteral(val)}`)+ .join(", ");+ const whereClauses = Object.entries(primaryKeyMatch)+ .map(([col, val]) => `${quoteIdent(col)} = ${quoteLiteral(val)}`)+ .join(" AND ");+ return `UPDATE ${tableName} SET ${setClauses} WHERE ${whereClauses} RETURNING *`;+}++export function buildDeleteQuery(params: {+ schema: string;+ table: string;+ primaryKeyMatch: Record<string, unknown>;+}): string {+ const { schema, table, primaryKeyMatch } = params;+ if (Object.keys(primaryKeyMatch).length === 0) {+ throw new Error("DELETE requires at least one primary key condition");+ }+ const tableName = `${quoteIdent(schema)}.${quoteIdent(table)}`;+ const whereClauses = Object.entries(primaryKeyMatch)+ .map(([col, val]) => `${quoteIdent(col)} = ${quoteLiteral(val)}`)+ .join(" AND ");+ return `DELETE FROM ${tableName} WHERE ${whereClauses}`;+}++// Note: RETURNING * in individual INSERT/UPDATE statements is harmless but unused when+// wrapped here — pgClient.query() returns only the last statement's result (COMMIT).+// The frontend re-fetches data after save anyway.+export function wrapInTransaction(statements: string[]): string {+ return `BEGIN;\n${statements.join(";\n")};\nCOMMIT;`;+}diff --git a/frontend/src/pages/pam/PamDataExplorerPage/use-data-explorer-session.ts b/frontend/src/pages/pam/PamDataExplorerPage/use-data-explorer-session.tsnew file mode 100644index 0000000000..3d529c4428--- /dev/null+++ b/frontend/src/pages/pam/PamDataExplorerPage/use-data-explorer-session.ts@@ -0,0 +1,576 @@+import { useCallback, useEffect, useRef, useState } from "react";+import ms from "ms";++import { apiRequest } from "@app/config/request";+import { MfaSessionStatus, TMfaSessionStatusResponse } from "@app/hooks/api/mfaSession/types";++import { DEFAULT_ACCESS_DURATION } from "../constants";+import type {+ DataExplorerClientMessage,+ DataExplorerServerMessage,+ FieldInfo,+ SchemaInfo,+ TableDetail,+ TableInfo+} from "./data-explorer-types";++type PendingRequest = {+ resolve: (msg: DataExplorerServerMessage) => void;+ reject: (err: Error) => void;+ timer: ReturnType<typeof setTimeout>;+ // Present on tab-scoped requests so we can reject all pending when a tab closes.+ connectionId?: string;+};++type MfaState = {+ required: boolean;+ sessionId?: string;+ method?: string;+ verifying: boolean;+};++type ApprovalState = {+ required: boolean;+ policyName?: string;+ policyId?: string;+ accessDurationMax?: string;+ creating: boolean;+ submitted: boolean;+ approvalRequestId?: string;+ errorMessage?: string;+};++type UseDataExplorerSessionOptions = {+ accountId: string;+ orgId: string;+ accountName: string;+ reason?: string;+ onSessionEnd?: (reason?: string) => void;+ // Server pushes connection-closed when a BE controller dies unexpectedly.+ onConnectionClosed?: (connectionId: string, reason: string) => void;+ // Called after a reconnect so the page can drop tabs + land on a fresh query tab.+ onReconnected?: () => void;+};++const REQUEST_TIMEOUT_MS = 30_000;++// Cadence for the visibility-driven keepalive. The BE idle timer is 10 min;+// 60s leaves plenty of headroom if a heartbeat drops on flaky networks.+const ACTIVITY_PING_INTERVAL_MS = 60_000;++type QueryResult = {+ rows: Record<string, unknown>[];+ fields: FieldInfo[];+ rowCount: number | null;+ isTruncated: boolean;+ transactionOpen: boolean;+ command: string;+ executionTimeMs: number;+};++export const useDataExplorerSession = ({+ accountId,+ orgId,+ accountName,+ reason: accessReason,+ onSessionEnd,+ onConnectionClosed,+ onReconnected+}: UseDataExplorerSessionOptions) => {+ const [isConnected, setIsConnected] = useState(false);+ const [isConnecting, setIsConnecting] = useState(false);+ const [errorMessage, setErrorMessage] = useState<string | null>(null);+ const [mfaState, setMfaState] = useState<MfaState | null>(null);+ const [approvalState, setApprovalState] = useState<ApprovalState | null>(null);++ const wsRef = useRef<WebSocket | null>(null);+ const pendingRequestsRef = useRef<Map<string, PendingRequest>>(new Map());+ const readyResolveRef = useRef<(() => void) | null>(null);+ const readyRejectRef = useRef<((err: Error) => void) | null>(null);+ const readyPromiseRef = useRef<Promise<void> | null>(null);+ const onSessionEndRef = useRef(onSessionEnd);+ const onConnectionClosedRef = useRef(onConnectionClosed);+ const onReconnectedRef = useRef(onReconnected);+ const hasConnectedBeforeRef = useRef(false);++ useEffect(() => {+ onSessionEndRef.current = onSessionEnd;+ }, [onSessionEnd]);+ useEffect(() => {+ onConnectionClosedRef.current = onConnectionClosed;+ }, [onConnectionClosed]);+ useEffect(() => {+ onReconnectedRef.current = onReconnected;+ }, [onReconnected]);++ const rejectAllPending = useCallback((reason: string) => {+ const pending = pendingRequestsRef.current;+ pending.forEach(({ reject: rej, timer }) => {+ clearTimeout(timer);+ rej(new Error(reason));+ });+ pending.clear();+ }, []);++ // --- WebSocket lifecycle (imperative, mirrors useWebAccessSession) ---++ const openWebSocket = useCallback(+ (ticket: string) => {+ const { protocol, host } = window.location;+ const wsProtocol = protocol === "https:" ? "wss:" : "ws:";+ const wsUrl = `${wsProtocol}//${host}/api/v1/pam/accounts/${accountId}/web-access?ticket=${encodeURIComponent(ticket)}`;+ const ws = new WebSocket(wsUrl);+ wsRef.current = ws;++ ws.onmessage = (event) => {+ let serverMsg: DataExplorerServerMessage;+ try {+ serverMsg = JSON.parse(event.data as string) as DataExplorerServerMessage;+ } catch {+ return;+ }++ if (serverMsg.type === "ready") {+ setIsConnected(true);+ setIsConnecting(false);+ readyResolveRef.current?.();+ if (hasConnectedBeforeRef.current) {+ onReconnectedRef.current?.();+ }+ hasConnectedBeforeRef.current = true;+ return;+ }++ if (serverMsg.type === "session_end") {+ wsRef.current = null;+ setIsConnected(false);+ setIsConnecting(false);+ rejectAllPending("Session ended");+ readyRejectRef.current?.(new Error("Session ended"));+ onSessionEndRef.current?.(serverMsg.reason);+ return;+ }++ if (serverMsg.type === "connection-closed") {+ // Informational only — the FE has no pending-request id to resolve.+ // Reject any pending requests tied to this connectionId.+ const pending = pendingRequestsRef.current;+ pending.forEach((p, id) => {+ if (p.connectionId === serverMsg.connectionId) {+ clearTimeout(p.timer);+ p.reject(new Error(serverMsg.reason || "Connection closed"));+ pending.delete(id);+ }+ });+ onConnectionClosedRef.current?.(serverMsg.connectionId, serverMsg.reason);+ return;+ }++ // Request-response correlation (all remaining typed messages carry `id`).+ if ("id" in serverMsg && serverMsg.id) {+ const pending = pendingRequestsRef.current.get(serverMsg.id);+ if (pending) {+ pendingRequestsRef.current.delete(serverMsg.id);+ clearTimeout(pending.timer);++ if (serverMsg.type === "error") {+ const errMsg = [serverMsg.error, serverMsg.detail, serverMsg.hint]+ .filter(Boolean)+ .join("\n");+ pending.reject(new Error(errMsg));+ } else if (serverMsg.type === "connection-open-failed") {+ pending.reject(new Error(serverMsg.error));+ } else {+ pending.resolve(serverMsg);+ }+ }+ }+ };++ ws.onclose = () => {+ // If wsRef was already cleared (by disconnect/cleanup or session_end handler), skip.+ if (wsRef.current !== ws) return;++ wsRef.current = null;+ setIsConnected(false);+ setIsConnecting(false);+ rejectAllPending("Connection closed");+ readyRejectRef.current?.(new Error("Connection closed"));+ onSessionEndRef.current?.();+ };++ ws.onerror = () => {+ // onclose always fires after onerror+ };+ },+ [accountId, rejectAllPending]+ );++ const connect = useCallback(+ async (mfaSessionId?: string) => {+ setIsConnecting(true);+ setErrorMessage(null);+ setMfaState(null);+ setApprovalState(null);++ readyPromiseRef.current = new Promise<void>((resolve, reject) => {+ readyResolveRef.current = resolve;+ readyRejectRef.current = reject;+ });+ // Prevent unhandled rejection — callers of sendRequest will see the error+ // when they await readyPromiseRef.current.+ readyPromiseRef.current.catch(() => {});++ try {+ const { data } = await apiRequest.post<{ ticket: string }>(+ `/api/v1/pam/accounts/${accountId}/web-access-ticket`,+ { mfaSessionId, reason: accessReason }+ );+ openWebSocket(data.ticket);+ } catch (err: unknown) {+ const axiosErr = err as {+ response?: {+ data?: {+ error?: string;+ message?: string;+ details?: {+ mfaSessionId?: string;+ mfaMethod?: string;+ policyId?: string;+ policyName?: string;+ constraints?: { accessDuration: { max: string } };+ };+ };+ };+ };++ if (axiosErr?.response?.data?.error === "SESSION_MFA_REQUIRED") {+ const { details } = axiosErr.response!.data!;+ setMfaState({+ required: true,+ sessionId: details?.mfaSessionId,+ method: details?.mfaMethod,+ verifying: false+ });+ setIsConnecting(false);+ return;+ }++ if (axiosErr?.response?.data?.error === "PolicyViolationError") {+ const { details } = axiosErr.response!.data!;+ setApprovalState({+ required: true,+ policyName: details?.policyName,+ policyId: details?.policyId,+ accessDurationMax: details?.constraints?.accessDuration.max,+ creating: false,+ submitted: false+ });+ setIsConnecting(false);+ return;+ }++ setErrorMessage(axiosErr?.response?.data?.message ?? "Failed to connect to database");+ setIsConnecting(false);+ readyRejectRef.current?.(new Error("Failed to connect"));+ }+ },+ [accountId, accessReason, openWebSocket]+ );++ const disconnect = useCallback(() => {+ const ws = wsRef.current;+ // Clear ref BEFORE close — so onclose sees wsRef.current !== ws and skips.+ wsRef.current = null;+ if (ws) ws.close();+ rejectAllPending("Disconnected");+ }, [rejectAllPending]);++ const reconnect = useCallback(() => {+ disconnect();+ connect();+ }, [disconnect, connect]);++ // MFA flow+ const handleMfaVerification = useCallback(async () => {+ if (!mfaState?.sessionId) return;++ const mfaUrl = `${window.location.origin}/mfa-session/${mfaState.sessionId}`;+ window.open(mfaUrl, "_blank");++ setMfaState((prev) => (prev ? { ...prev, verifying: true } : null));++ const MFA_POLL_INTERVAL = 2000;+ const MFA_TIMEOUT = 5 * 60 * 1000;+ const startTime = Date.now();++ const verified = await new Promise<boolean>((resolve) => {+ const interval = setInterval(async () => {+ if (Date.now() - startTime > MFA_TIMEOUT) {+ clearInterval(interval);+ resolve(false);+ return;+ }+ try {+ const resp = await apiRequest.get<TMfaSessionStatusResponse>(+ `/api/v2/mfa-sessions/${mfaState.sessionId}/status`+ );+ if (resp.data.status === MfaSessionStatus.ACTIVE) {+ clearInterval(interval);+ resolve(true);+ }+ } catch {+ clearInterval(interval);+ resolve(false);+ }+ }, MFA_POLL_INTERVAL);+ });++ if (verified) {+ connect(mfaState.sessionId);+ } else {+ setMfaState((prev) => (prev ? { ...prev, verifying: false } : null));+ setErrorMessage("MFA verification timed out or failed");+ }+ }, [mfaState, connect]);++ // Approval request flow+ const submitApprovalRequest = useCallback(+ async (justification?: string) => {+ if (!approvalState?.required) return;+ setApprovalState((prev) =>+ prev ? { ...prev, creating: true, errorMessage: undefined } : null+ );++ try {+ const { data: approvalData } = await apiRequest.post<{ request: { id: string } }>(+ "/api/v1/approval-policies/pam-access/requests",+ {+ requestData: {+ accessDuration:+ approvalState.accessDurationMax &&+ ms(approvalState.accessDurationMax) < ms(DEFAULT_ACCESS_DURATION)+ ? approvalState.accessDurationMax+ : DEFAULT_ACCESS_DURATION,+ accountName+ },+ justification: justification?.trim() || undefined+ }+ );+ setApprovalState((prev) =>+ prev+ ? {+ ...prev,+ creating: false,+ submitted: true,+ approvalRequestId: approvalData.request.id+ }+ : null+ );+ } catch {+ setApprovalState((prev) =>+ prev+ ? { ...prev, creating: false, errorMessage: "Failed to create approval request" }+ : null+ );+ }+ },+ [approvalState, accountName]+ );++ const approvalRequestUrl = approvalState?.approvalRequestId+ ? `${window.location.origin}/organizations/${orgId}/approvals/${approvalState.approvalRequestId}`+ : undefined;++ // --- Request helpers ---++ const sendRequest = useCallback(+ async <T extends DataExplorerServerMessage>(+ msg: Record<string, unknown>,+ opts?: { connectionId?: string }+ ): Promise<T> => {+ if (readyPromiseRef.current) {+ await readyPromiseRef.current;+ }++ const id = crypto.randomUUID();+ const fullMsg = { ...msg, id } as DataExplorerClientMessage;++ return new Promise<T>((resolve, reject) => {+ const timer = setTimeout(() => {+ pendingRequestsRef.current.delete(id);+ reject(new Error("Request timed out"));+ }, REQUEST_TIMEOUT_MS);++ pendingRequestsRef.current.set(id, {+ resolve: resolve as (m: DataExplorerServerMessage) => void,+ reject,+ timer,+ connectionId: opts?.connectionId+ });++ const ws = wsRef.current;+ if (ws && ws.readyState === WebSocket.OPEN) {+ ws.send(JSON.stringify(fullMsg));+ } else {+ pendingRequestsRef.current.delete(id);+ clearTimeout(timer);+ reject(new Error("WebSocket not connected"));+ }+ });+ },+ []+ );++ const openConnection = useCallback(async (): Promise<{+ connectionId: string;+ backendPid: number | null;+ }> => {+ const resp = await sendRequest<+ Extract<DataExplorerServerMessage, { type: "connection-opened" }>+ >({+ type: "open-connection"+ });+ return { connectionId: resp.connectionId, backendPid: resp.backendPid };+ }, [sendRequest]);++ const closeConnection = useCallback((connectionId: string): void => {+ const ws = wsRef.current;+ // Reject any pending requests tied to this connection immediately so the+ // caller doesn't have a dangling promise when the tab is gone.+ const pending = pendingRequestsRef.current;+ pending.forEach((p, id) => {+ if (p.connectionId === connectionId) {+ clearTimeout(p.timer);+ p.reject(new Error("Connection closed"));+ pending.delete(id);+ }+ });+ if (ws && ws.readyState === WebSocket.OPEN) {+ ws.send(JSON.stringify({ type: "close-connection", connectionId }));+ }+ }, []);++ const fetchSchemas = useCallback(async (): Promise<SchemaInfo[]> => {+ const resp = await sendRequest<Extract<DataExplorerServerMessage, { type: "schemas" }>>({+ type: "get-schemas"+ });+ return resp.data;+ }, [sendRequest]);++ const fetchTables = useCallback(+ async (schema: string): Promise<TableInfo[]> => {+ const resp = await sendRequest<Extract<DataExplorerServerMessage, { type: "tables" }>>({+ type: "get-tables",+ schema+ });+ return resp.data;+ },+ [sendRequest]+ );++ const fetchTableDetail = useCallback(+ async (+ connectionId: string,+ schema: string,+ table: string+ ): Promise<{ detail: TableDetail; transactionOpen: boolean }> => {+ const resp = await sendRequest<Extract<DataExplorerServerMessage, { type: "table-detail" }>>(+ { type: "get-table-detail", connectionId, schema, table },+ { connectionId }+ );+ return { detail: resp.data, transactionOpen: resp.transactionOpen };+ },+ [sendRequest]+ );++ const cancelQuery = useCallback((connectionId: string) => {+ const ws = wsRef.current;+ if (ws && ws.readyState === WebSocket.OPEN) {+ ws.send(JSON.stringify({ type: "cancel", connectionId }));+ }+ }, []);++ const executeQuery = useCallback(+ async (connectionId: string, sql: string): Promise<QueryResult> => {+ const resp = await sendRequest<Extract<DataExplorerServerMessage, { type: "query-result" }>>(+ { type: "query", connectionId, sql },+ { connectionId }+ );+ return {+ rows: resp.rows,+ fields: resp.fields,+ rowCount: resp.rowCount,+ isTruncated: resp.isTruncated,+ transactionOpen: resp.transactionOpen,+ command: resp.command,+ executionTimeMs: resp.executionTimeMs+ };+ },+ [sendRequest]+ );++ // Visibility-driven keepalive. While the browser tab is visible and the WS+ // is open, send a fire-and-forget { type: "activity" } every minute so the+ // BE idle timer doesn't fire on read-only sessions (filter/paginate/browse).+ // When the tab goes hidden we stop sending, and the BE idle timer takes over.+ useEffect(() => {+ if (!isConnected) return undefined;++ let interval: ReturnType<typeof setInterval> | null = null;++ const sendActivity = () => {+ const ws = wsRef.current;+ if (ws && ws.readyState === WebSocket.OPEN) {+ ws.send(JSON.stringify({ type: "activity" } satisfies DataExplorerClientMessage));+ }+ };++ const start = () => {+ if (interval) return;+ sendActivity();+ interval = setInterval(sendActivity, ACTIVITY_PING_INTERVAL_MS);+ };++ const stop = () => {+ if (interval) {+ clearInterval(interval);+ interval = null;+ }+ };++ const onVisibilityChange = () => {+ if (document.visibilityState === "visible") start();+ else stop();+ };++ if (document.visibilityState === "visible") start();+ document.addEventListener("visibilitychange", onVisibilityChange);++ return () => {+ document.removeEventListener("visibilitychange", onVisibilityChange);+ stop();+ };+ }, [isConnected]);++ return {+ isConnected,+ isConnecting,+ errorMessage,+ mfaState,+ approvalState,+ connect,+ disconnect,+ reconnect,+ handleMfaVerification,+ submitApprovalRequest,+ approvalRequestUrl,+ openConnection,+ closeConnection,+ fetchSchemas,+ fetchTables,+ fetchTableDetail,+ executeQuery,+ cancelQuery+ };+};diff --git a/frontend/src/pages/pam/PamDataExplorerPage/use-query-tabs.ts b/frontend/src/pages/pam/PamDataExplorerPage/use-query-tabs.tsnew file mode 100644index 0000000000..5d488a827a--- /dev/null+++ b/frontend/src/pages/pam/PamDataExplorerPage/use-query-tabs.ts@@ -0,0 +1,308 @@+import { useCallback, useRef, useState } from "react";++import { createNotification } from "@app/components/notifications";++import type { TableDetail } from "./data-explorer-types";++type TabBase = {+ id: string;+ connectionId: string;+ backendPid: number | null;+ isInTransaction: boolean;+ lastFocusedAt: number;+ isDead?: boolean;+};++type BrowseTab = TabBase & {+ kind: "browse";+ title: string;+ schema: string;+ table: string;+ tableDetail: TableDetail | null;+ isLoadingDetail: boolean;+};++export type QueryTab = TabBase & {+ kind: "query";+ title: string;+ sql: string;+};++type Tab = BrowseTab | QueryTab;++const MAX_TABS = 20;++type UseQueryTabsOptions = {+ openConnection: () => Promise<{ connectionId: string; backendPid: number | null }>;+ closeConnection: (connectionId: string) => void;+ fetchTableDetail: (+ connectionId: string,+ schema: string,+ table: string+ ) => Promise<{ detail: TableDetail; transactionOpen: boolean }>;+};++export const useQueryTabs = ({+ openConnection,+ closeConnection,+ fetchTableDetail+}: UseQueryTabsOptions) => {+ const [tabs, setTabs] = useState<Tab[]>([]);+ const [activeTabId, setActiveTabId] = useState<string | null>(null);+ const [isOpeningTab, setIsOpeningTab] = useState(false);+ const nextQueryNumberRef = useRef(1);++ const atTabLimit = tabs.length >= MAX_TABS;++ const guardLimit = useCallback((): boolean => {+ if (tabs.length >= MAX_TABS) {+ createNotification({+ title: "Tab limit reached",+ text: `Maximum ${MAX_TABS} tabs open. Close one to open another.`,+ type: "warning"+ });+ return false;+ }+ return true;+ }, [tabs.length]);++ // Shared shell for openQueryTab / openBrowseTab: enforces the tab-count cap,+ // toggles the spinner, asks the BE for a new connection, and surfaces any+ // failure as a toast. Returns null if the caller should bail out.+ const acquireTabConnection = useCallback(async (): Promise<{+ connectionId: string;+ backendPid: number | null;+ } | null> => {+ if (!guardLimit()) return null;+ setIsOpeningTab(true);+ try {+ return await openConnection();+ } catch (err) {+ createNotification({+ title: "Failed to open tab",+ text: err instanceof Error ? err.message : "Unknown error",+ type: "error"+ });+ return null;+ } finally {+ setIsOpeningTab(false);+ }+ }, [openConnection, guardLimit]);++ const openQueryTab = useCallback(async (): Promise<string | null> => {+ const conn = await acquireTabConnection();+ if (!conn) return null;+ const id = crypto.randomUUID();+ const title = `Query ${nextQueryNumberRef.current}`;+ nextQueryNumberRef.current += 1;+ setTabs((prev) => [+ ...prev,+ {+ kind: "query",+ id,+ connectionId: conn.connectionId,+ backendPid: conn.backendPid,+ isInTransaction: false,+ lastFocusedAt: Date.now(),+ title,+ sql: ""+ }+ ]);+ setActiveTabId(id);+ return id;+ }, [acquireTabConnection]);++ const openBrowseTab = useCallback(+ async (+ schema: string,+ table: string,+ { forceNew }: { forceNew: boolean }+ ): Promise<string | null> => {+ if (!forceNew) {+ const matches = tabs.filter(+ (t): t is BrowseTab =>+ t.kind === "browse" && t.schema === schema && t.table === table && !t.isDead+ );+ if (matches.length > 0) {+ const focus = matches.reduce((a, b) => (a.lastFocusedAt >= b.lastFocusedAt ? a : b));+ setActiveTabId(focus.id);+ setTabs((prev) =>+ prev.map((t) => (t.id === focus.id ? { ...t, lastFocusedAt: Date.now() } : t))+ );+ return focus.id;+ }+ }++ const conn = await acquireTabConnection();+ if (!conn) return null;+ const id = crypto.randomUUID();++ // Optimistic push with isLoadingDetail: true — the grid shows a skeleton+ // until fetchTableDetail resolves.+ setTabs((prev) => [+ ...prev,+ {+ kind: "browse",+ id,+ connectionId: conn.connectionId,+ backendPid: conn.backendPid,+ isInTransaction: false,+ lastFocusedAt: Date.now(),+ title: `${schema}.${table}`,+ schema,+ table,+ tableDetail: null,+ isLoadingDetail: true+ }+ ]);+ setActiveTabId(id);++ // Fire the detail fetch off the critical open path.+ (async () => {+ try {+ const { detail, transactionOpen } = await fetchTableDetail(+ conn.connectionId,+ schema,+ table+ );+ setTabs((prev) =>+ prev.map((t) =>+ t.id === id && t.kind === "browse"+ ? {+ ...t,+ tableDetail: detail,+ isLoadingDetail: false,+ isInTransaction: transactionOpen+ }+ : t+ )+ );+ } catch (err) {+ setTabs((prev) =>+ prev.map((t) =>+ t.id === id && t.kind === "browse"+ ? { ...t, isLoadingDetail: false, isDead: true }+ : t+ )+ );+ createNotification({+ title: "Failed to load table",+ text: err instanceof Error ? err.message : "Unknown error",+ type: "error"+ });+ }+ })().catch(() => {});++ return id;+ },+ [acquireTabConnection, fetchTableDetail, tabs]+ );++ const closeTab = useCallback(+ (id: string) => {+ // Side effects (closeConnection + setActiveTabId) are hoisted OUT of+ // the setTabs updater so StrictMode's double-invoke can't fire the WS+ // close frame twice. React requires updaters to be pure.+ const target = tabs.find((t) => t.id === id);+ if (!target) return;+ closeConnection(target.connectionId);+ const remaining = tabs.filter((t) => t.id !== id);+ if (activeTabId === id) {+ // Activate the most recently focused remaining tab, if any.+ const nextActive =+ remaining.length > 0+ ? remaining.reduce((a, b) => (a.lastFocusedAt >= b.lastFocusedAt ? a : b)).id+ : null;+ setActiveTabId(nextActive);+ }+ setTabs(remaining);+ },+ [tabs, activeTabId, closeConnection]+ );++ const setActiveTab = useCallback((id: string) => {+ setActiveTabId(id);+ setTabs((prev) => prev.map((t) => (t.id === id ? { ...t, lastFocusedAt: Date.now() } : t)));+ }, []);++ const updateTabSql = useCallback((id: string, sql: string) => {+ setTabs((prev) => prev.map((t) => (t.id === id && t.kind === "query" ? { ...t, sql } : t)));+ }, []);++ const setTabTransactionOpen = useCallback((id: string, open: boolean) => {+ setTabs((prev) => prev.map((t) => (t.id === id ? { ...t, isInTransaction: open } : t)));+ }, []);++ // Server pushed connection-closed for this tab's connection — mark it dead+ // but don't auto-remove. The user sees an error state and can close manually.+ const markConnectionDead = useCallback((connectionId: string) => {+ setTabs((prev) =>+ prev.map((t) => (t.connectionId === connectionId ? { ...t, isDead: true } : t))+ );+ }, []);++ // Reconnect flow — drop all tabs, reset next-query counter.+ const resetTabs = useCallback(() => {+ setTabs([]);+ setActiveTabId(null);+ nextQueryNumberRef.current = 1;+ }, []);++ const refreshBrowseTab = useCallback(+ async (id: string) => {+ const target = tabs.find((t) => t.id === id);+ if (!target || target.kind !== "browse") return;+ setTabs((prev) =>+ prev.map((t) => (t.id === id && t.kind === "browse" ? { ...t, isLoadingDetail: true } : t))+ );+ try {+ const { detail, transactionOpen } = await fetchTableDetail(+ target.connectionId,+ target.schema,+ target.table+ );+ setTabs((prev) =>+ prev.map((t) =>+ t.id === id && t.kind === "browse"+ ? {+ ...t,+ tableDetail: detail,+ isLoadingDetail: false,+ isInTransaction: transactionOpen+ }+ : t+ )+ );+ } catch (err) {+ setTabs((prev) =>+ prev.map((t) =>+ t.id === id && t.kind === "browse" ? { ...t, isLoadingDetail: false } : t+ )+ );+ createNotification({+ title: "Failed to refresh table",+ text: err instanceof Error ? err.message : "Unknown error",+ type: "error"+ });+ }+ },+ [tabs, fetchTableDetail]+ );++ return {+ tabs,+ activeTabId,+ atTabLimit,+ isOpeningTab,+ openQueryTab,+ openBrowseTab,+ closeTab,+ setActiveTab,+ updateTabSql,+ setTabTransactionOpen,+ markConnectionDead,+ resetTabs,+ refreshBrowseTab,+ MAX_TABS+ };+};