Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
perf: query result (#16517)
ecmadaod3f9d86ae621
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.jsonindex b8e42ef386..2675f22237 100644--- a/frontend/src/locales/en-US.json+++ b/frontend/src/locales/en-US.json@@ -1934,6 +1934,7 @@},"upload-file": "Upload file","copy-selected-results": "Copy selected data by {action} or {button}",+ "cancel-selection": "Cancel selection","format-default": "Default","column-display-format": "Column Display Format","next-row": "Next Row",diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.jsonindex 22cf00e4fd..4e51831291 100644--- a/frontend/src/locales/es-ES.json+++ b/frontend/src/locales/es-ES.json@@ -1934,6 +1934,7 @@},"upload-file": "Subir archivo","copy-selected-results": "Copiar datos seleccionados por {action} o {button}",+ "cancel-selection": "Cancelar selección","format-default": "Por defecto","column-display-format": "Formato de visualización de columna","next-row": "siguiente fila",diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.jsonindex bec3584326..c4814a73b3 100644--- a/frontend/src/locales/ja-JP.json+++ b/frontend/src/locales/ja-JP.json@@ -1934,6 +1934,7 @@},"upload-file": "ファイルをアップロードする","copy-selected-results": "選択したデータを{action}または{button}でコピーします",+ "cancel-selection": "選択をキャンセル","format-default": "デフォルト","column-display-format": "列表示形式","next-row": "次の行",diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.jsonindex 5ca2e2b691..72aac198d0 100644--- a/frontend/src/locales/vi-VN.json+++ b/frontend/src/locales/vi-VN.json@@ -1934,6 +1934,7 @@},"upload-file": "Tải lên tệp","copy-selected-results": "Sao chép dữ liệu đã chọn bằng {action} hoặc {button}",+ "cancel-selection": "Hủy lựa chọn","format-default": "Mặc định","column-display-format": "Định dạng hiển thị cột","next-row": "Dòng tiếp theo",diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.jsonindex c6163f87f5..c580c4265b 100644--- a/frontend/src/locales/zh-CN.json+++ b/frontend/src/locales/zh-CN.json@@ -1934,6 +1934,7 @@},"upload-file": "上传文件","copy-selected-results": "通过 {action} 或 {button} 来快速复制选定的数据",+ "cancel-selection": "取消选择","format-default": "默认","column-display-format": "列显示格式","next-row": "下一行",diff --git a/frontend/src/views/sql-editor/ConnectionPanel/ConnectionPane/TreeNode/DatabaseNode.vue b/frontend/src/views/sql-editor/ConnectionPanel/ConnectionPane/TreeNode/DatabaseNode.vueindex 35c7849e7a..edfe18e817 100644--- a/frontend/src/views/sql-editor/ConnectionPanel/ConnectionPane/TreeNode/DatabaseNode.vue+++ b/frontend/src/views/sql-editor/ConnectionPanel/ConnectionPane/TreeNode/DatabaseNode.vue@@ -1,10 +1,12 @@<template><div class="flex items-center max-w-full overflow-hidden gap-x-1">- <LinkIcon v-if="connected" class="w-4 textinfolabel" />+ <LinkIcon+ v-if="tabStore.currentTab?.connection.database === database.name"+ class="w-4 textinfolabel"+ /><NCheckboxv-else-if="!disallowBatchQuery && canQuery":checked="checked"- :disabled="tabStore.currentTab?.connection.database === database.name"@click.stop.prevent=""@update:checked="$emit('update:checked', $event)"/>@@ -76,10 +78,7 @@ const database = computed(const canQuery = computed(() => isDatabaseV1Queryable(database.value));const showRequestQueryButton = computed(() => {- return (- !disallowRequestQuery.value &&- !canQuery.value- );+ return !disallowRequestQuery.value && !canQuery.value;});const hasInstanceContext = computed(() => {diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/DataBlock.vue b/frontend/src/views/sql-editor/EditorCommon/ResultView/DataBlock.vueindex 815742f72d..961688d9fd 100644--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/DataBlock.vue+++ b/frontend/src/views/sql-editor/EditorCommon/ResultView/DataBlock.vue@@ -1,5 +1,5 @@<template>- <div class="space-y-5 m-2">+ <NScrollbar ref="scrollbarRef" class="space-y-5 m-2"><divv-for="(row, rowIndex) of rows":key="`rows-${rowIndex + offset}`"@@ -41,12 +41,13 @@:set-index="setIndex":row-index="offset + rowIndex":col-index="header.index"+ :column-type="getColumnType(header)"/></div></div></div></div>- </div>+ </NScrollbar><div v-if="rows.length === 0" class="text-center w-full my-12 textinfolabel">{{ $t("sql-editor.no-data-available") }}</div>@@ -54,13 +55,15 @@<script setup lang="ts">import type { Table } from "@tanstack/vue-table";-import { computed } from "vue";+import { NScrollbar } from "naive-ui";+import { computed, watch, ref } from "vue";import { FeatureBadge } from "@/components/FeatureGuard";import { useConnectionOfCurrentSQLEditorTab } from "@/store";-import { PlanFeature } from "@/types/proto/v1/subscription_service";import type { QueryRow, RowValue } from "@/types/proto/v1/sql_service";+import { PlanFeature } from "@/types/proto/v1/subscription_service";import TableCell from "./DataTable/TableCell.vue";import SensitiveDataIcon from "./DataTable/common/SensitiveDataIcon.vue";+import { getColumnType } from "./DataTable/common/utils";import { useSQLResultViewContext } from "./context";const props = defineProps<{@@ -73,6 +76,12 @@ const props = defineProps<{const { keyword } = useSQLResultViewContext();const { database } = useConnectionOfCurrentSQLEditorTab();+const scrollbarRef = ref<InstanceType<typeof NScrollbar>>();const rows = computed(() => props.table.getRowModel().rows);++watch(+ () => props.offset,+ () => scrollbarRef.value?.scrollTo({ top: 0 })+);</script>diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/DataTable.vue b/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/DataTable.vueindex 6a538c64c8..dad2aeaa2d 100644--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/DataTable.vue+++ b/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/DataTable.vue@@ -16,8 +16,8 @@><tr><th- v-for="header of table.getFlatHeaders()"- :key="header.index"+ v-for="header of columns"+ :key="`${setIndex}-${header.id}`"class="group relative px-2 py-2 min-w-[2rem] text-left text-xs font-medium text-gray-500 dark:text-gray-300 tracking-wider border-x border-block-border dark:border-zinc-500":class="{'cursor-pointer hover:bg-gray-100 dark:hover:bg-gray-800':@@ -60,12 +60,21 @@<!-- Add binary format button if this column has binary data --><BinaryFormatButton- v-if="isColumnWithBinaryData(header.index)"- :column-index="header.index"- :column-format="getColumnFormatOverride(header.index)"- :server-format="getColumnServerFormat(header.index)"- :has-single-bit-values="hasColumnSingleBitValues(header.index)"- @update:format="setColumnFormat(header.index, $event)"+ v-if="existBinaryValue(header.index)"+ :format="+ getBinaryFormat({+ colIndex: header.index,+ setIndex,+ })+ "+ @update:format="+ (format: BinaryFormat) =>+ setBinaryFormat({+ colIndex: header.index,+ setIndex,+ format,+ })+ "@click.stop/></div>@@ -82,15 +91,15 @@<tbody><trv-for="(row, rowIndex) of rows"- :key="rowIndex"+ :key="`${setIndex}-${rowIndex}`"class="group":data-row-index="offset + rowIndex"><td- v-for="(cell, cellIndex) of row.getVisibleCells()"- :key="cellIndex"+ v-for="(cell, columnIndex) of row.getVisibleCells()"+ :key="`${setIndex}-${rowIndex}-${columnIndex}`"class="relative max-w-[50vw] p-0 text-sm dark:text-gray-100 leading-5 whitespace-nowrap break-all border-x border-b border-block-border dark:border-zinc-500 group-even:bg-gray-100/50 dark:group-even:bg-gray-700/50"- :data-col-index="cellIndex"+ :data-col-index="columnIndex"><TableCell:table="table"@@ -98,13 +107,12 @@:keyword="keyword":set-index="setIndex":row-index="offset + rowIndex"- :col-index="cellIndex"+ :col-index="columnIndex":allow-select="true"- :column-format-override="getColumnFormatOverride(cellIndex)"- :column-type="props.columnTypeNames?.[cellIndex]"+ :column-type="getColumnTypeByIndex(columnIndex)"/><div- v-if="cellIndex === 0 && !selectionDisabled"+ v-if="columnIndex === 0 && !selectionDisabled"class="absolute inset-y-0 left-0 w-3 cursor-pointer hover:bg-accent/10 dark:hover:bg-accent/40":class="{'bg-accent/10 dark:bg-accent/40':@@ -132,19 +140,20 @@ import { NEmpty } from "naive-ui";import { computed, nextTick, onMounted, ref, watch } from "vue";import { FeatureBadge } from "@/components/FeatureGuard";import { useConnectionOfCurrentSQLEditorTab } from "@/store";-import { PlanFeature } from "@/types/proto/v1/subscription_service";import { type QueryRow, type RowValue } from "@/types/proto/v1/sql_service";+import { PlanFeature } from "@/types/proto/v1/subscription_service";import { useSQLResultViewContext } from "../context";import TableCell from "./TableCell.vue";import {- setColumnFormatOverride,- setBinaryFormat,- getBinaryFormat,+ useBinaryFormatContext,+ getBinaryFormatByColumnType,+ type BinaryFormat,} from "./binary-format-store";import BinaryFormatButton from "./common/BinaryFormatButton.vue";import ColumnSortedIcon from "./common/ColumnSortedIcon.vue";import SensitiveDataIcon from "./common/SensitiveDataIcon.vue";import { useSelectionContext } from "./common/selection-logic";+import { getColumnType } from "./common/utils";import useTableColumnWidthLogic from "./useTableResize";const props = defineProps<{@@ -154,7 +163,6 @@ const props = defineProps<{isSensitiveColumn: (index: number) => boolean;isColumnMissingSensitive: (index: number) => boolean;maxHeight?: number;- columnTypeNames?: string[]; // Column type names from QueryResult}>();const {@@ -173,134 +181,30 @@ const tableResize = useTableColumnWidthLogic({maxWidth: 640, // 40rem});+const { getBinaryFormat, setBinaryFormat } = useBinaryFormatContext();+const { keyword } = useSQLResultViewContext();const { database } = useConnectionOfCurrentSQLEditorTab();const rows = computed(() => props.table.getRowModel().rows);+const columns = computed(() => props.table.getFlatHeaders());-// Column format overrides - map of column index to format-const columnFormatOverrides = ref<Map<number, string | null>>(new Map());--// Check if a column contains any binary data-const isColumnWithBinaryData = (columnIndex: number): boolean => {- const columnRows = props.table.getPrePaginationRowModel().rows;-- // Check each row in the column for binary data- for (const row of columnRows) {- const cell = row.getVisibleCells()[columnIndex];- if (!cell) continue;-- const value = cell.getValue<RowValue>();- if (value?.bytesValue) {- return true;- }- }-- return false;+const getColumnTypeByIndex = (columnIndex: number) => {+ return getColumnType(columns.value[columnIndex]);};-// Determine the suitable format for a column based on column type and content-const getColumnServerFormat = (columnIndex: number): string | null => {- // Get column type name from direct columnTypeNames prop- let columnType = "";-- // Use column type names from props- if (props.columnTypeNames && columnIndex < props.columnTypeNames.length) {- columnType = props.columnTypeNames[columnIndex].toLowerCase();+const existBinaryValue = (columnIndex: number) => {+ if (!getBinaryFormatByColumnType(getColumnTypeByIndex(columnIndex))) {+ return false;}- // Default format based on column type (default to HEX)- let defaultFormat = "HEX";-- // Detect BIT column types (bit, varbit, bit varying) - for binary format display- const isBitColumn =- // Generic bit types- columnType === "bit" ||- columnType.startsWith("bit(") ||- (columnType.includes("bit") && !columnType.includes("binary")) ||- // PostgreSQL bit types- columnType === "varbit" ||- columnType === "bit varying";-- // Detect BINARY column types (binary, varbinary, bytea, blob, etc) - for hex format display- const isBinaryColumn =- // Generic binary types- columnType === "binary" ||- columnType.includes("binary") ||- // MySQL/MariaDB binary types- columnType.startsWith("binary(") ||- columnType.startsWith("varbinary") ||- columnType.includes("blob") ||- columnType === "longblob" ||- columnType === "mediumblob" ||- columnType === "tinyblob" ||- // PostgreSQL binary type- columnType === "bytea" ||- // SQL Server binary types- columnType === "image" ||- columnType === "varbinary(max)" ||- // Oracle binary types- columnType === "raw" ||- columnType === "long raw";-- // BIT columns default to binary format- if (isBitColumn) {- defaultFormat = "BINARY";- }-- // BINARY/VARBINARY/BLOB columns default to HEX format- if (isBinaryColumn) {- defaultFormat = "HEX";- }-- const columnRows = props.table.getPrePaginationRowModel().rows;-- // Look through rows to find byte values and determine format- for (const row of columnRows) {+ // Check each row in the column for binary data+ for (const row of rows.value) {const cell = row.getVisibleCells()[columnIndex];if (!cell) continue;const value = cell.getValue<RowValue>();if (value?.bytesValue) {- // Get default format based on content- // Ensure bytesValue exists before converting to array- const byteArray = value.bytesValue ? Array.from(value.bytesValue) : [];-- // For single byte values (could be boolean)- if (- byteArray.length === 1 &&- (byteArray[0] === 0 || byteArray[0] === 1)- ) {- return "BOOLEAN";- }-- // Check if it's readable text- const isReadableText = byteArray.every(- (byte) => byte >= 32 && byte <= 126- );- if (isReadableText) {- return "TEXT";- }-- // Return default format based on column type- return defaultFormat;- }- }-- return null;-};--// Check if a column has any single-bit values-const hasColumnSingleBitValues = (columnIndex: number): boolean => {- const columnRows = props.table.getPrePaginationRowModel().rows;-- // Check if any row in this column has a single-bit value- for (const row of columnRows) {- const cell = row.getVisibleCells()[columnIndex];- if (!cell) continue;-- const value = cell.getValue<RowValue>();- if (value?.bytesValue?.length === 1) {return true;}}@@ -308,81 +212,9 @@ const hasColumnSingleBitValues = (columnIndex: number): boolean => {return false;};-// Get the current format override for a column-const getColumnFormatOverride = (columnIndex: number): string | null => {- return columnFormatOverrides.value.get(columnIndex) || null;-};--// Set the format for a column-const setColumnFormat = (columnIndex: number, format: string | null) => {- if (format === null) {- columnFormatOverrides.value.delete(columnIndex);- } else {- columnFormatOverrides.value.set(columnIndex, format);- }-- // Store the format in the binary format store for use during copy- const databaseName = database.value?.name || "";- setColumnFormatOverride({- colIndex: columnIndex,- format,- setIndex: props.setIndex,- databaseName,- });-- // Force a re-render- columnFormatOverrides.value = new Map(columnFormatOverrides.value);-};-onMounted(() => {nextTick(() => {tableResize.reset();-- // Store auto-detected formats for all binary columns- // This ensures the format is available for copy operations- const databaseName = database.value?.name || "";-- // For each column with binary data, store its server-detected format- for (- let colIndex = 0;- colIndex < props.table.getAllColumns().length;- colIndex++- ) {- if (isColumnWithBinaryData(colIndex)) {- const serverFormat = getColumnServerFormat(colIndex);- if (serverFormat) {- // Important: Don't set column format override during initialization- // This would override cell-specific formats for all cells in the column- // We only want to set it when the user explicitly chooses a format- // setColumnFormatOverride(colIndex, serverFormat, props.setIndex, databaseName);-- // Only set formats for cells that don't already have a format- const rows = props.table.getPrePaginationRowModel().rows;- rows.forEach((row, rowIndex) => {- const cell = row.getVisibleCells()[colIndex];- if (cell && cell.getValue<RowValue>()?.bytesValue) {- // Check if this cell already has a format before overriding- const existingFormat = getBinaryFormat({- rowIndex,- colIndex,- setIndex: props.setIndex,- databaseName,- });- if (!existingFormat) {- // Only set if no format exists yet- setBinaryFormat({- rowIndex,- colIndex,- format: serverFormat,- setIndex: props.setIndex,- databaseName,- });- }- }- });- }- }- }});});diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/TableCell.vue b/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/TableCell.vueindex df11427a25..d0d5208501 100644--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/TableCell.vue+++ b/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/TableCell.vue@@ -5,7 +5,6 @@:class="classes"@click="handleClick"@dblclick="showDetail"- @contextmenu.prevent="handleContextMenu"ref="cellRef"><div@@ -17,17 +16,20 @@class="absolute right-1 top-1/2 translate-y-[-45%] flex items-center gap-1"><!-- Format button for binary data -->- <NButton- v-if="hasByteData && !props.columnFormatOverride"- size="tiny"- circle- class="dark:!bg-dark-bg"- @click.stop="showFormatDropdown"- >- <template #icon>- <IconCode class="w-3 h-3" />- </template>- </NButton>+ <BinaryFormatButton+ v-if="hasByteData"+ :format="binaryFormat"+ @update:format="+ (format: BinaryFormat) =>+ setBinaryFormat({+ colIndex,+ rowIndex,+ setIndex,+ format,+ })+ "+ @click.stop+ /><!-- Expand button for long content --><NButton@@ -42,18 +44,6 @@</template></NButton></div>-- <!-- Format dropdown menu -->- <NDropdown- v-if="hasByteData"- :trigger="'manual'"- :show="showFormatMenu"- :options="formatOptions"- :x="dropdownX"- :y="dropdownY"- @select="handleFormatSelect"- @clickoutside="showFormatMenu = false"- /></div></template>@@ -61,22 +51,21 @@import { type Table } from "@tanstack/vue-table";import { useResizeObserver } from "@vueuse/core";import { escape } from "lodash-es";-import { Code as IconCode } from "lucide-vue-next";-import { NButton, NDropdown } from "naive-ui";+import { NButton } from "naive-ui";import { twMerge } from "tailwind-merge";-import { computed, nextTick, ref, onMounted } from "vue";-import { useI18n } from "vue-i18n";+import { computed, ref, watchEffect } from "vue";import { useConnectionOfCurrentSQLEditorTab } from "@/store";import { Engine } from "@/types/proto/v1/common";import type { QueryRow, RowValue } from "@/types/proto/v1/sql_service";import { extractSQLRowValuePlain, getHighlightHTMLByRegExp } from "@/utils";import { useSQLResultViewContext } from "../context";import {- getBinaryFormat,- setBinaryFormat,- setColumnType,+ useBinaryFormatContext,+ formatBinaryValue,detectBinaryFormat,+ type BinaryFormat,} from "./binary-format-store";+import BinaryFormatButton from "./common/BinaryFormatButton.vue";import { useSelectionContext } from "./common/selection-logic";const props = defineProps<{@@ -86,12 +75,12 @@ const props = defineProps<{rowIndex: number;colIndex: number;allowSelect?: boolean;- columnFormatOverride?: string | null;- columnType?: string; // Column type from QueryResult+ columnType: string; // Column type from QueryResult}>();-const { t } = useI18n();const { detail, keyword } = useSQLResultViewContext();+const { database } = useConnectionOfCurrentSQLEditorTab();+const { getBinaryFormat, setBinaryFormat } = useBinaryFormatContext();const {state: selectionState,@@ -103,14 +92,6 @@ const wrapperRef = ref<HTMLDivElement>();const cellRef = ref<HTMLDivElement>();const truncated = ref(false);-// Dropdown menu state-const showFormatMenu = ref(false);-const dropdownX = ref(0);-const dropdownY = ref(0);--// Create a ref for temporary format override-const formatOverride = ref<string | null>(null);-const allowSelect = computed(() => {return props.allowSelect && !selectionDisabled.value;});@@ -120,59 +101,30 @@ const hasByteData = computed(() => {return !!props.value.bytesValue;});-// Check if it's a single bit value (for boolean display)-const isSingleBitValue = computed(() => {- if (props.value.bytesValue) {- return props.value.bytesValue.length === 1;- }- return false;+const binaryFormat = computed(() => {+ return getBinaryFormat({+ rowIndex: props.rowIndex,+ colIndex: props.colIndex,+ setIndex: props.setIndex,+ });});-// Format options for the dropdown-const formatOptions = computed(() => {- const currentFormat =- formatOverride.value === null ? "DEFAULT" : formatOverride.value;-- const options = [- {- label: t("sql-editor.format-default"),- key: "DEFAULT",- disabled: false,- },- {- label: t("sql-editor.binary-format"),- key: "BINARY",- disabled: false,- },- {- label: t("sql-editor.hex-format"),- key: "HEX",- disabled: false,- },- {- label: t("sql-editor.text-format"),- key: "TEXT",- disabled: false,- },- ];-- // Only show boolean option for single-byte values- if (isSingleBitValue.value) {- options.splice(3, 0, {- label: t("sql-editor.boolean-format"),- key: "BOOLEAN",- disabled: false,+watchEffect(() => {+ if (!hasByteData.value) {+ return;+ }+ if (!binaryFormat.value) {+ const binaryFormat = detectBinaryFormat({+ bytesValue: props.value.bytesValue,+ columnType: props.columnType,+ });+ setBinaryFormat({+ rowIndex: props.rowIndex,+ colIndex: props.colIndex,+ setIndex: props.setIndex,+ format: binaryFormat,});}-- // Add a checkmark to the currently selected option- options.forEach((option) => {- if (option.key === currentFormat) {- option.label = "✓ " + option.label;- }- });-- return options;});useResizeObserver(wrapperRef, (entries) => {@@ -185,7 +137,6 @@ useResizeObserver(wrapperRef, (entries) => {truncated.value = false;}});-const { database } = useConnectionOfCurrentSQLEditorTab();const clickable = computed(() => {if (truncated.value) return true;@@ -232,106 +183,32 @@ const classes = computed(() => {});// Format the binary value based on selected format-const formattedBinaryValue = computed(() => {- if (!props.value?.bytesValue) return props.value;-- // Deep clone the value to avoid mutating the original- const newValue = { ...props.value };-- // Determine the format to use - column override, cell override, or auto-detected format- let actualFormat = null;-- // If column has an override, use that- if (- props.columnFormatOverride !== null &&- props.columnFormatOverride !== undefined- ) {- actualFormat = props.columnFormatOverride;- }- // Otherwise use the cell's override if set- else if (formatOverride.value !== null) {- actualFormat = formatOverride.value;+const formattedValue = computed(() => {+ if (!props.value?.bytesValue) {+ return props.value;}- // Otherwise use auto-detected format- else {- // Auto-detect format based on content and column type- actualFormat = detectBinaryFormat({- bytesValue: newValue.bytesValue,- columnType: props.columnType,- });- // Store the auto-detected format for use during copy operations- const databaseName = database.value?.name || "";- setBinaryFormat({- rowIndex: props.rowIndex,- colIndex: props.colIndex,- format: actualFormat,- setIndex: props.setIndex,- databaseName,- });- }+ // Determine the format to use - column override, cell override, or auto-detected format+ const actualFormat = binaryFormat.value ?? "DEFAULT";// Skip formatting for DEFAULT (auto) formatif (actualFormat === "DEFAULT") {- return newValue;+ return props.value;}- // Ensure bytesValue exists before converting to array- const byteArray = newValue.bytesValue ? Array.from(newValue.bytesValue) : [];-- // Format based on selected format- switch (actualFormat) {- case "BINARY":- // Format as binary string without spaces- newValue.stringValue = byteArray- .map((byte) => byte.toString(2).padStart(8, "0"))- .join("");- break;- case "HEX":- // Format as hex string- newValue.stringValue =- "0x" +- byteArray- .map((byte) => byte.toString(16).toUpperCase().padStart(2, "0"))- .join("");- break;- case "TEXT":- // Format as text- try {- newValue.stringValue = new TextDecoder().decode(- new Uint8Array(byteArray)- );- } catch {- // Fallback to binary if text decoding fails- newValue.stringValue = byteArray- .map((byte) => byte.toString(2).padStart(8, "0"))- .join("");- }- break;- case "BOOLEAN":- // Only for single-byte values- if (byteArray.length === 1) {- newValue.stringValue = byteArray[0] === 1 ? "true" : "false";- } else {- // Fall back to BINARY for non-single-bit values- newValue.stringValue = byteArray- .map((byte) => byte.toString(2).padStart(8, "0"))- .join("");- }- break;- }-- return newValue;+ const stringValue = formatBinaryValue({+ bytesValue: props.value.bytesValue,+ format: actualFormat,+ });+ return {+ ...props.value,+ stringValue,+ };});const html = computed(() => {- // If it's binary data, use the formatted version- const valueToRender = hasByteData.value- ? formattedBinaryValue.value- : props.value;-// Extract the display value- const value = extractSQLRowValuePlain(valueToRender);+ const value = extractSQLRowValuePlain(formattedValue.value);if (value === undefined) {return `<span class="text-gray-400 italic">UNSET</span>`;@@ -371,109 +248,10 @@ const handleClick = (e: MouseEvent) => {const showDetail = () => {detail.value = {- show: true,set: props.setIndex,row: props.rowIndex,col: props.colIndex,table: props.table,};};--// Display the format dropdown menu-const showFormatDropdown = (e: MouseEvent) => {- if (!cellRef.value) return;-- // Position the dropdown relative to the click position- dropdownX.value = e.clientX;- dropdownY.value = e.clientY;- showFormatMenu.value = true;-};--// Handle right-click context menu for binary data-const handleContextMenu = (e: MouseEvent) => {- if (hasByteData.value) {- showFormatDropdown(e);- }-};--// Handle format selection from dropdown-const handleFormatSelect = (key: string) => {- // Get database name to scope the format to this database- const databaseName = database.value?.name || "";-- // If DEFAULT is selected, remove the override- if (key === "DEFAULT") {- formatOverride.value = null;- // Also remove from the global store if it exists- setBinaryFormat({- rowIndex: props.rowIndex,- colIndex: props.colIndex,- format: "DEFAULT",- setIndex: props.setIndex,- databaseName,- });- } else {- // Otherwise set the override- formatOverride.value = key;- // Store the format in the global binary format store- setBinaryFormat({- rowIndex: props.rowIndex,- colIndex: props.colIndex,- format: key,- setIndex: props.setIndex,- databaseName,- });- }-- showFormatMenu.value = false;-- // Force recomputation of html- nextTick();-};--// On component mount, check for any stored formats and store column type-onMounted(() => {- // Get database name to scope the format to this database- const databaseName = database.value?.name || "";-- // Store column type information for later format detection- if (props.columnType) {- setColumnType({- colIndex: props.colIndex,- columnType: props.columnType,- setIndex: props.setIndex,- databaseName,- });- }-- // Only proceed if we have binary data- if (hasByteData.value) {- // Check for a saved format and apply it- const savedFormat = getBinaryFormat({- rowIndex: props.rowIndex,- colIndex: props.colIndex,- setIndex: props.setIndex,- databaseName,- });-- if (savedFormat && savedFormat !== "DEFAULT") {- formatOverride.value = savedFormat;- } else {- // If no saved format yet, use our shared detection function- const detectedFormat = detectBinaryFormat({- bytesValue: props.value.bytesValue,- columnType: props.columnType,- });-- // Store this format immediately- setBinaryFormat({- rowIndex: props.rowIndex,- colIndex: props.colIndex,- format: detectedFormat,- setIndex: props.setIndex,- databaseName,- });- }- }-});</script>diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/binary-format-store.ts b/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/binary-format-store.tsindex a5583e0edd..9f77118c9b 100644--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/binary-format-store.ts+++ b/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/binary-format-store.ts@@ -1,218 +1,231 @@-import { ref } from 'vue';+import type { InjectionKey, Ref } from "vue";+import { provide, inject, ref } from "vue";-// Store for binary data formatting-// This store maps row/column coordinates to their selected format-type FormatMap = Map<string, string>;-type ColumnTypeMap = Map<string, string>;-type ColumnFormatMap = Map<string, string>;--// Create a global format map using Vue's ref for reactivity-const formattedBinaryValues = ref<FormatMap>(new Map());--// Store column types to help with auto-detection-const columnTypes = ref<ColumnTypeMap>(new Map());--// Store column format overrides-const columnFormatOverrides = ref<ColumnFormatMap>(new Map());--// Parameter interfaces-interface CellKeyParams {- rowIndex: number;+export type BinaryFormat = "DEFAULT" | "BINARY" | "HEX" | "TEXT" | "BOOLEAN";+interface ColumnKeyParams {colIndex: number;setIndex?: number;- databaseName?: string;+ contextId: string;}-interface ColumnKeyParams {- colIndex: number;- setIndex?: number;- databaseName?: string;+interface CellKeyParams extends ColumnKeyParams {+ rowIndex: number;}// Get a unique key for a cell's row/column positionconst getCellKey = (params: CellKeyParams): string => {- const { rowIndex, colIndex, setIndex = 0, databaseName = '' } = params;- return `${databaseName}:${setIndex}:${rowIndex}:${colIndex}`;+ const { rowIndex, colIndex, setIndex = 0, contextId } = params;+ return `${contextId}:${setIndex}:${rowIndex}:${colIndex}`;};// Get a key for a columnconst getColumnKey = (params: ColumnKeyParams): string => {- const { colIndex, setIndex = 0, databaseName = '' } = params;- return `${databaseName}:${setIndex}:col:${colIndex}`;-};--// Parameter interfaces for the public API functions-export interface BinaryFormatParams {- rowIndex: number;- colIndex: number;- format: string;- setIndex?: number;- databaseName?: string;-}--export interface GetBinaryFormatParams {- rowIndex: number;- colIndex: number;- setIndex?: number;- databaseName?: string;-}--// Store a format for a specific cell-export const setBinaryFormat = (params: BinaryFormatParams): void => {- const { rowIndex, colIndex, format, setIndex, databaseName } = params;- const key = getCellKey({ rowIndex, colIndex, setIndex, databaseName });- formattedBinaryValues.value.set(key, format);-};--// Get the format for a specific cell-export const getBinaryFormat = (params: GetBinaryFormatParams): string | undefined => {- const { rowIndex, colIndex, setIndex, databaseName } = params;- const key = getCellKey({ rowIndex, colIndex, setIndex, databaseName });- return formattedBinaryValues.value.get(key);+ const { colIndex, setIndex = 0, contextId } = params;+ return `${contextId}:${setIndex}:col:${colIndex}`;};-// Column type parameters-export interface ColumnTypeParams {+interface GetBinaryFormatParams {+ rowIndex?: number;colIndex: number;- columnType: string;- setIndex?: number;- databaseName?: string;+ setIndex: number;}-export interface GetColumnTypeParams {- colIndex: number;- setIndex?: number;- databaseName?: string;-}--// Column format parameters-export interface ColumnFormatParams {- colIndex: number;- format: string | null;- setIndex?: number;- databaseName?: string;-}--export interface GetColumnFormatParams {- colIndex: number;- setIndex?: number;- databaseName?: string;+// Parameter interfaces for the public API functions+interface BinaryFormatParams extends GetBinaryFormatParams {+ format: BinaryFormat;}-// Store column type information-export const setColumnType = (params: ColumnTypeParams): void => {- const { colIndex, columnType, setIndex, databaseName } = params;- const key = getColumnKey({ colIndex, setIndex, databaseName });- columnTypes.value.set(key, columnType.toLowerCase());+type BinaryFormatContext = {+ getBinaryFormat: (params: GetBinaryFormatParams) => BinaryFormat | undefined;+ setBinaryFormat: (params: BinaryFormatParams) => void;};-// Get column type information-export const getColumnType = (params: GetColumnTypeParams): string | undefined => {- const { colIndex, setIndex, databaseName } = params;- const key = getColumnKey({ colIndex, setIndex, databaseName });- return columnTypes.value.get(key);-};--// Store a column format override-export const setColumnFormatOverride = (params: ColumnFormatParams): void => {- const { colIndex, format, setIndex, databaseName } = params;- const key = getColumnKey({ colIndex, setIndex, databaseName });- if (format === null) {- columnFormatOverrides.value.delete(key);- } else {- columnFormatOverrides.value.set(key, format);- }+const KEY = Symbol(+ "bb.sql-editor.result-view.binary-format"+) as InjectionKey<BinaryFormatContext>;++export const provideBinaryFormatContext = (contextId: Ref<string>) => {+ const formattedBinaryValues = ref<Map<string, BinaryFormat>>(new Map());++ const getBinaryFormat = (+ params: GetBinaryFormatParams+ ): BinaryFormat | undefined => {+ const { rowIndex, colIndex, setIndex } = params;+ if (rowIndex !== undefined) {+ // find format for a specific cell.+ const key = getCellKey({+ rowIndex,+ colIndex,+ setIndex,+ contextId: contextId.value,+ });+ if (formattedBinaryValues.value.has(key)) {+ return formattedBinaryValues.value.get(key);+ }+ }+ // fallback to column format.+ const key = getColumnKey({+ colIndex,+ setIndex,+ contextId: contextId.value,+ });+ return formattedBinaryValues.value.get(key);+ };++ const setBinaryFormat = (params: BinaryFormatParams): void => {+ const { rowIndex, colIndex, format, setIndex } = params;+ const key =+ rowIndex !== undefined+ ? getCellKey({+ rowIndex,+ colIndex,+ setIndex,+ contextId: contextId.value,+ })+ : getColumnKey({+ colIndex,+ setIndex,+ contextId: contextId.value,+ });+ formattedBinaryValues.value.set(key, format);+ };++ const context: BinaryFormatContext = {+ getBinaryFormat,+ setBinaryFormat,+ };++ provide(KEY, context);+ return context;};-// Get a column format override-export const getColumnFormatOverride = (params: GetColumnFormatParams): string | undefined => {- const { colIndex, setIndex, databaseName } = params;- const key = getColumnKey({ colIndex, setIndex, databaseName });- return columnFormatOverrides.value.get(key);+export const useBinaryFormatContext = () => {+ return inject(KEY)!;};-export interface DetectBinaryFormatParams {- bytesValue: Uint8Array | undefined;- columnType?: string;-}-// Detect the best format for binary data based on content-export const detectBinaryFormat = (params: DetectBinaryFormatParams): string => {- const { bytesValue, columnType = '' } = params;- if (!bytesValue || bytesValue.length === 0) {- return 'HEX';+export const detectBinaryFormat = (params: {+ bytesValue: Uint8Array | undefined;+ columnType: string;+}): BinaryFormat => {+ const { bytesValue, columnType = "" } = params;+ if (!bytesValue || bytesValue.length === 0 || columnType === "") {+ return "DEFAULT";}-+const byteArray = Array.from(bytesValue);-+// For single bit values (could be boolean)if (byteArray.length === 1 && (byteArray[0] === 0 || byteArray[0] === 1)) {return "BOOLEAN";}-+// Check if it's readable text- const isReadableText = byteArray.every(byte => byte >= 32 && byte <= 126);+ const isReadableText = byteArray.every((byte) => byte >= 32 && byte <= 126);if (isReadableText) {return "TEXT";}-+// Default format based on column type- const lowerColumnType = columnType.toLowerCase();-- // Detect BIT column types - for binary format display (0s and 1s)- const isBitColumn = (- lowerColumnType === 'bit' ||- lowerColumnType.startsWith('bit(') ||- (lowerColumnType.includes('bit') && !lowerColumnType.includes('binary')) ||- lowerColumnType === 'varbit' ||- lowerColumnType === 'bit varying'- );-- // BIT columns default to binary format- if (isBitColumn) {- return "BINARY";- }-- // All other binary types default to HEX- return "HEX";+ return getBinaryFormatByColumnType(columnType) ?? "DEFAULT";};-export interface FormatBinaryValueParams {+export const formatBinaryValue = ({+ bytesValue,+ format,+}: {bytesValue: Uint8Array | undefined;- format: string;-}--export const formatBinaryValue = (params: FormatBinaryValueParams): string => {- const { bytesValue, format } = params;+ format: BinaryFormat;+}): string => {if (!bytesValue || bytesValue.length === 0) {- return '';+ return "";}-+const byteArray = Array.from(bytesValue);-+ const binaryValue = byteArray+ .map((byte) => byte.toString(2).padStart(8, "0"))+ .join("");+switch (format) {case "BINARY":- return byteArray- .map(byte => byte.toString(2).padStart(8, "0"))- .join("");+ return binaryValue;case "TEXT":try {return new TextDecoder().decode(new Uint8Array(byteArray));} catch {- // Fallback to HEX if text decoding fails- return "0x" + byteArray- .map(byte => byte.toString(16).toUpperCase().padStart(2, "0"))- .join("");+ // Fallback to BINARY if text decoding fails+ return binaryValue;}+ case "HEX":+ return (+ "0x" ++ byteArray+ .map((byte) => byte.toString(16).toUpperCase().padStart(2, "0"))+ .join("")+ );case "BOOLEAN":- if (byteArray.length === 1 && (byteArray[0] === 0 || byteArray[0] === 1)) {+ if (+ byteArray.length === 1 &&+ (byteArray[0] === 0 || byteArray[0] === 1)+ ) {return byteArray[0] === 1 ? "true" : "false";}- // Fall through to HEX for non-boolean data- case "HEX":+ // Fall through to DEFAULTdefault:- return "0x" + byteArray- .map(byte => byte.toString(16).toUpperCase().padStart(2, "0"))- .join("");+ return binaryValue;+ }+};++// Determine the suitable format for a column based on column type and content+export const getBinaryFormatByColumnType = (+ rawType: string+): BinaryFormat | undefined => {+ // Get column type name from direct columnTypeNames prop+ const columnType = rawType.toLowerCase();+ if (!columnType) {+ return;+ }++ // Detect BIT column types (bit, varbit, bit varying) - for binary format display+ const isBitColumn =+ // Generic bit types+ columnType === "bit" ||+ columnType.startsWith("bit(") ||+ (columnType.includes("bit") && !columnType.includes("binary")) ||+ // PostgreSQL bit types+ columnType === "varbit" ||+ columnType === "bit varying";++ // BIT columns default to binary format+ if (isBitColumn) {+ return "BINARY";}-};\ No newline at end of file++ // Detect BINARY column types (binary, varbinary, bytea, blob, etc) - for hex format display+ const isBinaryColumn =+ // Generic binary types+ columnType === "binary" ||+ columnType.includes("binary") ||+ // MySQL/MariaDB binary types+ columnType.startsWith("binary(") ||+ columnType.startsWith("varbinary") ||+ columnType.includes("blob") ||+ columnType === "longblob" ||+ columnType === "mediumblob" ||+ columnType === "tinyblob" ||+ // PostgreSQL binary type+ columnType === "bytea" ||+ // SQL Server binary types+ columnType === "image" ||+ columnType === "varbinary(max)" ||+ // Oracle binary types+ columnType === "raw" ||+ columnType === "long raw";++ // BINARY/VARBINARY/BLOB columns default to HEX format+ if (isBinaryColumn) {+ return "HEX";+ }++ return undefined;+};diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/common/BinaryFormatButton.vue b/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/common/BinaryFormatButton.vueindex e5a7b0bbf2..21f12bd968 100644--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/common/BinaryFormatButton.vue+++ b/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/common/BinaryFormatButton.vue@@ -12,17 +12,19 @@:secondary="hasColumnOverride"><template #icon>- <IconCode class="w-3 h-3" />+ <CodeIcon class="w-3 h-3" /></template></NButton></template><template #default><div class="p-2 w-52">- <div class="text-xs font-semibold mb-2">{{ $t("sql-editor.column-display-format") }}</div>+ <div class="text-xs font-semibold mb-2">+ {{ $t("sql-editor.column-display-format") }}+ </div><NRadioGroup:value="currentColumnFormat"class="flex flex-col gap-2"- @update:value="updateColumnFormat"+ @update:value="emit('update:format', $event as BinaryFormat)"><NRadio value="DEFAULT">{{ $t("sql-editor.format-default") }}@@ -36,7 +38,7 @@<NRadio value="TEXT">{{ $t("sql-editor.text-format") }}</NRadio>- <NRadio value="BOOLEAN" v-if="hasSingleBitValues">+ <NRadio value="BOOLEAN">{{ $t("sql-editor.boolean-format") }}</NRadio></NRadioGroup>@@ -47,45 +49,24 @@</template><script setup lang="ts">-import { Code as IconCode } from "lucide-vue-next";+import { CodeIcon } from "lucide-vue-next";import { NButton, NPopover, NRadioGroup, NRadio } from "naive-ui";import { computed } from "vue";+import { type BinaryFormat } from "../binary-format-store";-// Event interfaceconst emit = defineEmits<{- (e: "update:format", format: string | null): void;+ (e: "update:format", format: BinaryFormat): void;}>();-// Propsconst props = defineProps<{- // Current column index- columnIndex: number;- // Current format override for the column- columnFormat: string | null;- // Auto-detected server format- serverFormat: string | null;- // Whether this column contains any single-bit values (for boolean option)- hasSingleBitValues: boolean;+ format: BinaryFormat | undefined;}>();-// Track if there's currently a format override for the column-const hasColumnOverride = computed(() => {- return props.columnFormat !== null;-});--// The currently selected format for the radio groupconst currentColumnFormat = computed(() => {- return props.columnFormat || "DEFAULT";+ return props.format || "DEFAULT";});-// Update the column format-const updateColumnFormat = (format: string) => {- if (format === "DEFAULT") {- // Set to null to use server default- emit("update:format", null);- } else {- // Set to specific format- emit("update:format", format);- }-};-</script>\ No newline at end of file+const hasColumnOverride = computed(() => {+ return currentColumnFormat.value !== "DEFAULT";+});+</script>diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/common/selection-logic.ts b/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/common/selection-logic.tsindex 584e503820..c83cbe275f 100644--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/common/selection-logic.ts+++ b/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/common/selection-logic.ts@@ -12,13 +12,18 @@ import {type Ref,} from "vue";import { useI18n } from "vue-i18n";-import { pushNotification, useConnectionOfCurrentSQLEditorTab } from "@/store";+import { pushNotification } from "@/store";import type { QueryRow, RowValue } from "@/types/proto/v1/sql_service";import { extractSQLRowValuePlain, isDescendantOf, toClipboard } from "@/utils";-import { getBinaryFormat, formatBinaryValue, getColumnFormatOverride, detectBinaryFormat } from "../binary-format-store";import { useSQLResultViewContext } from "../../context";+import {+ formatBinaryValue,+ detectBinaryFormat,+ useBinaryFormatContext,+} from "../binary-format-store";+import { getColumnType } from "./utils";-export const PREVENT_DISMISS_SELECTION = "bb-prevent-dismiss-selection";+const PREVENT_DISMISS_SELECTION = "bb-prevent-dismiss-selection";export type SelectionState = {rows: number[];@@ -41,6 +46,7 @@ export const KEY = Symbol(export const provideSelectionContext = (table: Ref<Table<QueryRow>>) => {const { t } = useI18n();+ const { getBinaryFormat } = useBinaryFormatContext();const copying = ref(false);const state = ref<SelectionState>({@@ -124,11 +130,50 @@ export const provideSelectionContext = (table: Ref<Table<QueryRow>>) => {deep: false,});+ const getFormattedValue = ({+ value,+ colIndex,+ rowIndex,+ }: {+ value: RowValue;+ colIndex: number;+ rowIndex: number;+ }) => {+ // Special handling for binary data+ if (value && value.bytesValue) {+ // Get the result set index if available+ const setIndex = resultViewContext.detail?.value?.set ?? 0;++ // First check if there's a column format override+ const binaryFormat = getBinaryFormat({+ colIndex,+ rowIndex,+ setIndex,+ });+ if (binaryFormat) {+ // Column format overrides take precedence+ return formatBinaryValue({+ bytesValue: value.bytesValue,+ format: binaryFormat,+ });+ }++ const header = table.value.getFlatHeaders()[colIndex];+ const detectedFormat = detectBinaryFormat({+ bytesValue: value.bytesValue,+ columnType: getColumnType(header),+ });+ return formatBinaryValue({+ bytesValue: value.bytesValue,+ format: detectedFormat,+ });+ }++ // Fall back to default formatting+ return String(extractSQLRowValuePlain(value));+ };+const getValues = () => {- // Get the current database name for scoping the binary format- const { database } = useConnectionOfCurrentSQLEditorTab();- const databaseName = database.value?.name || '';-if (state.value.rows.length === 1 && state.value.columns.length === 1) {const row =table.value.getPrePaginationRowModel().rows[state.value.rows[0]];@@ -139,59 +184,13 @@ export const provideSelectionContext = (table: Ref<Table<QueryRow>>) => {if (!cell) {return "";}-+// Get the cell value- const value = cell.getValue() as RowValue;-- // Special handling for binary data- if (value && value.bytesValue) {- // Get the result set index if available- const setIndex = (resultViewContext.detail?.value?.set) ?? 0;-- // First check if there's a column format override- const columnFormatOverride = getColumnFormatOverride({- colIndex: state.value.columns[0],- setIndex,- databaseName- });- if (columnFormatOverride) {- // Column format overrides take precedence- return formatBinaryValue({- bytesValue: value.bytesValue,- format: columnFormatOverride- });- }-- // Then check for cell-specific format- const cellFormat = getBinaryFormat({- rowIndex: state.value.rows[0],- colIndex: state.value.columns[0],- setIndex,- databaseName- });- if (cellFormat && cellFormat !== "DEFAULT") {- // Use the stored format to format the binary data- return formatBinaryValue({- bytesValue: value.bytesValue,- format: cellFormat- });- }-- // If no stored format is found, detect based on content and column type- // This ensures copy uses the same auto-detection logic as display- const columnType = resultViewContext.columnTypeNames?.value?.[state.value.columns[0]] || '';- const detectedFormat = detectBinaryFormat({- bytesValue: value.bytesValue,- columnType- });- return formatBinaryValue({- bytesValue: value.bytesValue,- format: detectedFormat- });- }-- // Fall back to default formatting- return String(extractSQLRowValuePlain(value));+ return getFormattedValue({+ value: cell.getValue<RowValue>(),+ colIndex: state.value.columns[0],+ rowIndex: state.value.rows[0],+ });} else if (state.value.rows.length > 0) {const rows: Row<QueryRow>[] = [];for (const row of state.value.rows) {@@ -209,56 +208,11 @@ export const provideSelectionContext = (table: Ref<Table<QueryRow>>) => {const cells = row.getVisibleCells();return cells.map((cell, colIdx) => {- const value = cell.getValue() as RowValue;-- // Special handling for binary data- if (value && value.bytesValue) {- // Get the result set index if available- const setIndex = (resultViewContext.detail?.value?.set) ?? 0;-- // First check if there's a column format override- const columnFormatOverride = getColumnFormatOverride({- colIndex: colIdx,- setIndex,- databaseName- });- if (columnFormatOverride) {- // Column format overrides take precedence- return formatBinaryValue({- bytesValue: value.bytesValue,- format: columnFormatOverride- });- }-- // Then check for cell-specific format- const cellFormat = getBinaryFormat({- rowIndex: state.value.rows[rowIdx],- colIndex: colIdx,- setIndex,- databaseName- });- if (cellFormat && cellFormat !== "DEFAULT") {- // Use the stored format to format the binary data- return formatBinaryValue({- bytesValue: value.bytesValue,- format: cellFormat- });- }-- // If no stored format is found, detect based on content and column type- const columnType = resultViewContext.columnTypeNames?.value?.[colIdx] || '';- const detectedFormat = detectBinaryFormat({- bytesValue: value.bytesValue,- columnType- });- return formatBinaryValue({- bytesValue: value.bytesValue,- format: detectedFormat- });- }-- // Fall back to default formatting- return String(extractSQLRowValuePlain(value));+ return getFormattedValue({+ value: cell.getValue<RowValue>(),+ colIndex: colIdx,+ rowIndex: state.value.rows[rowIdx],+ });}).join("\t");})@@ -282,56 +236,11 @@ export const provideSelectionContext = (table: Ref<Table<QueryRow>>) => {.map((cells, rowIdx) =>cells.map((cell, colIdx) => {- const value = cell.getValue() as RowValue;-- // Special handling for binary data- if (value && value.bytesValue) {- // Get the result set index if available- const setIndex = (resultViewContext.detail?.value?.set) ?? 0;-- // First check if there's a column format override- const columnFormatOverride = getColumnFormatOverride({- colIndex: state.value.columns[colIdx],- setIndex,- databaseName- });- if (columnFormatOverride) {- // Column format overrides take precedence- return formatBinaryValue({- bytesValue: value.bytesValue,- format: columnFormatOverride- });- }-- // Then check for cell-specific format- const cellFormat = getBinaryFormat({- rowIndex: rowIdx,- colIndex: state.value.columns[colIdx],- setIndex,- databaseName- });- if (cellFormat && cellFormat !== "DEFAULT") {- // Use the stored format to format the binary data- return formatBinaryValue({- bytesValue: value.bytesValue,- format: cellFormat- });- }-- // If no stored format is found, detect based on content and column type- const columnType = resultViewContext.columnTypeNames?.value?.[state.value.columns[colIdx]] || '';- const detectedFormat = detectBinaryFormat({- bytesValue: value.bytesValue,- columnType- });- return formatBinaryValue({- bytesValue: value.bytesValue,- format: detectedFormat- });- }-- // Fall back to default formatting- return String(extractSQLRowValuePlain(value));+ return getFormattedValue({+ value: cell.getValue<RowValue>(),+ rowIndex: rowIdx,+ colIndex: state.value.columns[colIdx],+ });}).join("\t"))@@ -408,4 +317,4 @@ export const provideSelectionContext = (table: Ref<Table<QueryRow>>) => {export const useSelectionContext = () => {return inject(KEY)!;-};\ No newline at end of file+};diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/common/utils.ts b/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/common/utils.tsnew file mode 100644index 0000000000..35134ba35f--- /dev/null+++ b/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/common/utils.ts@@ -0,0 +1,14 @@+import type { Header } from "@tanstack/vue-table";+import type { QueryRow } from "@/types/proto/v1/sql_service";++interface ColumnMeta {+ columnType: string;+}++export const getColumnType = (+ column: Header<QueryRow, unknown> | undefined+) => {+ return (+ (column?.column.columnDef.meta as ColumnMeta | undefined)?.columnType ?? ""+ );+};diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/DetailPanel/DetailPanel.vue b/frontend/src/views/sql-editor/EditorCommon/ResultView/DetailPanel/DetailPanel.vueindex fa70ca2290..be0b0103a1 100644--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/DetailPanel/DetailPanel.vue+++ b/frontend/src/views/sql-editor/EditorCommon/ResultView/DetailPanel/DetailPanel.vue@@ -1,5 +1,6 @@<template><DrawerContent+ v-if="detail":title="$t('common.detail')"class="w-[100vw-4rem] min-w-[24rem] max-w-[100vw-4rem] md:w-[33vw]">@@ -74,44 +75,23 @@{{ $t("sql-editor.format") }}</template></NPopover>-+<!-- Binary data format selector -->- <NPopover v-if="isBinaryData">- <template #trigger>- <NButton- size="small"- style="--n-padding: 0 5px"- :type="binaryFormat !== serverFormat ? 'primary' : 'default'"- :secondary="binaryFormat !== serverFormat"- >- <template #icon>- <Code2Icon class="w-4 h-4" />- </template>- </NButton>- </template>- <template #default>- <div class="p-1">- <NRadioGroup :value="binaryFormat" class="flex flex-col gap-2" @update:value="updateBinaryFormat">- <NRadio value="DEFAULT">- {{ $t("sql-editor.format-default") }}- </NRadio>- <NRadio value="BINARY">- {{ $t("sql-editor.binary-format") }}- </NRadio>- <NRadio value="HEX">- {{ $t("sql-editor.hex-format") }}- </NRadio>- <NRadio value="BOOLEAN" v-if="isSingleBitValue">- {{ $t("sql-editor.boolean-format") }}- </NRadio>- <NRadio value="TEXT">- {{ $t("sql-editor.text-format") }}- </NRadio>- </NRadioGroup>- </div>- </template>- </NPopover>-+ <BinaryFormatButton+ v-if="isBinaryData"+ :format="binaryFormat"+ @update:format="+ (format: BinaryFormat) =>+ setBinaryFormat({+ colIndex: detail!.col,+ rowIndex: detail!.row,+ setIndex: detail!.set,+ format,+ })+ "+ @click.stop+ />+<NButton v-if="!disallowCopyingData" size="small" @click="handleCopy"><template #icon><ClipboardIcon class="w-4 h-4" />@@ -170,20 +150,26 @@ import {ClipboardIcon,BracesIcon,WrapTextIcon,- Code as Code2Icon,} from "lucide-vue-next";-import { NButton, NPopover, NScrollbar, NTooltip, NRadioGroup, NRadio } from "naive-ui";-import { computed, nextTick, ref } from "vue";+import { NButton, NPopover, NScrollbar, NTooltip } from "naive-ui";+import { computed } from "vue";import { useI18n } from "vue-i18n";import { DrawerContent } from "@/components/v2";import { pushNotification } from "@/store";import type { RowValue } from "@/types/proto/v1/sql_service";import { extractSQLRowValuePlain } from "@/utils";+import {+ useBinaryFormatContext,+ formatBinaryValue,+ type BinaryFormat,+} from "../DataTable/binary-format-store";+import BinaryFormatButton from "../DataTable/common/BinaryFormatButton.vue";import { useSQLResultViewContext } from "../context";import PrettyJSON from "./PrettyJSON.vue";const { t } = useI18n();const { dark, detail, disallowCopyingData } = useSQLResultViewContext();+const { getBinaryFormat, setBinaryFormat } = useBinaryFormatContext();const format = useLocalStorage<boolean>("bb.sql-editor.detail-panel.format",@@ -196,115 +182,26 @@ const wrap = useLocalStorage<boolean>(// Get the current value being displayed firstconst rawValue = computed(() => {- const { row, col, table } = detail.value;- if (!table) return undefined;+ if (!detail.value) {+ return;+ }+ const { row, col, table } = detail.value;return table.getPrePaginationRowModel().rows[row]?.getVisibleCells()[col]?.getValue<RowValue>();});-// Determine binary format based on column type and content-const getServerFormat = (): string => {- if (!rawValue.value?.bytesValue) return "HEX";-- // Get column information- const { col, table } = detail.value;- if (!table) return "HEX";-- // Get the column type from context's columnTypeNames- let columnType = '';-- // Get context and safely access columnTypeNames- const context = useSQLResultViewContext();- const columnTypeNames = context.columnTypeNames?.value;-- // Use column type names from context- if (columnTypeNames && col < columnTypeNames.length) {- columnType = columnTypeNames[col].toLowerCase();- }-- // Default format based on column type- let defaultFormat = "HEX";-- // Detect BIT column types (bit, varbit, bit varying) - for binary format display- const isBitColumn = (- // Generic bit types- columnType === 'bit' ||- columnType.startsWith('bit(') ||- (columnType.includes('bit') && !columnType.includes('binary')) ||-- // PostgreSQL bit types- columnType === 'varbit' ||- columnType === 'bit varying'- );-- // Detect BINARY column types (binary, varbinary, bytea, blob, etc) - for hex format display- const isBinaryColumn = (- // Generic binary types- columnType === 'binary' ||- columnType.includes('binary') ||-- // MySQL/MariaDB binary types- columnType.startsWith('binary(') ||- columnType.startsWith('varbinary') ||- columnType.includes('blob') ||- columnType === 'longblob' ||- columnType === 'mediumblob' ||- columnType === 'tinyblob' ||-- // PostgreSQL binary type- columnType === 'bytea' ||-- // SQL Server binary types- columnType === 'image' ||- columnType === 'varbinary(max)' ||-- // Oracle binary types- columnType === 'raw' ||- columnType === 'long raw'- );-- // BIT columns default to binary format- if (isBitColumn) {- defaultFormat = "BINARY";- }-- // BINARY/VARBINARY/BLOB columns default to HEX format- if (isBinaryColumn) {- defaultFormat = "HEX";- }-- const byteArray = Array.from(rawValue.value.bytesValue);-- // For single byte values (could be boolean)- if (byteArray.length === 1 && (byteArray[0] === 0 || byteArray[0] === 1)) {- return "BOOLEAN";- }-- // Check if it's readable text- const isReadableText = byteArray.every(byte => byte >= 32 && byte <= 126);- if (isReadableText) {- return "TEXT";- }-- // Return default format based on column type- return defaultFormat;-};--// Current display format (reactive to server changes)-const serverFormat = computed(() => getServerFormat());--// Create a ref for temporary format override-const formatOverride = ref<string | null>(null);--// The actual format to displayconst binaryFormat = computed(() => {- if (formatOverride.value === null) {- return "DEFAULT"; // No override, show as DEFAULT in radio group+ if (!detail.value) {+ return;}- return formatOverride.value;+ return getBinaryFormat({+ rowIndex: detail.value.row,+ colIndex: detail.value.col,+ setIndex: detail.value.set,+ });});// Check if the current value is binary data (using bytesValue)@@ -313,76 +210,37 @@ const isBinaryData = computed(() => {return !!rawValue.value.bytesValue;});-// Check if it's a single bit value (for boolean display)-const isSingleBitValue = computed(() => {- if (!rawValue.value?.bytesValue) return false;- return rawValue.value.bytesValue.length === 1;-});-// Format the binary value based on selected format-const formattedBinaryValue = computed(() => {- if (!rawValue.value?.bytesValue) return rawValue.value;-- // Deep clone the value to avoid mutating the original- const newValue = { ...rawValue.value };-- // Get the actual format to use (override or server default)- const actualFormat = formatOverride.value === null ? serverFormat.value : formatOverride.value;-- // Skip formatting if using default format- if (actualFormat === "DEFAULT") {- return newValue;+const formattedValue = computed(() => {+ if (!rawValue.value?.bytesValue) {+ return rawValue.value;}-- // Ensure bytesValue exists before converting to array- const byteArray = newValue.bytesValue ? Array.from(newValue.bytesValue) : [];-- // Format based on selected format- switch (actualFormat) {- case "BINARY":- // Format as binary string without spaces- newValue.stringValue = byteArray- .map(byte => byte.toString(2).padStart(8, "0"))- .join("");- break;- case "HEX":- // Format as hex string- newValue.stringValue = "0x" + byteArray- .map(byte => byte.toString(16).toUpperCase().padStart(2, "0"))- .join("");- break;- case "TEXT":- // Format as text- try {- newValue.stringValue = new TextDecoder().decode(new Uint8Array(byteArray));- } catch {- // Fallback to binary if text decoding fails- newValue.stringValue = byteArray- .map(byte => byte.toString(2).padStart(8, "0"))- .join("");- }- break;- case "BOOLEAN":- // Only for single-byte values- if (byteArray.length === 1) {- newValue.stringValue = byteArray[0] === 1 ? "true" : "false";- }- break;++ // Determine the format to use - column override, cell override, or auto-detected format+ const actualFormat = binaryFormat.value ?? "DEFAULT";++ // Skip formatting for DEFAULT (auto) format+ if (actualFormat === "DEFAULT") {+ return rawValue.value;}-- return newValue;++ const stringValue = formatBinaryValue({+ bytesValue: rawValue.value.bytesValue,+ format: actualFormat,+ });+ return {+ ...rawValue.value,+ stringValue,+ };});const content = computed(() => {- if (!rawValue.value) return undefined;-- // If it's binary data, use the formatted version- if (isBinaryData.value) {- return String(extractSQLRowValuePlain(formattedBinaryValue.value));+ if (!rawValue.value) {+ return;}-+// Otherwise use the raw value- return String(extractSQLRowValuePlain(rawValue.value));+ return String(extractSQLRowValuePlain(formattedValue.value));});const guessedIsJSON = computed(() => {@@ -395,9 +253,7 @@ const guessedIsJSON = computed(() => {});const totalCount = computed(() => {- const { table } = detail.value;- if (!table) return 0;- return table.getPrePaginationRowModel().rows.length;+ return detail.value?.table.getPrePaginationRowModel().rows.length ?? 0;});const contentClass = computed(() => {@@ -417,7 +273,7 @@ const contentClass = computed(() => {const { copy, copied } = useClipboard({source: computed(() => {const raw = content.value ?? "";-+// For JSON contentif (guessedIsJSON.value && format.value) {try {@@ -431,12 +287,12 @@ const { copy, copied } = useClipboard({return raw;}}-+// For binary data, copy according to the selected formatif (isBinaryData.value) {return raw;}-+return raw;}),legacy: true,@@ -454,6 +310,9 @@ const handleCopy = () => {};const move = (offset: number) => {+ if (!detail.value) {+ return;+ }const target = detail.value.row + offset;if (target < 0 || target >= totalCount.value) return;detail.value.row = target;@@ -469,18 +328,4 @@ onKeyStroke("ArrowDown", (e) => {e.stopPropagation();move(1);});--// Method to handle binary format updates and ensure re-rendering-const updateBinaryFormat = (value: string) => {- // If DEFAULT is selected, remove the override- if (value === "DEFAULT") {- formatOverride.value = null;- } else {- // Otherwise set the override- formatOverride.value = value;- }-- // Force render- nextTick();-};</script>diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/ResultViewV1.vue b/frontend/src/views/sql-editor/EditorCommon/ResultView/ResultViewV1.vueindex 783e652392..e97e10e748 100644--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/ResultViewV1.vue+++ b/frontend/src/views/sql-editor/EditorCommon/ResultView/ResultViewV1.vue@@ -108,13 +108,24 @@</template></div>- <Drawer v-model:show="detail.show" @close="detail.show = false">- <DetailPanel v-if="detail.show" />+ <Drawer :show="!!detail" @close="detail = undefined">+ <DetailPanel /></Drawer></NConfigProvider></template><script lang="ts" setup>+import { Info } from "lucide-vue-next";+import {+ darkTheme,+ NConfigProvider,+ NTabPane,+ NTabs,+ NTooltip,+} from "naive-ui";+import { Status } from "nice-grpc-common";+import { computed, ref, toRef } from "vue";+import { useI18n } from "vue-i18n";import { darkThemeOverrides } from "@/../naive-ui.config";import { BBSpin } from "@/bbkit";import SyncDatabaseButton from "@/components/DatabaseDetail/SyncDatabaseButton.vue";@@ -123,7 +134,7 @@ import { Drawer } from "@/components/v2";import {useAppFeature,useConnectionOfCurrentSQLEditorTab,- usePolicyV1Store+ usePolicyV1Store,} from "@/store";import type {ComposedDatabase,@@ -133,17 +144,7 @@ import type {} from "@/types";import { PolicyType } from "@/types/proto/v1/org_policy_service";import { hasWorkspacePermissionV2 } from "@/utils";-import { Info } from "lucide-vue-next";-import {- darkTheme,- NConfigProvider,- NTabPane,- NTabs,- NTooltip,-} from "naive-ui";-import { Status } from "nice-grpc-common";-import { computed, ref, toRef } from "vue";-import { useI18n } from "vue-i18n";+import { provideBinaryFormatContext } from "./DataTable/binary-format-store";import DetailPanel from "./DetailPanel";import EmptyView from "./EmptyView.vue";import ErrorView from "./ErrorView";@@ -161,6 +162,7 @@ const props = withDefaults(resultSet?: SQLResultSetV1;loading?: boolean;dark?: boolean;+ contextId: string;}>(),{executeParams: undefined,@@ -185,13 +187,9 @@ const disallowSyncSchema = useAppFeature("bb.feature.sql-editor.disallow-sync-schema");const keyword = ref("");-const detail: SQLResultViewContext["detail"] = ref({- show: false,- set: 0,- row: 0,- col: 0,- table: undefined,-});+const detail: SQLResultViewContext["detail"] = ref(undefined);++provideBinaryFormatContext(computed(() => props.contextId));const missingResource = computed((): DatabaseResource | undefined => {if (props.resultSet?.status !== Status.PERMISSION_DENIED) {@@ -209,10 +207,7 @@ const missingResource = computed((): DatabaseResource | undefined => {});const showRequestQueryButton = computed(() => {- return (- !disallowRequestQuery.value &&- missingResource.value- );+ return !disallowRequestQuery.value && missingResource.value;});const viewMode = computed((): ViewMode => {@@ -292,34 +287,10 @@ const filteredResults = computed(() => {});});-// Create a ref for column type names to share via context-// This needs to update when the user switches result tabs-const columnTypeNamesRef = computed(() => {- // If no result set, return undefined- if (!props.resultSet?.results) return undefined;-- // For single result mode, use the first result- if (viewMode.value === "SINGLE-RESULT") {- return props.resultSet.results[0]?.columnTypeNames;- }-- // For multi-result mode, use the active tab's result- // The active tab corresponds to the detail.set value- if (- viewMode.value === "MULTI-RESULT" &&- detail.value.set < filteredResults.value.length- ) {- return filteredResults.value[detail.value.set]?.columnTypeNames;- }-- return undefined;-});-provideSQLResultViewContext({dark: toRef(props, "dark"),disallowCopyingData,keyword,detail,- columnTypeNames: columnTypeNamesRef,});</script>diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/SelectionCopyTooltips.vue b/frontend/src/views/sql-editor/EditorCommon/ResultView/SelectionCopyTooltips.vueindex dc879e29f5..7c4c50534f 100644--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/SelectionCopyTooltips.vue+++ b/frontend/src/views/sql-editor/EditorCommon/ResultView/SelectionCopyTooltips.vue@@ -33,6 +33,11 @@</NButton></template></i18n-t>+ <div class="ml-1">+ <NButton size="tiny" secondary @click="deselect">+ {{ $t("sql-editor.cancel-selection") }}+ </NButton>+ </div></div></template>@@ -45,7 +50,7 @@ import { pushNotification } from "@/store";import { useSelectionContext } from "./DataTable/common/selection-logic";const { t } = useI18n();-const { state: selectionState, copy } = useSelectionContext();+const { state: selectionState, copy, deselect } = useSelectionContext();const shouldShow = computed(() =>diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/SingleResultViewV1.vue b/frontend/src/views/sql-editor/EditorCommon/ResultView/SingleResultViewV1.vueindex 95db5a2569..408b28b88e 100644--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/SingleResultViewV1.vue+++ b/frontend/src/views/sql-editor/EditorCommon/ResultView/SingleResultViewV1.vue@@ -137,7 +137,6 @@:offset="pageIndex * pageSize":is-sensitive-column="isSensitiveColumn":is-column-missing-sensitive="isColumnMissingSensitive"- :column-type-names="props.result.columnTypeNames"/></div>@@ -390,7 +389,7 @@ const columns = computed(() => {header: columnName,meta: {// Store column type in meta for easy access by other components- columnType: columnType,+ columnType,},sortingFn: (rowA, rowB) => {return compareQueryRowValues(@@ -405,11 +404,10 @@ const columns = computed(() => {});const data = computed(() => {- const data = props.result.rows;+ let temp = props.result.rows;const search = keyword.value.trim().toLowerCase();- let temp = data;if (search) {- temp = data.filter((item) => {+ temp = temp.filter((item) => {return item.values.some((col) => {const value = extractSQLRowValuePlain(col);if (isNullOrUndefined(value)) {diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/context.ts b/frontend/src/views/sql-editor/EditorCommon/ResultView/context.tsindex c9911b68c7..ee28c0558a 100644--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/context.ts+++ b/frontend/src/views/sql-editor/EditorCommon/ResultView/context.ts@@ -6,14 +6,15 @@ export type SQLResultViewContext = {dark: Ref<boolean>;disallowCopyingData: Ref<boolean>;keyword: Ref<string>;- columnTypeNames?: Ref<string[] | undefined>; // Column type names from QueryResult- detail: Ref<{- show: boolean;- set: number; // The index of selected result set.- row: number; // The row index of selected record.- col: number; // The column index of selected cell.- table: Table<QueryRow> | undefined;- }>;+ detail: Ref<+ | {+ set: number; // The index of selected result set.+ row: number; // The row index of selected record.+ col: number; // The column index of selected cell.+ table: Table<QueryRow>;+ }+ | undefined+ >;};export const KEY = Symbol(diff --git a/frontend/src/views/sql-editor/EditorPanel/ResultPanel/DatabaseQueryContext.vue b/frontend/src/views/sql-editor/EditorPanel/ResultPanel/DatabaseQueryContext.vueindex 0506460cdd..e953ad2707 100644--- a/frontend/src/views/sql-editor/EditorPanel/ResultPanel/DatabaseQueryContext.vue+++ b/frontend/src/views/sql-editor/EditorPanel/ResultPanel/DatabaseQueryContext.vue@@ -31,7 +31,7 @@class="w-full h-auto grow":execute-params="context.params":database="database"- :context="context"+ :context-id="context.id":result-set="context.resultSet"@execute="execQuery"/>diff --git a/frontend/src/views/sql-editor/EditorPanel/TerminalPanel/TerminalPanel.vue b/frontend/src/views/sql-editor/EditorPanel/TerminalPanel/TerminalPanel.vueindex 6c5b96e3b5..9e219189fb 100644--- a/frontend/src/views/sql-editor/EditorPanel/TerminalPanel/TerminalPanel.vue+++ b/frontend/src/views/sql-editor/EditorPanel/TerminalPanel/TerminalPanel.vue@@ -45,6 +45,7 @@:database="databaseStore.getDatabaseByName(query.params.connection.database)"+ :context-id="query.id":loading="query.status === 'RUNNING'":dark="true"/>