feat(mongodb): distinguish missing fields from BSON null in grid

This commit is contained in:
二丫讲梵 authored and GitHub committed 2026-09-10 11:59:28 +08:00
1 parent 464f2f33c5
commit 0f07d337c3
16 files changed
+542 -69

No files matched your search

@@ -0,0 +1,62 @@
// @vitest-environment happy-dom
import { computed, ref } from "vue";
import { describe, expect, it, vi } from "vitest";
import { useDataGridCellDetailEdit } from "@/composables/useDataGridCellDetailEdit";
import { MONGO_DOCUMENT_GRID_NULL } from "@/lib/mongo/mongoDocumentValues";
import type { DataGridCellDetail } from "@/lib/dataGrid/dataGridDetail";
function detail(value: string): DataGridCellDetail {
return {
rowNumber: 1,
rowId: 3,
colIndex: 1,
column: "value",
type: "",
comment: "",
value,
rawValue: value,
rawValuePreview: value,
displayValue: "NULL",
displayValuePreview: "NULL",
isValuePreviewTruncated: false,
imagePreviewUrl: null,
length: value.length,
formattedJson: "",
isEditable: true,
};
}
describe("useDataGridCellDetailEdit", () => {
it("preserves the Mongo collection null marker in detail editing and set-null", async () => {
const activeDetail = ref<DataGridCellDetail | null>(detail(MONGO_DOCUMENT_GRID_NULL));
const applyCellValue = vi.fn();
const editorText = (value: string | number | boolean | null) => (value === MONGO_DOCUMENT_GRID_NULL ? "NULL" : String(value ?? ""));
const editor = useDataGridCellDetailEdit({
activeDetail: computed(() => activeDetail.value),
activeTab: ref("details"),
jsonFormatted: computed(() => false),
databaseType: computed(() => "mongodb"),
resultRows: computed(() => [["id", MONGO_DOCUMENT_GRID_NULL]]),
getColumnInfo: () => undefined,
cellEditorText: editorText,
nullValue: () => MONGO_DOCUMENT_GRID_NULL,
getRowItem: () => ({ sourceIndex: 0, isNew: false, isDeleted: false }),
hydrateLargeValueCell: async () => true,
applyCellValue,
restoreCellValue: vi.fn(),
syncEditor: vi.fn(),
refreshDetail: vi.fn(),
warnFormattedJsonEdit: vi.fn(),
});
await editor.startDetailEdit();
expect(editor.detailEditValue.value).toBe("NULL");
editor.commitDetailEdit();
expect(applyCellValue).toHaveBeenLastCalledWith(3, 1, MONGO_DOCUMENT_GRID_NULL);
editor.setDetailNull();
expect(applyCellValue).toHaveBeenLastCalledWith(3, 1, MONGO_DOCUMENT_GRID_NULL);
});
});
@@ -2,6 +2,8 @@
import { computed, nextTick, ref, type Ref } from "vue";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { clearDataGridPendingSnapshot, DATA_GRID_QUICK_ENTRY_DRAFT_ROW_ID, useDataGridEditor } from "@/composables/useDataGridEditor";
import { clearDataGridClipboardCopy, parseDataGridClipboard, rememberDataGridClipboardCopy } from "@/lib/dataGrid/dataGridClipboard";
import { buildMongoUpdateDocument, MONGO_DOCUMENT_GRID_NULL, mongoDocumentGridInputValue, mongoDocumentGridValue } from "@/lib/mongo/mongoDocumentValues";
import type { CellValue } from "@/lib/dataGrid/cellValue";
const mocks = vi.hoisted(() => ({
@@ -46,6 +48,7 @@ function createEditorWithResult(
existingRows: CellValue[][] = [],
onCellValueChanged?: (rowId: number, columnIndex: number) => void,
tableColumns?: Array<{ name: string; data_type: string; extra?: string; column_default?: string }>,
mongoCollectionGrid = false,
) {
let editor: ReturnType<typeof useDataGridEditor>;
const result = ref<{ columns: string[]; rows: CellValue[][] }>({
@@ -56,7 +59,8 @@ function createEditorWithResult(
editor = useDataGridEditor({
result: computed(() => result.value),
editable: computed(() => true),
databaseType: computed(() => "postgres"),
databaseType: computed(() => (mongoCollectionGrid ? "mongodb" : "postgres")),
normalizeEditorInput: mongoCollectionGrid ? mongoDocumentGridInputValue : undefined,
connectionId: computed(() => "connection-1"),
database: computed(() => "app"),
tableMeta: computed(() => ({
@@ -1188,3 +1192,21 @@ describe("useDataGridEditor cell edit focus", () => {
vi.unstubAllGlobals();
});
});
describe("Mongo collection-grid clipboard round-trip", () => {
it.each([null, MONGO_DOCUMENT_GRID_NULL, "\u0000dbx:mongo-document-grid:string:literal", "NULL"])("preserves BSON value %j through paste and save", (bsonValue) => {
const encoded = mongoDocumentGridValue(bsonValue) as string;
const editor = createEditor(undefined, true, undefined, undefined, [["before", "", ""]], undefined, undefined, true);
try {
// The OS clipboard is display text; the internal matrix retains encoding.
rememberDataGridClipboardCopy("copied text", [[encoded]]);
const pasted = parseDataGridClipboard("copied text")[0]![0]!;
editor.applyCellValue(0, 0, pasted);
const changes = editor.dirtyRows.value.get(0)!;
expect(changes.get(0)).toBe(encoded);
expect(buildMongoUpdateDocument(changes, ["value"], { value: "before" })).toEqual({ $set: { value: bsonValue } });
} finally {
clearDataGridClipboardCopy();
}
});
});
@@ -1,4 +1,5 @@
import { computed, ref } from "vue";
import { createPinia, setActivePinia } from "pinia";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { useDataGridExport, type UseDataGridExportOptions } from "@/composables/useDataGridExport";
import type { DatabaseType } from "@/types/database";
@@ -7,9 +8,10 @@ import { copyToClipboard } from "@/lib/common/clipboard";
import type { DataGridTableMeta } from "@/lib/dataGrid/dataGridSql";
import type { CellSelectionMatrix, SelectionData } from "@/lib/dataGrid/gridSelection";
import type { CellValue } from "@/lib/dataGrid/cellValue";
import { extractDataGridSelection, exportQueryResultJson } from "@/lib/backend/api";
import { extractDataGridSelection, exportQueryResultCsv, exportQueryResultJson } from "@/lib/backend/api";
import { DEFAULT_DATA_GRID_EXTRACTOR_OPTIONS } from "@/lib/dataGrid/dataGridCopyExtractor";
import { clearDataGridClipboardCopy, parseDataGridClipboard } from "@/lib/dataGrid/dataGridClipboard";
import { MONGO_DOCUMENT_GRID_NULL, mongoDocumentGridExternalValue } from "@/lib/mongo/mongoDocumentValues";
const toast = vi.fn();
@@ -46,6 +48,7 @@ vi.mock("@/lib/backend/api", async (importOriginal) => {
return {
...original,
extractDataGridSelection: vi.fn(),
exportQueryResultCsv: vi.fn(),
exportQueryResultJson: vi.fn(),
};
});
@@ -72,6 +75,7 @@ function createMongoExportState(options: {
contextColumn?: number;
syntheticContext?: boolean;
fullExportResult?: UseDataGridExportOptions["fullExportResult"];
externalCellValue?: UseDataGridExportOptions["externalCellValue"];
}) {
const items = options.items ?? [options.item];
const selectedRowIds = options.selectedRowIds ?? new Set<number>();
@@ -102,6 +106,7 @@ function createMongoExportState(options: {
selectedRowIds: ref(selectedRowIds),
hasRowSelection: computed(() => selectedRowIds.size > 0),
fullExportResult: options.fullExportResult,
externalCellValue: options.externalCellValue,
};
return useDataGridExport(state);
}
@@ -1513,6 +1518,74 @@ describe("useDataGridExport prepared row statements", () => {
expect(copyToClipboard).not.toHaveBeenCalled();
});
it("restores Mongo collection-grid values before bulk copy, extractors, and CSV export", async () => {
const item = { ...row(["1", MONGO_DOCUMENT_GRID_NULL]), sourceIndex: 0 };
const state = createMongoExportState({
columns: ["_id", "nullable"],
item,
mongoDocuments: [{ _id: "1", nullable: null }],
externalCellValue: (value) => mongoDocumentGridExternalValue(value) as CellValue,
selectedCellMatrix: {
rowIndexes: [0],
columnIndexes: [1],
columns: ["nullable"],
rows: [[MONGO_DOCUMENT_GRID_NULL]],
},
});
await state.copyAll();
expect(copyToClipboard).toHaveBeenCalledWith("_id\tnullable\n1\t");
vi.mocked(extractDataGridSelection).mockResolvedValueOnce({ text: "", mimeType: "text/tab-separated-values", fileExtension: "tsv", rowCount: 1, columnCount: 1 });
await expect(state.copyWithExtractor("tsv")).resolves.toBe(true);
expect(extractDataGridSelection).toHaveBeenCalledWith(expect.objectContaining({ rows: [[null]] }));
setActivePinia(createPinia());
await state.exportCurrentPageCsv();
expect(exportQueryResultCsv).toHaveBeenCalledWith(expect.any(String), ["_id", "nullable"], [["1", null]], expect.anything());
const reservedString = MONGO_DOCUMENT_GRID_NULL;
const fullExportState = createMongoExportState({
columns: ["_id", "value"],
item: { ...row(["1", mongoDocumentGridExternalValue(reservedString)]), sourceIndex: 0 },
mongoDocuments: [{ _id: "1", value: reservedString }],
externalCellValue: (value) => mongoDocumentGridExternalValue(value) as CellValue,
fullExportResult: async () => ({
columns: ["_id", "value"],
column_types: ["", ""],
rows: [["1", reservedString]],
mongo_documents: [{ _id: "1", value: reservedString }],
affected_rows: 1,
execution_time_ms: 1,
}),
});
await fullExportState.exportCsv();
expect(exportQueryResultCsv).toHaveBeenLastCalledWith(expect.any(String), ["_id", "value"], [["1", reservedString]], expect.anything());
});
it("exports missing Mongo fields as null while retaining explicit empty strings", async () => {
const columns = ["_id", "missing", "nullable", "empty"];
const document = { _id: "1", nullable: null, empty: "" };
const item = { ...row(["1", "", MONGO_DOCUMENT_GRID_NULL, ""]), sourceIndex: 0 };
const state = createMongoExportState({
columns,
item,
mongoDocuments: [document],
externalCellValue: mongoDocumentGridExternalValue,
fullExportResult: async () => ({
columns,
column_types: ["", "", "", ""],
rows: [item.data],
mongo_copy_documents: [document],
affected_rows: 1,
execution_time_ms: 1,
}),
});
await state.exportJson();
expect(exportQueryResultJson).toHaveBeenCalledWith(expect.any(String), columns, [["1", null, null, ""]]);
});
it("preserves Mongo Extended JSON objects and dates in JSON exports", async () => {
const columns = ["_id", "valueMap", "createdTime"];
const mongoCopyDocument = {
@@ -1,5 +1,5 @@
import { computed, ref, watch, type ComputedRef, type Ref } from "vue";
import { cellDetailEditorText, canFormatCellDetailJson, compactJsonText, formatJsonText, looksLikeJsonContainerText, valueEditorActions, type CellDetailTab } from "@/lib/dataGrid/cellDetailPresentation";
import { canFormatCellDetailJson, compactJsonText, formatJsonText, looksLikeJsonContainerText, valueEditorActions, type CellDetailTab } from "@/lib/dataGrid/cellDetailPresentation";
import type { DataGridCellDetail } from "@/lib/dataGrid/dataGridDetail";
import { dataGridCellEditorText } from "@/lib/dataGrid/dataGridCellCoercion";
import type { CellValue } from "@/lib/dataGrid/cellValue";
@@ -19,6 +19,9 @@ export interface UseDataGridCellDetailEditOptions {
databaseType: ComputedRef<DatabaseType | undefined>;
resultRows: ComputedRef<readonly (readonly CellValue[])[]>;
getColumnInfo: (columnIndex: number) => ColumnInfo | Pick<ColumnInfo, "data_type"> | undefined;
cellEditorText?: (value: CellValue, columnIndex: number) => string;
normalizeEditorInput?: (value: string, columnIndex: number) => string;
nullValue?: (columnIndex: number) => string | null;
getRowItem: (rowId: number) => DetailEditRowItem | undefined;
hydrateLargeValueCell: (rowId: number, columnIndex: number) => Promise<boolean>;
applyCellValue: (rowId: number, columnIndex: number, value: string | null) => void;
@@ -63,6 +66,7 @@ export function useDataGridCellDetailEdit(options: UseDataGridCellDetailEditOpti
});
function editorText(value: CellValue, columnIndex: number): string {
if (options.cellEditorText) return options.cellEditorText(value, columnIndex);
return dataGridCellEditorText({
value,
databaseType: options.databaseType.value,
@@ -131,7 +135,8 @@ export function useDataGridCellDetailEdit(options: UseDataGridCellDetailEditOpti
isEditingDetail.value = false;
const item = options.getRowItem(detail.rowId);
if (!item || item.isDeleted) return;
options.applyCellValue(detail.rowId, detail.colIndex, detailEditValue.value);
const value = detailEditValue.value === detailEditOriginalValue.value && (typeof detail.value === "string" || detail.value === null) ? detail.value : (options.normalizeEditorInput?.(detailEditValue.value, detail.colIndex) ?? detailEditValue.value);
options.applyCellValue(detail.rowId, detail.colIndex, value);
detailEditOriginalValue.value = detailEditValue.value;
allowActiveCellDetailResync = true;
options.refreshDetail();
@@ -175,8 +180,11 @@ export function useDataGridCellDetailEdit(options: UseDataGridCellDetailEditOpti
}
function setValueEditorNull() {
const detail = options.activeDetail.value;
if (!detail || !detail.isEditable) return;
const value = options.nullValue?.(detail.colIndex) ?? null;
setDetailNull();
detailEditValue.value = cellDetailEditorText(null);
detailEditValue.value = editorText(value, detail.colIndex);
detailEditOriginalValue.value = detailEditValue.value;
syncEditorFromDetailEdit();
isEditingDetail.value = options.activeTab.value === "valueEditor";
@@ -211,7 +219,7 @@ export function useDataGridCellDetailEdit(options: UseDataGridCellDetailEditOpti
if (!detail || !detail.isEditable) return;
const item = options.getRowItem(detail.rowId);
if (!item || item.isDeleted) return;
options.applyCellValue(detail.rowId, detail.colIndex, null);
options.applyCellValue(detail.rowId, detail.colIndex, options.nullValue?.(detail.colIndex) ?? null);
resetDetailEdit();
options.refreshDetail();
}
@@ -119,6 +119,10 @@ export interface UseDataGridEditorOptions {
dataGridQuickEntryEnabled?: ComputedRef<boolean>;
confirmDangerousRowDeletion?: ComputedRef<boolean>;
initialEditColumn?: ComputedRef<number>;
/** Converts a grid value to the text presented by the cell editor. */
cellEditorText?: (value: CellValue, columnIndex: number) => string;
/** Normalizes user-entered editor text before cell type coercion. */
normalizeEditorInput?: (value: string, columnIndex: number) => string;
getRowItem: (rowId: number) => RowItem | undefined;
pageSize: Ref<number>;
currentPage: Ref<number>;
@@ -241,6 +245,8 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
dataGridQuickEntryEnabled = computed(() => false),
confirmDangerousRowDeletion = computed(() => true),
initialEditColumn,
cellEditorText,
normalizeEditorInput,
getRowItem,
pageSize,
currentPage,
@@ -640,7 +646,7 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
function coerceCellValue(value: string, oldValue: CellValue | undefined, columnIndex: number, options: ApplyCellValueOptions = {}): CellValue {
return coerceDataGridCellValue({
value,
value: normalizeEditorInput?.(value, columnIndex) ?? value,
oldValue,
databaseType: resolvedDatabaseType.value,
columnInfo: tableColumnForGridColumn(columnIndex),
@@ -650,11 +656,13 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
}
function coerceCommittedCellValue(value: string, currentValue: CellValue | undefined, oldValue: CellValue | undefined, columnIndex: number): CellValue {
const editorText = dataGridCellEditorText({
value: currentValue,
databaseType: resolvedDatabaseType.value,
columnInfo: tableColumnForGridColumn(columnIndex),
});
const editorText =
cellEditorText?.(currentValue ?? null, columnIndex) ??
dataGridCellEditorText({
value: currentValue,
databaseType: resolvedDatabaseType.value,
columnInfo: tableColumnForGridColumn(columnIndex),
});
// Keep the original CellValue when the editor text was not changed. This
// avoids turning a displayed value such as number 1 into string "1" when
// result and table metadata use different representations.
@@ -819,11 +827,13 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
suppressNextBlurCommit = false;
editingCell.value = { rowId, col: colIdx };
const val = item?.data[colIdx] ?? null;
editValue.value = dataGridCellEditorText({
value: val,
databaseType: resolvedDatabaseType.value,
columnInfo: tableColumnForGridColumn(colIdx),
});
editValue.value =
cellEditorText?.(val, colIdx) ??
dataGridCellEditorText({
value: val,
databaseType: resolvedDatabaseType.value,
columnInfo: tableColumnForGridColumn(colIdx),
});
focusEditInput(selectOnFocus);
}
@@ -84,6 +84,8 @@ export interface UseDataGridExportOptions {
mongoUpdateTarget?: ComputedRef<MongoCopyUpdateTarget | undefined>;
databaseType: ComputedRef<DatabaseType | undefined>;
displayValue?: (value: CellValue, columnIndex: number) => string;
cellClipboardText?: (value: CellValue, columnIndex: number) => string | undefined;
externalCellValue?: (value: CellValue, columnIndex: number) => CellValue;
identifierQuote?: ComputedRef<string | undefined>;
connectionId: ComputedRef<string | undefined>;
database: ComputedRef<string | undefined>;
@@ -355,7 +357,7 @@ export function useDataGridExport(options: UseDataGridExportOptions) {
const document = documents[rowIndex];
if (!document || typeof document !== "object" || Array.isArray(document)) return row;
const source = document as Record<string, unknown>;
return columnsToExport.map((column, columnIndex) => (Object.prototype.hasOwnProperty.call(source, column) ? (source[column] as CellValue) : (row[columnIndex] ?? null)));
return columnsToExport.map((column) => (Object.prototype.hasOwnProperty.call(source, column) ? (source[column] as CellValue) : null));
});
}
@@ -366,6 +368,11 @@ export function useDataGridExport(options: UseDataGridExportOptions) {
});
}
function externalizeRows(rows: CellValue[][]): CellValue[][] {
if (!options.externalCellValue) return rows;
return rows.map((row) => row.map((value, columnIndex) => options.externalCellValue!(value, columnIndex)));
}
async function resultToExport(
rowIds?: number[],
onProgress?: (info: { rowsExported: number; totalRows: number | null }) => void,
@@ -386,7 +393,14 @@ export function useDataGridExport(options: UseDataGridExportOptions) {
if (result) {
const columnComments = buildXlsxHeaderOverrides(result.columns, commentsForExportColumns(result.columns), headerMode);
return {
...applyGlobalDateTimeExportFormat({ columns: result.columns, columnTypes: result.column_types ?? [], rows: preserveMongoExtendedJson ? mongoDocumentRowsForJson(result.columns, result.rows, result.mongo_copy_documents) : result.rows }, formatDateTime && !preserveMongoExtendedJson),
...applyGlobalDateTimeExportFormat(
// fullExportResult returns source rows, not the collection grid's
// marker-encoded rows. Applying externalCellValue here would
// mistake a real BSON string in the reserved namespace for a grid
// marker and corrupt the exported value.
{ columns: result.columns, columnTypes: result.column_types ?? [], rows: preserveMongoExtendedJson ? mongoDocumentRowsForJson(result.columns, result.rows, result.mongo_copy_documents) : result.rows },
formatDateTime && !preserveMongoExtendedJson,
),
columnComments,
spatialColumns: result.spatial_columns,
spatialValues: result.spatial_values,
@@ -403,7 +417,7 @@ export function useDataGridExport(options: UseDataGridExportOptions) {
const columnComments = buildXlsxHeaderOverrides(normalized.columns, normalized.columnComments, headerMode);
return {
...applyGlobalDateTimeExportFormat(
{ columns: normalized.columns, columnTypes: normalized.columnTypes, rows: preserveMongoExtendedJson ? mongoDocumentRowsForJson(normalized.columns, normalized.rows, normalized.mongoCopyDocuments) : normalized.rows },
{ columns: normalized.columns, columnTypes: normalized.columnTypes, rows: preserveMongoExtendedJson ? mongoDocumentRowsForJson(normalized.columns, normalized.rows, normalized.mongoCopyDocuments) : externalizeRows(normalized.rows) },
formatDateTime && !preserveMongoExtendedJson,
),
columnComments,
@@ -421,7 +435,7 @@ export function useDataGridExport(options: UseDataGridExportOptions) {
{
columns: columns.value,
columnTypes: (columnTypes.value ?? []).map((type) => type ?? ""),
rows: preserveMongoExtendedJson && databaseType.value === "mongodb" ? mongoLocalRowsForJson(exportItems) : exportItems.map((item) => item.data),
rows: preserveMongoExtendedJson && databaseType.value === "mongodb" ? mongoLocalRowsForJson(exportItems) : externalizeRows(exportItems.map((item) => item.data)),
},
formatDateTime && !preserveMongoExtendedJson,
),
@@ -537,6 +551,11 @@ export function useDataGridExport(options: UseDataGridExportOptions) {
return binaryCellClipboardText(value, columnTypes.value?.[columnIndex], databaseType.value) ?? value;
}
function externalCellValue(value: CellValue, columnIndex: number): CellValue {
const externalValue = options.externalCellValue?.(value, columnIndex);
return externalValue === undefined ? value : externalValue;
}
function rowToJsonObject(item: RowItem): Record<string, unknown> {
if (options.databaseType.value === "mongodb" && item.sourceIndex !== undefined) {
const original = options.mongoDocuments?.value?.[item.sourceIndex];
@@ -545,7 +564,7 @@ export function useDataGridExport(options: UseDataGridExportOptions) {
}
const obj: Record<string, unknown> = {};
columns.value.forEach((col, i) => {
const value = binaryClipboardCellValue(item.data[i], i);
const value = externalCellValue(binaryClipboardCellValue(item.data[i], i), i);
if (typeof value === "string" && columnTypes.value?.[i]?.trim().toLowerCase() === "json") {
try {
obj[col] = JSON.parse(value);
@@ -577,7 +596,7 @@ export function useDataGridExport(options: UseDataGridExportOptions) {
const [resolvedItem] = await resolveVisibleRowValues([item], [sourceIndex]);
const val = resolvedItem?.data[contextCell.value.col] ?? null;
// 外部剪贴板呈现文本型 MySQL VARBINARY(NULL 也按空串输出);内部网格副本仍保留原 hex,保证回粘无损。
const rawValue = clipboardCellValue(binaryClipboardCellValue(val, contextCell.value.col));
const rawValue = options.cellClipboardText?.(val, sourceIndex) ?? clipboardCellValue(binaryClipboardCellValue(val, contextCell.value.col));
const copyValue = options.databaseType.value === "oracle" && isTemporalColumnType(options.columnTypes.value?.[contextCell.value.col]) ? (options.displayValue?.(val, sourceIndex) ?? rawValue) : rawValue;
await copyText(copyValue, { rows: [[val]] });
}
@@ -716,6 +735,10 @@ export function useDataGridExport(options: UseDataGridExportOptions) {
buildMongoInsert: buildMongoExtractorInsert,
buildMongoUpdate: buildMongoExtractorUpdate,
canBuildMongoUpdate: canBuildMongoExtractorUpdate,
externalCellValue: (value, columnIndex) => {
const externalValue = options.externalCellValue?.(value as CellValue, columnIndex);
return externalValue === undefined ? value : externalValue;
},
contextCell,
contextSelectionIsSynthetic,
});
@@ -723,7 +746,7 @@ export function useDataGridExport(options: UseDataGridExportOptions) {
async function copyAll() {
const rows = (await resolveVisibleRowValues(displayItems.value.filter((item) => !item.isDraft))).map((item) => item.data);
// formatTsv 引用处理解码后文本中可能出现的制表符/换行;内部副本仍用原始 rows(hex)保证回粘无损。
const decodedRows = rows.map((row) => row.map((cell, index) => binaryClipboardCellValue(cell, index)));
const decodedRows = rows.map((row) => row.map((cell, index) => externalCellValue(binaryClipboardCellValue(cell, index), index)));
await copyText(formatTsv(columns.value, decodedRows), { rows, header: columns.value });
}
@@ -60,6 +60,7 @@ interface UseDataGridExtractorOptions {
contextCell: ComputedRef<{ rowId: number; rowIndex: number; col: number } | null> | Ref<{ rowId: number; rowIndex: number; col: number } | null>;
contextSelectionIsSynthetic: ComputedRef<boolean> | Ref<boolean>;
copyText: (text: string, gridCopy?: { rows: readonly (readonly unknown[])[]; header?: readonly unknown[] }) => Promise<boolean>;
externalCellValue?: (value: unknown, columnIndex: number) => unknown;
canCopySqlInsert: (request: DataGridExtractRequest) => boolean;
buildMongoInsert: (extractorOptions: DataGridExtractorOptions, rowLimit?: number) => Promise<string | undefined>;
buildMongoUpdate?: (request: DataGridExtractRequest, rowLimit?: number) => Promise<string | undefined>;
@@ -83,12 +84,14 @@ export function useDataGridExtractor(options: UseDataGridExtractorOptions) {
// 除 SQL 外的剪贴板展示格式都可把文本型 MySQL VARBINARY 从 `0x<hex>` 还原为原始字符串。
// SQL 必须继续持有 hex 才能保证 round-trip;rawRows 则始终保存原值,供 DBX 内部网格回粘使用。
function extractorCellValue(value: unknown, columnType: string | undefined, normalizeValues: boolean, presentBinaryText: boolean): unknown {
function extractorCellValue(value: unknown, columnType: string | undefined, normalizeValues: boolean, presentBinaryText: boolean, columnIndex: number): unknown {
if (presentBinaryText) {
const text = binaryCellClipboardText(value, columnType, options.databaseType.value);
if (text !== null) return text;
}
return normalizeValues ? normalizeCellValue(value, columnType) : value;
const normalized = normalizeValues ? normalizeCellValue(value, columnType) : value;
const externalValue = options.externalCellValue?.(normalized, columnIndex);
return externalValue === undefined ? normalized : externalValue;
}
function selectionData(): SelectionData | null {
@@ -210,7 +213,7 @@ export function useDataGridExtractor(options: UseDataGridExtractorOptions) {
const normalizeValues = descriptor.category === "json" || descriptor.category === "sql";
const presentBinaryText = descriptor.category !== "sql";
const rawRows = sourceRows.map((row) => requiredSourceIndexes.map((sourceIndex) => row[sourceIndex]));
const rows = rawRows.map((row) => row.map((value, index) => extractorCellValue(value, columnTypes[index], normalizeValues, presentBinaryText)));
const rows = rawRows.map((row) => row.map((value, index) => extractorCellValue(value, columnTypes[index], normalizeValues, presentBinaryText, index)));
const tableMeta =
descriptor.category === "sql"
? compactTableMeta(
@@ -269,7 +272,7 @@ export function useDataGridExtractor(options: UseDataGridExtractorOptions) {
return sourceIndex !== undefined && values.has(sourceIndex) ? values.get(sourceIndex) : value;
});
});
const rows = rawRows.map((row) => row.map((value, index) => extractorCellValue(value, limitedSource.columnTypes[index], limitedSource.normalizeValues, limitedSource.presentBinaryText)));
const rows = rawRows.map((row) => row.map((value, index) => extractorCellValue(value, limitedSource.columnTypes[index], limitedSource.normalizeValues, limitedSource.presentBinaryText, index)));
const resolvedRequest = { ...request, rows };
requestSources.set(resolvedRequest, { ...limitedSource, rawRows });
return resolvedRequest;