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 cancel query, transaction controls, and run selection to SQL query runner
Bernie Gandin1dae0d74afd6
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 f91cba7f68..5dbe9a5413 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@@ -60,6 +60,9 @@ export const handlePostgresSession = async (await pgClient.connect();+ const { rows: pidRows } = await pgClient.query<{ pid: number }>("SELECT pg_backend_pid() AS pid");+ const backendPid = pidRows[0]?.pid;+const repl = createPamSqlRepl(pgClient);sendMessage({@@ -101,13 +104,45 @@ export const handlePostgresSession = async (});};+ // Cancel the currently running query via pg_cancel_backend.+ // Runs on a separate connection so it is not blocked by the sequential queue.+ const cancelRunningQuery = async () => {+ if (!backendPid) return;+ const pid = backendPid;+ const cancelClient = new pg.Client({+ host: "localhost",+ port: relayPort,+ user: credentials.username,+ database: connectionDetails.database,+ password: "",+ ssl: false,+ connectionTimeoutMillis: 5_000+ });+ try {+ await cancelClient.connect();+ await cancelClient.query("SELECT pg_cancel_backend($1)", [pid]);+ } catch (err) {+ logger.debug(err, "Failed to cancel backend query");+ } finally {+ await cancelClient.end().catch(() => {});+ }+ };+// Sequential message processing to prevent concurrent query issueslet processingPromise = Promise.resolve();socket.on("message", (rawData: Buffer | ArrayBuffer | Buffer[]) => {+ const message = parseClientMessage(rawData, PostgresClientMessageSchema);++ // Cancel is handled immediately outside the sequential queue so it can+ // interrupt a running query rather than waiting behind it.+ if (message?.type === PostgresClientMessageType.Cancel) {+ void cancelRunningQuery();+ return;+ }+processingPromise = processingPromise.then(async () => {- const message = parseClientMessage(rawData, PostgresClientMessageSchema);if (!message) {sendMessage({type: TerminalServerMessageType.Output,diff --git a/backend/src/ee/services/pam-web-access/pam-postgres-ws-types.ts b/backend/src/ee/services/pam-web-access/pam-postgres-ws-types.tsindex c88208b5b9..ff82eedfb8 100644--- a/backend/src/ee/services/pam-web-access/pam-postgres-ws-types.ts+++ b/backend/src/ee/services/pam-web-access/pam-postgres-ws-types.ts@@ -8,7 +8,8 @@ export enum PostgresClientMessageType {GetSchemas = "get-schemas",GetTables = "get-tables",GetTableDetail = "get-table-detail",- Query = "query"+ Query = "query",+ Cancel = "cancel"}export enum PostgresServerMessageType {@@ -54,13 +55,16 @@ const QueryRequestSchema = CorrelatedBaseSchema.extend({sql: z.string().max(50 * 1024)});+const CancelSchema = z.object({ type: z.literal(PostgresClientMessageType.Cancel) });+export const PostgresClientMessageSchema = z.discriminatedUnion("type", [InputSchema,ControlSchema,GetSchemasRequestSchema,GetTablesRequestSchema,GetTableDetailRequestSchema,- QueryRequestSchema+ QueryRequestSchema,+ CancelSchema]);export type TPostgresClientMessage = z.infer<typeof PostgresClientMessageSchema>;diff --git a/frontend/src/pages/pam/PamDataExplorerPage/PamDataExplorerPage.tsx b/frontend/src/pages/pam/PamDataExplorerPage/PamDataExplorerPage.tsxindex fb456dfc24..36fde710eb 100644--- a/frontend/src/pages/pam/PamDataExplorerPage/PamDataExplorerPage.tsx+++ b/frontend/src/pages/pam/PamDataExplorerPage/PamDataExplorerPage.tsx@@ -78,7 +78,8 @@ export const PamDataExplorerPage = () => {fetchSchemas,fetchTables,fetchTableDetail,- executeQuery+ executeQuery,+ cancelQuery} = useDataExplorerSession({accountId,projectId,@@ -501,6 +502,7 @@ export const PamDataExplorerPage = () => {<QueryPaneltab={tab}executeQuery={executeQuery}+ cancelQuery={cancelQuery}tableDetail={tableDetail}onSqlChange={(sql) => updateTabSql(tab.id, sql)}/>diff --git a/frontend/src/pages/pam/PamDataExplorerPage/components/QueryPanel.tsx b/frontend/src/pages/pam/PamDataExplorerPage/components/QueryPanel.tsxindex 485e73bd75..366f817776 100644--- a/frontend/src/pages/pam/PamDataExplorerPage/components/QueryPanel.tsx+++ b/frontend/src/pages/pam/PamDataExplorerPage/components/QueryPanel.tsx@@ -19,15 +19,22 @@ type QueryResult = {type Props = {tab: QueryTab;executeQuery: (sql: string) => Promise<QueryResult>;+ cancelQuery: () => void;tableDetail: TableDetail | null;onSqlChange: (sql: string) => void;};-export function QueryPanel({ tab, executeQuery, tableDetail, onSqlChange }: Props) {+const TRANSACTION_START_COMMANDS = new Set(["BEGIN", "START"]);+const TRANSACTION_END_COMMANDS = new Set(["COMMIT", "ROLLBACK"]);++export function QueryPanel({ tab, executeQuery, cancelQuery, 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 [isInTransaction, setIsInTransaction] = useState(false);+ const [hasSelection, setHasSelection] = useState(false);+ const sqlToRunRef = useRef<string>(tab.sql);const containerRef = useRef<HTMLDivElement>(null);const editorPaneRef = useRef<HTMLDivElement>(null);@@ -39,12 +46,14 @@ export function QueryPanel({ tab, executeQuery, tableDetail, onSqlChange }: Prop}}, []);- const handleRun = async () => {- if (!tab.sql.trim() || isRunning) return;+ const runSql = async (sqlToRun: string) => {setIsRunning(true);setError(null);try {- const res = await executeQuery(tab.sql);+ const res = await executeQuery(sqlToRun);+ const cmd = res.command.toUpperCase();+ if (TRANSACTION_START_COMMANDS.has(cmd)) setIsInTransaction(true);+ if (TRANSACTION_END_COMMANDS.has(cmd)) setIsInTransaction(false);setResult(res);} catch (err) {setError(err instanceof Error ? err.message : String(err));@@ -54,6 +63,20 @@ export function QueryPanel({ tab, executeQuery, tableDetail, onSqlChange }: Prop}};+ 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;@@ -79,13 +102,31 @@ export function QueryPanel({ tab, executeQuery, tableDetail, onSqlChange }: Propreturn (<div className="flex h-full w-full flex-col overflow-hidden">- <QueryToolbar isRunning={isRunning} result={result} error={error} onRun={handleRun} />+ <QueryToolbar+ isRunning={isRunning}+ result={result}+ error={error}+ isInTransaction={isInTransaction}+ hasSelection={hasSelection}+ onRun={handleRun}+ onCommit={handleCommit}+ onRollback={handleRollback}+ onCancel={cancelQuery}+ /><divref={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} />+ <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 */}diff --git a/frontend/src/pages/pam/PamDataExplorerPage/components/QueryResultsTable.tsx b/frontend/src/pages/pam/PamDataExplorerPage/components/QueryResultsTable.tsxindex 2030a7fe22..7526c76ac3 100644--- a/frontend/src/pages/pam/PamDataExplorerPage/components/QueryResultsTable.tsx+++ b/frontend/src/pages/pam/PamDataExplorerPage/components/QueryResultsTable.tsx@@ -138,10 +138,20 @@ export function QueryResultsTable({ result, error, isRunning, tableDetail }: ProUPDATE: "updated",DELETE: "deleted"};+ const staticMessage: Record<string, string> = {+ BEGIN: "Transaction started",+ COMMIT: "Transaction committed",+ ROLLBACK: "Transaction rolled back"+ };- const message = verb[cmdUpper]- ? `${count} row${count !== 1 ? "s" : ""} ${verb[cmdUpper]}`- : "No rows returned";+ let message: string;+ if (staticMessage[cmdUpper]) {+ message = staticMessage[cmdUpper];+ } else if (verb[cmdUpper]) {+ 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">diff --git a/frontend/src/pages/pam/PamDataExplorerPage/components/QueryToolbar.tsx b/frontend/src/pages/pam/PamDataExplorerPage/components/QueryToolbar.tsxindex d58139743f..0764898c62 100644--- a/frontend/src/pages/pam/PamDataExplorerPage/components/QueryToolbar.tsx+++ b/frontend/src/pages/pam/PamDataExplorerPage/components/QueryToolbar.tsx@@ -1,4 +1,4 @@-import { PlayIcon } from "lucide-react";+import { CheckIcon, PlayIcon, RotateCcwIcon, SquareIcon } from "lucide-react";import { Button } from "@app/components/v3/generic/Button";@@ -14,17 +14,72 @@ type Props = {isRunning: boolean;result: QueryResult | null;error: string | null;+ isInTransaction: boolean;+ hasSelection: boolean;onRun: () => void;+ onCommit: () => void;+ onRollback: () => void;+ onCancel: () => void;};-export function QueryToolbar({ isRunning, result, error, onRun }: Props) {+export function QueryToolbar({+ isRunning,+ result,+ error,+ isInTransaction,+ hasSelection,+ onRun,+ onCommit,+ onRollback,+ onCancel+}: 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">+ <Button+ size="xs"+ onClick={() => onRun()}+ isPending={isRunning}+ isDisabled={isRunning}+ className="gap-1.5"+ ><PlayIcon className="size-3" />- Run+ {hasSelection ? "Run Selection" : "Run"}</Button>- <span className="text-xs text-mineshaft-500">{isMac ? "⌘" : "Ctrl"}+Enter</span>+ {isRunning ? (+ <Button size="xs" variant="outline" onClick={onCancel} className="gap-1.5">+ <SquareIcon className="size-3 text-red-400" />+ Cancel+ </Button>+ ) : (+ <span className="text-xs text-mineshaft-500">{isMac ? "⌘" : "Ctrl"}+Enter</span>+ )}+ {isInTransaction && (+ <>+ <span className="rounded bg-yellow-500/15 px-2 py-0.5 text-xs font-medium text-yellow-400">+ Transaction open+ </span>+ <Button+ size="xs"+ variant="outline"+ 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>+ </>+ )}{!isRunning && result && !error && (<span className="ml-auto text-xs text-mineshaft-400">{result.rowCount != nulldiff --git a/frontend/src/pages/pam/PamDataExplorerPage/components/SqlEditor.tsx b/frontend/src/pages/pam/PamDataExplorerPage/components/SqlEditor.tsxindex 51b22b41d8..1b7b8d1980 100644--- a/frontend/src/pages/pam/PamDataExplorerPage/components/SqlEditor.tsx+++ b/frontend/src/pages/pam/PamDataExplorerPage/components/SqlEditor.tsx@@ -8,16 +8,28 @@ import { EditorView, keymap, type ViewUpdate } from "@codemirror/view";type Props = {value: string;onChange: (value: string) => void;- onExecute: () => void;+ onExecute: (sql: string) => void;+ onSelectionChange: (hasSelection: boolean) => void;+ onSqlToRunChange: (sql: string) => void;};-export function SqlEditor({ value, onChange, onExecute }: Props) {+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;@@ -30,8 +42,12 @@ export function SqlEditor({ value, onChange, onExecute }: Props) {keymap.of([{key: "Mod-Enter",- run: () => {- onExecuteRef.current();+ 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;}},@@ -50,7 +66,21 @@ export function SqlEditor({ value, onChange, onExecute }: Props) {}),EditorView.updateListener.of((update: ViewUpdate) => {if (update.docChanged) {- onChangeRef.current(update.state.doc.toString());+ 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);+ }}})]@@ -59,6 +89,8 @@ export function SqlEditor({ value, onChange, onExecute }: Props) {});viewRef.current = view;+ onSqlToRunChangeRef.current(value);+return () => {view.destroy();viewRef.current = null;diff --git a/frontend/src/pages/pam/PamDataExplorerPage/use-data-explorer-session.ts b/frontend/src/pages/pam/PamDataExplorerPage/use-data-explorer-session.tsindex 5ec38ce200..396919a811 100644--- a/frontend/src/pages/pam/PamDataExplorerPage/use-data-explorer-session.ts+++ b/frontend/src/pages/pam/PamDataExplorerPage/use-data-explorer-session.ts@@ -392,6 +392,13 @@ export const useDataExplorerSession = ({[sendRequest]);+ const cancelQuery = useCallback(() => {+ const ws = wsRef.current;+ if (ws && ws.readyState === WebSocket.OPEN) {+ ws.send(JSON.stringify({ type: "cancel" }));+ }+ }, []);+const executeQuery = useCallback(async (sql: string@@ -435,6 +442,7 @@ export const useDataExplorerSession = ({fetchSchemas,fetchTables,fetchTableDetail,- executeQuery+ executeQuery,+ cancelQuery};};