25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。
TypeScript aicliclickhousedatabasedatabase-clientdatabase-managementdockerguimcpmongodbmysqlpostgresqlredisrustsql-serversqlitetaurivue
fix(grid): keep pasted empty strings as empty strings instead of NULL (issue #12727) (#12748)
弈秋44754e7cc058
diff --git a/apps/desktop/src/components/grid/DataGrid.vue b/apps/desktop/src/components/grid/DataGrid.vueindex c266d241ac..cf99f048c6 100644--- a/apps/desktop/src/components/grid/DataGrid.vue+++ b/apps/desktop/src/components/grid/DataGrid.vue@@ -9722,6 +9722,12 @@ function clipboardShortcut(event: KeyboardEvent, key: string): boolean {return isPlainClipboardShortcut(event, key);}+// The copy/extract "NULL text" a copy writes for a NULL cell, so a paste can+// turn the very same text back into NULL instead of the literal string+// (issue #12727). Empty means "no configured sentinel": empty clipboard fields+// then stay empty strings, which is what the DBX grid copies for both.+const clipboardNullText = computed(() => settingsStore.editorSettings.dataGridExtractorOptions.dsv.nullText);+async function pasteClipboardIntoSelection() {if (!props.editable) return;const operation = dataGridResultLifecycle.beginOperation();@@ -9746,7 +9752,7 @@ async function pasteClipboardAsNewRows() {const result = await prepareGridRows(async (options) => {const insertPaste = await parseInsertStatementPasteInBatches(text, options, limits);if (options.signal?.aborted || options.isCurrent?.() === false) return undefined;- const rows = insertPaste?.rows ?? (await parseDataGridClipboardInBatches(text, options, limits));+ const rows = insertPaste?.rows ?? (await parseDataGridClipboardInBatches(text, options, limits, clipboardNullText.value));if (!rows) return undefined;return appendPastedRowsAsNewRowsInBatches(rows, columnIndexes, insertPaste?.columnNames, options);});@@ -9848,7 +9854,7 @@ function pasteTextIntoGrid(text: string): boolean | Promise<boolean> {return prepareGridRows(async (options) => {const insertPaste = await parseInsertStatementPasteInBatches(text, options, limits);if (options.signal?.aborted || options.isCurrent?.() === false) return false;- const rows = insertPaste?.rows ?? (await parseDataGridClipboardInBatches(text, options, limits));+ const rows = insertPaste?.rows ?? (await parseDataGridClipboardInBatches(text, options, limits, clipboardNullText.value));if (!rows || options.signal?.aborted || options.isCurrent?.() === false) return false;return applyParsedGridPaste(rows, insertPaste?.columnNames, options);})@@ -9860,7 +9866,7 @@ function pasteTextIntoGrid(text: string): boolean | Promise<boolean> {}try {const insertPaste = parseInsertStatementPaste(text, limits);- return applyParsedGridPaste(insertPaste?.rows ?? parseDataGridClipboard(text, limits), insertPaste?.columnNames);+ return applyParsedGridPaste(insertPaste?.rows ?? parseDataGridClipboard(text, limits, clipboardNullText.value), insertPaste?.columnNames);} catch (error) {reportGridPasteError(error);return false;@@ -9884,7 +9890,7 @@ function applyParsedGridPaste(rows: readonly (readonly (string | null)[])[], colfunction pasteRowsIntoSelection(rows: readonly (readonly (string | null)[])[]): boolean {const allowDraftSelectionValue = selectedRangeTargetsOnlyDraftRow();- if (rows.length === 1 && rows[0]?.length === 1 && fillSelectionWithValue(rows[0][0])) {+ if (rows.length === 1 && rows[0]?.length === 1 && fillSelectionWithValue(rows[0][0], { preserveEmptyString: true })) {toast(t("grid.pasted"));return true;}@@ -9902,7 +9908,9 @@ function pasteRowsIntoSelection(rows: readonly (readonly (string | null)[])[]):const item = displayItemAt(rowIndex);if (!item) continue;const visibleCol = start.colIndex + cell.columnOffset;- applied = applyVisibleSelectedCellValue(item, visibleCol, cell.value, allowDraftSelectionValue) || applied;+ // Pasting is a literal value transfer, so an empty field stays an empty+ // string instead of clearing the cell to NULL (issue #12727).+ applied = applyVisibleSelectedCellValue(item, visibleCol, cell.value, allowDraftSelectionValue, { preserveEmptyString: true }) || applied;}} finally {commitBatch();diff --git a/apps/desktop/src/components/grid/__tests__/DataGridBatchPasteFromCell.spec.ts b/apps/desktop/src/components/grid/__tests__/DataGridBatchPasteFromCell.spec.tsindex 7e415e05bc..6fb2180d4f 100644--- a/apps/desktop/src/components/grid/__tests__/DataGridBatchPasteFromCell.spec.ts+++ b/apps/desktop/src/components/grid/__tests__/DataGridBatchPasteFromCell.spec.ts@@ -411,6 +411,36 @@ describe("DataGrid multi-row paste from a blank cell", () => {expect(save.mock.calls[0]![0].dirtyRows.size).toBe(0);});+ it("keeps a pasted empty string as an empty string instead of NULL", async () => {+ const save = vi.fn<CustomSaveHandler["save"]>().mockResolvedValue();+ const { host } = mountGrid({ customSaveHandler: { canInsert: true, save } });+ await settle();+ await addBlankRow(host);+ await selectCell(visibleCells(pendingRows(host)[0]!)[0]!);+ await paste(host, "2\t\tAda\tLovelace");+ host.querySelector<HTMLElement>("[data-toolbar-action='save']")!.click();+ await settle();++ expect(save.mock.calls[0]![0].newRows).toEqual([[2, "", "Ada", "Lovelace"]]);+ });++ it("saves the configured NULL text as NULL while keeping an empty field empty", async () => {+ const save = vi.fn<CustomSaveHandler["save"]>().mockResolvedValue();+ const { host } = mountGrid({ customSaveHandler: { canInsert: true, save } });+ await settle();+ const settingsStore = useSettingsStore();+ settingsStore.updateEditorSettings({+ dataGridExtractorOptions: { ...settingsStore.editorSettings.dataGridExtractorOptions, dsv: { ...settingsStore.editorSettings.dataGridExtractorOptions.dsv, nullText: "\\N" } },+ });+ await addBlankRow(host);+ await selectCell(visibleCells(pendingRows(host)[0]!)[0]!);+ await paste(host, "\\N\tkeep\tAda\tLovelace");+ host.querySelector<HTMLElement>("[data-toolbar-action='save']")!.click();+ await settle();++ expect(save.mock.calls[0]![0].newRows).toEqual([[null, "keep", "Ada", "Lovelace"]]);+ });+it("expands beyond pre-added blank rows when pasted rows exceed them", async () => {const { host } = mountGrid();await settle();diff --git a/apps/desktop/src/composables/__tests__/useDataGridEditor.spec.ts b/apps/desktop/src/composables/__tests__/useDataGridEditor.spec.tsindex a2cb970563..1c0ccacaf9 100644--- a/apps/desktop/src/composables/__tests__/useDataGridEditor.spec.ts+++ b/apps/desktop/src/composables/__tests__/useDataGridEditor.spec.ts@@ -1219,6 +1219,26 @@ describe("useDataGridEditor appendPastedRowsToNewRow", () => {]);});+ it("keeps a pasted empty string as an empty string instead of NULL", () => {+ const editor = createEditor();+ editor.newRows.value = [];++ const result = editor.appendPastedRowsAsNewRows([["", null, "Lovelace"]], [0, 1, 2]);++ expect(result).toEqual({ ok: true, rowCount: 1 });+ expect(editor.newRows.value).toEqual([["", null, "Lovelace"]]);+ });++ it("keeps a pasted empty string when filling a blank target row", () => {+ const editor = createEditor();+ editor.newRows.value = [[null, null, null]];++ const result = editor.appendPastedRowsToNewRow(-1, [["", "Lovelace"]], [0, 2]);++ expect(result).toEqual({ ok: true, rowCount: 1 });+ expect(editor.newRows.value).toEqual([["", null, "Lovelace"]]);+ });+it("rejects a non-empty terminal new-row draft", () => {const editor = createEditor();editor.newRows.value = [];diff --git a/apps/desktop/src/composables/useDataGridEditor.ts b/apps/desktop/src/composables/useDataGridEditor.tsindex 7ed735e70d..b3895955d9 100644--- a/apps/desktop/src/composables/useDataGridEditor.ts+++ b/apps/desktop/src/composables/useDataGridEditor.ts@@ -1449,7 +1449,11 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {continue;}const value = pastedRow[valueIndex];- nextRow[columnIndex] = value === null ? null : coerceCellValue(value, nextRow[columnIndex], columnIndex);+ // A pasted cell is literal text, never a "clear this cell" gesture, so an+ // empty field has to stay an empty string instead of collapsing to NULL+ // (issue #12727). Without this the coercion below reads the blank draft+ // row's `null` as the previous value and rewrites '' as NULL on save.+ nextRow[columnIndex] = value === null ? null : coerceCellValue(value, nextRow[columnIndex], columnIndex, { preserveEmptyString: true });}mappedRows.push(nextRow);mappedMeta.push(rowIndex < reusableNewRowCount && sourceMeta[targetNewIndex! + rowIndex] ? cloneNewRowMeta([sourceMeta[targetNewIndex! + rowIndex]!])[0]! : allocateNewRowMeta(targetPlacement));diff --git a/apps/desktop/src/lib/__tests__/dataGrid/dataGridCellCoercion.spec.ts b/apps/desktop/src/lib/__tests__/dataGrid/dataGridCellCoercion.spec.tsindex 1f45009929..f3f8bb10dd 100644--- a/apps/desktop/src/lib/__tests__/dataGrid/dataGridCellCoercion.spec.ts+++ b/apps/desktop/src/lib/__tests__/dataGrid/dataGridCellCoercion.spec.ts@@ -103,6 +103,36 @@ describe("coerceDataGridCellValue", () => {expect(coerceDataGridCellValue({ ...options, preserveEmptyString: true })).toBe("");});+ it.each([+ ["a numeric column", "postgres" as const, { data_type: "integer" }],+ ["a boolean column", "postgres" as const, { data_type: "boolean" }],+ ["a MySQL TINYINT(1) column", "mysql" as const, { data_type: "tinyint(1)" }],+ ["a PostgreSQL array column", "postgres" as const, { data_type: "text[]" }],+ ["a date column", "postgres" as const, { data_type: "date" }],+ ["a timestamp column", "postgres" as const, { data_type: "timestamp without time zone" }],+ ["a time column", "mysql" as const, { data_type: "time" }],+ ["a uuid column", "postgres" as const, { data_type: "uuid" }],+ ["a jsonb column", "postgres" as const, { data_type: "jsonb" }],+ ["a bytea column", "postgres" as const, { data_type: "bytea" }],+ ["an unclassified column", "postgres" as const, { data_type: "some_custom_type" }],+ ["a column with no metadata", "postgres" as const, undefined],+ ])("keeps an empty string NULL in %s instead of coercing it", (_name, databaseType, columnInfo) => {+ const options = { value: "", oldValue: null, databaseType, columnInfo };++ expect(coerceDataGridCellValue({ ...options, preserveEmptyString: true })).toBeNull();+ });++ it.each([+ ["varchar", "mysql" as const, { data_type: "varchar(255)" }],+ ["text", "postgres" as const, { data_type: "text" }],+ ["char", "sqlserver" as const, { data_type: "char(4)" }],+ ["clob", "oracle" as const, { data_type: "clob" }],+ ])("keeps a pasted empty string in a %s column", (_name, databaseType, columnInfo) => {+ const options = { value: "", oldValue: null, databaseType, columnInfo };++ expect(coerceDataGridCellValue({ ...options, preserveEmptyString: true })).toBe("");+ });+it.each([null, false, true])("coerces MySQL TINYINT(1) from metadata when the sampled value is %p", (oldValue) => {expect(coerceDataGridCellValue({diff --git a/apps/desktop/src/lib/__tests__/dataGrid/dataGridClipboard.spec.ts b/apps/desktop/src/lib/__tests__/dataGrid/dataGridClipboard.spec.tsindex ca8f2929b6..0c8b7621e2 100644--- a/apps/desktop/src/lib/__tests__/dataGrid/dataGridClipboard.spec.ts+++ b/apps/desktop/src/lib/__tests__/dataGrid/dataGridClipboard.spec.ts@@ -144,6 +144,22 @@ describe("parseDataGridClipboard", () => {expect(parseDataGridClipboard("null")).toEqual([["null"]]);});+ it("turns the configured null text back into NULL while leaving other fields alone", () => {+ expect(parseDataGridClipboard("NULL\tkeep", {}, "NULL")).toEqual([[null, "keep"]]);+ expect(parseDataGridClipboard("null\tkeep", {}, "NULL")).toEqual([["null", "keep"]]);+ expect(parseDataGridClipboard("\tkeep", {}, "NULL")).toEqual([["", "keep"]]);+ });++ it("keeps an empty clipboard field empty when no null text is configured", () => {+ expect(parseDataGridClipboard("\tkeep", {}, "")).toEqual([["", "keep"]]);+ });++ it("applies the configured null text through the batched parser", async () => {+ const text = Array.from({ length: 50 }, (_, index) => `${index % 2 === 0 ? "NULL" : `keep-${index}`}`).join("\n");++ expect(await parseDataGridClipboardInBatches(text, {}, {}, "NULL")).toEqual(text.split("\n").map((cell, index) => [index % 2 === 0 ? null : cell]));+ });+it("does not reuse null metadata after a literal NULL is copied", () => {rememberDataGridClipboardCopy("NULL", [[null]]);rememberDataGridClipboardCopy("NULL", [["NULL"]]);diff --git a/apps/desktop/src/lib/dataGrid/dataGridCellCoercion.ts b/apps/desktop/src/lib/dataGrid/dataGridCellCoercion.tsindex da776dbd71..e03f4b09fd 100644--- a/apps/desktop/src/lib/dataGrid/dataGridCellCoercion.ts+++ b/apps/desktop/src/lib/dataGrid/dataGridCellCoercion.ts@@ -1,7 +1,7 @@import type { GridCellValue } from "@/lib/dataGrid/dataGridSql";import type { DatabaseType, ColumnInfo } from "@/types/database";import { binaryCellBytesToHexValue, binaryCellUtf8Text, isBlobCellColumnType, isBlobTextPreviewDatabase } from "@/lib/dataGrid/binaryCellDownload";-import { isNumericColumnType } from "@/lib/dataGrid/dataGridColumnType";+import { isNumericColumnType, resolveDataGridTypeVisualKind } from "@/lib/dataGrid/dataGridColumnType";import { isBooleanColumnType } from "@/lib/dataGrid/dataGridBooleanColumn";export interface CoerceDataGridCellValueOptions {@@ -25,7 +25,7 @@ let cachedRuntimeNumberFormat: NumericInputNumberFormat | undefined;export function coerceDataGridCellValue(options: CoerceDataGridCellValueOptions): GridCellValue {const { value, oldValue } = options;if (value === "" && options.emptyStringAsNull) return null;- if (value === "" && oldValue === null && !options.preserveEmptyString) return null;+ if (value === "" && oldValue === null && !keepsEmptyStringInColumn(options)) return null;const blobValue = coerceBlobTextValue(options);if (blobValue !== undefined) return blobValue;const postgresArrayValue = coercePostgresArrayValue(options);@@ -61,6 +61,16 @@ export function coerceDataGridCellValue(options: CoerceDataGridCellValueOptions)return normalizeSmartQuotedJsonInput(numericText);}+// A literal empty string only exists in columns that store text. Every other+// type — numeric, boolean, temporal, uuid, JSON, binary, arrays — has no ''+// value of its own, so a blank cell in one of them has to stay NULL instead of+// coercing to 0 / false / '' (issue #12727). Types the grid cannot classify+// stay on the conservative NULL side as well.+function keepsEmptyStringInColumn(options: CoerceDataGridCellValueOptions): boolean {+ if (!options.preserveEmptyString) return false;+ return resolveDataGridTypeVisualKind(options.columnInfo?.data_type, options.databaseType) === "string";+}+function isBooleanInputColumn(options: CoerceDataGridCellValueOptions): boolean {if (isBooleanColumnType(options.columnInfo?.data_type, options.databaseType)) return true;return options.databaseType === "mysql" && options.columnInfo?.data_type.trim().toLowerCase() === "tinyint(1)";diff --git a/apps/desktop/src/lib/dataGrid/dataGridClipboard.ts b/apps/desktop/src/lib/dataGrid/dataGridClipboard.tsindex 3503216a48..924adf27a1 100644--- a/apps/desktop/src/lib/dataGrid/dataGridClipboard.ts+++ b/apps/desktop/src/lib/dataGrid/dataGridClipboard.ts@@ -54,15 +54,15 @@ export function rememberDataGridClipboardCopy(text: string, rows: readonly (readinternalClipboardCopy = { text, rows: [...headerRows, ...copiedRows], writeRevision: getClipboardWriteRevision() };}-export function parseDataGridClipboard(text: string, limits: DataGridClipboardLimits = {}): Array<Array<string | null>> {- return finishDataGridRowPreparation(prepareDataGridClipboard(text, limits));+export function parseDataGridClipboard(text: string, limits: DataGridClipboardLimits = {}, nullText = ""): Array<Array<string | null>> {+ return finishDataGridRowPreparation(prepareDataGridClipboard(text, limits, nullText));}-export function parseDataGridClipboardInBatches(text: string, options: DataGridRowPreparationOptions = {}, limits: DataGridClipboardLimits = {}): Promise<Array<Array<string | null>> | null> {- return runDataGridRowPreparation(prepareDataGridClipboard(text, limits), options, null);+export function parseDataGridClipboardInBatches(text: string, options: DataGridRowPreparationOptions = {}, limits: DataGridClipboardLimits = {}, nullText = ""): Promise<Array<Array<string | null>> | null> {+ return runDataGridRowPreparation(prepareDataGridClipboard(text, limits, nullText), options, null);}-function* prepareDataGridClipboard(text: string, limits: DataGridClipboardLimits): Generator<DataGridRowPreparationProgress, Array<Array<string | null>>> {+function* prepareDataGridClipboard(text: string, limits: DataGridClipboardLimits, nullText = ""): Generator<DataGridRowPreparationProgress, Array<Array<string | null>>> {const maxRows = limits.maxRows ?? 100_000;const maxCells = limits.maxCells ?? 1_000_000;let cells = 0;@@ -83,9 +83,13 @@ function* prepareDataGridClipboard(text: string, limits: DataGridClipboardLimitslet start = 0;let nextYield = DATA_GRID_CLIPBOARD_BATCH_CHARS;if (text.length > DATA_GRID_CLIPBOARD_BATCH_CHARS) yield { completed: 0, total: text.length, phase: "parsing" };+ // Only the configured NULL text becomes NULL again; every other field — an+ // empty one included — keeps its literal text so a pasted '' stays '' (issue #12727).+ const nullTextIsConfigured = nullText.length > 0;const appendCell = (end: number) => {if (rows.length >= maxRows || ++cells > maxCells) throw new DataGridClipboardCapacityError();- row.push(text.slice(start, end));+ const cell = text.slice(start, end);+ row.push(nullTextIsConfigured && cell === nullText ? null : cell);};for (let index = 0; index < text.length; index++) {if (index >= nextYield) {