Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

chore: binary fix for MySQL (#15634)

Vincent Huang347bcaa6a4e1
diff --git a/backend/plugin/db/mysql/query.go b/backend/plugin/db/mysql/query.go
index 4a6a03be2d..711597caa1 100644
--- a/backend/plugin/db/mysql/query.go
+++ b/backend/plugin/db/mysql/query.go
@@ -29,7 +29,7 @@ func makeValueByTypeName(typeName string, _ *sql.ColumnType) any {
return new(sql.NullInt64)
case "FLOAT", "DOUBLE", "FLOAT4", "FLOAT8":
return new(sql.NullFloat64)
- case "BIT", "VARBIT":
+ case "BIT", "VARBIT", "BINARY", "VARBINARY":
return new([]byte)
default:
return new(sql.NullString)
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index b8c94c902f..656bf56067 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -222,7 +222,7 @@
"encoding": "Encoding",
"finish": "Finish",
"title": "Title",
- "text-wrap": "Text wrap",
+ "text-wrap": "Text Wrap",
"catalog": "Catalog",
"summary": "Summary",
"errors": "Errors",
@@ -1733,6 +1733,10 @@
"vertical-display": "Vertical display",
"no-history-found": "No history found",
"search-history": "Search History",
+ "binary-format": "Binary format",
+ "hex-format": "Hexadecimal format",
+ "boolean-format": "Boolean format",
+ "text-format": "Text format",
"hint-tips": {
"confirm-to-close-unsaved-sheet": {
"title": "Close the unsaved sheet?",
@@ -1794,8 +1798,6 @@
},
"executing-query": "Executing query",
"request-query": "Request query",
- "previous-row": "Previous row",
- "next-row": "Next row",
"copy-success": "Copy success",
"connect-in-new-tab": "Connect in new tab",
"copy-name": "Copy name",
@@ -1845,7 +1847,11 @@
"contact-the-admin-to-grant-access": "Contact to the admin to grant access."
},
"upload-file": "Upload file",
- "copy-selected-results": "Copy selected data by {action} or {button}"
+ "copy-selected-results": "Copy selected data by {action} or {button}",
+ "format-default": "Default",
+ "column-display-format": "Column Display Format",
+ "next-row": "Next Row",
+ "previous-row": "Previous Row"
},
"schema-editor": {
"self": "Schema Editor",
diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.json
index 115d77cd05..ee862a1da3 100644
--- a/frontend/src/locales/es-ES.json
+++ b/frontend/src/locales/es-ES.json
@@ -1733,6 +1733,10 @@
"vertical-display": "Pantalla vertical",
"no-history-found": "No se encontró historial",
"search-history": "Historial de búsqueda",
+ "binary-format": "Formato binario",
+ "hex-format": "Formato hexadecimal",
+ "boolean-format": "Formato booleano",
+ "text-format": "Formato de texto",
"hint-tips": {
"confirm-to-close-unsaved-sheet": {
"title": "¿Cerrar la hoja no guardada?",
@@ -1845,7 +1849,9 @@
"contact-the-admin-to-grant-access": "Póngase en contacto con el administrador para otorgar acceso."
},
"upload-file": "Subir archivo",
- "copy-selected-results": "Copiar datos seleccionados por {action} o {button}"
+ "copy-selected-results": "Copiar datos seleccionados por {action} o {button}",
+ "format-default": "Por defecto",
+ "column-display-format": "Formato de visualización de columna"
},
"schema-editor": {
"self": "Editor de esquema",
@@ -2597,4 +2603,4 @@
"last-visit": "Última visita",
"changelog-for-version": "Registro de cambios para {version}"
}
-}
\ No newline at end of file
+}
diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.json
index 92de392abe..e9790a7ce3 100644
--- a/frontend/src/locales/ja-JP.json
+++ b/frontend/src/locales/ja-JP.json
@@ -1845,7 +1845,13 @@
"contact-the-admin-to-grant-access": "管理者に連絡してアクセスを許可してください。"
},
"upload-file": "ファイルをアップロードする",
- "copy-selected-results": "選択したデータを{action}または{button}でコピーします"
+ "copy-selected-results": "選択したデータを{action}または{button}でコピーします",
+ "binary-format": "バイナリ形式",
+ "format-default": "デフォルト",
+ "hex-format": "16進形式",
+ "text-format": "テキスト形式",
+ "boolean-format": "ブール形式",
+ "column-display-format": "列表示形式"
},
"schema-editor": {
"self": "スキーマエディタ",
@@ -2597,4 +2603,4 @@
"last-visit": "最終訪問",
"changelog-for-version": "{version} の変更履歴"
}
-}
\ No newline at end of file
+}
diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.json
index bbbe62ea8f..506ea9b959 100644
--- a/frontend/src/locales/vi-VN.json
+++ b/frontend/src/locales/vi-VN.json
@@ -1733,6 +1733,10 @@
"vertical-display": "Hiển thị dọc",
"no-history-found": "Không tìm thấy lịch sử",
"search-history": "Tìm kiếm Lịch sử",
+ "binary-format": "Định dạng nhị phân",
+ "hex-format": "Định dạng thập lục phân",
+ "boolean-format": "Định dạng Boolean",
+ "text-format": "Định dạng văn bản",
"hint-tips": {
"confirm-to-close-unsaved-sheet": {
"title": "Đóng trang tính chưa lưu?",
@@ -1845,7 +1849,9 @@
"contact-the-admin-to-grant-access": "Liên hệ với quản trị viên để cấp quyền truy cập."
},
"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}"
+ "copy-selected-results": "Sao chép dữ liệu đã chọn bằng {action} hoặc {button}",
+ "format-default": "Mặc định",
+ "column-display-format": "Định dạng hiển thị cột"
},
"schema-editor": {
"self": "Trình soạn thảo lược đồ",
@@ -2597,4 +2603,4 @@
"last-visit": "Lần truy cập cuối",
"changelog-for-version": "Nhật ký thay đổi cho phiên bản {version}"
}
-}
\ No newline at end of file
+}
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index 7ef6e558b3..7e1825dc84 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -1733,6 +1733,10 @@
"vertical-display": "竖向展示",
"no-history-found": "暂无历史记录",
"search-history": "搜索历史记录",
+ "binary-format": "二进制格式",
+ "hex-format": "十六进制格式",
+ "boolean-format": "布尔格式",
+ "text-format": "文本格式",
"hint-tips": {
"confirm-to-close-unsaved-sheet": {
"title": "确定关闭未保存的工作表?",
@@ -1845,7 +1849,9 @@
"contact-the-admin-to-grant-access": "联系管理员以授予访问权限。"
},
"upload-file": "上传文件",
- "copy-selected-results": "通过 {action} 或 {button} 来快速复制选定的数据"
+ "copy-selected-results": "通过 {action} 或 {button} 来快速复制选定的数据",
+ "format-default": "默认",
+ "column-display-format": "列显示格式"
},
"schema-editor": {
"self": "Schema 编辑器",
diff --git a/frontend/src/utils/v1/sql.ts b/frontend/src/utils/v1/sql.ts
index e2465f3db8..48f0944ea5 100644
--- a/frontend/src/utils/v1/sql.ts
+++ b/frontend/src/utils/v1/sql.ts
@@ -22,19 +22,47 @@ export const extractSQLRowValuePlain = (value: RowValue | undefined) => {
const plainObject = RowValue.toJSON(value) as Record<string, any>;
const keys = Object.keys(plainObject);
if (keys.length === 0) {
- return undefined; // Will bi displayed as "UNSET"
+ return undefined; // Will be displayed as "UNSET"
}
if (keys.length > 1) {
console.debug("mixed type in row value", value);
}
+
+ // First check if there's a formatted stringValue which should take precedence
+ if (value.stringValue) {
+ return value.stringValue;
+ }
+
+ // Handle binary data with auto-format detection
if (value.bytesValue) {
+ // Ensure bytesValue exists before converting to array
const byteArray = Array.from(value.bytesValue);
- const binaryString = byteArray
- .map((byte) => byte.toString(2).padStart(8, "0"))
- .join("")
- .replace(/^0+/g, "");
- return binaryString.length === 0 ? "0" : binaryString;
+
+ // For single byte/bit values (could be boolean)
+ if (byteArray.length === 1) {
+ // If it's 0 or 1, display as boolean
+ if (byteArray[0] === 0 || byteArray[0] === 1) {
+ return byteArray[0] === 1 ? "true" : "false";
+ }
+ }
+
+ // Check if it's readable text
+ const isReadableText = byteArray.every(byte => byte >= 32 && byte <= 126);
+ if (isReadableText) {
+ try {
+ return new TextDecoder().decode(new Uint8Array(byteArray));
+ } catch {
+ // If text decoding fails, fallback to hex
+ }
+ }
+
+ // The column type isn't available in this context
+ // Default to HEX format for most binary data as it's more compact
+ return "0x" + byteArray
+ .map((byte) => byte.toString(16).toUpperCase().padStart(2, "0"))
+ .join("");
}
+
if (value.timestampValue && value.timestampValue.googleTimestamp) {
return formatTimestamp(value.timestampValue);
}
diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/DataTable.vue b/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/DataTable.vue
index 7fe5e13331..7cde13ea96 100644
--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/DataTable.vue
+++ b/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/DataTable.vue
@@ -64,6 +64,17 @@
header.column.getToggleSortingHandler()?.($event)
"
/>
+
+ <!-- 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)"
+ @click.stop
+ />
</div>
<!-- The drag-to-resize handler -->
@@ -96,6 +107,8 @@
:row-index="offset + rowIndex"
:col-index="cellIndex"
:allow-select="true"
+ :column-format-override="getColumnFormatOverride(cellIndex)"
+ :column-type="props.columnTypeNames?.[cellIndex]"
/>
<div
v-if="cellIndex === 0 && !selectionDisabled"
@@ -129,11 +142,12 @@ import {
FeatureBadgeForInstanceLicense,
} from "@/components/FeatureGuard";
import { useSubscriptionV1Store } from "@/store";
-import type { QueryRow, RowValue } from "@/types/proto/v1/sql_service";
+import { type QueryRow, type RowValue } from "@/types/proto/v1/sql_service";
import { useSQLResultViewContext } from "../context";
import TableCell from "./TableCell.vue";
import ColumnSortedIcon from "./common/ColumnSortedIcon.vue";
import SensitiveDataIcon from "./common/SensitiveDataIcon.vue";
+import BinaryFormatButton from "./common/BinaryFormatButton.vue";
import { useSelectionContext } from "./common/selection-logic";
import useTableColumnWidthLogic from "./useTableResize";
@@ -144,6 +158,7 @@ const props = defineProps<{
isSensitiveColumn: (index: number) => boolean;
isColumnMissingSensitive: (index: number) => boolean;
maxHeight?: number;
+ columnTypeNames?: string[]; // Column type names from QueryResult
}>();
const {
@@ -171,6 +186,155 @@ const hasSensitiveFeature = computed(() => {
const rows = computed(() => props.table.getRowModel().rows);
+// 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;
+};
+
+// 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();
+ }
+
+ // 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) {
+ 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;
+ }
+ }
+
+ 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);
+ }
+
+ // Force a re-render
+ columnFormatOverrides.value = new Map(columnFormatOverrides.value);
+};
+
onMounted(() => {
nextTick(() => {
tableResize.reset();
diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/TableCell.vue b/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/TableCell.vue
index 6b6e24e6a2..6a84484f24 100644
--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/TableCell.vue
+++ b/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/TableCell.vue
@@ -5,14 +5,31 @@
:class="classes"
@click="handleClick"
@dblclick="showDetail"
+ @contextmenu.prevent="handleContextMenu"
+ ref="cellRef"
>
<div
ref="wrapperRef"
class="whitespace-nowrap font-mono text-start line-clamp-1"
v-html="html"
></div>
- <div v-if="clickable" class="absolute right-1 top-1/2 translate-y-[-45%]">
+ <div 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>
+
+ <!-- Expand button for long content -->
+ <NButton
+ v-if="clickable"
size="tiny"
circle
class="dark:!bg-dark-bg"
@@ -23,6 +40,18 @@
</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>
@@ -30,15 +59,17 @@
import { type Table } from "@tanstack/vue-table";
import { useResizeObserver } from "@vueuse/core";
import { escape } from "lodash-es";
-import { NButton } from "naive-ui";
+import { Code as IconCode } from "lucide-vue-next";
+import { NButton, NDropdown } from "naive-ui";
import { twMerge } from "tailwind-merge";
-import { computed, ref } from "vue";
+import { computed, nextTick, ref } 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 { useSelectionContext } from "./common/selection-logic";
+import { useI18n } from "vue-i18n";
const props = defineProps<{
table: Table<QueryRow>;
@@ -47,8 +78,11 @@ const props = defineProps<{
rowIndex: number;
colIndex: number;
allowSelect?: boolean;
+ columnFormatOverride?: string | null;
+ columnType?: string; // Column type from QueryResult
}>();
+const { t } = useI18n();
const { detail, keyword } = useSQLResultViewContext();
const {
@@ -58,12 +92,80 @@ const {
selectRow,
} = useSelectionContext();
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;
});
+// Check if the value is binary data
+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;
+});
+
+// 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,
+ });
+ }
+
+ // Add a checkmark to the currently selected option
+ options.forEach(option => {
+ if (option.key === currentFormat) {
+ option.label = "✓ " + option.label;
+ }
+ });
+
+ return options;
+});
+
useResizeObserver(wrapperRef, (entries) => {
const div = entries[0].target as HTMLDivElement;
const contentWidth = div.scrollWidth;
@@ -120,8 +222,131 @@ const classes = computed(() => {
return twMerge(classes);
});
+// 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;
+ }
+ // Otherwise use auto-detected format
+ else {
+ // Use column type directly from props if available
+ const columnType = props.columnType?.toLowerCase() || '';
+
+ // Default format based on column type
+ let defaultFormat = "BINARY";
+
+ // Detect BIT column types - for binary format display (0s and 1s)
+ const isBitColumn = (
+ columnType === 'bit' ||
+ columnType.startsWith('bit(') ||
+ (columnType.includes('bit') && !columnType.includes('binary')) ||
+ columnType === 'varbit' ||
+ columnType === 'bit varying'
+ );
+
+ // Detect BINARY column types - for hex format display (0x...)
+ const isBinaryColumn = (
+ columnType === 'binary' ||
+ columnType.includes('binary') ||
+ columnType.startsWith('binary(') ||
+ columnType.startsWith('varbinary') ||
+ columnType.includes('blob') ||
+ columnType === 'bytea'
+ );
+
+ // Set default format based on column type
+ if (isBitColumn) {
+ defaultFormat = "BINARY";
+ } else if (isBinaryColumn) {
+ defaultFormat = "HEX";
+ }
+
+ // Now also consider content-based auto-detection
+ const byteArray = newValue.bytesValue ? Array.from(newValue.bytesValue) : [];
+
+ // For single bit values (could be boolean)
+ if (byteArray.length === 1 && (byteArray[0] === 0 || byteArray[0] === 1)) {
+ actualFormat = "BOOLEAN";
+ }
+ // Check if it's readable text
+ else if (byteArray.every(byte => byte >= 32 && byte <= 126)) {
+ actualFormat = "TEXT";
+ }
+ // Default to format based on column type
+ else {
+ actualFormat = defaultFormat;
+ }
+ }
+
+ // Skip formatting for DEFAULT (auto) format
+ if (actualFormat === "DEFAULT") {
+ return newValue;
+ }
+
+ // 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 html = computed(() => {
- const value = extractSQLRowValuePlain(props.value);
+ // 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);
+
if (value === undefined) {
return `<span class="text-gray-400 italic">UNSET</span>`;
}
@@ -167,4 +392,37 @@ const showDetail = () => {
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) => {
+ // If DEFAULT is selected, remove the override
+ if (key === "DEFAULT") {
+ formatOverride.value = null;
+ } else {
+ // Otherwise set the override
+ formatOverride.value = key;
+ }
+
+ showFormatMenu.value = false;
+
+ // Force recomputation of html
+ nextTick();
+};
</script>
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.vue
new file mode 100644
index 0000000000..e5a7b0bbf2
--- /dev/null
+++ b/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/common/BinaryFormatButton.vue
@@ -0,0 +1,91 @@
+<!-- Button to change binary data format for an entire column -->
+<template>
+ <div>
+ <NPopover trigger="click" placement="bottom">
+ <template #trigger>
+ <NButton
+ size="tiny"
+ circle
+ class="ml-1 dark:!bg-dark-bg"
+ @click.stop
+ :type="hasColumnOverride ? 'primary' : 'default'"
+ :secondary="hasColumnOverride"
+ >
+ <template #icon>
+ <IconCode 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>
+ <NRadioGroup
+ :value="currentColumnFormat"
+ class="flex flex-col gap-2"
+ @update:value="updateColumnFormat"
+ >
+ <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="TEXT">
+ {{ $t("sql-editor.text-format") }}
+ </NRadio>
+ <NRadio value="BOOLEAN" v-if="hasSingleBitValues">
+ {{ $t("sql-editor.boolean-format") }}
+ </NRadio>
+ </NRadioGroup>
+ </div>
+ </template>
+ </NPopover>
+ </div>
+</template>
+
+<script setup lang="ts">
+import { Code as IconCode } from "lucide-vue-next";
+import { NButton, NPopover, NRadioGroup, NRadio } from "naive-ui";
+import { computed } from "vue";
+
+// Event interface
+const emit = defineEmits<{
+ (e: "update:format", format: string | null): void;
+}>();
+
+// Props
+const 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;
+}>();
+
+// 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 group
+const currentColumnFormat = computed(() => {
+ return props.columnFormat || "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
diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/DetailPanel/DetailPanel.vue b/frontend/src/views/sql-editor/EditorCommon/ResultView/DetailPanel/DetailPanel.vue
index b411d0eb6b..fa70ca2290 100644
--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/DetailPanel/DetailPanel.vue
+++ b/frontend/src/views/sql-editor/EditorCommon/ResultView/DetailPanel/DetailPanel.vue
@@ -74,6 +74,44 @@
{{ $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>
+
<NButton v-if="!disallowCopyingData" size="small" @click="handleCopy">
<template #icon>
<ClipboardIcon class="w-4 h-4" />
@@ -132,9 +170,10 @@ import {
ClipboardIcon,
BracesIcon,
WrapTextIcon,
+ Code as Code2Icon,
} from "lucide-vue-next";
-import { NButton, NPopover, NScrollbar, NTooltip } from "naive-ui";
-import { computed } from "vue";
+import { NButton, NPopover, NScrollbar, NTooltip, NRadioGroup, NRadio } from "naive-ui";
+import { computed, nextTick, ref } from "vue";
import { useI18n } from "vue-i18n";
import { DrawerContent } from "@/components/v2";
import { pushNotification } from "@/store";
@@ -155,16 +194,195 @@ const wrap = useLocalStorage<boolean>(
true
);
-const content = computed(() => {
+// Get the current value being displayed first
+const rawValue = computed(() => {
const { row, col, table } = detail.value;
if (!table) return undefined;
- const value = table
+ 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;
+};
- return String(extractSQLRowValuePlain(value));
+// 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 display
+const binaryFormat = computed(() => {
+ if (formatOverride.value === null) {
+ return "DEFAULT"; // No override, show as DEFAULT in radio group
+ }
+ return formatOverride.value;
+});
+
+// Check if the current value is binary data (using bytesValue)
+const isBinaryData = computed(() => {
+ if (!rawValue.value) return false;
+ 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;
+ }
+
+ // 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;
+ }
+
+ return newValue;
+});
+
+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));
+ }
+
+ // Otherwise use the raw value
+ return String(extractSQLRowValuePlain(rawValue.value));
});
const guessedIsJSON = computed(() => {
@@ -199,6 +417,8 @@ const contentClass = computed(() => {
const { copy, copied } = useClipboard({
source: computed(() => {
const raw = content.value ?? "";
+
+ // For JSON content
if (guessedIsJSON.value && format.value) {
try {
const obj = JSON.parse(raw);
@@ -211,6 +431,12 @@ const { copy, copied } = useClipboard({
return raw;
}
}
+
+ // For binary data, copy according to the selected format
+ if (isBinaryData.value) {
+ return raw;
+ }
+
return raw;
}),
legacy: true,
@@ -243,4 +469,18 @@ 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.vue
index 5ffc89a889..39cc72749b 100644
--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/ResultViewV1.vue
+++ b/frontend/src/views/sql-editor/EditorCommon/ResultView/ResultViewV1.vue
@@ -282,10 +282,31 @@ 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/SingleResultViewV1.vue b/frontend/src/views/sql-editor/EditorCommon/ResultView/SingleResultViewV1.vue
index e978161c0b..abacf2189e 100644
--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/SingleResultViewV1.vue
+++ b/frontend/src/views/sql-editor/EditorCommon/ResultView/SingleResultViewV1.vue
@@ -122,6 +122,7 @@
:offset="pageIndex * pageSize"
:is-sensitive-column="isSensitiveColumn"
:is-column-missing-sensitive="isColumnMissingSensitive"
+ :column-type-names="props.result.columnTypeNames"
/>
</div>
@@ -341,10 +342,15 @@ const columns = computed(() => {
return props.result.columnNames.map<ColumnDef<QueryRow, RowValue>>(
(columnName, index) => {
const columnType = props.result.columnTypeNames[index] as string;
+
return {
id: `${columnName}@${index}`,
accessorFn: (item) => item.values[index],
header: columnName,
+ meta: {
+ // Store column type in meta for easy access by other components
+ columnType: columnType
+ },
sortingFn: (rowA, rowB) => {
return compareQueryRowValues(
columnType,
diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/context.ts b/frontend/src/views/sql-editor/EditorCommon/ResultView/context.ts
index 3509d12680..c9911b68c7 100644
--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/context.ts
+++ b/frontend/src/views/sql-editor/EditorCommon/ResultView/context.ts
@@ -6,6 +6,7 @@ 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.