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
feat(pam): add SQL query runner to Postgres data explorer
Bernie Gandin94604854e912
diff --git a/backend/src/ee/services/pam-web-access/pam-postgres-session-handler.ts b/backend/src/ee/services/pam-web-access/pam-postgres-session-handler.tsindex d60d1277ed..e7c2643e3c 100644--- a/backend/src/ee/services/pam-web-access/pam-postgres-session-handler.ts+++ b/backend/src/ee/services/pam-web-access/pam-postgres-session-handler.ts@@ -193,16 +193,18 @@ export const handlePostgresSession = async (case PostgresClientMessageType.Query: {try {- // Multi-statement SQL (transactions) is executed via PostgreSQL's simple query- // protocol, which returns only the last statement's result. For transaction-wrapped- // batches (BEGIN;...;COMMIT;), the result is from COMMIT (no rows/fields).+ // node-postgres returns an array of QueryResult objects when the SQL contains+ // multiple statements (simple query protocol). We take the last result so the+ // caller always sees a single consistent response — same behaviour as psql.const startTime = performance.now();- const result = await pgClient.query(message.sql);+ const rawResult = await pgClient.query(message.sql);const executionTimeMs = Math.round(performance.now() - startTime);+ const MAX_ROWS = 1000;+ const result = Array.isArray(rawResult) ? rawResult[rawResult.length - 1] : rawResult;sendResponse({type: PostgresServerMessageType.QueryResult,id: message.id,- rows: (result.rows ?? []) as Record<string, unknown>[],+ rows: (result.rows ?? []).slice(0, MAX_ROWS) as Record<string, unknown>[],fields: (result.fields ?? []).map((f) => ({ name: f.name })),rowCount: result.rowCount,command: result.command ?? "",diff --git a/frontend/package-lock.json b/frontend/package-lock.jsonindex ab852cf019..cd39fc920c 100644--- a/frontend/package-lock.json+++ b/frontend/package-lock.json@@ -10,6 +10,11 @@"dependencies": {"@casl/ability": "^6.7.2","@casl/react": "^4.0.0",+ "@codemirror/commands": "^6.10.3",+ "@codemirror/lang-sql": "^6.10.0",+ "@codemirror/state": "^6.6.0",+ "@codemirror/theme-one-dark": "^6.1.3",+ "@codemirror/view": "^6.41.0","@dagrejs/dagre": "^1.1.4","@dnd-kit/core": "^6.3.1","@dnd-kit/modifiers": "^9.0.0",@@ -525,6 +530,91 @@"react": "^16.0.0 || ^17.0.0 || ^18.0.0"}},+ "node_modules/@codemirror/autocomplete": {+ "version": "6.20.1",+ "resolved": "https://registry.npmjs.org/@codemirror/autocomplete/-/autocomplete-6.20.1.tgz",+ "integrity": "sha512-1cvg3Vz1dSSToCNlJfRA2WSI4ht3K+WplO0UMOgmUYPivCyy2oueZY6Lx7M9wThm7SDUBViRmuT+OG/i8+ON9A==",+ "license": "MIT",+ "dependencies": {+ "@codemirror/language": "^6.0.0",+ "@codemirror/state": "^6.0.0",+ "@codemirror/view": "^6.17.0",+ "@lezer/common": "^1.0.0"+ }+ },+ "node_modules/@codemirror/commands": {+ "version": "6.10.3",+ "resolved": "https://registry.npmjs.org/@codemirror/commands/-/commands-6.10.3.tgz",+ "integrity": "sha512-JFRiqhKu+bvSkDLI+rUhJwSxQxYb759W5GBezE8Uc8mHLqC9aV/9aTC7yJSqCtB3F00pylrLCwnyS91Ap5ej4Q==",+ "license": "MIT",+ "dependencies": {+ "@codemirror/language": "^6.0.0",+ "@codemirror/state": "^6.6.0",+ "@codemirror/view": "^6.27.0",+ "@lezer/common": "^1.1.0"+ }+ },+ "node_modules/@codemirror/lang-sql": {+ "version": "6.10.0",+ "resolved": "https://registry.npmjs.org/@codemirror/lang-sql/-/lang-sql-6.10.0.tgz",+ "integrity": "sha512-6ayPkEd/yRw0XKBx5uAiToSgGECo/GY2NoJIHXIIQh1EVwLuKoU8BP/qK0qH5NLXAbtJRLuT73hx7P9X34iO4w==",+ "license": "MIT",+ "dependencies": {+ "@codemirror/autocomplete": "^6.0.0",+ "@codemirror/language": "^6.0.0",+ "@codemirror/state": "^6.0.0",+ "@lezer/common": "^1.2.0",+ "@lezer/highlight": "^1.0.0",+ "@lezer/lr": "^1.0.0"+ }+ },+ "node_modules/@codemirror/language": {+ "version": "6.12.3",+ "resolved": "https://registry.npmjs.org/@codemirror/language/-/language-6.12.3.tgz",+ "integrity": "sha512-QwCZW6Tt1siP37Jet9Tb02Zs81TQt6qQrZR2H+eGMcFsL1zMrk2/b9CLC7/9ieP1fjIUMgviLWMmgiHoJrj+ZA==",+ "license": "MIT",+ "dependencies": {+ "@codemirror/state": "^6.0.0",+ "@codemirror/view": "^6.23.0",+ "@lezer/common": "^1.5.0",+ "@lezer/highlight": "^1.0.0",+ "@lezer/lr": "^1.0.0",+ "style-mod": "^4.0.0"+ }+ },+ "node_modules/@codemirror/state": {+ "version": "6.6.0",+ "resolved": "https://registry.npmjs.org/@codemirror/state/-/state-6.6.0.tgz",+ "integrity": "sha512-4nbvra5R5EtiCzr9BTHiTLc+MLXK2QGiAVYMyi8PkQd3SR+6ixar/Q/01Fa21TBIDOZXgeWV4WppsQolSreAPQ==",+ "license": "MIT",+ "dependencies": {+ "@marijn/find-cluster-break": "^1.0.0"+ }+ },+ "node_modules/@codemirror/theme-one-dark": {+ "version": "6.1.3",+ "resolved": "https://registry.npmjs.org/@codemirror/theme-one-dark/-/theme-one-dark-6.1.3.tgz",+ "integrity": "sha512-NzBdIvEJmx6fjeremiGp3t/okrLPYT0d9orIc7AFun8oZcRk58aejkqhv6spnz4MLAevrKNPMQYXEWMg4s+sKA==",+ "license": "MIT",+ "dependencies": {+ "@codemirror/language": "^6.0.0",+ "@codemirror/state": "^6.0.0",+ "@codemirror/view": "^6.0.0",+ "@lezer/highlight": "^1.0.0"+ }+ },+ "node_modules/@codemirror/view": {+ "version": "6.41.0",+ "resolved": "https://registry.npmjs.org/@codemirror/view/-/view-6.41.0.tgz",+ "integrity": "sha512-6H/qadXsVuDY219Yljhohglve8xf4B8xJkVOEWfA5uiYKiTFppjqsvsfR5iPA0RbvRBoOyTZpbLIxe9+0UR8xA==",+ "license": "MIT",+ "dependencies": {+ "@codemirror/state": "^6.6.0",+ "crelt": "^1.0.6",+ "style-mod": "^4.1.0",+ "w3c-keyname": "^2.2.4"+ }+ },"node_modules/@dagrejs/dagre": {"version": "1.1.4","resolved": "https://registry.npmjs.org/@dagrejs/dagre/-/dagre-1.1.4.tgz",@@ -2006,6 +2096,30 @@"yjs": ">=13.5.22"}},+ "node_modules/@lezer/common": {+ "version": "1.5.1",+ "resolved": "https://registry.npmjs.org/@lezer/common/-/common-1.5.1.tgz",+ "integrity": "sha512-6YRVG9vBkaY7p1IVxL4s44n5nUnaNnGM2/AckNgYOnxTG2kWh1vR8BMxPseWPjRNpb5VtXnMpeYAEAADoRV1Iw==",+ "license": "MIT"+ },+ "node_modules/@lezer/highlight": {+ "version": "1.2.3",+ "resolved": "https://registry.npmjs.org/@lezer/highlight/-/highlight-1.2.3.tgz",+ "integrity": "sha512-qXdH7UqTvGfdVBINrgKhDsVTJTxactNNxLk7+UMwZhU13lMHaOBlJe9Vqp907ya56Y3+ed2tlqzys7jDkTmW0g==",+ "license": "MIT",+ "dependencies": {+ "@lezer/common": "^1.3.0"+ }+ },+ "node_modules/@lezer/lr": {+ "version": "1.4.8",+ "resolved": "https://registry.npmjs.org/@lezer/lr/-/lr-1.4.8.tgz",+ "integrity": "sha512-bPWa0Pgx69ylNlMlPvBPryqeLYQjyJjqPx+Aupm5zydLIF3NE+6MMLT8Yi23Bd9cif9VS00aUebn+6fDIGBcDA==",+ "license": "MIT",+ "dependencies": {+ "@lezer/common": "^1.0.0"+ }+ },"node_modules/@lottiefiles/dotlottie-react": {"version": "0.12.0","resolved": "https://registry.npmjs.org/@lottiefiles/dotlottie-react/-/dotlottie-react-0.12.0.tgz",@@ -2024,6 +2138,12 @@"integrity": "sha512-01d+UjJ8NG7ZStYQxtb8FPzknzGmauG7gEkcH+wHfSdiSQJY9PoBNVSTB9V6F5hAnmFqOxaocTtd7TIEEnzMnA==","license": "MIT"},+ "node_modules/@marijn/find-cluster-break": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/@marijn/find-cluster-break/-/find-cluster-break-1.0.2.tgz",+ "integrity": "sha512-l0h88YhZFyKdXIFNfSWpyjStDjGHwZ/U7iobcK1cQQD8sejsONdQtTVU+1wVN1PBw40PiiHB1vA5S7VTfQiP9g==",+ "license": "MIT"+ },"node_modules/@mdx-js/react": {"version": "3.1.1","resolved": "https://registry.npmjs.org/@mdx-js/react/-/react-3.1.1.tgz",@@ -9049,6 +9169,12 @@"dev": true,"license": "MIT"},+ "node_modules/crelt": {+ "version": "1.0.6",+ "resolved": "https://registry.npmjs.org/crelt/-/crelt-1.0.6.tgz",+ "integrity": "sha512-VQ2MBenTq1fWZUH9DJNGti7kKv6EeAuYr3cLwxUWhIu1baTaXh4Ib5W2CqHVqib4/MqbYGJqiL3Zb8GJZr3l4g==",+ "license": "MIT"+ },"node_modules/cross-fetch": {"version": "4.0.0","resolved": "https://registry.npmjs.org/cross-fetch/-/cross-fetch-4.0.0.tgz",@@ -16141,6 +16267,12 @@"url": "https://github.com/sponsors/sindresorhus"}},+ "node_modules/style-mod": {+ "version": "4.1.3",+ "resolved": "https://registry.npmjs.org/style-mod/-/style-mod-4.1.3.tgz",+ "integrity": "sha512-i/n8VsZydrugj3Iuzll8+x/00GH2vnYsk1eomD8QiRrSAeW6ItbCQDtfXCeJHd0iwiNagqjQkvpvREEPtW3IoQ==",+ "license": "MIT"+ },"node_modules/style-to-object": {"version": "1.0.8","resolved": "https://registry.npmjs.org/style-to-object/-/style-to-object-1.0.8.tgz",@@ -17163,6 +17295,12 @@"node": ">=0.10.0"}},+ "node_modules/w3c-keyname": {+ "version": "2.2.8",+ "resolved": "https://registry.npmjs.org/w3c-keyname/-/w3c-keyname-2.2.8.tgz",+ "integrity": "sha512-dpojBhNsCNN7T82Tm7k26A6G9ML3NkhDsnw9n/eoxSRlVBB4CEtIQ/KTCLI2Fwf3ataSXRhYFkQi3SlnFwPvPQ==",+ "license": "MIT"+ },"node_modules/web-namespaces": {"version": "2.0.1","resolved": "https://registry.npmjs.org/web-namespaces/-/web-namespaces-2.0.1.tgz",diff --git a/frontend/package.json b/frontend/package.jsonindex 2f770fdf7f..6115fa5ade 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -22,6 +22,11 @@"dependencies": {"@casl/ability": "^6.7.2","@casl/react": "^4.0.0",+ "@codemirror/commands": "^6.10.3",+ "@codemirror/lang-sql": "^6.10.0",+ "@codemirror/state": "^6.6.0",+ "@codemirror/theme-one-dark": "^6.1.3",+ "@codemirror/view": "^6.41.0","@dagrejs/dagre": "^1.1.4","@dnd-kit/core": "^6.3.1","@dnd-kit/modifiers": "^9.0.0",diff --git a/frontend/src/pages/pam/PamAccountsPage/components/PamAccessAccountModal.tsx b/frontend/src/pages/pam/PamAccountsPage/components/PamAccessAccountModal.tsxindex 14ef7a4a83..36f4bcd941 100644--- a/frontend/src/pages/pam/PamAccountsPage/components/PamAccessAccountModal.tsx+++ b/frontend/src/pages/pam/PamAccountsPage/components/PamAccessAccountModal.tsx@@ -88,13 +88,12 @@ export const PamAccessAccountModal = ({ isOpen, onOpenChange, account, projectIdif (!account) return null;+ const showDataExplorer = account.resource.resourceType === PamResourceType.Postgres;const showWebAccess =- account.resource.resourceType === PamResourceType.Postgres ||+ showDataExplorer ||account.resource.resourceType === PamResourceType.SSH ||account.resource.resourceType === PamResourceType.Redis;- const showDataExplorer = account.resource.resourceType === PamResourceType.Postgres;-return (<Modal isOpen={isOpen} onOpenChange={onOpenChange}><ModalContent@@ -188,10 +187,10 @@ export const PamAccessAccountModal = ({ isOpen, onOpenChange, account, projectIdaccountId: account.id}}target="_blank"- className={`flex w-full items-center justify-center gap-2 rounded-md px-4 py-2 text-sm font-medium transition-colors ${showDataExplorer ? "border border-primary/30 bg-primary/10 text-primary hover:bg-primary/20" : "bg-primary text-black hover:bg-primary/80"}`}+ className="flex w-full items-center justify-center gap-2 rounded-md border border-mineshaft-600 bg-mineshaft-700 px-4 py-2 text-sm font-medium text-mineshaft-200 transition-colors hover:bg-mineshaft-600"><FontAwesomeIcon icon={faTerminal} />- {showDataExplorer ? "Open Console" : "Connect in Browser"}+ Open Console</Link></div></div>diff --git a/frontend/src/pages/pam/PamDataExplorerPage/PamDataExplorerPage.tsx b/frontend/src/pages/pam/PamDataExplorerPage/PamDataExplorerPage.tsxindex 682c2e420e..bdabb39f52 100644--- a/frontend/src/pages/pam/PamDataExplorerPage/PamDataExplorerPage.tsx+++ b/frontend/src/pages/pam/PamDataExplorerPage/PamDataExplorerPage.tsx@@ -1,6 +1,15 @@import { useCallback, useEffect, useRef, useState } from "react";import { useParams } from "@tanstack/react-router";-import { AlertTriangleIcon, DatabaseIcon, ShieldCheckIcon, UnplugIcon } from "lucide-react";+import {+ AlertTriangleIcon,+ DatabaseIcon,+ PlusIcon,+ ShieldCheckIcon,+ TableIcon,+ TerminalSquareIcon,+ UnplugIcon,+ XIcon+} from "lucide-react";import { Spinner } from "@app/components/v2";import {@@ -14,12 +23,15 @@ import {AlertDialogTitle} from "@app/components/v3/generic/AlertDialog";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, TableDetail, TableInfo } from "./data-explorer-types";import { useDataExplorerSession } from "./use-data-explorer-session";+import { BROWSE_TAB_ID, useQueryTabs } from "./use-query-tabs";export const PamDataExplorerPage = () => {const { accountId, projectId, orgId } = useParams({@@ -49,6 +61,8 @@ export const PamDataExplorerPage = () => {const [approvalJustification, setApprovalJustification] = useState("");+ const { tabs, activeTabId, addTab, closeTab, setActiveTab, updateTabSql } = useQueryTabs();+const {isConnected,isConnecting,@@ -201,15 +215,19 @@ export const PamDataExplorerPage = () => {const handleTableSelect = useCallback((tableName: string) => {- if (tableName === selectedTable) return;+ if (tableName === selectedTable) {+ setActiveTab(BROWSE_TAB_ID);+ return;+ }if (unsavedChangeCountRef.current > 0) {setPendingTableSwitch(tableName);return;}setSelectedTable(tableName);loadTableDetail(selectedSchema, tableName);+ setActiveTab(BROWSE_TAB_ID);},- [selectedTable, selectedSchema, loadTableDetail]+ [selectedTable, selectedSchema, loadTableDetail, setActiveTab]);const handleDiscardAndSwitch = useCallback(() => {@@ -218,7 +236,8 @@ export const PamDataExplorerPage = () => {setSelectedTable(pendingTableSwitch);loadTableDetail(selectedSchema, pendingTableSwitch);setPendingTableSwitch(null);- }, [pendingTableSwitch, selectedSchema, loadTableDetail]);+ setActiveTab(BROWSE_TAB_ID);+ }, [pendingTableSwitch, selectedSchema, loadTableDetail, setActiveTab]);const handleChangeCountUpdate = useCallback((count: number) => {unsavedChangeCountRef.current = count;@@ -390,28 +409,104 @@ export const PamDataExplorerPage = () => {isLoadingTables={isLoadingTables}/>- {selectedTable ? (- <DataExplorerGrid- key={`${selectedSchema}.${selectedTable}`}- tableDetail={tableDetail}- tableType={tables.find((t) => t.name === selectedTable)?.tableType}- schema={selectedSchema}- table={selectedTable}- executeQuery={executeQuery}- isLoading={isLoadingDetail}- onChangeCountUpdate={handleChangeCountUpdate}- onFullRefresh={handleFullRefresh}- />- ) : (- <div className="flex flex-1 items-center justify-center">- <div className="text-center">- <DatabaseIcon className="mx-auto mb-3 size-12 text-mineshaft-600" />- <p className="text-sm text-mineshaft-400">- Select a table from the sidebar to browse data- </p>- </div>+ <div className="flex flex-1 flex-col overflow-hidden">+ <div className="flex shrink-0 items-center overflow-x-auto border-b border-mineshaft-600 bg-mineshaft-800">+ <button+ type="button"+ onClick={() => setActiveTab(BROWSE_TAB_ID)}+ className={cn(+ "flex shrink-0 items-center gap-1.5 border-b-2 px-4 py-2 text-xs font-medium transition-colors",+ activeTabId === BROWSE_TAB_ID+ ? "border-primary text-mineshaft-100"+ : "border-transparent text-mineshaft-400 hover:text-mineshaft-200"+ )}+ >+ <TableIcon className="size-3.5" />+ Browse+ </button>++ {tabs.map((tab) => (+ <div+ key={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",+ activeTabId === tab.id+ ? "border-primary text-mineshaft-100"+ : "border-transparent text-mineshaft-400 hover:text-mineshaft-200"+ )}+ >+ <span className="flex items-center gap-1.5">+ <TerminalSquareIcon 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-500 opacity-0 transition-opacity group-hover:opacity-100 hover:text-mineshaft-200"+ aria-label={`Close ${tab.title}`}+ >+ <XIcon className="size-3" />+ </button>+ </div>+ ))}++ <button+ type="button"+ onClick={addTab}+ 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 hover:border-mineshaft-500 hover:text-mineshaft-100"+ aria-label="New query tab"+ >+ <PlusIcon className="size-3" />+ New query+ </button></div>- )}++ <div className={cn("flex flex-1 overflow-hidden", activeTabId !== BROWSE_TAB_ID && "hidden")}>+ {selectedTable ? (+ <DataExplorerGrid+ key={`${selectedSchema}.${selectedTable}`}+ tableDetail={tableDetail}+ tableType={tables.find((t) => t.name === selectedTable)?.tableType}+ schema={selectedSchema}+ table={selectedTable}+ executeQuery={executeQuery}+ isLoading={isLoadingDetail}+ onChangeCountUpdate={handleChangeCountUpdate}+ onFullRefresh={handleFullRefresh}+ />+ ) : (+ <div className="flex flex-1 items-center justify-center">+ <div className="text-center">+ <DatabaseIcon className="mx-auto mb-3 size-12 text-mineshaft-600" />+ <p className="text-sm text-mineshaft-400">+ Select a table from the sidebar to browse data+ </p>+ </div>+ </div>+ )}+ </div>++ {tabs.map((tab) => (+ <div+ key={tab.id}+ className={cn("flex flex-1 overflow-hidden", activeTabId !== tab.id && "hidden")}+ >+ <QueryPanel+ tab={tab}+ executeQuery={executeQuery}+ tableDetail={tableDetail}+ onSqlChange={(sql) => updateTabSql(tab.id, sql)}+ />+ </div>+ ))}+ </div></div>{/* Status bar */}diff --git a/frontend/src/pages/pam/PamDataExplorerPage/components/QueryPanel.tsx b/frontend/src/pages/pam/PamDataExplorerPage/components/QueryPanel.tsxnew file mode 100644index 0000000000..b1bdfee872--- /dev/null+++ b/frontend/src/pages/pam/PamDataExplorerPage/components/QueryPanel.tsx@@ -0,0 +1,111 @@+import { useCallback, useEffect, useRef, useState } from "react";++import { cn } from "@app/components/v3/utils";++import type { FieldInfo, TableDetail } from "../data-explorer-types";+import type { QueryTab } from "../use-query-tabs";+import { QueryResultsTable } from "./QueryResultsTable";+import { QueryToolbar } from "./QueryToolbar";+import { SqlEditor } from "./SqlEditor";++type QueryResult = {+ rows: Record<string, unknown>[];+ fields: FieldInfo[];+ rowCount: number | null;+ command: string;+ executionTimeMs: number;+};++type Props = {+ tab: QueryTab;+ executeQuery: (sql: string) => Promise<QueryResult>;+ tableDetail: TableDetail | null;+ onSqlChange: (sql: string) => void;+};++export function QueryPanel({ tab, executeQuery, tableDetail, onSqlChange }: 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 containerRef = useRef<HTMLDivElement>(null);+ const editorPaneRef = useRef<HTMLDivElement>(null);+ const splitPctRef = useRef(40);++ useEffect(() => {+ if (editorPaneRef.current) {+ editorPaneRef.current.style.height = `${splitPctRef.current}%`;+ }+ }, []);++ const handleRun = useCallback(async () => {+ if (!tab.sql.trim() || isRunning) return;+ setIsRunning(true);+ setError(null);+ try {+ const res = await executeQuery(tab.sql);+ setResult(res);+ } catch (err) {+ setError(err instanceof Error ? err.message : String(err));+ setResult(null);+ } finally {+ setIsRunning(false);+ }+ }, [tab.sql, isRunning, executeQuery]);++ const onMouseDown = useCallback((e: React.MouseEvent) => {+ e.preventDefault();+ setIsDragging(true);+ }, []);++ useEffect(() => {+ if (!isDragging) return;++ 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} result={result} error={error} onRun={handleRun} />+ <div+ ref={containerRef}+ className={cn("flex flex-1 flex-col overflow-hidden", isDragging && "select-none")}+ >+ <div ref={editorPaneRef} className="min-h-0 overflow-hidden">+ <SqlEditor value={tab.sql} onChange={onSqlChange} onExecute={handleRun} />+ </div>++ {/* eslint-disable-next-line jsx-a11y/no-static-element-interactions */}+ <div+ className={cn(+ "h-1 shrink-0 cursor-row-resize bg-mineshaft-600 transition-colors hover:bg-primary/50",+ isDragging && "bg-primary/50"+ )}+ onMouseDown={onMouseDown}+ />++ <div className="min-h-0 flex-1 overflow-hidden bg-bunker-800">+ <QueryResultsTable result={result} error={error} isRunning={isRunning} tableDetail={tableDetail} />+ </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..33b6ce35b0--- /dev/null+++ b/frontend/src/pages/pam/PamDataExplorerPage/components/QueryResultsTable.tsx@@ -0,0 +1,163 @@+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, ForeignKeyInfo, TableDetail } from "../data-explorer-types";++const MAX_ROWS = 500;++type QueryResult = {+ rows: Record<string, unknown>[];+ fields: FieldInfo[];+ rowCount: number | null;+ command: string;+ executionTimeMs: number;+};++type Props = {+ result: QueryResult | null;+ error: string | null;+ isRunning: boolean;+ tableDetail: TableDetail | null;+};++type RowData = Record<string, unknown>;++function getColumnIndicator(+ name: string,+ primaryKeys: string[],+ fkMap: Map<string, ForeignKeyInfo>+): { type: "pk" | "fk"; tooltip?: string } | undefined {+ if (primaryKeys.includes(name)) return { type: "pk" };+ const fk = fkMap.get(name);+ if (fk) {+ const targetCol = fk.targetColumns[fk.columns.indexOf(name)] ?? fk.targetColumns[0];+ return { type: "fk", tooltip: `\u2192 ${fk.targetSchema}.${fk.targetTable}(${targetCol})` };+ }+ return undefined;+}++function buildColumns(fields: FieldInfo[], tableDetail: TableDetail | null): ColumnDef<RowData>[] {+ const colTypeMap = new Map<string, string>();+ const primaryKeys: string[] = [];+ const fkMap = new Map<string, ForeignKeyInfo>();++ if (tableDetail) {+ tableDetail.columns.forEach((c) => colTypeMap.set(c.name, c.type));+ tableDetail.primaryKeys.forEach((pk) => primaryKeys.push(pk));+ tableDetail.foreignKeys.forEach((fk) => {+ fk.columns.forEach((c) => {+ if (!fkMap.has(c)) fkMap.set(c, fk);+ });+ });+ }++ return fields.map((f) => {+ const typeLabel = colTypeMap.get(f.name);+ const columnIndicator = tableDetail+ ? getColumnIndicator(f.name, primaryKeys, fkMap)+ : undefined;+ return {+ id: f.name,+ accessorKey: f.name,+ header: f.name,+ meta: {+ label: f.name,+ ...(typeLabel ? { typeLabel } : {}),+ ...(columnIndicator ? { columnIndicator } : {}),+ cell: { variant: "short-text" as const }+ },+ enableSorting: true,+ enablePinning: true,+ enableHiding: true+ };+ });+}++function ResultsGrid({+ result,+ tableDetail+}: {+ result: QueryResult;+ tableDetail: TableDetail | null;+}) {+ const displayRows = useMemo(() => result.rows.slice(0, MAX_ROWS), [result.rows]);+ const isTruncated = result.rows.length >= MAX_ROWS;++ const columns = useMemo(() => buildColumns(result.fields, tableDetail), [result.fields, tableDetail]);++ const getRowId = useCallback((_row: RowData, index: number) => String(index), []);++ const gridProps = useDataGrid<RowData>({+ data: displayRows,+ 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 {MAX_ROWS} rows+ </div>+ )}+ </div>+ );+}++export function QueryResultsTable({ result, error, isRunning, tableDetail }: 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-500">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 message = verb[cmdUpper]+ ? `${count} row${count !== 1 ? "s" : ""} ${verb[cmdUpper]}`+ : result.command;++ return (+ <div className="flex h-full flex-col items-center justify-center gap-2">+ <span className="rounded bg-mineshaft-700 px-3 py-1.5 font-mono text-sm text-mineshaft-200">+ {message}+ </span>+ <p className="text-xs text-mineshaft-500">{result.executionTimeMs}ms</p>+ </div>+ );+ }++ return <ResultsGrid result={result} tableDetail={tableDetail} />;+}diff --git a/frontend/src/pages/pam/PamDataExplorerPage/components/QueryToolbar.tsx b/frontend/src/pages/pam/PamDataExplorerPage/components/QueryToolbar.tsxnew file mode 100644index 0000000000..fd41b53951--- /dev/null+++ b/frontend/src/pages/pam/PamDataExplorerPage/components/QueryToolbar.tsx@@ -0,0 +1,41 @@+import { PlayIcon } from "lucide-react";++const isMac = navigator.userAgent.includes("Mac");++import { Button } from "@app/components/v3/generic/Button";++type QueryResult = {+ rowCount: number | null;+ command: string;+ executionTimeMs: number;+};++type Props = {+ isRunning: boolean;+ result: QueryResult | null;+ error: string | null;+ onRun: () => void;+};++export function QueryToolbar({ isRunning, result, error, onRun }: Props) {+ return (+ <div className="flex shrink-0 items-center gap-3 border-b border-mineshaft-600 bg-mineshaft-800 px-3 py-1.5">+ <Button size="xs" onClick={onRun} isPending={isRunning} className="gap-1.5">+ <PlayIcon className="size-3" />+ Run+ </Button>+ <span className="text-xs text-mineshaft-500">+ {isMac ? "⌘" : "Ctrl"}+Enter+ </span>+ {!isRunning && result && !error && (+ <span className="ml-auto text-xs text-mineshaft-400">+ {result.rowCount != null+ ? `${result.rowCount} row${result.rowCount !== 1 ? "s" : ""}`+ : result.command}+ {" · "}+ {result.executionTimeMs}ms+ </span>+ )}+ </div>+ );+}diff --git a/frontend/src/pages/pam/PamDataExplorerPage/components/SqlEditor.tsx b/frontend/src/pages/pam/PamDataExplorerPage/components/SqlEditor.tsxnew file mode 100644index 0000000000..ad645bd246--- /dev/null+++ b/frontend/src/pages/pam/PamDataExplorerPage/components/SqlEditor.tsx@@ -0,0 +1,81 @@+import { useEffect, useRef } from "react";+import { defaultKeymap, history, historyKeymap } from "@codemirror/commands";+import { PostgreSQL, sql } from "@codemirror/lang-sql";+import { EditorState } from "@codemirror/state";+import { oneDark } from "@codemirror/theme-one-dark";+import { EditorView, keymap, type ViewUpdate } from "@codemirror/view";++type Props = {+ value: string;+ onChange: (value: string) => void;+ onExecute: () => void;+};++export function SqlEditor({ value, onChange, onExecute }: Props) {+ const containerRef = useRef<HTMLDivElement>(null);+ const viewRef = useRef<EditorView | null>(null);+ const onExecuteRef = useRef(onExecute);+ const onChangeRef = useRef(onChange);+ onExecuteRef.current = onExecute;+ onChangeRef.current = onChange;++ useEffect(() => {+ if (!containerRef.current) return undefined;++ const view = new EditorView({+ state: EditorState.create({+ doc: value,+ extensions: [+ history(),+ keymap.of([+ {+ key: "Mod-Enter",+ run: () => {+ onExecuteRef.current();+ return true;+ }+ },+ ...historyKeymap,+ ...defaultKeymap+ ]),+ sql({ dialect: PostgreSQL }),+ oneDark,+ EditorView.theme({+ "&": { height: "100%", fontSize: "13px" },+ ".cm-scroller": {+ overflow: "auto",+ fontFamily: "ui-monospace, 'Cascadia Code', 'Source Code Pro', Menlo, monospace"+ },+ ".cm-content": { padding: "8px 0" }+ }),+ EditorView.updateListener.of((update: ViewUpdate) => {+ if (update.docChanged) {+ onChangeRef.current(update.state.doc.toString());+ }+ })+ ]+ }),+ parent: containerRef.current+ });++ viewRef.current = view;+ return () => {+ view.destroy();+ viewRef.current = null;+ };+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, []);++ // Sync external value changes into the editor+ useEffect(() => {+ const view = viewRef.current;+ if (view) {+ const current = view.state.doc.toString();+ if (current !== value) {+ view.dispatch({ changes: { from: 0, to: current.length, insert: value } });+ }+ }+ }, [value]);++ return <div ref={containerRef} className="h-full w-full" />;+}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..865a021310--- /dev/null+++ b/frontend/src/pages/pam/PamDataExplorerPage/use-query-tabs.ts@@ -0,0 +1,68 @@+import { useCallback, useState } from "react";++export type QueryTab = {+ id: string;+ title: string;+ sql: string;+};++type TabState = {+ tabs: QueryTab[];+ activeTabId: string;+ nextTabNumber: number;+};++export const BROWSE_TAB_ID = "browse";++const DEFAULT_STATE: TabState = { tabs: [], activeTabId: BROWSE_TAB_ID, nextTabNumber: 1 };++export function useQueryTabs() {+ const [state, setState] = useState<TabState>(DEFAULT_STATE);++ const update = useCallback((updater: (prev: TabState) => TabState) => {+ setState((prev) => updater(prev));+ }, []);++ const addTab = useCallback(() => {+ update((prev) => {+ const newTab: QueryTab = {+ id: crypto.randomUUID(),+ title: `Query ${prev.nextTabNumber}`,+ sql: ""+ };+ return { tabs: [...prev.tabs, newTab], activeTabId: newTab.id, nextTabNumber: prev.nextTabNumber + 1 };+ });+ }, [update]);++ const closeTab = useCallback(+ (id: string) => {+ update((prev) => {+ const idx = prev.tabs.findIndex((t) => t.id === id);+ const newTabs = prev.tabs.filter((t) => t.id !== id);+ const newActiveId =+ prev.activeTabId === id+ ? (newTabs[idx - 1]?.id ?? newTabs[0]?.id ?? BROWSE_TAB_ID)+ : prev.activeTabId;+ return { ...prev, tabs: newTabs, activeTabId: newActiveId };+ });+ },+ [update]+ );++ const setActiveTab = useCallback(+ (id: string) => update((prev) => ({ ...prev, activeTabId: id })),+ [update]+ );++ const updateTabSql = useCallback(+ (id: string, sql: string) => {+ update((prev) => ({+ ...prev,+ tabs: prev.tabs.map((t) => (t.id === id ? { ...t, sql } : t))+ }));+ },+ [update]+ );++ return { tabs: state.tabs, activeTabId: state.activeTabId, addTab, closeTab, setActiveTab, updateTabSql };+}