Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat: support copy as sql or csv (#20521)
ecmadaof77f38bdf344
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.jsonindex e13b7b2739..932c958bb6 100644--- a/frontend/src/locales/en-US.json+++ b/frontend/src/locales/en-US.json@@ -255,6 +255,7 @@"continue-anyway": "Continue anyway","copied": "Copied","copy": "Copy",+ "copy-all": "Copy all","copy-failed": "Copy failed","create": "Create","created": "Created",@@ -2674,8 +2675,12 @@"connect-to-a-database": "Connect to database","connection-lost": "Connection lost. Will try to reconnect when executing next query.","copy-all-column-names": "Copy all column names",+ "copy-all-rows-as-csv": "Copy all rows as CSV",+ "copy-all-rows-as-sql": "Copy all rows as SQL","copy-name": "Copy name","copy-selected-results": "Copy selected data by <action></action> or <button></button>",+ "copy-selected-rows-as-csv": "Copy selected rows as CSV",+ "copy-selected-rows-as-sql": "Copy selected rows as SQL","copy-url": "Copy URL","ddl-dml-requires-data-change-plan": "To execute DDL/DML statements in <environment></environment>, please submit a Data Change Plan for approval.","download-as-file": "Download as {{file}}",diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.jsonindex ef453fd743..e1626045c2 100644--- a/frontend/src/locales/es-ES.json+++ b/frontend/src/locales/es-ES.json@@ -255,6 +255,7 @@"continue-anyway": "De todas maneras, continúe","copied": "Copiado","copy": "Copiar",+ "copy-all": "Copiar todo","copy-failed": "Error al copiar","create": "Crear","created": "Creado",@@ -2674,8 +2675,12 @@"connect-to-a-database": "Conectar a base de datos","connection-lost": "Conexión perdida. \nIntentará volver a conectarse al ejecutar la siguiente consulta.","copy-all-column-names": "Copiar todos los nombres de las columnas",+ "copy-all-rows-as-csv": "Copiar todas las filas como CSV",+ "copy-all-rows-as-sql": "Copiar todas las filas como SQL","copy-name": "Copiar nombre","copy-selected-results": "Copiar datos seleccionados por <action></action> o <button></button>",+ "copy-selected-rows-as-csv": "Copiar las filas seleccionadas como CSV",+ "copy-selected-rows-as-sql": "Copiar las filas seleccionadas como SQL","copy-url": "Copiar URL","ddl-dml-requires-data-change-plan": "Para ejecutar sentencias DDL/DML en <environment></environment>, envíe un Plan de Cambio de Datos para su aprobación.","download-as-file": "Descargar como {{file}}",diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.jsonindex eaba3ac936..2eceb11b94 100644--- a/frontend/src/locales/ja-JP.json+++ b/frontend/src/locales/ja-JP.json@@ -255,6 +255,7 @@"continue-anyway": "まだ続けたい","copied": "コピーされました","copy": "コピー",+ "copy-all": "すべてコピー","copy-failed": "コピーに失敗しました","create": "作成する","created": "作成済",@@ -2674,8 +2675,12 @@"connect-to-a-database": "データベースに接続","connection-lost": "接続切断。次回クエリが実行されるときに再接続が試行されます。","copy-all-column-names": "すべての列名をコピーします",+ "copy-all-rows-as-csv": "すべての行を CSV としてコピー",+ "copy-all-rows-as-sql": "すべての行を SQL としてコピー","copy-name": "名前をコピーする","copy-selected-results": "選択したデータを<action></action>または<button></button>でコピーします",+ "copy-selected-rows-as-csv": "選択した行を CSV としてコピー",+ "copy-selected-rows-as-sql": "選択した行を SQL としてコピー","copy-url": "URLをコピー","ddl-dml-requires-data-change-plan": "<environment></environment> で DDL/DML ステートメントを実行するには、承認のためデータ変更プランを送信してください。","download-as-file": "{{file}} 形式でダウンロード",diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.jsonindex f6adca1089..6ff71cedfb 100644--- a/frontend/src/locales/vi-VN.json+++ b/frontend/src/locales/vi-VN.json@@ -255,6 +255,7 @@"continue-anyway": "Tiếp tục","copied": "Đã sao chép","copy": "Sao chép",+ "copy-all": "Sao chép tất cả","copy-failed": "Sao chép thất bại","create": "Tạo","created": "Đã tạo",@@ -2674,8 +2675,12 @@"connect-to-a-database": "Kết nối cơ sở dữ liệu","connection-lost": "Mất kết nối. Sẽ thử kết nối lại khi thực hiện truy vấn tiếp theo.","copy-all-column-names": "Sao chép tất cả tên cột",+ "copy-all-rows-as-csv": "Sao chép tất cả các hàng dưới dạng CSV",+ "copy-all-rows-as-sql": "Sao chép tất cả các hàng dưới dạng SQL","copy-name": "Sao chép tên","copy-selected-results": "Sao chép dữ liệu đã chọn bằng <action></action> hoặc <button></button>",+ "copy-selected-rows-as-csv": "Sao chép các hàng đã chọn dưới dạng CSV",+ "copy-selected-rows-as-sql": "Sao chép các hàng đã chọn dưới dạng SQL","copy-url": "Sao chép URL","ddl-dml-requires-data-change-plan": "Để thực thi câu lệnh DDL/DML trong <environment></environment>, vui lòng gửi Kế hoạch Thay đổi Dữ liệu để được phê duyệt.","download-as-file": "Tải xuống dưới dạng {{file}}",diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.jsonindex 4189a094e0..6589e226c8 100644--- a/frontend/src/locales/zh-CN.json+++ b/frontend/src/locales/zh-CN.json@@ -255,6 +255,7 @@"continue-anyway": "仍要继续","copied": "已拷贝","copy": "拷贝",+ "copy-all": "复制全部","copy-failed": "复制失败","create": "创建","created": "已创建",@@ -2674,8 +2675,12 @@"connect-to-a-database": "连接数据库","connection-lost": "连接丢失。下一次执行查询时将尝试重新连接。","copy-all-column-names": "复制所有列名",+ "copy-all-rows-as-csv": "将所有行复制为 CSV",+ "copy-all-rows-as-sql": "将所有行复制为 SQL","copy-name": "复制名称","copy-selected-results": "通过 <action></action> 或 <button></button> 来快速复制选定的数据",+ "copy-selected-rows-as-csv": "将选定行复制为 CSV",+ "copy-selected-rows-as-sql": "将选定行复制为 SQL","copy-url": "复制 URL","ddl-dml-requires-data-change-plan": "如需在 <environment></environment> 中执行 DDL/DML 语句,请创建变更计划以获得审批。","download-as-file": "下载为 {{file}} 格式",diff --git a/frontend/src/react/components/sql-editor/ResultView/ResultCopyContextMenu.tsx b/frontend/src/react/components/sql-editor/ResultView/ResultCopyContextMenu.tsxnew file mode 100644index 0000000000..6b51a25765--- /dev/null+++ b/frontend/src/react/components/sql-editor/ResultView/ResultCopyContextMenu.tsx@@ -0,0 +1,64 @@+import { CopyIcon } from "lucide-react";+import type { ReactElement } from "react";+import { useTranslation } from "react-i18next";+import {+ ContextMenu,+ ContextMenuContent,+ ContextMenuItem,+ ContextMenuTrigger,+} from "@/react/components/ui/context-menu";+import { useSelectionContext } from "./context";+import { formatAsCSV, formatAsSQL, formatAsText } from "./copy-formats";++/**+ * Right-click context menu for the result grid. Wraps the grid's scroll+ * container (passed as a single element via Base UI's `render` pattern) and+ * offers a plain "Copy", "Copy selected rows as CSV", and — for SQL engines —+ * "Copy selected rows as SQL". When copying is disallowed the children are+ * returned untouched.+ */+export function ResultCopyContextMenu({+ children,+}: {+ children: ReactElement;+}) {+ const { t } = useTranslation();+ const { state, disabled, copy, canCopyAsInsert } = useSelectionContext();++ if (disabled) return children;++ // Plain "Copy" honors any selection (cells / rows / columns). CSV and SQL are+ // row-oriented: they only narrow when rows are selected, so their scope and+ // label track row selection — otherwise they (accurately) copy all rows.+ const hasSelection = state.rows.length > 0 || state.columns.length > 0;+ const hasRowSelection = state.rows.length > 0;+ const scope = hasRowSelection ? "selected" : "all";++ return (+ <ContextMenu>+ <ContextMenuTrigger render={children} />+ <ContextMenuContent>+ <ContextMenuItem+ onClick={() => copy(hasSelection ? "selected" : "all", formatAsText)}+ >+ <CopyIcon className="size-4" />+ {hasSelection ? t("common.copy") : t("common.copy-all")}+ </ContextMenuItem>+ <ContextMenuItem onClick={() => copy(scope, formatAsCSV)}>+ <CopyIcon className="size-4" />+ {hasRowSelection+ ? t("sql-editor.copy-selected-rows-as-csv")+ : t("sql-editor.copy-all-rows-as-csv")}+ </ContextMenuItem>+ {canCopyAsInsert && (+ <ContextMenuItem onClick={() => copy(scope, formatAsSQL)}>+ <CopyIcon className="size-4" />+ {hasRowSelection+ ? t("sql-editor.copy-selected-rows-as-sql")+ : t("sql-editor.copy-all-rows-as-sql")}+ </ContextMenuItem>+ )}+ </ContextMenuContent>+ </ContextMenu>+ );+}diff --git a/frontend/src/react/components/sql-editor/ResultView/SelectionCopyTooltips.tsx b/frontend/src/react/components/sql-editor/ResultView/SelectionCopyTooltips.tsxindex f9c7cc4d27..ef4e1be0fc 100644--- a/frontend/src/react/components/sql-editor/ResultView/SelectionCopyTooltips.tsx+++ b/frontend/src/react/components/sql-editor/ResultView/SelectionCopyTooltips.tsx@@ -1,7 +1,14 @@-import { CopyIcon, InfoIcon } from "lucide-react";+import { ChevronDownIcon, CopyIcon, InfoIcon } from "lucide-react";import { useTranslation } from "react-i18next";import { Button } from "@/react/components/ui/button";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from "@/react/components/ui/dropdown-menu";import { useSelectionContext } from "./context";+import { formatAsCSV, formatAsSQL, formatAsText } from "./copy-formats";// react-i18next's `Trans` wipes children when placeholder tags are empty// (`<action></action>` calls `React.cloneElement(component, {}, ...[])`,@@ -29,7 +36,8 @@ export function SelectionCopyTooltips() {const { t } = useTranslation();const {state: { rows, columns },- copySelected,+ copy,+ canCopyAsInsert,deselect,} = useSelectionContext();@@ -79,17 +87,54 @@ export function SelectionCopyTooltips() {);}if (token === "button") {+ // Single split button: click copies as plain text; hovering the+ // caret reveals CSV and, for SQL engines, SQL.return (- <Button- key={i}- size="sm"- variant="default"- className="h-6 px-2 gap-x-1"- onClick={copySelected}- >- <CopyIcon className="size-3" />- {t("common.copy")}- </Button>+ <span key={i} className="inline-flex items-center">+ <Button+ size="sm"+ variant="default"+ className="h-6 px-2 gap-x-1 rounded-r-none"+ onClick={() => copy("selected", formatAsText)}+ >+ <CopyIcon className="size-3" />+ {t("common.copy")}+ </Button>+ <DropdownMenu>+ <DropdownMenuTrigger+ openOnHover+ delay={100}+ render={+ <Button+ size="sm"+ variant="default"+ aria-label={t("common.copy")}+ className="h-6 w-5 px-0 rounded-l-none border-l border-white/30"+ >+ <ChevronDownIcon className="size-3" />+ </Button>+ }+ />+ <DropdownMenuContent align="end" className="min-w-0">+ <DropdownMenuItem+ onClick={() => copy("selected", formatAsCSV)}+ className="px-2 py-1 text-xs gap-x-1.5"+ >+ <CopyIcon className="size-3" />+ {t("sql-editor.copy-selected-rows-as-csv")}+ </DropdownMenuItem>+ {canCopyAsInsert && (+ <DropdownMenuItem+ onClick={() => copy("selected", formatAsSQL)}+ className="px-2 py-1 text-xs gap-x-1.5"+ >+ <CopyIcon className="size-3" />+ {t("sql-editor.copy-selected-rows-as-sql")}+ </DropdownMenuItem>+ )}+ </DropdownMenuContent>+ </DropdownMenu>+ </span>);}return <span key={i}>{token}</span>;diff --git a/frontend/src/react/components/sql-editor/ResultView/SingleResultView.tsx b/frontend/src/react/components/sql-editor/ResultView/SingleResultView.tsxindex d4298f5202..be31ebc711 100644--- a/frontend/src/react/components/sql-editor/ResultView/SingleResultView.tsx+++ b/frontend/src/react/components/sql-editor/ResultView/SingleResultView.tsx@@ -3,6 +3,7 @@ import { isEmpty } from "lodash-es";import {ArrowDownIcon,ArrowUpIcon,+ ChevronDownIcon,ChevronRightIcon,CopyIcon,InfoIcon,@@ -30,6 +31,12 @@ import {import { EngineIcon } from "@/react/components/EngineIcon";import { Alert } from "@/react/components/ui/alert";import { Button } from "@/react/components/ui/button";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from "@/react/components/ui/dropdown-menu";import { EllipsisText } from "@/react/components/ui/ellipsis-text";import { Switch } from "@/react/components/ui/switch";import { Tooltip } from "@/react/components/ui/tooltip";@@ -66,6 +73,7 @@ import {import { instanceV1Name } from "@/utils/v1/instance";import { compareQueryRowValues, extractSQLRowValuePlain } from "@/utils/v1/sql";import { SQLResultViewProvider, useSelectionContext } from "./context";+import { formatAsCSV, formatAsSQL, formatAsText } from "./copy-formats";import { DetailPanel } from "./DetailPanel";import { EmptyView } from "./EmptyView";import { ErrorView } from "./ErrorView";@@ -191,6 +199,8 @@ export function SingleResultView(props: SingleResultViewProps) {<SQLResultViewProviderdark={dark}disallowCopyingData={disallowCopyingData}+ engine={engine}+ schema={props.params.connection.schema}rows={rows}columns={columns}>@@ -252,7 +262,7 @@ function SingleResultViewInner({const resultRowsLimit = useSQLEditorEditorState((s) => s.resultRowsLimit);const policyMaxRows = queryDataPolicy.maximumResultRows;const { runQuery } = useExecuteSQL();- const { copyAll } = useSelectionContext();+ const { copy, canCopyAsInsert } = useSelectionContext();const supportFormats = useMemo(() => [@@ -579,19 +589,57 @@ function SingleResultViewInner({</span></div>{!disallowCopyingData && rows.length > 0 && (+ // Split button: the main action copies as plain text (TSV); the+ // dropdown caret (hover) offers CSV and, for SQL engines, SQL.// `variant="outline"` is `bg-transparent + text-control`, which// disappears inside the admin-mode dark backdrop. Force an// opaque light-on-dark surface in `.dark` to match the Vue// toolbar's contrast (light gray bg + dark text).- <Button- size="sm"- variant="outline"- className="h-7 px-2 dark:bg-gray-700 dark:text-gray-100 dark:border-zinc-600 dark:hover:bg-gray-600"- onClick={copyAll}- >- <CopyIcon className="size-4" />- {t("common.copy")}- </Button>+ <div className="flex items-center">+ <Button+ size="sm"+ variant="outline"+ className="h-7 px-2 rounded-r-none border-r-0 dark:bg-gray-700 dark:text-gray-100 dark:border-zinc-600 dark:hover:bg-gray-600"+ onClick={() => copy("all", formatAsText)}+ >+ <CopyIcon className="size-4" />+ {t("common.copy-all")}+ </Button>+ <DropdownMenu>+ <DropdownMenuTrigger+ openOnHover+ delay={100}+ render={+ <Button+ size="sm"+ variant="outline"+ aria-label={t("common.copy")}+ className="h-7 w-6 px-0 rounded-l-none dark:bg-gray-700 dark:text-gray-100 dark:border-zinc-600 dark:hover:bg-gray-600"+ >+ <ChevronDownIcon className="size-4" />+ </Button>+ }+ />+ <DropdownMenuContent align="end" className="min-w-0">+ <DropdownMenuItem+ onClick={() => copy("all", formatAsCSV)}+ className="px-2 py-1 text-xs gap-x-1.5"+ >+ <CopyIcon className="size-3" />+ {t("sql-editor.copy-all-rows-as-csv")}+ </DropdownMenuItem>+ {canCopyAsInsert && (+ <DropdownMenuItem+ onClick={() => copy("all", formatAsSQL)}+ className="px-2 py-1 text-xs gap-x-1.5"+ >+ <CopyIcon className="size-3" />+ {t("sql-editor.copy-all-rows-as-sql")}+ </DropdownMenuItem>+ )}+ </DropdownMenuContent>+ </DropdownMenu>+ </div>)}{showExport ? (<DataExportButtondiff --git a/frontend/src/react/components/sql-editor/ResultView/VirtualDataBlock.tsx b/frontend/src/react/components/sql-editor/ResultView/VirtualDataBlock.tsxindex 2311f0d7c9..25935f583a 100644--- a/frontend/src/react/components/sql-editor/ResultView/VirtualDataBlock.tsx+++ b/frontend/src/react/components/sql-editor/ResultView/VirtualDataBlock.tsx@@ -17,6 +17,7 @@ import type { MaskingReason } from "@/types/proto-es/v1/sql_service_pb";import type { SearchParams } from "@/utils/v1/advanced-search/common";import { getPlainValue } from "./cell-value";import { useBinaryFormatContext } from "./context";+import { ResultCopyContextMenu } from "./ResultCopyContextMenu";import { TableCell } from "./TableCell";import type { ResultTableColumn, ResultTableRow } from "./types";@@ -116,89 +117,91 @@ export const VirtualDataBlock = forwardRef<);return (- <div- ref={containerRef}- className="relative w-full flex-1 min-h-0 overflow-auto rounded-sm border"- >+ <ResultCopyContextMenu><div- style={{- height: `${virtualizer.getTotalSize()}px`,- position: "relative",- }}+ ref={containerRef}+ className="relative w-full flex-1 min-h-0 overflow-auto rounded-sm border">- {virtualizer.getVirtualItems().map((virtualRow) => {- const rowIndex = virtualRow.index;- const row = rows[rowIndex];- if (!row) return null;- const isActive = activeRowIndex === rowIndex;- return (- <div- key={virtualRow.key}- ref={virtualizer.measureElement}- data-index={rowIndex}- className="font-mono mx-2 absolute inset-x-0"- style={{- top: 0,- transform: `translateY(${virtualRow.start}px)`,- }}- >- <p className="font-bold text-control-light dark:text-gray-300 overflow-hidden whitespace-nowrap mb-1">- ******************************** {rowIndex + 1}. row- ********************************- </p>+ <div+ style={{+ height: `${virtualizer.getTotalSize()}px`,+ position: "relative",+ }}+ >+ {virtualizer.getVirtualItems().map((virtualRow) => {+ const rowIndex = virtualRow.index;+ const row = rows[rowIndex];+ if (!row) return null;+ const isActive = activeRowIndex === rowIndex;+ return (<div- className={cn(- "py-2 px-3 bg-control-bg dark:bg-gray-700 rounded relative",- isActive && "border-2 border-accent/20 bg-accent/10!"- )}+ key={virtualRow.key}+ ref={virtualizer.measureElement}+ data-index={rowIndex}+ className="font-mono mx-2 absolute inset-x-0"+ style={{+ top: 0,+ transform: `translateY(${virtualRow.start}px)`,+ }}>- <CopyJSONButton- getContent={() => buildRowJSON(rowIndex)}- label={t("common.copy")}- />- {columns.map((column, columnIndex) => {- const reason = getMaskingReason?.(columnIndex);- return (- <div- key={column.id}- className="flex items-start text-control-light dark:text-gray-300 text-sm"- >- <div className="min-w-28 text-left flex items-center font-medium pt-1">- <div className="flex items-center gap-x-1">- {column.name}- {reason && (- <MaskingReasonPopover- reason={reason}- statement={statement}- database={database.name}- />- )}+ <p className="font-bold text-control-light dark:text-gray-300 overflow-hidden whitespace-nowrap mb-1">+ ******************************** {rowIndex + 1}. row+ ********************************+ </p>+ <div+ className={cn(+ "py-2 px-3 bg-control-bg dark:bg-gray-700 rounded relative",+ isActive && "border-2 border-accent/20 bg-accent/10!"+ )}+ >+ <CopyJSONButton+ getContent={() => buildRowJSON(rowIndex)}+ label={t("common.copy")}+ />+ {columns.map((column, columnIndex) => {+ const reason = getMaskingReason?.(columnIndex);+ return (+ <div+ key={column.id}+ className="flex items-start text-control-light dark:text-gray-300 text-sm"+ >+ <div className="min-w-28 text-left flex items-center font-medium pt-1">+ <div className="flex items-center gap-x-1">+ {column.name}+ {reason && (+ <MaskingReasonPopover+ reason={reason}+ statement={statement}+ database={database.name}+ />+ )}+ </div>+ :+ </div>+ <div className="flex-1">+ <TableCell+ value={row.item.values[columnIndex]}+ keyword={search.query}+ scope={search.scopes.find(+ (s) => s.id === columns[columnIndex]?.id+ )}+ rowIndex={rowIndex}+ colIndex={columnIndex}+ columnType={column.columnType}+ allowSelect+ database={database}+ /></div>- :- </div>- <div className="flex-1">- <TableCell- value={row.item.values[columnIndex]}- keyword={search.query}- scope={search.scopes.find(- (s) => s.id === columns[columnIndex]?.id- )}- rowIndex={rowIndex}- colIndex={columnIndex}- columnType={column.columnType}- allowSelect- database={database}- /></div>- </div>- );- })}+ );+ })}+ </div></div>- </div>- );- })}+ );+ })}+ </div></div>- </div>+ </ResultCopyContextMenu>);});diff --git a/frontend/src/react/components/sql-editor/ResultView/VirtualDataTable.tsx b/frontend/src/react/components/sql-editor/ResultView/VirtualDataTable.tsxindex bf48e583e1..71f86a7c6f 100644--- a/frontend/src/react/components/sql-editor/ResultView/VirtualDataTable.tsx+++ b/frontend/src/react/components/sql-editor/ResultView/VirtualDataTable.tsx@@ -22,6 +22,7 @@ import {import { ColumnSortedIcon } from "./ColumnSortedIcon";import { getPlainValue } from "./cell-value";import { useBinaryFormatContext, useSelectionContext } from "./context";+import { ResultCopyContextMenu } from "./ResultCopyContextMenu";import { TableCell } from "./TableCell";import type {ResultTableColumn,@@ -264,208 +265,210 @@ export const VirtualDataTable = forwardRef<);return (- <div- ref={containerRef}- className="relative w-full flex-1 min-h-0 overflow-auto rounded-sm border dark:border-zinc-500"- >- {/* Header */}+ <ResultCopyContextMenu><div- className="sticky top-0 z-1 bg-control-bg dark:bg-gray-700 flex shadow-sm"- style={{ minWidth: minRowWidth }}+ ref={containerRef}+ className="relative w-full flex-1 min-h-0 overflow-auto rounded-sm border dark:border-zinc-500">- {/* Index header */}- <HeaderCell- width={indexColWidth}- onResizeStart={(e) => tableResize.onResizeStart(0, e)}+ {/* Header */}+ <div+ className="sticky top-0 z-1 bg-control-bg dark:bg-gray-700 flex shadow-sm"+ style={{ minWidth: minRowWidth }}>- <div- className={cn(- "textinfolabel pr-1 opacity-0",- selectionDisabled ? "pl-1" : "pl-4"- )}+ {/* Index header */}+ <HeaderCell+ width={indexColWidth}+ onResizeStart={(e) => tableResize.onResizeStart(0, e)}>- {totalRows}- </div>- </HeaderCell>-- {/* Data column headers */}- {columns.map((header, columnIndex) => {- const slotWidth = tableResize.getColumnWidth(columnIndex + 1);- const isLast = columnIndex === columns.length - 1;- const isSelected =- selectionState.rows.length === 0 &&- selectionState.columns.includes(columnIndex);- const reason = getMaskingReason?.(columnIndex);- return (- <HeaderCell- key={`${columnIndex}-${header.id}`}- width={slotWidth}- borderRight={!isLast}- onResizeStart={(e) =>- tableResize.onResizeStart(columnIndex + 1, e)- }- onClick={(e) => handleSelectColumn(e, columnIndex)}+ <divclassName={cn(- "px-3 py-1.5 min-w-8 text-left text-xs font-medium text-control-light dark:text-gray-300 tracking-wider",- !selectionDisabled &&- "cursor-pointer hover:bg-control-bg-hover dark:hover:bg-gray-800",- isSelected && "bg-accent/10! dark:bg-accent/40!"+ "textinfolabel pr-1 opacity-0",+ selectionDisabled ? "pl-1" : "pl-4")}>- <div className="flex items-center min-w-0 gap-x-1">- <span className="min-w-0 truncate select-none">- {String(header.name).length > 0 ? (- header.name- ) : (- <br className="min-h-4 inline-flex" />- )}- </span>- {reason && (- <span className="shrink-0">- <MaskingReasonPopover- reason={reason}- statement={statement}- database={database.name}- />- </span>+ {totalRows}+ </div>+ </HeaderCell>++ {/* Data column headers */}+ {columns.map((header, columnIndex) => {+ const slotWidth = tableResize.getColumnWidth(columnIndex + 1);+ const isLast = columnIndex === columns.length - 1;+ const isSelected =+ selectionState.rows.length === 0 &&+ selectionState.columns.includes(columnIndex);+ const reason = getMaskingReason?.(columnIndex);+ return (+ <HeaderCell+ key={`${columnIndex}-${header.id}`}+ width={slotWidth}+ borderRight={!isLast}+ onResizeStart={(e) =>+ tableResize.onResizeStart(columnIndex + 1, e)+ }+ onClick={(e) => handleSelectColumn(e, columnIndex)}+ className={cn(+ "px-3 py-1.5 min-w-8 text-left text-xs font-medium text-control-light dark:text-gray-300 tracking-wider",+ !selectionDisabled &&+ "cursor-pointer hover:bg-control-bg-hover dark:hover:bg-gray-800",+ isSelected && "bg-accent/10! dark:bg-accent/40!")}- <span- onClick={(e) => {- e.stopPropagation();- onToggleSort(columnIndex);- }}- role="button"- tabIndex={-1}- className="shrink-0 inline-flex"- >- <ColumnSortedIcon- isSorted={getColumnSortDirection(columnIndex)}- />- </span>- {binaryColumnSet.has(columnIndex) && (+ >+ <div className="flex items-center min-w-0 gap-x-1">+ <span className="min-w-0 truncate select-none">+ {String(header.name).length > 0 ? (+ header.name+ ) : (+ <br className="min-h-4 inline-flex" />+ )}+ </span>+ {reason && (+ <span className="shrink-0">+ <MaskingReasonPopover+ reason={reason}+ statement={statement}+ database={database.name}+ />+ </span>+ )}<span- onClick={(e) => e.stopPropagation()}- className="shrink-0"+ onClick={(e) => {+ e.stopPropagation();+ onToggleSort(columnIndex);+ }}+ role="button"+ tabIndex={-1}+ className="shrink-0 inline-flex">- <BinaryFormatButton- format={getBinaryFormat({ colIndex: columnIndex })}- onFormatChange={(format: BinaryFormat) =>- setBinaryFormat({ colIndex: columnIndex, format })- }+ <ColumnSortedIcon+ isSorted={getColumnSortDirection(columnIndex)}/></span>- )}- </div>- </HeaderCell>- );- })}- </div>+ {binaryColumnSet.has(columnIndex) && (+ <span+ onClick={(e) => e.stopPropagation()}+ className="shrink-0"+ >+ <BinaryFormatButton+ format={getBinaryFormat({ colIndex: columnIndex })}+ onFormatChange={(format: BinaryFormat) =>+ setBinaryFormat({ colIndex: columnIndex, format })+ }+ />+ </span>+ )}+ </div>+ </HeaderCell>+ );+ })}+ </div>- {/* Virtualized body */}- <div- style={{- height: `${virtualizer.getTotalSize()}px`,- minWidth: minRowWidth,- position: "relative",- }}- >- {virtualizer.getVirtualItems().map((virtualRow) => {- const rowIndex = virtualRow.index;- const row = rows[rowIndex];- if (!row) return null;- const isActive = activeRowIndex === rowIndex;- const rowSelected =- selectionState.columns.length === 0 &&- selectionState.rows.includes(rowIndex);- return (- <div- key={virtualRow.key}- data-row-index={rowIndex}- className="flex absolute inset-x-0 group"- style={{- top: 0,- transform: `translateY(${virtualRow.start}px)`,- height: `${ROW_HEIGHT}px`,- minWidth: minRowWidth,- }}- >- {/* Index cell */}+ {/* Virtualized body */}+ <div+ style={{+ height: `${virtualizer.getTotalSize()}px`,+ minWidth: minRowWidth,+ position: "relative",+ }}+ >+ {virtualizer.getVirtualItems().map((virtualRow) => {+ const rowIndex = virtualRow.index;+ const row = rows[rowIndex];+ if (!row) return null;+ const isActive = activeRowIndex === rowIndex;+ const rowSelected =+ selectionState.columns.length === 0 &&+ selectionState.rows.includes(rowIndex);+ return (<div- className={cn(- "relative flex items-center shrink-0 text-sm dark:text-gray-100 leading-5 whitespace-nowrap break-all border-block-border dark:border-zinc-500 border-r border-b group-even:bg-control-bg/40 dark:group-even:bg-gray-700/50",- isActive && "bg-accent/10! dark:bg-accent/40!",- rowSelected && "bg-accent/20! dark:bg-accent/40!"- )}- data-col-index={0}+ key={virtualRow.key}+ data-row-index={rowIndex}+ className="flex absolute inset-x-0 group"style={{+ top: 0,+ transform: `translateY(${virtualRow.start}px)`,height: `${ROW_HEIGHT}px`,- width: `${indexColWidth}px`,+ minWidth: minRowWidth,}}>- <span+ {/* Index cell */}+ <divclassName={cn(- "textinfolabel pr-1 truncate",- selectionDisabled ? "pl-1" : "pl-4"+ "relative flex items-center shrink-0 text-sm dark:text-gray-100 leading-5 whitespace-nowrap break-all border-block-border dark:border-zinc-500 border-r border-b group-even:bg-control-bg/40 dark:group-even:bg-gray-700/50",+ isActive && "bg-accent/10! dark:bg-accent/40!",+ rowSelected && "bg-accent/20! dark:bg-accent/40!")}+ data-col-index={0}+ style={{+ height: `${ROW_HEIGHT}px`,+ width: `${indexColWidth}px`,+ }}>- {rowIndex + 1}- </span>- {!selectionDisabled && (- <button- type="button"- aria-label={`Select row ${rowIndex + 1}`}- onClick={(e) => handleSelectRow(e, rowIndex)}- className={cn(- "absolute inset-y-0 left-0 w-3 cursor-pointer bg-accent/5 hover:bg-accent/10 dark:bg-white/10 dark:hover:bg-accent/40",- rowSelected && "bg-accent/20! dark:bg-accent/40!"- )}- />- )}- </div>-- {/* Data cells */}- {row.item.values.map((cell, columnIndex) => {- const cellWidth = tableResize.getColumnWidth(columnIndex + 1);- const isLastCol = columnIndex === row.item.values.length - 1;- return (- <div- key={`${rowIndex}-${columnIndex + 1}`}+ <spanclassName={cn(- "relative shrink-0 text-sm dark:text-gray-100 leading-5 whitespace-nowrap break-all border-block-border dark:border-zinc-500 border-b group-even:bg-control-bg/40 dark:group-even:bg-gray-700/50",- !isLastCol && "border-r",- // Match the Vue version: an active (search-matched) row- // highlights every cell in that row, not just the index- // column.- isActive && "bg-accent/10! dark:bg-accent/40!"+ "textinfolabel pr-1 truncate",+ selectionDisabled ? "pl-1" : "pl-4")}- data-col-index={columnIndex + 1}- style={{- height: `${ROW_HEIGHT}px`,- width: `${cellWidth}px`,- }}>- <div className="h-full flex items-center overflow-hidden">- <TableCell- value={cell}- keyword={search.query}- scope={search.scopes.find(- (s) => s.id === columns[columnIndex]?.id- )}- rowIndex={rowIndex}- colIndex={columnIndex}- allowSelect- columnType={getColumnTypeByIndex(columnIndex)}- database={database}- />+ {rowIndex + 1}+ </span>+ {!selectionDisabled && (+ <button+ type="button"+ aria-label={`Select row ${rowIndex + 1}`}+ onClick={(e) => handleSelectRow(e, rowIndex)}+ className={cn(+ "absolute inset-y-0 left-0 w-3 cursor-pointer bg-accent/5 hover:bg-accent/10 dark:bg-white/10 dark:hover:bg-accent/40",+ rowSelected && "bg-accent/20! dark:bg-accent/40!"+ )}+ />+ )}+ </div>++ {/* Data cells */}+ {row.item.values.map((cell, columnIndex) => {+ const cellWidth = tableResize.getColumnWidth(columnIndex + 1);+ const isLastCol = columnIndex === row.item.values.length - 1;+ return (+ <div+ key={`${rowIndex}-${columnIndex + 1}`}+ className={cn(+ "relative shrink-0 text-sm dark:text-gray-100 leading-5 whitespace-nowrap break-all border-block-border dark:border-zinc-500 border-b group-even:bg-control-bg/40 dark:group-even:bg-gray-700/50",+ !isLastCol && "border-r",+ // Match the Vue version: an active (search-matched) row+ // highlights every cell in that row, not just the index+ // column.+ isActive && "bg-accent/10! dark:bg-accent/40!"+ )}+ data-col-index={columnIndex + 1}+ style={{+ height: `${ROW_HEIGHT}px`,+ width: `${cellWidth}px`,+ }}+ >+ <div className="h-full flex items-center overflow-hidden">+ <TableCell+ value={cell}+ keyword={search.query}+ scope={search.scopes.find(+ (s) => s.id === columns[columnIndex]?.id+ )}+ rowIndex={rowIndex}+ colIndex={columnIndex}+ allowSelect+ columnType={getColumnTypeByIndex(columnIndex)}+ database={database}+ />+ </div></div>- </div>- );- })}- </div>- );- })}+ );+ })}+ </div>+ );+ })}+ </div></div>- </div>+ </ResultCopyContextMenu>);});diff --git a/frontend/src/react/components/sql-editor/ResultView/context.tsx b/frontend/src/react/components/sql-editor/ResultView/context.tsxindex 216c8c286f..f6b5b15bdd 100644--- a/frontend/src/react/components/sql-editor/ResultView/context.tsx+++ b/frontend/src/react/components/sql-editor/ResultView/context.tsx@@ -9,6 +9,7 @@ import {} from "react";import { useTranslation } from "react-i18next";import { useAppStore } from "@/react/stores/app";+import { Engine } from "@/types/proto-es/v1/common_pb";import type { RowValue } from "@/types/proto-es/v1/sql_service_pb";import { isDescendantOf } from "@/utils/dom";import { extractSQLRowValuePlain } from "@/utils/v1/sql";@@ -22,7 +23,11 @@ import {getColumnKey,} from "./binary-format";import {- isSingleCellSelected,+ type CopyFormatter,+ type CopyScope,+ formatAsText,+} from "./copy-formats";+import {type SelectionState,toggleCellInSelection,toggleColumnInSelection,@@ -92,8 +97,14 @@ export interface SelectionContext {toggleSelectColumn: (column: number) => void;toggleSelectCell: (row: number, column: number) => void;deselect: () => void;- copySelected: () => void;- copyAll: () => void;+ // Copy the result to the clipboard. `scope` "selected" uses the current+ // selection (falling back to all rows for row-oriented formats); "all"+ // copies every row. `format` chooses the rendering — `formatAsText` (plain+ // TSV, mirrors the grid selection), `formatAsCSV`, or `formatAsSQL`.+ copy: (scope: CopyScope, format: CopyFormatter) => void;+ // Whether "copy as SQL (INSERT)" is meaningful: copying is allowed and the+ // engine has a SQL INSERT form. Callers use it to show/hide the SQL option.+ canCopyAsInsert: boolean;}const SelectionCtx = createContext<SelectionContext | null>(null);@@ -112,9 +123,21 @@ export function useSelectionContext(): SelectionContext {// Combined provider — mounts all three contexts in nested order.// =============================================================================+// Non-SQL engines have no meaningful INSERT form — hide "copy as INSERT".+const NON_SQL_ENGINES = new Set<Engine>([+ Engine.MONGODB,+ Engine.REDIS,+ Engine.ELASTICSEARCH,+ Engine.COSMOSDB,+ Engine.DYNAMODB,+]);+interface SQLResultViewProviderProps {dark?: boolean;disallowCopyingData?: boolean;+ engine: Engine;+ // Connected schema, used to qualify the generated INSERT's table name.+ schema?: string;rows: ResultTableRow[];columns: ResultTableColumn[];children: ReactNode;@@ -132,6 +155,8 @@ interface SQLResultViewProviderProps {export function SQLResultViewProvider({dark = false,disallowCopyingData = false,+ engine,+ schema,rows,columns,children,@@ -228,13 +253,6 @@ export function SQLResultViewProvider({);// ----- copy helpers ------ const escapeTSVValue = (val: string): string => {- if (val.includes("\t") || val.includes("\n") || val.includes('"')) {- return `"${val.replaceAll('"', '""')}"`;- }- return val;- };-const getFormattedValue = useCallback(({value,@@ -269,69 +287,9 @@ export function SQLResultViewProvider({[columns, getBinaryFormat]);- const buildClipboardPayload = useCallback(- (state: SelectionState): string => {- if (isSingleCellSelected(state)) {- const row = rows[state.rows[0]];- if (!row) return "";- const cell = row.item.values[state.columns[0]];- if (!cell) return "";- return getFormattedValue({- value: cell,- colIndex: state.columns[0],- rowIndex: state.rows[0],- });- }-- if (state.rows.length > 0) {- const columnNames = ["index", ...columns.map((c) => c.name)];- const lines: string[] = [];- for (const rowIndex of state.rows) {- const queryRow = rows[rowIndex]?.item;- if (!queryRow) continue;- const cells = queryRow.values- .map((cell, colIdx) =>- escapeTSVValue(- getFormattedValue({ value: cell, colIndex: colIdx, rowIndex })- )- )- .join("\t");- lines.push(`${rowIndex}\t${cells}`);- }- if (lines.length === 0) return "";- return `${columnNames.join("\t")}\n${lines.join("\n")}`;- }-- if (state.columns.length > 0) {- const columnNames = state.columns.map((i) => columns[i]?.name ?? "");- const lines: string[] = [];- for (let rowIdx = 0; rowIdx < rows.length; rowIdx++) {- const cells = state.columns.map((columnIndex, colIdx) => {- const cell = rows[rowIdx].item.values[columnIndex];- if (!cell) return "";- return escapeTSVValue(- getFormattedValue({- value: cell,- rowIndex: rowIdx,- colIndex: state.columns[colIdx],- })- );- });- lines.push(cells.join("\t"));- }- if (lines.length === 0) return "";- return `${columnNames.join("\t")}\n${lines.join("\n")}`;- }-- return "";- },- [columns, rows, getFormattedValue]- );-- const copyToClipboard = useCallback(- async (state: SelectionState) => {+ const writeTextToClipboard = useCallback(+ async (payload: string) => {if (selectionDisabled || copying) return;- const payload = buildClipboardPayload(state);if (!payload) return;setCopying(true);try {@@ -355,19 +313,43 @@ export function SQLResultViewProvider({requestAnimationFrame(() => setCopying(false));}},- [selectionDisabled, copying, buildClipboardPayload, t]+ [selectionDisabled, copying, t]);- const copySelected = useCallback(() => {- void copyToClipboard(selectionState);- }, [copyToClipboard, selectionState]);+ const canCopyAsInsert = !selectionDisabled && !NON_SQL_ENGINES.has(engine);- const copyAll = useCallback(() => {- void copyToClipboard({- rows: rows.map((_, i) => i),- columns: [],- });- }, [copyToClipboard, rows]);+ // Unified copy: resolve the cell-value accessor + payload context once, then+ // delegate rendering to the chosen formatter (formatAsText / CSV / SQL).+ const copy = useCallback(+ (scope: CopyScope, format: CopyFormatter) => {+ if (selectionDisabled) return;+ const payload = format({+ scope,+ selection: selectionState,+ rows,+ columns,+ engine,+ schema,+ getFormattedValue: (rowIndex, colIndex) => {+ const cell = rows[rowIndex]?.item.values[colIndex];+ return cell+ ? getFormattedValue({ value: cell, rowIndex, colIndex })+ : "";+ },+ });+ void writeTextToClipboard(payload);+ },+ [+ selectionDisabled,+ selectionState,+ rows,+ columns,+ engine,+ schema,+ getFormattedValue,+ writeTextToClipboard,+ ]+ );// Click outside the result-scroll buttons → deselect (mirrors Vue// global click listener in `selection-logic.ts`).@@ -399,12 +381,12 @@ export function SQLResultViewProvider({if ((e.key === "c" || e.key === "C") && (e.metaKey || e.ctrlKey)) {e.preventDefault();e.stopImmediatePropagation();- copySelected();+ copy("selected", formatAsText);}};document.addEventListener("keydown", handler);return () => document.removeEventListener("keydown", handler);- }, [selectionDisabled, selectionState, deselect, copySelected]);+ }, [selectionDisabled, selectionState, deselect, copy]);const selection = useMemo<SelectionContext>(() => ({@@ -414,8 +396,8 @@ export function SQLResultViewProvider({toggleSelectColumn,toggleSelectCell,deselect,- copySelected,- copyAll,+ copy,+ canCopyAsInsert,}),[selectionState,@@ -424,8 +406,8 @@ export function SQLResultViewProvider({toggleSelectColumn,toggleSelectCell,deselect,- copySelected,- copyAll,+ copy,+ canCopyAsInsert,]);diff --git a/frontend/src/react/components/sql-editor/ResultView/copy-formats.test.ts b/frontend/src/react/components/sql-editor/ResultView/copy-formats.test.tsnew file mode 100644index 0000000000..70e6445201--- /dev/null+++ b/frontend/src/react/components/sql-editor/ResultView/copy-formats.test.ts@@ -0,0 +1,129 @@+import { create } from "@bufbuild/protobuf";+import { describe, expect, it, vi } from "vitest";+import { Engine } from "@/types/proto-es/v1/common_pb";+import type { RowValue } from "@/types/proto-es/v1/sql_service_pb";+import {+ QueryRowSchema,+ RowValueSchema,+} from "@/types/proto-es/v1/sql_service_pb";+import type { CopyFormatterContext } from "./copy-formats";+import { formatAsCSV, formatAsSQL, formatAsText } from "./copy-formats";+import type { ResultTableColumn, ResultTableRow } from "./types";++// `copy-formats` → `@/utils/v1/sql` pulls in the heavy `@/types` barrel (and+// the React router). Mock it with a minimal real implementation.+vi.mock("@/types", () => ({+ getDateForPbTimestampProtoEs: (ts: { seconds: bigint; nanos: number }) =>+ new Date(Number(ts.seconds) * 1000 + Math.floor((ts.nanos ?? 0) / 1e6)),+}));++const rv = (kind: RowValue["kind"]): RowValue =>+ create(RowValueSchema, { kind });++const columns: ResultTableColumn[] = [+ { id: "name", name: "name", columnType: "TEXT" },+ { id: "age", name: "age", columnType: "INT" },+];++const rows: ResultTableRow[] = [+ {+ key: 0,+ item: create(QueryRowSchema, {+ values: [+ rv({ case: "stringValue", value: "alice" }),+ rv({ case: "int32Value", value: 30 }),+ ],+ }),+ },+ {+ key: 1,+ item: create(QueryRowSchema, {+ values: [+ rv({ case: "stringValue", value: "bob" }),+ rv({ case: "int32Value", value: 25 }),+ ],+ }),+ },+];++// Display values for text/CSV. Row 1 col 0 holds a comma to exercise CSV+// quoting (the SQL path reads the raw RowValue, not this table).+const display: Record<string, string> = {+ "0,0": "alice",+ "0,1": "30",+ "1,0": "bob,jr",+ "1,1": "25",+};+const getFormattedValue = (r: number, c: number) => display[`${r},${c}`] ?? "";++const ctx = (over: Partial<CopyFormatterContext>): CopyFormatterContext => ({+ scope: "all",+ selection: { rows: [], columns: [] },+ rows,+ columns,+ engine: Engine.POSTGRES,+ schema: "public",+ getFormattedValue,+ ...over,+});++describe("formatAsText", () => {+ it("copies all rows as TSV with a leading index column", () => {+ expect(formatAsText(ctx({ scope: "all" }))).toBe(+ "index\tname\tage\n0\talice\t30\n1\tbob,jr\t25"+ );+ });++ it("copies a single selected cell as its plain value", () => {+ expect(+ formatAsText(+ ctx({ scope: "selected", selection: { rows: [0], columns: [1] } })+ )+ ).toBe("30");+ });++ it("copies a selected column for every row", () => {+ expect(+ formatAsText(+ ctx({ scope: "selected", selection: { rows: [], columns: [0] } })+ )+ ).toBe("name\nalice\nbob,jr");+ });+});++describe("formatAsCSV", () => {+ it("copies a header row plus RFC-4180-quoted rows", () => {+ expect(formatAsCSV(ctx({ scope: "all" }))).toBe(+ `name,age\nalice,30\n"bob,jr",25`+ );+ });++ it("copies only the selected rows", () => {+ expect(+ formatAsCSV(+ ctx({ scope: "selected", selection: { rows: [1], columns: [] } })+ )+ ).toBe(`name,age\n"bob,jr",25`);+ });+});++describe("formatAsSQL", () => {+ it("renders a batched INSERT from the raw row values", () => {+ expect(formatAsSQL(ctx({ scope: "all" }))).toBe(+ `INSERT INTO "public"."<table_name>" ("name", "age") VALUES\n` ++ ` ('alice', 30),\n` ++ ` ('bob', 25);`+ );+ });++ it("scopes to the selected rows when scope is selected", () => {+ expect(+ formatAsSQL(+ ctx({ scope: "selected", selection: { rows: [1], columns: [] } })+ )+ ).toBe(+ `INSERT INTO "public"."<table_name>" ("name", "age") VALUES\n` ++ ` ('bob', 25);`+ );+ });+});diff --git a/frontend/src/react/components/sql-editor/ResultView/copy-formats.ts b/frontend/src/react/components/sql-editor/ResultView/copy-formats.tsnew file mode 100644index 0000000000..635f28bbb3--- /dev/null+++ b/frontend/src/react/components/sql-editor/ResultView/copy-formats.ts@@ -0,0 +1,129 @@+import type { Engine } from "@/types/proto-es/v1/common_pb";+import type { RowValue } from "@/types/proto-es/v1/sql_service_pb";+import { generateInsertStatementFromRows } from "@/utils/v1/sql";+import { isSingleCellSelected, type SelectionState } from "./selection-math";+import type { ResultTableColumn, ResultTableRow } from "./types";++export type CopyScope = "all" | "selected";++/**+ * Everything a copy formatter needs to render the clipboard payload. The+ * provider builds this once per copy and hands it to the chosen formatter.+ */+export interface CopyFormatterContext {+ scope: CopyScope;+ selection: SelectionState;+ rows: ResultTableRow[];+ columns: ResultTableColumn[];+ engine: Engine;+ // Connected schema, used to qualify the INSERT table name.+ schema?: string;+ // Display string for one cell, honoring binary-format overrides. Returns ""+ // for a missing cell.+ getFormattedValue: (rowIndex: number, colIndex: number) => string;+}++export type CopyFormatter = (ctx: CopyFormatterContext) => string;++// Placeholder table name for the generated INSERT: arbitrary result queries+// (joins, expressions) have no single source table, so the user fills this in.+const INSERT_TABLE_PLACEHOLDER = "<table_name>";++// Row indices for row-oriented formats (CSV / SQL): the selected rows+// (ascending) when scope is "selected" and any are selected, otherwise all.+const resolveRowIndices = (ctx: CopyFormatterContext): number[] => {+ if (ctx.scope === "selected" && ctx.selection.rows.length > 0) {+ return [...ctx.selection.rows].sort((a, b) => a - b);+ }+ return ctx.rows.map((_, i) => i);+};++const escapeTSVValue = (val: string): string =>+ /[\t\n"]/.test(val) ? `"${val.replaceAll('"', '""')}"` : val;++const escapeCSVValue = (val: string): string =>+ /[,\n\r"]/.test(val) ? `"${val.replaceAll('"', '""')}"` : val;++/**+ * Default "plain" copy: tab-separated values mirroring the in-grid selection —+ * a single cell, whole rows (with a leading `index` column), or whole columns.+ * Scope "all" copies every row.+ */+export const formatAsText: CopyFormatter = (ctx) => {+ const { columns, rows, getFormattedValue } = ctx;+ const state: SelectionState =+ ctx.scope === "all"+ ? { rows: rows.map((_, i) => i), columns: [] }+ : ctx.selection;++ if (isSingleCellSelected(state)) {+ return getFormattedValue(state.rows[0], state.columns[0]);+ }++ if (state.rows.length > 0) {+ const header = ["index", ...columns.map((c) => c.name)];+ const lines: string[] = [];+ for (const rowIndex of state.rows) {+ if (!rows[rowIndex]) continue;+ const cells = columns+ .map((_, colIdx) => escapeTSVValue(getFormattedValue(rowIndex, colIdx)))+ .join("\t");+ lines.push(`${rowIndex}\t${cells}`);+ }+ if (lines.length === 0) return "";+ return `${header.join("\t")}\n${lines.join("\n")}`;+ }++ if (state.columns.length > 0) {+ const header = state.columns.map((i) => columns[i]?.name ?? "");+ const lines: string[] = [];+ for (let rowIdx = 0; rowIdx < rows.length; rowIdx++) {+ const cells = state.columns.map((colIdx) =>+ escapeTSVValue(getFormattedValue(rowIdx, colIdx))+ );+ lines.push(cells.join("\t"));+ }+ if (lines.length === 0) return "";+ return `${header.join("\t")}\n${lines.join("\n")}`;+ }++ return "";+};++/**+ * CSV copy: a header row of column names plus one comma-separated line per row,+ * RFC-4180 quoted. Always all columns.+ */+export const formatAsCSV: CopyFormatter = (ctx) => {+ const { columns, rows, getFormattedValue } = ctx;+ const rowIndices = resolveRowIndices(ctx);+ const lines = [columns.map((c) => escapeCSVValue(c.name)).join(",")];+ for (const rowIndex of rowIndices) {+ if (!rows[rowIndex]) continue;+ lines.push(+ columns+ .map((_, colIdx) => escapeCSVValue(getFormattedValue(rowIndex, colIdx)))+ .join(",")+ );+ }+ return lines.join("\n");+};++/**+ * SQL copy: a single batched, engine-aware INSERT statement. Always all+ * columns. Returns "" when there are no rows to copy.+ */+export const formatAsSQL: CopyFormatter = (ctx) => {+ const { columns, rows, engine, schema } = ctx;+ const rowValues = resolveRowIndices(ctx)+ .map((i) => rows[i]?.item.values)+ .filter((values): values is RowValue[] => values !== undefined);+ if (rowValues.length === 0) return "";+ return generateInsertStatementFromRows({+ engine,+ schema,+ table: INSERT_TABLE_PLACEHOLDER,+ columns: columns.map((c) => c.name),+ rows: rowValues,+ });+};diff --git a/frontend/src/utils/v1/sql.test.ts b/frontend/src/utils/v1/sql.test.tsnew file mode 100644index 0000000000..878f5ffaaa--- /dev/null+++ b/frontend/src/utils/v1/sql.test.ts@@ -0,0 +1,166 @@+import { create } from "@bufbuild/protobuf";+import { TimestampSchema } from "@bufbuild/protobuf/wkt";+import { describe, expect, it, vi } from "vitest";+import { Engine } from "@/types/proto-es/v1/common_pb";++// `sql.ts` imports `getDateForPbTimestampProtoEs` from the heavy `@/types`+// barrel, which transitively pulls in the React router. Mock it with a+// minimal real implementation so the unit under test stays isolated.+vi.mock("@/types", () => ({+ getDateForPbTimestampProtoEs: (ts: { seconds: bigint; nanos: number }) =>+ new Date(Number(ts.seconds) * 1000 + Math.floor((ts.nanos ?? 0) / 1e6)),+}));++import type { RowValue } from "@/types/proto-es/v1/sql_service_pb";+import {+ RowValue_TimestampSchema,+ RowValueSchema,+} from "@/types/proto-es/v1/sql_service_pb";+import { generateInsertStatementFromRows, rowValueToSQLLiteral } from "./sql";++const rv = (kind: RowValue["kind"]): RowValue =>+ create(RowValueSchema, { kind });++describe("rowValueToSQLLiteral", () => {+ it("renders NULL for undefined and nullValue", () => {+ expect(rowValueToSQLLiteral(undefined, Engine.POSTGRES)).toBe("NULL");+ expect(+ rowValueToSQLLiteral(rv({ case: "nullValue", value: 0 }), Engine.POSTGRES)+ ).toBe("NULL");+ });++ it("renders booleans as TRUE/FALSE by default", () => {+ expect(+ rowValueToSQLLiteral(+ rv({ case: "boolValue", value: true }),+ Engine.POSTGRES+ )+ ).toBe("TRUE");+ expect(+ rowValueToSQLLiteral(+ rv({ case: "boolValue", value: false }),+ Engine.POSTGRES+ )+ ).toBe("FALSE");+ });++ it("renders booleans as 1/0 for MySQL-family engines", () => {+ expect(+ rowValueToSQLLiteral(rv({ case: "boolValue", value: true }), Engine.MYSQL)+ ).toBe("1");+ expect(+ rowValueToSQLLiteral(+ rv({ case: "boolValue", value: false }),+ Engine.MYSQL+ )+ ).toBe("0");+ });++ it("renders numbers as bare literals", () => {+ expect(+ rowValueToSQLLiteral(rv({ case: "int32Value", value: 42 }), Engine.MYSQL)+ ).toBe("42");+ expect(+ rowValueToSQLLiteral(+ rv({ case: "int64Value", value: 9999999999n }),+ Engine.MYSQL+ )+ ).toBe("9999999999");+ expect(+ rowValueToSQLLiteral(+ rv({ case: "doubleValue", value: 3.14 }),+ Engine.MYSQL+ )+ ).toBe("3.14");+ });++ it("single-quotes strings and doubles embedded single quotes", () => {+ expect(+ rowValueToSQLLiteral(+ rv({ case: "stringValue", value: "hello" }),+ Engine.POSTGRES+ )+ ).toBe("'hello'");+ expect(+ rowValueToSQLLiteral(+ rv({ case: "stringValue", value: "O'Brien" }),+ Engine.POSTGRES+ )+ ).toBe("'O''Brien'");+ });++ it("escapes backslashes only for MySQL-family engines", () => {+ const value = rv({ case: "stringValue", value: "a\\b" });+ // MySQL treats backslash as an escape character → must double it.+ expect(rowValueToSQLLiteral(value, Engine.MYSQL)).toBe("'a\\\\b'");+ // Postgres (standard_conforming_strings) treats backslash literally.+ expect(rowValueToSQLLiteral(value, Engine.POSTGRES)).toBe("'a\\b'");+ });++ it("renders bytes as engine-specific binary literals", () => {+ const value = rv({+ case: "bytesValue",+ value: new Uint8Array([0x01, 0x02, 0xab]),+ });+ expect(rowValueToSQLLiteral(value, Engine.MYSQL)).toBe("0x0102AB");+ expect(rowValueToSQLLiteral(value, Engine.MSSQL)).toBe("0x0102AB");+ expect(rowValueToSQLLiteral(value, Engine.POSTGRES)).toBe("'\\x0102AB'");+ });++ it("single-quotes timestamps", () => {+ const seconds = BigInt(Date.UTC(2026, 3, 20, 13, 56, 0) / 1000);+ const value = rv({+ case: "timestampValue",+ value: create(RowValue_TimestampSchema, {+ googleTimestamp: create(TimestampSchema, { seconds, nanos: 0 }),+ accuracy: 0,+ }),+ });+ expect(rowValueToSQLLiteral(value, Engine.POSTGRES)).toBe(+ "'2026-04-20 13:56:00'"+ );+ });+});++describe("generateInsertStatementFromRows", () => {+ it("builds a single batched INSERT with engine-aware quoting", () => {+ const rows: RowValue[][] = [+ [+ rv({ case: "stringValue", value: "new-instance" }),+ rv({ case: "stringValue", value: "new_db" }),+ rv({ case: "boolValue", value: false }),+ rv({ case: "nullValue", value: 0 }),+ ],+ [+ rv({ case: "stringValue", value: "other" }),+ rv({ case: "stringValue", value: "db2" }),+ rv({ case: "boolValue", value: true }),+ rv({ case: "stringValue", value: "sample" }),+ ],+ ];+ const sql = generateInsertStatementFromRows({+ engine: Engine.POSTGRES,+ schema: "public",+ table: "<table_name>",+ columns: ["instance", "name", "deleted", "environment"],+ rows,+ });+ expect(sql).toBe(+ `INSERT INTO "public"."<table_name>" ("instance", "name", "deleted", "environment") VALUES\n` ++ ` ('new-instance', 'new_db', FALSE, NULL),\n` ++ ` ('other', 'db2', TRUE, 'sample');`+ );+ });++ it("omits the schema prefix when schema is empty", () => {+ const rows: RowValue[][] = [[rv({ case: "int32Value", value: 1 })]];+ const sql = generateInsertStatementFromRows({+ engine: Engine.MYSQL,+ schema: undefined,+ table: "<table_name>",+ columns: ["id"],+ rows,+ });+ expect(sql).toBe("INSERT INTO `<table_name>` (`id`) VALUES\n (1);");+ });+});diff --git a/frontend/src/utils/v1/sql.ts b/frontend/src/utils/v1/sql.tsindex 0a4ac0c57a..8a05deab6d 100644--- a/frontend/src/utils/v1/sql.ts+++ b/frontend/src/utils/v1/sql.ts@@ -234,6 +234,118 @@ export const generateSimpleInsertStatement = (return `INSERT INTO ${schemaAndTable} (${columnNames}) VALUES (${placeholders});`;};+// MySQL-family engines use backtick identifiers, treat backslash as an escape+// character inside string literals, and render booleans as 1/0.+const MYSQL_FAMILY_ENGINES = new Set<Engine>([+ Engine.MYSQL,+ Engine.MARIADB,+ Engine.TIDB,+ Engine.OCEANBASE,+ Engine.CLICKHOUSE,+ Engine.STARROCKS,+ Engine.DORIS,+]);++const isMySQLFamilyEngine = (engine: Engine): boolean =>+ MYSQL_FAMILY_ENGINES.has(engine);++const escapeSQLStringLiteral = (value: string, engine: Engine): string => {+ let escaped = value;+ // Escape backslashes first so the quote-doubling below isn't affected.+ if (isMySQLFamilyEngine(engine)) {+ escaped = escaped.replaceAll("\\", "\\\\");+ }+ escaped = escaped.replaceAll("'", "''");+ return `'${escaped}'`;+};++const bytesToHex = (bytes: Uint8Array): string =>+ Array.from(bytes)+ .map((b) => b.toString(16).toUpperCase().padStart(2, "0"))+ .join("");++// rowValueToSQLLiteral renders a RowValue as an engine-aware SQL literal,+// suitable for inlining into an INSERT statement. It is type-aware: numbers+// stay bare, strings/JSON/timestamps are single-quoted and escaped, booleans+// follow the engine convention, and NULL is emitted for null/unset cells.+export const rowValueToSQLLiteral = (+ value: RowValue | undefined,+ engine: Engine+): string => {+ if (value === undefined || value.kind?.case === undefined) {+ return "NULL";+ }+ const { kind } = value;+ switch (kind.case) {+ case "nullValue":+ return "NULL";+ case "boolValue":+ if (isMySQLFamilyEngine(engine)) {+ return kind.value ? "1" : "0";+ }+ return kind.value ? "TRUE" : "FALSE";+ case "int32Value":+ case "uint32Value":+ case "doubleValue":+ case "floatValue":+ return String(kind.value);+ case "int64Value":+ case "uint64Value":+ return kind.value.toString();+ case "stringValue":+ return escapeSQLStringLiteral(kind.value, engine);+ case "bytesValue": {+ const hex = bytesToHex(kind.value);+ // Postgres-family bytea literal vs MySQL/MSSQL 0x literal.+ if (+ engine === Engine.POSTGRES ||+ engine === Engine.COCKROACHDB ||+ engine === Engine.REDSHIFT+ ) {+ return `'\\x${hex}'`;+ }+ return `0x${hex}`;+ }+ default: {+ // valueValue (JSON / composite), timestamps, and anything else fall+ // back to their plain display form, single-quoted.+ const plain = extractSQLRowValuePlain(value);+ if (plain === null || plain === undefined) {+ return "NULL";+ }+ return escapeSQLStringLiteral(String(plain), engine);+ }+ }+};++// generateInsertStatementFromRows builds a single batched INSERT statement for+// the given rows. Each `rows[i]` is the cell array of one result row, aligned+// with `columns`.+export const generateInsertStatementFromRows = (params: {+ engine: Engine;+ schema: string | undefined;+ table: string;+ columns: string[];+ rows: RowValue[][];+}): string => {+ const { engine, schema, table, columns, rows } = params;+ const schemaAndTable = generateSchemaAndTableNameInSQL(+ engine,+ schema ?? "",+ table+ );+ const columnNames = columns+ .map((column) => wrapSQLIdentifier(column, engine))+ .join(", ");+ const valueLines = rows+ .map(+ (row) =>+ ` (${row.map((cell) => rowValueToSQLLiteral(cell, engine)).join(", ")})`+ )+ .join(",\n");+ return `INSERT INTO ${schemaAndTable} (${columnNames}) VALUES\n${valueLines};`;+};+export const generateSimpleUpdateStatement = (engine: Engine,schema: string,