Skip to content

armgit / dbx

Public Imported from GitHub
0

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。

feat(grid): support exporting formatted data with column formatters (#11812)

lxk95544896db4ffe2
diff --git a/apps/desktop/src/components/editor/EditorSettingsDialog.vue b/apps/desktop/src/components/editor/EditorSettingsDialog.vue
index 180653237e..ac7aa79be4 100644
--- a/apps/desktop/src/components/editor/EditorSettingsDialog.vue
+++ b/apps/desktop/src/components/editor/EditorSettingsDialog.vue
@@ -950,6 +950,7 @@ const editExportBatchSize = ref(settingsStore.editorSettings.exportBatchSize);
const editPreferredExportPath = ref(settingsStore.editorSettings.preferredExportPath);
const editDamengClientBinDir = ref(settingsStore.editorSettings.damengClientBinDir);
const editAutoOpenExportFolder = ref(settingsStore.editorSettings.autoOpenExportFolder);
+const editApplyColumnFormattersOnExport = ref(settingsStore.editorSettings.applyColumnFormattersOnExport);
const editCsvQuoteMode = ref<CsvQuoteMode>(settingsStore.editorSettings.csvQuoteMode);
const editCsvNullMode = ref<CsvNullMode>(settingsStore.editorSettings.csvNullMode);
const editGlobalDateTimeDisplayFormat = ref(settingsStore.editorSettings.globalDateTimeDisplayFormat);
@@ -1241,6 +1242,7 @@ function currentEditorSettingsDraft(): EditorSettingsDraft {
preferredExportPath: editPreferredExportPath.value,
damengClientBinDir: editDamengClientBinDir.value,
autoOpenExportFolder: editAutoOpenExportFolder.value,
+ applyColumnFormattersOnExport: editApplyColumnFormattersOnExport.value,
csvQuoteMode: editCsvQuoteMode.value,
csvNullMode: editCsvNullMode.value,
globalDateTimeDisplayFormat: editGlobalDateTimeDisplayFormat.value,
@@ -1931,6 +1933,7 @@ function syncEditorSettingsDraftFromStore() {
editPreferredExportPath.value = settingsStore.editorSettings.preferredExportPath;
editDamengClientBinDir.value = settingsStore.editorSettings.damengClientBinDir;
editAutoOpenExportFolder.value = settingsStore.editorSettings.autoOpenExportFolder;
+ editApplyColumnFormattersOnExport.value = settingsStore.editorSettings.applyColumnFormattersOnExport;
editCsvQuoteMode.value = settingsStore.editorSettings.csvQuoteMode;
editCsvNullMode.value = settingsStore.editorSettings.csvNullMode;
editGlobalDateTimeDisplayFormat.value = settingsStore.editorSettings.globalDateTimeDisplayFormat;
@@ -2093,6 +2096,7 @@ const editorSettingsDraftRefs: EditorSettingsDraftRefMap = {
preferredExportPath: editPreferredExportPath,
damengClientBinDir: editDamengClientBinDir,
autoOpenExportFolder: editAutoOpenExportFolder,
+ applyColumnFormattersOnExport: editApplyColumnFormattersOnExport,
csvQuoteMode: editCsvQuoteMode,
csvNullMode: editCsvNullMode,
exportRowLimitEnabled: editExportRowLimitEnabled,
@@ -2695,6 +2699,7 @@ function resetDefaultsForTab(tab: SettingsCategory) {
editPreferredExportPath.value = DEFAULT_EDITOR_SETTINGS.preferredExportPath;
editDamengClientBinDir.value = DEFAULT_EDITOR_SETTINGS.damengClientBinDir;
editAutoOpenExportFolder.value = DEFAULT_EDITOR_SETTINGS.autoOpenExportFolder;
+ editApplyColumnFormattersOnExport.value = DEFAULT_EDITOR_SETTINGS.applyColumnFormattersOnExport;
editCsvQuoteMode.value = DEFAULT_EDITOR_SETTINGS.csvQuoteMode;
editCsvNullMode.value = DEFAULT_EDITOR_SETTINGS.csvNullMode;
editGlobalDateTimeDisplayFormat.value = DEFAULT_EDITOR_SETTINGS.globalDateTimeDisplayFormat;
@@ -2862,6 +2867,7 @@ function resetAllDefaults() {
editPreferredExportPath.value = DEFAULT_EDITOR_SETTINGS.preferredExportPath;
editDamengClientBinDir.value = DEFAULT_EDITOR_SETTINGS.damengClientBinDir;
editAutoOpenExportFolder.value = DEFAULT_EDITOR_SETTINGS.autoOpenExportFolder;
+ editApplyColumnFormattersOnExport.value = DEFAULT_EDITOR_SETTINGS.applyColumnFormattersOnExport;
editCsvQuoteMode.value = DEFAULT_EDITOR_SETTINGS.csvQuoteMode;
editCsvNullMode.value = DEFAULT_EDITOR_SETTINGS.csvNullMode;
editGlobalDateTimeDisplayFormat.value = DEFAULT_EDITOR_SETTINGS.globalDateTimeDisplayFormat;
@@ -9518,6 +9524,15 @@ onUnmounted(() => {
</div>
<Switch id="export-auto-open-folder" v-model="editAutoOpenExportFolder" class="mt-0.5" />
</div>
+ <div data-settings-search-id="data-export-apply-column-formatters" :class="['flex items-start justify-between gap-3', settingsSearchTargetClass('data-export-apply-column-formatters')]">
+ <div class="space-y-0.5">
+ <Label for="export-apply-column-formatters">{{ t("settings.applyColumnFormattersOnExport") }}</Label>
+ <p class="text-xs text-muted-foreground">
+ {{ t("settings.applyColumnFormattersOnExportDescription") }}
+ </p>
+ </div>
+ <Switch id="export-apply-column-formatters" v-model="editApplyColumnFormattersOnExport" class="mt-0.5" />
+ </div>
<div class="space-y-2">
<Label>{{ t("settings.exportBatchSize") }}</Label>
<div class="flex items-center gap-3">
diff --git a/apps/desktop/src/components/grid/DataGrid.vue b/apps/desktop/src/components/grid/DataGrid.vue
index bdebd98a48..0697ed9e56 100644
--- a/apps/desktop/src/components/grid/DataGrid.vue
+++ b/apps/desktop/src/components/grid/DataGrid.vue
@@ -8800,7 +8800,9 @@ const {
sourceColumns: visibleSourceColumns,
columnComments: visibleColumnComments,
allColumnComments,
- displayValue: formatCellCached,
+ displayValue: (value, index) => formatCell(value, index, undefined, false),
+ hasColumnFormatter: (index: number) => Boolean(resolvedColumnFormatters.value[index]),
+ applyColumnFormattersOnExport: computed(() => settingsStore.editorSettings.applyColumnFormattersOnExport),
cellClipboardText: (value) => (usesMongoDocumentGridValues.value ? mongoDocumentGridClipboardText(value) : undefined),
externalCellValue: (value) => (usesMongoDocumentGridValues.value ? mongoDocumentGridExternalValue(value) : value),
mongoDocuments: computed(() => props.result.mongo_copy_documents ?? props.result.mongo_documents),
diff --git a/apps/desktop/src/composables/__tests__/useDataGridExtractor.includeDatabaseName.spec.ts b/apps/desktop/src/composables/__tests__/useDataGridExtractor.includeDatabaseName.spec.ts
index b9322c2d6b..62dd0dd023 100644
--- a/apps/desktop/src/composables/__tests__/useDataGridExtractor.includeDatabaseName.spec.ts
+++ b/apps/desktop/src/composables/__tests__/useDataGridExtractor.includeDatabaseName.spec.ts
@@ -127,4 +127,44 @@ describe("useDataGridExtractor includeDatabaseName payload", () => {
["D", "DATE"],
]);
});
+
+ it("formats cells with active column formatters for non-SQL extractors and keeps raw values for SQL extractors", async () => {
+ const state = useDataGridExtractor({
+ columns: computed(() => ["id", "amount"]),
+ allColumns: computed(() => ["id", "amount"]),
+ displayItems: computed(() => [{ id: 1, data: [1, 100], isDraft: false }]),
+ allDisplayItems: computed(() => [{ id: 1, data: [1, 100], isDraft: false }]),
+ allSourceColumns: computed(() => undefined),
+ visibleColumnIndexes: computed(() => [0, 1]),
+ columnTypes: computed(() => ["int", "decimal"]),
+ allColumnTypes: computed(() => ["int", "decimal"]),
+ extractorOptions: computed(() => DEFAULT_DATA_GRID_EXTRACTOR_OPTIONS),
+ databaseType: computed(() => "postgres"),
+ identifierQuote: computed(() => undefined),
+ tableMeta: computed(() => qualifiedMeta()),
+ includeDatabaseName: computed(() => false),
+ hasCellSelection: computed(() => false),
+ selectedCells: computed(() => ({ columns: [], rows: [] })),
+ selectedCellMatrix: computed(() => null),
+ hasRowSelection: computed(() => true),
+ hasColumnSelection: computed(() => false),
+ selectedRowIds: ref(new Set<number>([1])),
+ contextCell: ref(null),
+ contextSelectionIsSynthetic: ref(false),
+ copyText: vi.fn(async () => true),
+ canCopySqlInsert: () => true,
+ buildMongoInsert: vi.fn(async () => undefined),
+ hasColumnFormatter: (idx) => idx === 1,
+ displayValue: (val, idx) => (idx === 1 ? `$${val}` : String(val)),
+ applyColumnFormattersOnExport: computed(() => true),
+ });
+
+ await state.extractWithExtractor("csv");
+ const csvRequest = mocks.extract.mock.calls.at(-1)![0];
+ expect(csvRequest.rows).toEqual([[1, "$100"]]);
+
+ await state.extractWithExtractor("sql-inserts");
+ const sqlRequest = mocks.extract.mock.calls.at(-1)![0];
+ expect(sqlRequest.rows).toEqual([[1, 100]]);
+ });
});
diff --git a/apps/desktop/src/composables/useDataGridExport.ts b/apps/desktop/src/composables/useDataGridExport.ts
index 0575edbbd3..699cdc7a0a 100644
--- a/apps/desktop/src/composables/useDataGridExport.ts
+++ b/apps/desktop/src/composables/useDataGridExport.ts
@@ -1,4 +1,5 @@
import { computed, type ComputedRef, type Ref, createApp, watch, getCurrentScope, onScopeDispose } from "vue";
+import { getActivePinia } from "pinia";
import { useI18n } from "vue-i18n";
import { useDataGridExtractor } from "@/composables/useDataGridExtractor";
import { isTauriRuntime } from "@/lib/backend/tauriRuntime";
@@ -115,6 +116,8 @@ export interface UseDataGridExportOptions {
mongoUpdateTarget?: ComputedRef<MongoCopyUpdateTarget | undefined>;
databaseType: ComputedRef<DatabaseType | undefined>;
displayValue?: (value: CellValue, columnIndex: number) => string;
+ hasColumnFormatter?: (columnIndex: number) => boolean;
+ applyColumnFormattersOnExport?: ComputedRef<boolean>;
cellClipboardText?: (value: CellValue, columnIndex: number) => string | undefined;
externalCellValue?: (value: CellValue, columnIndex: number) => CellValue;
identifierQuote?: ComputedRef<string | undefined>;
@@ -349,9 +352,26 @@ export function useDataGridExport(options: UseDataGridExportOptions) {
}
}
- function applyGlobalDateTimeExportFormat(result: { columns: string[]; columnTypes: string[]; rows: CellValue[][] }, enabled: boolean) {
+ function shouldApplyColumnFormatter(columnIndex: number): boolean {
+ if (!options.hasColumnFormatter?.(columnIndex)) return false;
+ if (options.applyColumnFormattersOnExport?.value !== undefined) {
+ return options.applyColumnFormattersOnExport.value;
+ }
+ return getActivePinia() ? useSettingsStore().editorSettings.applyColumnFormattersOnExport : true;
+ }
+
+ function applyGlobalDateTimeExportFormat(result: { columns: string[]; columnTypes: string[]; rows: CellValue[][] }, enabled: boolean, sourceIndexes?: number[]) {
const pattern = enabled ? useSettingsStore().editorSettings.globalDateTimeExportFormat : "";
- return pattern ? { ...result, rows: formatTemporalRowsForExport(result.rows, result.columnTypes, pattern) } : result;
+ if (!pattern) return result;
+ const applyFormatters = options.applyColumnFormattersOnExport?.value ?? (getActivePinia() ? useSettingsStore().editorSettings.applyColumnFormattersOnExport : true);
+ const effectiveTypes = result.columnTypes.map((type, colIdx) => {
+ const sourceIdx = sourceIndexes ? sourceIndexes[colIdx] : (visibleColumnIndexesOption?.value?.[colIdx] ?? colIdx);
+ if (applyFormatters && sourceIdx !== undefined && options.hasColumnFormatter?.(sourceIdx)) {
+ return undefined;
+ }
+ return type;
+ });
+ return { ...result, rows: formatTemporalRowsForExport(result.rows, effectiveTypes, pattern) };
}
function tableCommentsForColumns(targetColumns: readonly string[]): Array<string | undefined> {
@@ -502,11 +522,14 @@ export function useDataGridExport(options: UseDataGridExportOptions) {
});
}
- function externalizeRows(rows: CellValue[][], columnIndexes?: number[]): CellValue[][] {
+ function externalizeRows(rows: CellValue[][], columnIndexes?: number[], applyFormatters = true, sourceIndexes?: number[]): CellValue[][] {
if (columnIndexes) {
- return rows.map((row) => columnIndexes.map((colIdx) => externalCellValue(row[colIdx], colIdx)));
+ return rows.map((row) => columnIndexes.map((colIdx, i) => externalCellValue(row[colIdx], colIdx, sourceIndexes?.[i], applyFormatters)));
}
- return rows.map((row) => row.map((value, columnIndex) => externalCellValue(value, columnIndex)));
+ if (sourceIndexes) {
+ return rows.map((row) => row.map((value, colIdx) => externalCellValue(value, colIdx, sourceIndexes[colIdx], applyFormatters)));
+ }
+ return rows.map((row) => row.map((value, columnIndex) => externalCellValue(value, columnIndex, undefined, applyFormatters)));
}
async function resultToExport(
@@ -545,14 +568,16 @@ export function useDataGridExport(options: UseDataGridExportOptions) {
const exportedSpatialColumns = projected?.spatialColumns ?? result.spatial_columns;
const exportedSpatialValues = projected?.spatialValues ?? result.spatial_values;
const columnComments = buildXlsxHeaderOverrides(exportedColumns, commentsForExportColumns(exportedColumns), headerMode);
+ const resolvedRows = preserveMongoExtendedJson ? mongoDocumentRowsForJson(exportedColumns, exportedRows, result.mongo_copy_documents) : externalizeRows(exportedRows, undefined, formatDateTime, projectionSourceIndexes);
return {
...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: exportedColumns, columnTypes: exportedColumnTypes, rows: preserveMongoExtendedJson ? mongoDocumentRowsForJson(exportedColumns, exportedRows, result.mongo_copy_documents) : exportedRows },
+ { columns: exportedColumns, columnTypes: exportedColumnTypes, rows: resolvedRows },
formatDateTime && !preserveMongoExtendedJson,
+ projectionSourceIndexes,
),
columnComments,
spatialColumns: exportedSpatialColumns,
@@ -580,8 +605,13 @@ 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) : externalizeRows(normalized.rows) },
+ {
+ columns: normalized.columns,
+ columnTypes: normalized.columnTypes,
+ rows: preserveMongoExtendedJson ? mongoDocumentRowsForJson(normalized.columns, normalized.rows, normalized.mongoCopyDocuments) : externalizeRows(normalized.rows, undefined, formatDateTime, sourceIndexes),
+ },
formatDateTime && !preserveMongoExtendedJson,
+ sourceIndexes,
),
columnComments,
spatialColumns: normalized.spatialColumns,
@@ -615,9 +645,12 @@ export function useDataGridExport(options: UseDataGridExportOptions) {
: externalizeRows(
exportItems.map((item) => item.data),
validColumnIndexes,
+ formatDateTime,
+ targetSourceIndexes,
),
},
formatDateTime && !preserveMongoExtendedJson,
+ targetSourceIndexes,
),
columnComments: commentHeader,
...(spatialColumns?.length ? { spatialColumns } : {}),
@@ -749,7 +782,7 @@ export function useDataGridExport(options: UseDataGridExportOptions) {
return isTemporalColumnType(colType);
}
- function externalCellValue(value: CellValue, columnIndex: number, sourceIndex?: number): CellValue {
+ function externalCellValue(value: CellValue, columnIndex: number, sourceIndex?: number, applyFormatters = true): CellValue {
const externalValue = options.externalCellValue?.(value, columnIndex);
const resolvedValue = externalValue === undefined ? value : externalValue;
if (resolvedValue !== null && resolvedValue !== undefined && options.displayValue) {
@@ -757,6 +790,9 @@ export function useDataGridExport(options: UseDataGridExportOptions) {
if (isOracleTemporalColumn(columnIndex, resolvedSourceIndex)) {
return options.displayValue(resolvedValue, resolvedSourceIndex);
}
+ if (applyFormatters && shouldApplyColumnFormatter(resolvedSourceIndex)) {
+ return options.displayValue(resolvedValue, resolvedSourceIndex);
+ }
}
return resolvedValue;
}
@@ -804,7 +840,8 @@ export function useDataGridExport(options: UseDataGridExportOptions) {
const val = resolvedItem?.data[columnIndex] ?? null;
// 外部剪贴板呈现文本型 MySQL VARBINARY(NULL 也按空串输出);内部网格副本仍保留原 hex,保证回粘无损。
const rawValue = options.cellClipboardText?.(val, sourceIndex) ?? clipboardCellValue(binaryClipboardCellValue(val, columnIndex));
- const copyValue = isOracleTemporalColumn(columnIndex, sourceIndex) ? (options.displayValue?.(val, sourceIndex) ?? rawValue) : rawValue;
+ const shouldFormat = isOracleTemporalColumn(columnIndex, sourceIndex) || shouldApplyColumnFormatter(sourceIndex);
+ const copyValue = shouldFormat ? (options.displayValue?.(val, sourceIndex) ?? rawValue) : rawValue;
await copyText(copyValue, { rows: [[val]] });
}
@@ -950,6 +987,8 @@ export function useDataGridExport(options: UseDataGridExportOptions) {
partialLoadInfo: partialLoadCopyInfo,
canBuildMongoUpdate: canBuildMongoExtractorUpdate,
displayValue: options.displayValue,
+ hasColumnFormatter: options.hasColumnFormatter,
+ applyColumnFormattersOnExport: options.applyColumnFormattersOnExport,
externalCellValue: (value, columnIndex) => {
const externalValue = options.externalCellValue?.(value as CellValue, columnIndex);
return externalValue === undefined ? value : externalValue;
@@ -1026,17 +1065,17 @@ export function useDataGridExport(options: UseDataGridExportOptions) {
const editorSettings = useSettingsStore().editorSettings;
const originalRows = editorSettings.exportRowLimitEnabled ? original.rows.slice(0, editorSettings.exportRowLimit) : original.rows;
const items = exportAll
- ? originalRows.map((row, sourceIndex) => ({ sourceIndex, data: sourceIndexes.map((index) => row[index]) }))
+ ? originalRows.map((row, sourceIndex) => ({ sourceIndex, data: sourceIndexes.map((index) => externalCellValue(row[index], index, index)) }))
: rowsToExport(rowIds).map((item) => ({
sourceIndex: item.sourceIndex,
isNew: item.isNew,
- data: externalizeRows([item.data], indexes)[0]!,
+ data: externalizeRows([item.data], indexes, true, sourceIndexes)[0]!,
isDirtyCol: (indexes ?? columns.value.map((_, index) => index)).map((index) => item.isDirtyCol[index] ?? false),
}));
const selected = snapshotExportSelection(original, names, sourceIndexes, items);
if (!selected) return false;
const types = sourceIndexes.map((index) => original.column_types?.[index] ?? "");
- selected.rows = applyGlobalDateTimeExportFormat({ columns: names, columnTypes: types, rows: selected.rows as CellValue[][] }, true).rows;
+ selected.rows = applyGlobalDateTimeExportFormat({ columns: names, columnTypes: types, rows: selected.rows as CellValue[][] }, true, sourceIndexes).rows;
let outputPath = exportFileName(full ? "export" : "export-page", format, { page: !full });
if (isTauriRuntime()) {
const path = await promptExportSavePath({ defaultFileName: outputPath, filters: [{ name: FORMAT_META[format]!.label, extensions: [format] }], preferredPath: useSettingsStore().editorSettings.preferredExportPath });
@@ -1625,6 +1664,24 @@ export function useDataGridExport(options: UseDataGridExportOptions) {
};
}
+ function hasActiveColumnFormatters(columnIndexes?: number[]): boolean {
+ if (!options.hasColumnFormatter) return false;
+ const applyFormatters = options.applyColumnFormattersOnExport?.value ?? (getActivePinia() ? useSettingsStore().editorSettings.applyColumnFormattersOnExport : true);
+ if (!applyFormatters) return false;
+ const allCount = options.allColumns?.value?.length ?? options.columns.value.length;
+ if (columnIndexes && columnIndexes.length > 0) {
+ const visibleIndexes = visibleColumnIndexesOption?.value;
+ return columnIndexes.some((index) => {
+ const sourceIndex = visibleIndexes ? (visibleIndexes[index] ?? index) : index;
+ return options.hasColumnFormatter!(sourceIndex);
+ });
+ }
+ for (let i = 0; i < allCount; i++) {
+ if (options.hasColumnFormatter(i)) return true;
+ }
+ return false;
+ }
+
async function exportFullTableDataViaBackend(format: "csv" | "xlsx" | "json" | "markdown" | "sql" | "txt", rowIds?: number[], headerMode: XlsxHeaderMode = "name", autoFilter = true, sqlExportOptions?: SqlExportOptions, openAfterExport = false, columnIndexes?: number[]): Promise<boolean> {
const meta = tableMeta.value;
// The backend table exporter currently builds two-part table names. External
@@ -1632,6 +1689,9 @@ export function useDataGridExport(options: UseDataGridExportOptions) {
if (rowIds !== undefined || columnIndexes !== undefined || context.value !== "table-data" || !meta || meta.catalog || !connectionId.value || !database.value) {
return false;
}
+ if (format !== "sql" && hasActiveColumnFormatters(columnIndexes)) {
+ return false;
+ }
const fmt = FORMAT_META[format];
const splitSqlOutput = format === "sql" && sqlExportOptions?.splitMaxMb !== undefined;
@@ -1753,6 +1813,9 @@ export function useDataGridExport(options: UseDataGridExportOptions) {
if (rowIds !== undefined || columnIndexes !== undefined || context.value !== "results" || !queryResultExportRequest) {
return false;
}
+ if (format !== "sql" && hasActiveColumnFormatters(columnIndexes)) {
+ return false;
+ }
if (databaseType.value === "mongodb") return false;
// The full result is already in memory — don't re-execute the query on the
// backend just to stream the same rows back to a file.
diff --git a/apps/desktop/src/composables/useDataGridExtractor.ts b/apps/desktop/src/composables/useDataGridExtractor.ts
index 0ad897995e..b5f939f6f4 100644
--- a/apps/desktop/src/composables/useDataGridExtractor.ts
+++ b/apps/desktop/src/composables/useDataGridExtractor.ts
@@ -1,7 +1,9 @@
import { computed, type ComputedRef, type Ref } from "vue";
+import { getActivePinia } from "pinia";
import { useI18n } from "vue-i18n";
import * as api from "@/lib/backend/api";
import { useToast } from "@/composables/useToast";
+import { useSettingsStore } from "@/stores/settingsStore";
import { dedupeColumnIndexes, type CellSelectionMatrix, type SelectionData } from "@/lib/dataGrid/gridSelection";
import {
DATA_GRID_COPY_EXTRACTOR_DESCRIPTORS,
@@ -77,6 +79,8 @@ interface UseDataGridExtractorOptions {
contextSelectionIsSynthetic: ComputedRef<boolean> | Ref<boolean>;
copyText: (text: string, gridCopy?: { rows: readonly (readonly unknown[])[]; header?: readonly unknown[] }) => Promise<boolean>;
displayValue?: (value: CellValue, columnIndex: number) => string;
+ hasColumnFormatter?: (columnIndex: number) => boolean;
+ applyColumnFormattersOnExport?: ComputedRef<boolean>;
externalCellValue?: (value: unknown, columnIndex: number) => unknown;
/** Present when the grid cannot guarantee the whole result set is loaded; drives the partial-copy hint. */
partialLoadInfo?: ComputedRef<PartialLoadCopyInfo | null>;
@@ -109,8 +113,16 @@ export function useDataGridExtractor(options: UseDataGridExtractorOptions) {
return (dbType === "oracle" || dbType === "oceanbase-oracle") && isTemporalColumnType(columnType);
}
+ function shouldApplyColumnFormatter(columnIndex: number): boolean {
+ if (!options.hasColumnFormatter?.(columnIndex)) return false;
+ if (options.applyColumnFormattersOnExport?.value !== undefined) {
+ return options.applyColumnFormattersOnExport.value;
+ }
+ return getActivePinia() ? useSettingsStore().editorSettings.applyColumnFormattersOnExport : true;
+ }
+
// 除 SQL 外的剪贴板展示格式都可把文本型 MySQL VARBINARY 从 `0x<hex>` 还原为原始字符串,
- // 并把 Oracle temporal 单元格渲染为与网格一致的显示文本;SQL 必须继续持有 hex / 原始时间值
+ // 并把 Oracle temporal 单元格及配置了列格式化的单元格渲染为与网格一致的显示文本;SQL 必须继续持有 hex / 原始时间值
// (display 格式化会丢时区与高精度小数秒)才能保证 round-trip;rawRows 则始终保存原值,供 DBX 内部网格回粘使用。
function extractorCellValue(value: unknown, columnType: string | undefined, normalizeValues: boolean, keepUnsafeJsonText: boolean, presentBinaryText: boolean, columnIndex: number, sourceIndex?: number): unknown {
if (presentBinaryText) {
@@ -120,8 +132,10 @@ export function useDataGridExtractor(options: UseDataGridExtractorOptions) {
const normalized = normalizeValues ? normalizeCellValue(value, columnType, keepUnsafeJsonText) : value;
const externalValue = options.externalCellValue?.(normalized, columnIndex);
const resolvedValue = externalValue === undefined ? normalized : externalValue;
- if (presentBinaryText && resolvedValue !== null && resolvedValue !== undefined && options.displayValue && isOracleTemporal(columnType)) {
- return options.displayValue(resolvedValue as CellValue, sourceIndex ?? columnIndex);
+ const resolvedSourceIndex = sourceIndex ?? columnIndex;
+ const shouldFormat = isOracleTemporal(columnType) || shouldApplyColumnFormatter(resolvedSourceIndex);
+ if (presentBinaryText && resolvedValue !== null && resolvedValue !== undefined && options.displayValue && shouldFormat) {
+ return options.displayValue(resolvedValue as CellValue, resolvedSourceIndex);
}
return resolvedValue;
}
diff --git a/apps/desktop/src/i18n/locales/az.ts b/apps/desktop/src/i18n/locales/az.ts
index 81882a304d..006306cc7a 100644
--- a/apps/desktop/src/i18n/locales/az.ts
+++ b/apps/desktop/src/i18n/locales/az.ts
@@ -7975,6 +7975,8 @@ export default withEnglishFallback({
globalDateTimeDisplayFormatDescription: "Bütün verilənlər bazalarında sütuna məxsus formatlayıcısı olmayan tarix və vaxt sütunlarına tətbiq olunur.",
globalDateTimeExportFormat: "Qlobal ixrac formatı",
globalDateTimeExportFormatDescription: "CSV, Excel, JSON, Markdown və mətn ixraclarında tarix və vaxt sütunlarını vahid qaydada formatlayır.",
+ applyColumnFormattersOnExport: "İxrac zamanı sütun formatlayıcılarını tətbiq et",
+ applyColumnFormattersOnExportDescription: "CSV, Excel, JSON, Markdown, HTML və mətn ixraclarında aktiv formatlayıcısı olan sütunları formatlanmış mətn kimi ixrac edir.",
globalDateTimeImportFormat: "Qlobal idxal formatı",
globalDateTimeImportFormatDescription: "İdxal edilən tarix və vaxt dəyərlərini bu formatla təhlil edir. Ümumi formatları avtomatik aşkarlamaq üçün boş buraxın.",
dateTimeFormatRaw: "Verilənlər bazasının dəyərini saxla",
diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.ts
index e6bcc71af8..3aad18ec26 100644
--- a/apps/desktop/src/i18n/locales/en.ts
+++ b/apps/desktop/src/i18n/locales/en.ts
@@ -9105,6 +9105,8 @@ export default {
globalDateTimeDisplayFormatDescription: "Applies to temporal columns without a column-specific formatter in every database.",
globalDateTimeExportFormat: "Global export format",
globalDateTimeExportFormatDescription: "Formats temporal columns consistently in CSV, Excel, JSON, Markdown, and text exports.",
+ applyColumnFormattersOnExport: "Apply column formatters on export",
+ applyColumnFormattersOnExportDescription: "Export formatted text for columns with active formatters (date/time, mask, custom template, etc.) when exporting CSV, Excel, JSON, Markdown, HTML, and text.",
globalDateTimeImportFormat: "Global import format",
globalDateTimeImportFormatDescription: "Parses imported temporal values with this format. Leave empty to detect common formats automatically.",
dateTimeFormatRaw: "Keep database value",
diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.ts
index f37eed1aa4..90d280137d 100644
--- a/apps/desktop/src/i18n/locales/es.ts
+++ b/apps/desktop/src/i18n/locales/es.ts
@@ -8936,6 +8936,8 @@ export default withEnglishFallback({
globalDateTimeDisplayFormatDescription: "Se aplica a todos los campos de fecha y hora que no tienen un formato de columna configurado individualmente en las bases de datos.",
globalDateTimeExportFormat: "Formato de exportación global",
globalDateTimeExportFormatDescription: "Formatea uniformemente los campos de fecha y hora al exportar a CSV, Excel, JSON, Markdown y texto.",
+ applyColumnFormattersOnExport: "Aplicar formatos de columna al exportar",
+ applyColumnFormattersOnExportDescription: "Exporta texto formateado para columnas con formateadores activos (fecha/hora, máscara, plantilla personalizada, etc.) al exportar a CSV, Excel, JSON, Markdown, HTML y texto.",
globalDateTimeImportFormat: "Formato de importación global",
globalDateTimeImportFormatDescription: "Analiza las fechas y horas en los archivos importados según este formato; si se deja vacío, se reconocen automáticamente los formatos comunes.",
dateTimeFormatRaw: "Mantener el valor original de la base de datos",
diff --git a/apps/desktop/src/i18n/locales/id.ts b/apps/desktop/src/i18n/locales/id.ts
index b7ea62acc9..91b0c90549 100644
--- a/apps/desktop/src/i18n/locales/id.ts
+++ b/apps/desktop/src/i18n/locales/id.ts
@@ -8787,6 +8787,8 @@ export default withEnglishFallback({
globalDateTimeDisplayFormatDescription: "Berlaku untuk kolom temporal tanpa formatter khusus kolom di setiap database.",
globalDateTimeExportFormat: "Format ekspor global",
globalDateTimeExportFormatDescription: "Memformat kolom temporal secara konsisten dalam ekspor CSV, Excel, JSON, Markdown, dan teks.",
+ applyColumnFormattersOnExport: "Terapkan pemformat kolom saat mengekspor",
+ applyColumnFormattersOnExportDescription: "Ekspor teks berformat untuk kolom dengan pemformat aktif (tanggal/waktu, topeng, templat kustom, dll.) saat mengekspor CSV, Excel, JSON, Markdown, HTML, dan teks.",
globalDateTimeImportFormat: "Format impor global",
globalDateTimeImportFormatDescription: "Mengurai nilai temporal yang diimpor dengan format ini. Kosongkan untuk mendeteksi format umum secara otomatis.",
dateTimeFormatRaw: "Pertahankan nilai database",
diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.ts
index 771975c9bb..0030a36a85 100644
--- a/apps/desktop/src/i18n/locales/it.ts
+++ b/apps/desktop/src/i18n/locales/it.ts
@@ -8683,6 +8683,8 @@ export default withEnglishFallback({
globalDateTimeDisplayFormatDescription: "Applicato a tutti i campi data/ora nei database che non hanno una configurazione di formato colonna individuale.",
globalDateTimeExportFormat: "Formato di esportazione globale",
globalDateTimeExportFormatDescription: "Formatta uniformemente i campi data/ora durante l'esportazione in CSV, Excel, JSON, Markdown e testo.",
+ applyColumnFormattersOnExport: "Applica formattatori di colonna durante l'esportazione",
+ applyColumnFormattersOnExportDescription: "Esporta testo formattato per le colonne con formattatori attivi (data/ora, maschera, modello personalizzato, ecc.) durante l'esportazione in CSV, Excel, JSON, Markdown, HTML e testo.",
globalDateTimeImportFormat: "Formato di importazione globale",
globalDateTimeImportFormatDescription: "Analizza i campi data/ora nei file importati secondo questo formato; lascia vuoto per rilevare automaticamente i formati comuni.",
dateTimeFormatRaw: "Mantieni il valore originale del database",
diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.ts
index 6e7bdf037b..b88c07826a 100644
--- a/apps/desktop/src/i18n/locales/ja.ts
+++ b/apps/desktop/src/i18n/locales/ja.ts
@@ -8693,6 +8693,8 @@ export default withEnglishFallback({
globalDateTimeDisplayFormatDescription: "すべてのデータベースで列形式が個別に設定されていない日時フィールドに適用されます。",
globalDateTimeExportFormat: "グローバルエクスポート形式",
globalDateTimeExportFormatDescription: "CSV、Excel、JSON、Markdown、テキストをエクスポートする際に日時フィールドを統一フォーマットします。",
+ applyColumnFormattersOnExport: "エクスポート時に列フォーマッターを適用",
+ applyColumnFormattersOnExportDescription: "CSV、Excel、JSON、Markdown、HTML、テキストのエクスポート時に、列フォーマッターが設定された列の表示用テキストを出力します。",
globalDateTimeImportFormat: "グローバルインポート形式",
globalDateTimeImportFormatDescription: "この形式でインポートファイル内の日時を解析します。空欄の場合は一般的な形式を自動認識します。",
dateTimeFormatRaw: "データベースの元の値を保持",
diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.ts
index 24c9bdb782..22ad62a7f6 100644
--- a/apps/desktop/src/i18n/locales/ko.ts
+++ b/apps/desktop/src/i18n/locales/ko.ts
@@ -7966,6 +7966,8 @@ export default withEnglishFallback({
globalDateTimeDisplayFormatDescription: "컬럼별 포매터가 없는 시간 컬럼에 모든 데이터베이스에서 적용됩니다.",
globalDateTimeExportFormat: "전역 내보내기 형식",
globalDateTimeExportFormatDescription: "CSV, Excel, JSON, Markdown 및 텍스트 내보내기에서 시간 컬럼을 일관되게 서식합니다.",
+ applyColumnFormattersOnExport: "내보내기 시 열 서식 적용",
+ applyColumnFormattersOnExportDescription: "CSV, Excel, JSON, Markdown, HTML 및 텍스트를 내보낼 때 열 서식이 설정된 열의 서식 지정된 텍스트를 내보냅니다.",
globalDateTimeImportFormat: "전역 가져오기 형식",
globalDateTimeImportFormatDescription: "가져온 시간 값을 이 형식으로 파싱합니다. 자동 감지하려면 비워 두세요.",
dateTimeFormatRaw: "데이터베이스 값 유지",
diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.ts
index b20b234b44..040d6346bc 100644
--- a/apps/desktop/src/i18n/locales/pt-BR.ts
+++ b/apps/desktop/src/i18n/locales/pt-BR.ts
@@ -8681,6 +8681,8 @@ export default withEnglishFallback({
globalDateTimeDisplayFormatDescription: "Aplicado a todos os campos de data e hora em todos os bancos de dados que não tenham formato de coluna configurado individualmente.",
globalDateTimeExportFormat: "Formato de exportação global",
globalDateTimeExportFormatDescription: "Formata campos de data e hora de forma uniforme ao exportar para CSV, Excel, JSON, Markdown e texto.",
+ applyColumnFormattersOnExport: "Aplicar formatadores de coluna na exportação",
+ applyColumnFormattersOnExportDescription: "Exporta texto formatado para colunas com formatadores ativos (data/hora, máscara, modelo personalizado, etc.) ao exportar para CSV, Excel, JSON, Markdown, HTML e texto.",
globalDateTimeImportFormat: "Formato de importação global",
globalDateTimeImportFormatDescription: "Analisa datas e horas em arquivos importados de acordo com este formato; deixe em branco para detectar automaticamente formatos comuns.",
dateTimeFormatRaw: "Manter valor original do banco de dados",
diff --git a/apps/desktop/src/i18n/locales/ru.ts b/apps/desktop/src/i18n/locales/ru.ts
index 55aff79128..af4d5365ca 100644
--- a/apps/desktop/src/i18n/locales/ru.ts
+++ b/apps/desktop/src/i18n/locales/ru.ts
@@ -9440,6 +9440,8 @@ export default withEnglishFallback({
globalDateTimeDisplayFormatDescription: "Применяется к временным столбцам без собственного форматтера в любой базе данных.",
globalDateTimeExportFormat: "Глобальный формат экспорта",
globalDateTimeExportFormatDescription: "Единообразно форматирует временные столбцы при экспорте в CSV, Excel, JSON, Markdown и текст.",
+ applyColumnFormattersOnExport: "Применять форматирование столбцов при экспорте",
+ applyColumnFormattersOnExportDescription: "Экспортировать отформатированный текст для столбцов с активными модулями форматирования (дата/время, маска, шаблон и др.) при экспорте в CSV, Excel, JSON, Markdown, HTML и текст.",
globalDateTimeImportFormat: "Глобальный формат импорта",
globalDateTimeImportFormatDescription: "Разбирает импортируемые временные значения с этим форматом. Оставьте пустым для автоматического определения распространённых форматов.",
dateTimeFormatRaw: "Сохранять значение базы данных",
diff --git a/apps/desktop/src/i18n/locales/tr.ts b/apps/desktop/src/i18n/locales/tr.ts
index e2b157ac95..a23d28b1c9 100644
--- a/apps/desktop/src/i18n/locales/tr.ts
+++ b/apps/desktop/src/i18n/locales/tr.ts
@@ -7877,6 +7877,8 @@ export default withEnglishFallback({
globalDateTimeDisplayFormatDescription: "Her veritabanında, sütuna özgü biçimlendiricisi olmayan zaman sütunları için geçerlidir.",
globalDateTimeExportFormat: "Genel dışa aktarma biçimi",
globalDateTimeExportFormatDescription: "Zaman sütunlarını CSV, Excel, JSON, Markdown ve metin dışa aktarımlarında tutarlı biçimlendirir.",
+ applyColumnFormattersOnExport: "Dışa aktarmada sütun biçimlendiricilerini uygula",
+ applyColumnFormattersOnExportDescription: "CSV, Excel, JSON, Markdown, HTML ve metin dışa aktarımlarında etkin biçimlendiriciye sahip sütunları biçimlendirilmiş metin olarak dışa aktarır.",
globalDateTimeImportFormat: "Genel içe aktarma biçimi",
globalDateTimeImportFormatDescription: "İçe aktarılan zaman değerlerini bu biçimle ayrıştırır. Yaygın biçimleri otomatik algılamak için boş bırakın.",
dateTimeFormatRaw: "Veritabanı değerini koru",
diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.ts
index f373d84079..332777fdd9 100644
--- a/apps/desktop/src/i18n/locales/zh-CN.ts
+++ b/apps/desktop/src/i18n/locales/zh-CN.ts
@@ -9085,6 +9085,8 @@ export default withEnglishFallback({
globalDateTimeDisplayFormatDescription: "应用于所有数据库中未单独配置列格式的日期时间字段。",
globalDateTimeExportFormat: "全局导出格式",
globalDateTimeExportFormatDescription: "导出 CSV、Excel、JSON、Markdown 和文本时统一格式化日期时间字段。",
+ applyColumnFormattersOnExport: "导出时应用列格式化",
+ applyColumnFormattersOnExportDescription: "导出 CSV、Excel、JSON、Markdown、HTML 和文本时,将已配置列格式化(时间、掩码、自定义模板等)的列导出为格式化后的文本。",
globalDateTimeImportFormat: "全局导入格式",
globalDateTimeImportFormatDescription: "按此格式解析导入文件中的日期时间;留空时自动识别常见格式。",
dateTimeFormatRaw: "保持数据库原始值",
diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.ts
index 1bc77dc04c..348f75adc7 100644
--- a/apps/desktop/src/i18n/locales/zh-TW.ts
+++ b/apps/desktop/src/i18n/locales/zh-TW.ts
@@ -8010,6 +8010,8 @@ export default withEnglishFallback({
globalDateTimeDisplayFormatDescription: "套用到所有資料庫中未單獨設定欄位格式的日期時間欄位。",
globalDateTimeExportFormat: "全域匯出格式",
globalDateTimeExportFormatDescription: "匯出 CSV、Excel、JSON、Markdown 和文字時統一格式化日期時間欄位。",
+ applyColumnFormattersOnExport: "匯出時套用欄位格式化",
+ applyColumnFormattersOnExportDescription: "匯出 CSV、Excel、JSON、Markdown、HTML 和文字時,將已設定欄位格式化(時間、遮罩、自訂範本等)的欄位匯出為格式化後的文字。",
globalDateTimeImportFormat: "全域匯入格式",
globalDateTimeImportFormatDescription: "依此格式解析匯入檔案中的日期時間;留空時自動辨識常見格式。",
dateTimeFormatRaw: "保留資料庫原始值",
diff --git a/apps/desktop/src/lib/settings/editorSettingsDraft.ts b/apps/desktop/src/lib/settings/editorSettingsDraft.ts
index 0f8abbb9f5..c25dd7ed35 100644
--- a/apps/desktop/src/lib/settings/editorSettingsDraft.ts
+++ b/apps/desktop/src/lib/settings/editorSettingsDraft.ts
@@ -147,6 +147,7 @@ export const EDITOR_SETTINGS_DRAFT_KEYS = [
"preferredExportPath",
"damengClientBinDir",
"autoOpenExportFolder",
+ "applyColumnFormattersOnExport",
"csvQuoteMode",
"csvNullMode",
"exportRowLimitEnabled",
diff --git a/apps/desktop/src/lib/settings/settingsSearch.ts b/apps/desktop/src/lib/settings/settingsSearch.ts
index 867d246afa..f9ae282e00 100644
--- a/apps/desktop/src/lib/settings/settingsSearch.ts
+++ b/apps/desktop/src/lib/settings/settingsSearch.ts
@@ -272,6 +272,7 @@ export const SETTINGS_SEARCH_DEFINITIONS: readonly SettingsSearchDefinition[] =
{ id: "data-export-preferred-path", category: "data", titleKey: "settings.preferredExportPath", descriptionKey: "settings.preferredExportPathDescription", targetId: "data" },
{ id: "data-dameng-client-bin-dir", category: "data", titleKey: "settings.damengClientBinDir", descriptionKey: "settings.damengClientBinDirDescription", targetId: "data" },
{ id: "data-export-auto-open-folder", category: "data", titleKey: "settings.autoOpenExportFolder", descriptionKey: "settings.autoOpenExportFolderDescription", targetId: "data", visible: desktopOnly },
+ { id: "data-export-apply-column-formatters", category: "data", titleKey: "settings.applyColumnFormattersOnExport", descriptionKey: "settings.applyColumnFormattersOnExportDescription", targetId: "data" },
{ id: "data-export-batch", category: "data", titleKey: "settings.exportBatchSize", descriptionKey: "settings.exportBatchSizeDescription", targetId: "data" },
{ id: "data-export-row-limit-enabled", category: "data", titleKey: "settings.exportRowLimitEnabled", descriptionKey: "settings.exportRowLimitEnabledDescription", targetId: "data" },
{ id: "data-export-row-limit", category: "data", titleKey: "settings.exportRowLimit", descriptionKey: "settings.exportRowLimitDescription", targetId: "data" },
diff --git a/apps/desktop/src/lib/settings/settingsTransfer.ts b/apps/desktop/src/lib/settings/settingsTransfer.ts
index 7067b34641..7acade9eb6 100644
--- a/apps/desktop/src/lib/settings/settingsTransfer.ts
+++ b/apps/desktop/src/lib/settings/settingsTransfer.ts
@@ -201,6 +201,7 @@ const SETTINGS_TRANSFER_CATEGORY_KEYS: Record<SettingsTransferCategoryId, readon
"preferredExportPath",
"damengClientBinDir",
"autoOpenExportFolder",
+ "applyColumnFormattersOnExport",
"csvQuoteMode",
"csvNullMode",
"exportRowLimitEnabled",
diff --git a/apps/desktop/src/stores/__tests__/settingsStore.spec.ts b/apps/desktop/src/stores/__tests__/settingsStore.spec.ts
index d4d92eccaf..779bac8b10 100644
--- a/apps/desktop/src/stores/__tests__/settingsStore.spec.ts
+++ b/apps/desktop/src/stores/__tests__/settingsStore.spec.ts
@@ -1173,6 +1173,23 @@ describe("normalizeEditorSettings - autoOpenExportFolder", () => {
});
});
+describe("normalizeEditorSettings - applyColumnFormattersOnExport", () => {
+ it("defaults applyColumnFormattersOnExport to true", () => {
+ expect(normalizeEditorSettings({}).applyColumnFormattersOnExport).toBe(true);
+ });
+
+ it("preserves boolean values", () => {
+ expect(normalizeEditorSettings({ applyColumnFormattersOnExport: true }).applyColumnFormattersOnExport).toBe(true);
+ expect(normalizeEditorSettings({ applyColumnFormattersOnExport: false }).applyColumnFormattersOnExport).toBe(false);
+ });
+
+ it("falls back to default for non-boolean values", () => {
+ expect(normalizeEditorSettings({ applyColumnFormattersOnExport: "false" } as any).applyColumnFormattersOnExport).toBe(true);
+ expect(normalizeEditorSettings({ applyColumnFormattersOnExport: null } as any).applyColumnFormattersOnExport).toBe(true);
+ expect(normalizeEditorSettings({ applyColumnFormattersOnExport: 0 } as any).applyColumnFormattersOnExport).toBe(true);
+ });
+});
+
// --- Helpers for Pinia store tests ---
function makeTestConfig(overrides: Partial<AiConfigItem> & { id: string }): AiConfigItem {
diff --git a/apps/desktop/src/stores/settingsStore.ts b/apps/desktop/src/stores/settingsStore.ts
index 765a153337..8dee64647e 100644
--- a/apps/desktop/src/stores/settingsStore.ts
+++ b/apps/desktop/src/stores/settingsStore.ts
@@ -1158,6 +1158,7 @@ export interface EditorSettings {
exportBatchSize: number;
preferredExportPath: string;
autoOpenExportFolder: boolean;
+ applyColumnFormattersOnExport: boolean;
csvQuoteMode: CsvQuoteMode;
csvNullMode: CsvNullMode;
/** Global Redis key-search templates; overridden by non-empty connection templates. */
@@ -1485,6 +1486,7 @@ export const DEFAULT_EDITOR_SETTINGS: EditorSettings = {
exportBatchSize: 2000,
preferredExportPath: "",
autoOpenExportFolder: false,
+ applyColumnFormattersOnExport: true,
csvQuoteMode: DEFAULT_CSV_QUOTE_MODE,
csvNullMode: DEFAULT_CSV_NULL_MODE,
redisKeyTemplates: [],
@@ -2181,6 +2183,7 @@ export function normalizeEditorSettings(settings: Partial<EditorSettings>, exist
exportBatchSize: typeof settings.exportBatchSize === "number" && settings.exportBatchSize >= 100 && settings.exportBatchSize <= 100000 ? Math.round(settings.exportBatchSize) : DEFAULT_EDITOR_SETTINGS.exportBatchSize,
preferredExportPath: typeof settings.preferredExportPath === "string" ? settings.preferredExportPath.trim() : DEFAULT_EDITOR_SETTINGS.preferredExportPath,
autoOpenExportFolder: typeof settings.autoOpenExportFolder === "boolean" ? settings.autoOpenExportFolder : DEFAULT_EDITOR_SETTINGS.autoOpenExportFolder,
+ applyColumnFormattersOnExport: typeof settings.applyColumnFormattersOnExport === "boolean" ? settings.applyColumnFormattersOnExport : DEFAULT_EDITOR_SETTINGS.applyColumnFormattersOnExport,
csvQuoteMode: normalizeCsvQuoteMode(settings.csvQuoteMode),
csvNullMode: normalizeCsvNullMode(settings.csvNullMode),
redisKeyTemplates: normalizeRedisKeyTemplates(settings.redisKeyTemplates),
@@ -3034,6 +3037,7 @@ export const useSettingsStore = defineStore("settings", () => {
if (partial.exportBatchSize !== undefined) editorSettings.value.exportBatchSize = Math.min(100000, Math.max(100, Math.round(partial.exportBatchSize)));
if (partial.preferredExportPath !== undefined) editorSettings.value.preferredExportPath = typeof partial.preferredExportPath === "string" ? partial.preferredExportPath.trim() : "";
if (partial.autoOpenExportFolder !== undefined) editorSettings.value.autoOpenExportFolder = partial.autoOpenExportFolder === true;
+ if (partial.applyColumnFormattersOnExport !== undefined) editorSettings.value.applyColumnFormattersOnExport = partial.applyColumnFormattersOnExport === true;
if (partial.csvQuoteMode !== undefined) editorSettings.value.csvQuoteMode = normalizeCsvQuoteMode(partial.csvQuoteMode);
if (partial.csvNullMode !== undefined) editorSettings.value.csvNullMode = normalizeCsvNullMode(partial.csvNullMode);
if (partial.redisKeyTemplates !== undefined) editorSettings.value.redisKeyTemplates = normalizeRedisKeyTemplates(partial.redisKeyTemplates);
diff --git a/packages/app-tests/useDataGridExport.test.ts b/packages/app-tests/useDataGridExport.test.ts
index ee5da99ac7..f8281d9e23 100644
--- a/packages/app-tests/useDataGridExport.test.ts
+++ b/packages/app-tests/useDataGridExport.test.ts
@@ -114,6 +114,10 @@ function buildExportHarness(
sql?: string;
exportSql?: string;
pageSql?: string;
+ displayValue?: (value: any, columnIndex: number) => string;
+ hasColumnFormatter?: (columnIndex: number) => boolean;
+ applyColumnFormattersOnExport?: any;
+ contextCell?: any;
} = {},
) {
const exportColumns = options.columns ?? ["id", "name"];
@@ -122,6 +126,7 @@ function buildExportHarness(
[2, "Lin"],
];
const rowItems = exportRows.map((data, index) => ({ id: index + 1, data, isNew: false, isDeleted: false, isDirtyCol: data.map(() => false), status: "" }));
+ const contextCell = options.contextCell ?? ref(null);
const exportProgressDialog = ref(false);
const exportProgressState = ref({
title: "",
@@ -182,7 +187,7 @@ function buildExportHarness(
hasCellSelection: computed(() => false),
selectedCells: computed(() => ({ columns: [], rows: [] })),
selectedRange: computed(() => null),
- contextCell: ref(null),
+ contextCell,
getRowItem: (rowId: number) => rowItems.find((item) => item.id === rowId),
selectedRowIds: ref(new Set<number>()),
hasRowSelection: computed(() => false),
@@ -193,6 +198,9 @@ function buildExportHarness(
allExportResults: computed(() => options.allExportResults),
currentResultLabel: computed(() => options.currentResultLabel),
exportFileBaseName: computed(() => options.exportFileBaseName),
+ displayValue: options.displayValue,
+ hasColumnFormatter: options.hasColumnFormatter,
+ applyColumnFormattersOnExport: options.applyColumnFormattersOnExport,
exportProgressDialog,
exportProgressState,
exportCancelHandler,
@@ -205,10 +213,18 @@ function buildExportHarness(
exportProgressDialog,
exportProgressState,
exportCancelHandler,
+ contextCell,
};
}
-function buildTableDataExportHarness() {
+function buildTableDataExportHarness(
+ options: {
+ displayValue?: (value: any, columnIndex: number) => string;
+ hasColumnFormatter?: (columnIndex: number) => boolean;
+ applyColumnFormattersOnExport?: any;
+ fullExportResult?: any;
+ } = {},
+) {
const exportProgressDialog = ref(false);
const exportProgressState = ref({
title: "",
@@ -254,6 +270,10 @@ function buildTableDataExportHarness() {
getRowItem: () => undefined,
selectedRowIds: ref(new Set<number>()),
hasRowSelection: computed(() => false),
+ fullExportResult: options.fullExportResult,
+ displayValue: options.displayValue,
+ hasColumnFormatter: options.hasColumnFormatter,
+ applyColumnFormattersOnExport: options.applyColumnFormattersOnExport,
exportProgressDialog,
exportProgressState,
exportCancelHandler,
@@ -1208,3 +1228,123 @@ test("table data export passes row limit when enabled", async () => {
restoreStorage();
}
});
+
+test("selected query result CSV export formats column values when column formatter is active", async () => {
+ const restoreStorage = installMemoryStorage();
+ try {
+ const { composable } = buildExportHarness({
+ columns: ["id", "amount", "name"],
+ columnTypes: ["integer", "numeric", "text"],
+ rows: [
+ [1, 100, "Ada"],
+ [2, null, "Lin"],
+ ],
+ hasColumnFormatter: (idx) => idx === 1,
+ displayValue: (val, idx) => (idx === 1 ? `$${val}.00` : String(val)),
+ });
+
+ await composable.exportCsv([1, 2]);
+
+ assert.equal(apiMock.exportQueryResultCsv.mock.calls.length, 1);
+ assert.deepEqual(apiMock.exportQueryResultCsv.mock.calls[0][1], ["id", "amount", "name"]);
+ assert.deepEqual(apiMock.exportQueryResultCsv.mock.calls[0][2], [
+ [1, "$100.00", "Ada"],
+ [2, null, "Lin"],
+ ]);
+ } finally {
+ restoreStorage();
+ }
+});
+
+test("selected query result CSV export preserves raw values when applyColumnFormattersOnExport is false", async () => {
+ const restoreStorage = installMemoryStorage();
+ try {
+ useSettingsStore().updateEditorSettings({ applyColumnFormattersOnExport: false });
+ const { composable } = buildExportHarness({
+ columns: ["id", "amount"],
+ columnTypes: ["integer", "numeric"],
+ rows: [[1, 100]],
+ hasColumnFormatter: (idx) => idx === 1,
+ displayValue: (val, idx) => (idx === 1 ? `$${val}.00` : String(val)),
+ });
+
+ await composable.exportCsv([1]);
+
+ assert.equal(apiMock.exportQueryResultCsv.mock.calls.length, 1);
+ assert.deepEqual(apiMock.exportQueryResultCsv.mock.calls[0][2], [[1, 100]]);
+ } finally {
+ restoreStorage();
+ }
+});
+
+test("table data CSV export bypasses backend streaming when column formatters are active", async () => {
+ const restoreStorage = installMemoryStorage();
+ try {
+ const fullExportResult = vi.fn(async () => ({
+ columns: ["id", "name"],
+ rows: [
+ [1, "Alice"],
+ [2, "Bob"],
+ ],
+ column_types: ["integer", "text"],
+ }));
+ const { composable } = buildTableDataExportHarness({
+ hasColumnFormatter: (idx) => idx === 1,
+ displayValue: (val, idx) => (idx === 1 ? String(val).toUpperCase() : String(val)),
+ fullExportResult,
+ });
+
+ await composable.exportCsv();
+
+ assert.equal(apiMock.startTableExport.mock.calls.length, 0);
+ assert.equal(fullExportResult.mock.calls.length, 1);
+ assert.equal(apiMock.exportQueryResultCsv.mock.calls.length, 1);
+ assert.deepEqual(apiMock.exportQueryResultCsv.mock.calls[0][2], [
+ [1, "ALICE"],
+ [2, "BOB"],
+ ]);
+ } finally {
+ restoreStorage();
+ }
+});
+
+test("table data SQL export does not bypass backend streaming even when column formatters are active", async () => {
+ const restoreStorage = installMemoryStorage();
+ try {
+ const { composable } = buildTableDataExportHarness({
+ hasColumnFormatter: (idx) => idx === 1,
+ displayValue: (val, idx) => (idx === 1 ? String(val).toUpperCase() : String(val)),
+ });
+
+ await composable.exportSql();
+
+ assert.equal(apiMock.startTableExport.mock.calls.length, 1);
+ } finally {
+ restoreStorage();
+ }
+});
+
+test("copyCell applies column formatter when active and preserves raw values when disabled", async () => {
+ const restoreStorage = installMemoryStorage();
+ try {
+ const { composable, contextCell } = buildExportHarness({
+ columns: ["id", "price"],
+ rows: [[1, 42]],
+ hasColumnFormatter: (idx) => idx === 1,
+ displayValue: (val, idx) => (idx === 1 ? `$${val}` : String(val)),
+ });
+ contextCell.value = { rowId: 1, rowIndex: 0, col: 1 };
+
+ await composable.copyCell();
+ assert.equal(clipboardMock.copyToClipboard.mock.calls.length, 1);
+ assert.equal(clipboardMock.copyToClipboard.mock.calls[0][0], "$42");
+
+ clipboardMock.copyToClipboard.mockClear();
+ useSettingsStore().updateEditorSettings({ applyColumnFormattersOnExport: false });
+ await composable.copyCell();
+ assert.equal(clipboardMock.copyToClipboard.mock.calls.length, 1);
+ assert.equal(clipboardMock.copyToClipboard.mock.calls[0][0], "42");
+ } finally {
+ restoreStorage();
+ }
+});