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(export): add streaming TXT data export

Abeautifulsnow78b3bb1ba12b
diff --git a/apps/desktop/src/components/grid/DataGrid.vue b/apps/desktop/src/components/grid/DataGrid.vue
index 0cdce71602..52733d94cd 100644
--- a/apps/desktop/src/components/grid/DataGrid.vue
+++ b/apps/desktop/src/components/grid/DataGrid.vue
@@ -296,7 +296,7 @@ interface DataGridProps {
cacheKey?: string;
onExecuteSql?: (sql: string) => Promise<void>;
fullExportResult?: (onProgress?: (info: { rowsExported: number; totalRows: number | null }) => void) => Promise<QueryResult | undefined>;
- queryResultExportRequest?: (options: { exportId: string; filePath: string; format: "csv" | "xlsx" }) => Promise<api.QueryResultExportRequest | undefined>;
+ queryResultExportRequest?: (options: { exportId: string; filePath: string; format: "csv" | "xlsx" | "txt" }) => Promise<api.QueryResultExportRequest | undefined>;
allExportResults?: Array<{ sheetName: string; result: QueryResult }>;
exportFileBaseName?: string;
customSaveHandler?: import("@/composables/useDataGridEditor").CustomSaveHandler;
@@ -4870,6 +4870,12 @@ function exportSelectedRowsSql() {
return exportSql(rowIds);
}
+function exportSelectedRowsTxt() {
+ const rowIds = affectedRowIds();
+ if (rowIds.length === 0) return;
+ return exportTxt(rowIds);
+}
+
function executePreviewAction(action: { execute: (ctx: any) => any }) {
const config = action.execute({
result: props.result,
@@ -6546,6 +6552,8 @@ const {
exportAllResultsXlsx,
exportSql,
exportCurrentPageSql,
+ exportTxt,
+ exportCurrentPageTxt,
copySql,
} = useDataGridExport({
columns: visibleColumns,
@@ -6601,11 +6609,21 @@ const exportMenuItems = computed(() => {
{ value: "selected-json", label: t("grid.exportSelectedRowsJson") },
{ value: "selected-markdown", label: t("grid.exportSelectedRowsMarkdown") },
{ value: "selected-sql", label: t("grid.exportSelectedRowsSql") },
+ { value: "selected-txt", label: t("grid.exportSelectedRowsTxt") },
]
: [];
if (!hasFullResultExport) {
- return [{ value: "csv", label: t("grid.exportCsv") }, { value: "xlsx", label: t("grid.exportXlsx") }, { value: "json", label: t("grid.exportJson") }, { value: "markdown", label: t("grid.exportMarkdown") }, { value: "sql", label: t("grid.exportSql") }, ...allResultItems, ...selectedItems];
+ return [
+ { value: "csv", label: t("grid.exportCsv") },
+ { value: "xlsx", label: t("grid.exportXlsx") },
+ { value: "json", label: t("grid.exportJson") },
+ { value: "markdown", label: t("grid.exportMarkdown") },
+ { value: "sql", label: t("grid.exportSql") },
+ { value: "txt", label: t("grid.exportTxt") },
+ ...allResultItems,
+ ...selectedItems,
+ ];
}
return [
@@ -6614,11 +6632,13 @@ const exportMenuItems = computed(() => {
{ value: "page-json", label: t("grid.exportCurrentPageJson") },
{ value: "page-markdown", label: t("grid.exportCurrentPageMarkdown") },
{ value: "page-sql", label: t("grid.exportCurrentPageSql") },
+ { value: "page-txt", label: t("grid.exportCurrentPageTxt") },
{ value: "csv", label: t("grid.exportCurrentResultCsv"), separatorBefore: true },
{ value: "xlsx", label: t("grid.exportCurrentResultXlsx") },
{ value: "json", label: t("grid.exportCurrentResultJson") },
{ value: "markdown", label: t("grid.exportCurrentResultMarkdown") },
{ value: "sql", label: t("grid.exportCurrentResultSql") },
+ { value: "txt", label: t("grid.exportCurrentResultTxt") },
...allResultItems,
...selectedItems,
];
@@ -6635,17 +6655,20 @@ function selectExportMenuItem(value: string) {
"page-json": exportCurrentPageJson,
"page-markdown": exportCurrentPageMarkdown,
"page-sql": exportCurrentPageSql,
+ "page-txt": exportCurrentPageTxt,
csv: exportCsv,
xlsx: exportXlsx,
"all-results-xlsx": exportAllResultsXlsx,
json: exportJson,
markdown: exportMarkdown,
sql: exportSql,
+ txt: exportTxt,
"selected-csv": exportSelectedRowsCsv,
"selected-xlsx": exportSelectedRowsXlsx,
"selected-json": exportSelectedRowsJson,
"selected-markdown": exportSelectedRowsMarkdown,
"selected-sql": exportSelectedRowsSql,
+ "selected-txt": exportSelectedRowsTxt,
};
actions[value]?.();
}
@@ -8670,6 +8693,7 @@ defineExpose({
exportJson,
exportSql,
exportXlsx,
+ exportTxt,
});
// ---- CustomContextMenu ----
@@ -8782,6 +8806,7 @@ function exportSubmenu(): ContextMenuItem {
{ label: t("grid.exportJson"), action: exportJson },
{ label: t("grid.exportMarkdown"), action: exportMarkdown },
{ label: t("grid.exportSql"), action: exportSql },
+ { label: t("grid.exportTxt"), action: exportTxt },
];
if (isMultiRow.value) {
items.push(
@@ -8791,6 +8816,7 @@ function exportSubmenu(): ContextMenuItem {
{ label: t("grid.exportSelectedRowsJson"), action: exportSelectedRowsJson },
{ label: t("grid.exportSelectedRowsMarkdown"), action: exportSelectedRowsMarkdown },
{ label: t("grid.exportSelectedRowsSql"), action: exportSelectedRowsSql },
+ { label: t("grid.exportSelectedRowsTxt"), action: exportSelectedRowsTxt },
);
}
return { label: t("grid.export"), icon: Upload, children: items };
diff --git a/apps/desktop/src/components/layout/ContentArea.vue b/apps/desktop/src/components/layout/ContentArea.vue
index 311baa78d3..e579eae727 100644
--- a/apps/desktop/src/components/layout/ContentArea.vue
+++ b/apps/desktop/src/components/layout/ContentArea.vue
@@ -1127,7 +1127,7 @@ defineExpose({ focusSearch, refreshData, handleModRTarget, requestQueryEditorExe
:total-row-count-loading="activeTab.resultTotalRowCountLoading"
:on-execute-sql="async (sql: string) => emit('executeSql', sql)"
:full-export-result="(onProgress?: (info: { rowsExported: number; totalRows: number | null }) => void) => queryStore.fetchTabResultForExport(activeTab.id, onProgress)"
- :query-result-export-request="(options: { exportId: string; filePath: string; format: 'csv' | 'xlsx' }) => queryStore.buildQueryResultExportRequest(activeTab.id, options)"
+ :query-result-export-request="(options: { exportId: string; filePath: string; format: 'csv' | 'xlsx' | 'txt' }) => queryStore.buildQueryResultExportRequest(activeTab.id, options)"
:all-export-results="allResultExportSheets"
:export-file-base-name="activeTab.title"
@update:order-by-input="(v: string) => (activeTab.orderByInput = v)"
diff --git a/apps/desktop/src/composables/useDataGridExport.ts b/apps/desktop/src/composables/useDataGridExport.ts
index 2328f4d00c..fdc66729b7 100644
--- a/apps/desktop/src/composables/useDataGridExport.ts
+++ b/apps/desktop/src/composables/useDataGridExport.ts
@@ -8,7 +8,7 @@ import { displayCellValue, type CellValue } from "@/lib/dataGrid/cellValue";
import { tryStartExclusiveActivation, type ActionActivationGuard } from "@/lib/connection/actionActivation";
import { copyToClipboard } from "@/lib/common/clipboard";
import { buildDataGridCopyInsertStatement, buildDataGridCopyUpdateStatements, type DataGridCopyInsertMode, type DataGridTableMeta } from "@/lib/dataGrid/dataGridSql";
-import { formatSqlInsert } from "@/lib/export/exportFormats";
+import { formatSqlInsert, formatTsv } from "@/lib/export/exportFormats";
import { uuid } from "@/lib/common/utils";
import { useSettingsStore } from "@/stores/settingsStore";
import { expandNestedJsonStringsForCopy } from "@/lib/common/jsonCopyValue";
@@ -17,6 +17,24 @@ import type { DatabaseType, QueryResult } from "@/types/database";
import type { QueryResultExportRequest } from "@/lib/backend/api";
import { DBX_ROWID_COLUMN } from "@/lib/table/tableEditing";
+/**
+ * Format metadata for backend table exports. Each entry maps a format key
+ * to its default file extension and native save-dialog filter label.
+ *
+ * When a new export format is added only this table needs to be updated;
+ * the extension / filterName ternary chains that used to live inside
+ * exportFullTableDataViaBackend / exportQueryResultViaBackend are no
+ * longer needed.
+ */
+const FORMAT_META: Record<string, { ext: string; label: string }> = {
+ csv: { ext: "csv", label: "CSV" },
+ xlsx: { ext: "xlsx", label: "Excel" },
+ json: { ext: "json", label: "JSON" },
+ markdown: { ext: "md", label: "Markdown" },
+ sql: { ext: "sql", label: "SQL" },
+ txt: { ext: "txt", label: "Text" },
+};
+
interface RowItem {
id: number;
sourceIndex?: number;
@@ -53,7 +71,7 @@ export interface UseDataGridExportOptions {
selectedRowIds: Ref<Set<number>> | ComputedRef<Set<number>>;
hasRowSelection: ComputedRef<boolean>;
fullExportResult?: (onProgress?: (info: { rowsExported: number; totalRows: number | null }) => void) => Promise<QueryResult | undefined>;
- queryResultExportRequest?: (options: { exportId: string; filePath: string; format: "csv" | "xlsx" }) => Promise<QueryResultExportRequest | undefined>;
+ queryResultExportRequest?: (options: { exportId: string; filePath: string; format: "csv" | "xlsx" | "txt" }) => Promise<QueryResultExportRequest | undefined>;
/**
* True when the in-memory result already holds the complete result set —
* i.e. the query ran without server-side pagination, was not truncated, and
@@ -824,6 +842,34 @@ export function useDataGridExport(options: UseDataGridExportOptions) {
});
}
+ async function exportTxt(rowIds?: number[]) {
+ await runExclusiveExport(async () => {
+ try {
+ if (await exportQueryResultViaBackend("txt", rowIds)) return;
+ if (await exportFullTableDataViaBackend("txt", rowIds)) return;
+ const result = await resultToExport(rowIds);
+ const content = formatTsv(result.columns, result.rows);
+ await saveTextFile(content, exportFileName(tableMeta.value?.tableName || "export", "txt", { preferFallback: true }), "Text", "txt");
+ toast(t("grid.exported"));
+ } catch (e: any) {
+ toast(t("grid.exportFailed", { message: e?.message || String(e) }), 5000);
+ }
+ });
+ }
+
+ async function exportCurrentPageTxt() {
+ await runExclusiveExport(async () => {
+ try {
+ const result = await resultToExport(undefined, undefined, false);
+ const content = formatTsv(result.columns, result.rows);
+ await saveTextFile(content, exportFileName("export-page", "txt", { page: true }), "Text", "txt");
+ toast(t("grid.exported"));
+ } catch (e: any) {
+ toast(t("grid.exportFailed", { message: e?.message || String(e) }), 5000);
+ }
+ });
+ }
+
async function exportXlsx(rowIds?: number[]) {
await runExclusiveExport(async () => {
try {
@@ -949,7 +995,7 @@ export function useDataGridExport(options: UseDataGridExportOptions) {
});
}
- async function exportFullTableDataViaBackend(format: "csv" | "xlsx" | "json" | "markdown" | "sql", rowIds?: number[]): Promise<boolean> {
+ async function exportFullTableDataViaBackend(format: "csv" | "xlsx" | "json" | "markdown" | "sql" | "txt", rowIds?: number[]): Promise<boolean> {
const meta = tableMeta.value;
// The backend table exporter currently builds two-part table names. External
// Doris/StarRocks catalogs need the data-tab paginator's three-part SQL.
@@ -957,8 +1003,9 @@ export function useDataGridExport(options: UseDataGridExportOptions) {
return false;
}
- const extension = format === "markdown" ? "md" : format;
- const filterName = format === "csv" ? "CSV" : format === "xlsx" ? "Excel" : format === "json" ? "JSON" : format === "markdown" ? "Markdown" : "SQL";
+ const fmt = FORMAT_META[format];
+ const extension = fmt?.ext ?? format;
+ const filterName = fmt?.label ?? format.toUpperCase();
let outputPath = exportFileName(meta.tableName || "export", extension, { preferFallback: true });
if (isTauriRuntime()) {
const { save } = await import("@tauri-apps/plugin-dialog");
@@ -1031,7 +1078,7 @@ export function useDataGridExport(options: UseDataGridExportOptions) {
return true;
}
- async function exportQueryResultViaBackend(format: "csv" | "xlsx", rowIds?: number[]): Promise<boolean> {
+ async function exportQueryResultViaBackend(format: "csv" | "xlsx" | "txt", rowIds?: number[]): Promise<boolean> {
if (rowIds !== undefined || context.value !== "results" || !queryResultExportRequest) {
return false;
}
@@ -1039,8 +1086,9 @@ export function useDataGridExport(options: UseDataGridExportOptions) {
// backend just to stream the same rows back to a file.
if (hasCompleteLocalResult?.value) return false;
- const extension = format;
- const filterName = format === "csv" ? "CSV" : "Excel";
+ const fmt = FORMAT_META[format];
+ const extension = fmt?.ext ?? format;
+ const filterName = fmt?.label ?? format.toUpperCase();
let outputPath = exportFileName("query-result", extension);
if (isTauriRuntime()) {
const { save } = await import("@tauri-apps/plugin-dialog");
@@ -1195,6 +1243,8 @@ export function useDataGridExport(options: UseDataGridExportOptions) {
exportCurrentPageJson,
exportMarkdown,
exportCurrentPageMarkdown,
+ exportTxt,
+ exportCurrentPageTxt,
exportXlsx,
exportCurrentPageXlsx,
exportAllResultsXlsx,
diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.ts
index 98645be842..4bbf62c31b 100644
--- a/apps/desktop/src/i18n/locales/en.ts
+++ b/apps/desktop/src/i18n/locales/en.ts
@@ -731,20 +731,24 @@ export default {
exportCurrentPageJson: "Export Current Page as JSON",
exportCurrentPageMarkdown: "Export Current Page as Markdown",
exportCurrentPageSql: "Export Current Page as SQL INSERT",
+ exportCurrentPageTxt: "Export Current Page as TXT",
exportCurrentResultCsv: "Export Current Result Set All Data as CSV",
exportCurrentResultXlsx: "Export Current Result Set All Data as XLSX",
exportCurrentResultJson: "Export Current Result Set All Data as JSON",
exportCurrentResultMarkdown: "Export Current Result Set All Data as Markdown",
exportCurrentResultSql: "Export Current Result Set All Data as SQL INSERT",
+ exportCurrentResultTxt: "Export Current Result Set All Data as TXT",
exportAllResultsXlsx: "Export This Run's All Result Sets as XLSX",
exportJson: "Export JSON",
exportMarkdown: "Export Markdown",
exportSql: "Export SQL INSERT",
+ exportTxt: "Export TXT",
exportSelectedRowsCsv: "Export Selected Rows as CSV",
exportSelectedRowsXlsx: "Export Selected Rows as XLSX",
exportSelectedRowsJson: "Export Selected Rows as JSON",
exportSelectedRowsMarkdown: "Export Selected Rows as Markdown",
exportSelectedRowsSql: "Export Selected Rows as SQL INSERT",
+ exportSelectedRowsTxt: "Export Selected Rows as TXT",
exported: "Exported",
exportFailed: "Export failed: {message}",
copied: "Copied",
diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.ts
index a8a5c8094a..d3169bf6d5 100644
--- a/apps/desktop/src/i18n/locales/es.ts
+++ b/apps/desktop/src/i18n/locales/es.ts
@@ -680,20 +680,24 @@ export default withEnglishFallback({
exportCurrentPageJson: "Exportar página actual como JSON",
exportCurrentPageMarkdown: "Exportar página actual como Markdown",
exportCurrentPageSql: "Exportar página actual como SQL INSERT",
+ exportCurrentPageTxt: "Exportar página actual como TXT",
exportCurrentResultCsv: "Exportar todos los datos del resultado actual como CSV",
exportCurrentResultXlsx: "Exportar todos los datos del resultado actual como XLSX",
exportCurrentResultJson: "Exportar todos los datos del resultado actual como JSON",
exportCurrentResultMarkdown: "Exportar todos los datos del resultado actual como Markdown",
exportCurrentResultSql: "Exportar todos los datos del resultado actual como SQL INSERT",
+ exportCurrentResultTxt: "Exportar todos los datos del resultado actual como TXT",
exportAllResultsXlsx: "Exportar todos los resultados de esta ejecución como XLSX",
exportJson: "Exportar JSON",
exportMarkdown: "Exportar Markdown",
exportSql: "Exportar SQL INSERT",
+ exportTxt: "Exportar TXT",
exportSelectedRowsCsv: "Exportar filas seleccionadas como CSV",
exportSelectedRowsXlsx: "Exportar filas seleccionadas como XLSX",
exportSelectedRowsJson: "Exportar filas seleccionadas como JSON",
exportSelectedRowsMarkdown: "Exportar filas seleccionadas como Markdown",
exportSelectedRowsSql: "Exportar filas seleccionadas como SQL INSERT",
+ exportSelectedRowsTxt: "Exportar filas seleccionadas como TXT",
exported: "Exportado",
exportFailed: "Error al exportar: {message}",
copied: "Copiado",
diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.ts
index 636157df18..9d49090dde 100644
--- a/apps/desktop/src/i18n/locales/it.ts
+++ b/apps/desktop/src/i18n/locales/it.ts
@@ -678,20 +678,24 @@ export default withEnglishFallback({
exportCurrentPageJson: "Esporta pagina corrente come JSON",
exportCurrentPageMarkdown: "Esporta pagina corrente come Markdown",
exportCurrentPageSql: "Esporta pagina corrente come SQL INSERT",
+ exportCurrentPageTxt: "Esporta pagina corrente come TXT",
exportCurrentResultCsv: "Esporta tutti i dati del risultato corrente come CSV",
exportCurrentResultXlsx: "Esporta tutti i dati del risultato corrente come XLSX",
exportCurrentResultJson: "Esporta tutti i dati del risultato corrente come JSON",
exportCurrentResultMarkdown: "Esporta tutti i dati del risultato corrente come Markdown",
exportCurrentResultSql: "Esporta tutti i dati del risultato corrente come SQL INSERT",
+ exportCurrentResultTxt: "Esporta tutti i dati del risultato corrente come TXT",
exportAllResultsXlsx: "Esporta tutti i set di risultati di questa esecuzione come XLSX",
exportJson: "Esporta JSON",
exportMarkdown: "Esporta Markdown",
exportSql: "Esporta SQL INSERT",
+ exportTxt: "Esporta TXT",
exportSelectedRowsCsv: "Esporta Righe Selezionate come CSV",
exportSelectedRowsXlsx: "Esporta Righe Selezionate come XLSX",
exportSelectedRowsJson: "Esporta Righe Selezionate come JSON",
exportSelectedRowsMarkdown: "Esporta Righe Selezionate come Markdown",
exportSelectedRowsSql: "Esporta Righe Selezionate come SQL INSERT",
+ exportSelectedRowsTxt: "Esporta Righe Selezionate come TXT",
exported: "Esportato",
exportFailed: "Esportazione non riuscita: {message}",
copied: "Copiato",
diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.ts
index 76c2ae716f..c799e754e3 100644
--- a/apps/desktop/src/i18n/locales/ja.ts
+++ b/apps/desktop/src/i18n/locales/ja.ts
@@ -677,20 +677,24 @@ export default withEnglishFallback({
exportCurrentPageJson: "現在のページをJSONでエクスポート",
exportCurrentPageMarkdown: "現在のページをMarkdownでエクスポート",
exportCurrentPageSql: "現在のページをSQL INSERTでエクスポート",
+ exportCurrentPageTxt: "現在のページをTXTでエクスポート",
exportCurrentResultCsv: "現在の結果セット全データをCSVでエクスポート",
exportCurrentResultXlsx: "現在の結果セット全データをXLSXでエクスポート",
exportCurrentResultJson: "現在の結果セット全データをJSONでエクスポート",
exportCurrentResultMarkdown: "現在の結果セット全データをMarkdownでエクスポート",
exportCurrentResultSql: "現在の結果セット全データをSQL INSERTでエクスポート",
+ exportCurrentResultTxt: "現在の結果セット全データをTXTでエクスポート",
exportAllResultsXlsx: "今回実行の全結果セットをXLSXでエクスポート",
exportJson: "JSONエクスポート",
exportMarkdown: "Markdownエクスポート",
exportSql: "SQL INSERTエクスポート",
+ exportTxt: "TXTエクスポート",
exportSelectedRowsCsv: "選択行をCSVでエクスポート",
exportSelectedRowsXlsx: "選択行をXLSXでエクスポート",
exportSelectedRowsJson: "選択行をJSONでエクスポート",
exportSelectedRowsMarkdown: "選択行をMarkdownでエクスポート",
exportSelectedRowsSql: "選択行をSQL INSERTでエクスポート",
+ exportSelectedRowsTxt: "選択行をTXTでエクスポート",
exported: "エクスポートしました",
exportFailed: "エクスポートに失敗しました: {message}",
copied: "コピーしました",
diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.ts
index 28bd12d18b..65d01f6197 100644
--- a/apps/desktop/src/i18n/locales/pt-BR.ts
+++ b/apps/desktop/src/i18n/locales/pt-BR.ts
@@ -680,20 +680,24 @@ export default withEnglishFallback({
exportCurrentPageJson: "Exportar página atual como JSON",
exportCurrentPageMarkdown: "Exportar página atual como Markdown",
exportCurrentPageSql: "Exportar página atual como SQL INSERT",
+ exportCurrentPageTxt: "Exportar página atual como TXT",
exportCurrentResultCsv: "Exportar todos os dados do resultado atual como CSV",
exportCurrentResultXlsx: "Exportar todos os dados do resultado atual como XLSX",
exportCurrentResultJson: "Exportar todos os dados do resultado atual como JSON",
exportCurrentResultMarkdown: "Exportar todos os dados do resultado atual como Markdown",
exportCurrentResultSql: "Exportar todos os dados do resultado atual como SQL INSERT",
+ exportCurrentResultTxt: "Exportar todos os dados do resultado atual como TXT",
exportAllResultsXlsx: "Exportar todos os conjuntos de resultados desta execução como XLSX",
exportJson: "Exportar JSON",
exportMarkdown: "Exportar Markdown",
exportSql: "Exportar SQL INSERT",
+ exportTxt: "Exportar TXT",
exportSelectedRowsCsv: "Exportar Linhas Selecionadas como CSV",
exportSelectedRowsXlsx: "Exportar Linhas Selecionadas como XLSX",
exportSelectedRowsJson: "Exportar Linhas Selecionadas como JSON",
exportSelectedRowsMarkdown: "Exportar Linhas Selecionadas como Markdown",
exportSelectedRowsSql: "Exportar Linhas Selecionadas como SQL INSERT",
+ exportSelectedRowsTxt: "Exportar Linhas Selecionadas como TXT",
exported: "Exportado",
exportFailed: "Falha na exportação: {message}",
copied: "Copiado",
diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.ts
index d8d1106032..312ce47dfb 100644
--- a/apps/desktop/src/i18n/locales/zh-CN.ts
+++ b/apps/desktop/src/i18n/locales/zh-CN.ts
@@ -732,20 +732,24 @@ export default withEnglishFallback({
exportCurrentPageJson: "导出当前页 JSON",
exportCurrentPageMarkdown: "导出当前页 Markdown",
exportCurrentPageSql: "导出当前页 SQL INSERT",
+ exportCurrentPageTxt: "导出当前页 TXT",
exportCurrentResultCsv: "导出当前结果集全部数据 CSV",
exportCurrentResultXlsx: "导出当前结果集全部数据 XLSX",
exportCurrentResultJson: "导出当前结果集全部数据 JSON",
exportCurrentResultMarkdown: "导出当前结果集全部数据 Markdown",
exportCurrentResultSql: "导出当前结果集全部数据 SQL INSERT",
+ exportCurrentResultTxt: "导出当前结果集全部数据 TXT",
exportAllResultsXlsx: "导出本次执行全部结果集为 XLSX",
exportJson: "导出 JSON",
exportMarkdown: "导出 Markdown",
exportSql: "导出 SQL INSERT",
+ exportTxt: "导出 TXT",
exportSelectedRowsCsv: "导出选中行为 CSV",
exportSelectedRowsXlsx: "导出选中行为 XLSX",
exportSelectedRowsJson: "导出选中行为 JSON",
exportSelectedRowsMarkdown: "导出选中行为 Markdown",
exportSelectedRowsSql: "导出选中行为 SQL INSERT",
+ exportSelectedRowsTxt: "导出选中行为 TXT",
exported: "导出完成",
exportFailed: "导出失败:{message}",
copied: "已复制",
diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.ts
index a5ce719aac..8d022f8158 100644
--- a/apps/desktop/src/i18n/locales/zh-TW.ts
+++ b/apps/desktop/src/i18n/locales/zh-TW.ts
@@ -679,20 +679,24 @@ export default withEnglishFallback({
exportCurrentPageJson: "匯出目前頁 JSON",
exportCurrentPageMarkdown: "匯出目前頁 Markdown",
exportCurrentPageSql: "匯出目前頁 SQL INSERT",
+ exportCurrentPageTxt: "匯出目前頁 TXT",
exportCurrentResultCsv: "匯出目前結果集全部資料 CSV",
exportCurrentResultXlsx: "匯出目前結果集全部資料 XLSX",
exportCurrentResultJson: "匯出目前結果集全部資料 JSON",
exportCurrentResultMarkdown: "匯出目前結果集全部資料 Markdown",
exportCurrentResultSql: "匯出目前結果集全部資料 SQL INSERT",
+ exportCurrentResultTxt: "匯出目前結果集全部資料 TXT",
exportAllResultsXlsx: "匯出本次執行全部結果集為 XLSX",
exportJson: "匯出 JSON",
exportMarkdown: "匯出 Markdown",
exportSql: "匯出 SQL INSERT",
+ exportTxt: "匯出 TXT",
exportSelectedRowsCsv: "匯出選取資料列為 CSV",
exportSelectedRowsXlsx: "匯出選取資料列為 XLSX",
exportSelectedRowsJson: "匯出選取資料列為 JSON",
exportSelectedRowsMarkdown: "匯出選取資料列為 Markdown",
exportSelectedRowsSql: "匯出選取資料列為 SQL INSERT",
+ exportSelectedRowsTxt: "匯出選取資料列為 TXT",
exported: "匯出完成",
exportFailed: "匯出失敗:{message}",
copied: "已複製",
diff --git a/apps/desktop/src/lib/backend/tauri.ts b/apps/desktop/src/lib/backend/tauri.ts
index edef4c8993..8479c1368c 100644
--- a/apps/desktop/src/lib/backend/tauri.ts
+++ b/apps/desktop/src/lib/backend/tauri.ts
@@ -2234,7 +2234,7 @@ export interface TableExportRequest {
schema?: string;
tableName: string;
filePath: string;
- format: "csv" | "xlsx" | "json" | "markdown" | "sql";
+ format: "csv" | "xlsx" | "json" | "markdown" | "sql" | "txt";
columns?: string[];
columnTypes?: Array<string | null | undefined>;
primaryKeys?: string[];
@@ -2275,7 +2275,7 @@ export interface QueryResultExportRequest {
databaseType: DatabaseType;
useAgentCursor: boolean;
filePath: string;
- format: "csv" | "xlsx";
+ format: "csv" | "xlsx" | "txt";
pageSize: number;
rowLimit?: number | null;
totalRows?: number | null;
diff --git a/apps/desktop/src/lib/export/exportFormats.ts b/apps/desktop/src/lib/export/exportFormats.ts
index bb3270f9d3..11fdf0260d 100644
--- a/apps/desktop/src/lib/export/exportFormats.ts
+++ b/apps/desktop/src/lib/export/exportFormats.ts
@@ -10,6 +10,23 @@ export function formatCsv(columns: string[], rows: ExportCellValue[][]): string
return `${header}\n${body}`;
}
+// Tab-separated values with a header row, mirroring Navicat's "Text File (*.txt)"
+// export: fields are joined by a tab, NULL becomes empty, and a field is only
+// wrapped in double quotes (with " doubled) when it contains a tab, newline,
+// or quote - i.e. the minimum needed to round-trip the value.
+export function formatTsv(columns: string[], rows: ExportCellValue[][]): string {
+ const esc = (value: ExportCellValue) => {
+ const text = value === null ? "" : String(value);
+ if (text.includes("\t") || text.includes("\n") || text.includes("\r") || text.includes('"')) {
+ return `"${text.replace(/"/g, '""')}"`;
+ }
+ return text;
+ };
+ const header = columns.map(esc).join("\t");
+ const body = rows.map((row) => row.map(esc).join("\t")).join("\n");
+ return `${header}\n${body}`;
+}
+
export interface FormatSqlInsertOptions {
databaseType?: DatabaseType;
schema?: string;
diff --git a/apps/desktop/src/stores/queryStore.ts b/apps/desktop/src/stores/queryStore.ts
index 03895fe8f5..81342be559 100644
--- a/apps/desktop/src/stores/queryStore.ts
+++ b/apps/desktop/src/stores/queryStore.ts
@@ -71,7 +71,7 @@ function cloneTabDraft<T>(value: T): T {
interface BuildQueryResultExportRequestOptions {
exportId: string;
filePath: string;
- format: "csv" | "xlsx";
+ format: "csv" | "xlsx" | "txt";
}
type DroppedTableObjectType = "TABLE" | "VIEW" | "MATERIALIZED_VIEW";
diff --git a/crates/dbx-core/src/csv_export.rs b/crates/dbx-core/src/csv_export.rs
index 21b6f7bfef..4dfbf61ddb 100644
--- a/crates/dbx-core/src/csv_export.rs
+++ b/crates/dbx-core/src/csv_export.rs
@@ -48,6 +48,27 @@ pub(crate) fn value_to_query_result_csv_text(value: &Value) -> String {
}
}
+pub(crate) fn escape_tsv(value: &str) -> String {
+ if value.contains('\t') || value.contains('\n') || value.contains('\r') || value.contains('"') {
+ format!("\"{}\"", value.replace('"', "\"\""))
+ } else {
+ value.to_string()
+ }
+}
+
+pub(crate) fn format_tsv_rows(rows: &[Vec<Value>]) -> String {
+ rows.iter()
+ .map(|row| row.iter().map(|cell| escape_tsv(&value_to_csv_text(cell))).collect::<Vec<_>>().join("\t"))
+ .collect::<Vec<_>>()
+ .join("\n")
+}
+
+pub(crate) fn format_tsv(columns: &[String], rows: &[Vec<Value>]) -> String {
+ let header = columns.iter().map(|col| escape_tsv(col)).collect::<Vec<_>>().join("\t");
+ let body = format_tsv_rows(rows);
+ format!("{header}\n{body}")
+}
+
/// Format query-result rows as CSV text without a header row, using the
/// query-result NULL semantics (NULL → "NULL"). Used by the streaming
/// query-result export for batches after the first.
@@ -176,7 +197,7 @@ pub async fn export_table_data_csv_core(state: &AppState, options: TableCsvExpor
#[cfg(test)]
mod tests {
- use super::{format_csv, format_query_result_csv};
+ use super::{format_csv, format_query_result_csv, format_tsv};
use serde_json::json;
#[test]
@@ -197,5 +218,14 @@ mod tests {
assert_eq!(out, "\"id\",\"note\"\n\"1\",\"NULL\"");
}
+ #[test]
+ fn formats_tsv_with_empty_null_and_escaped_special_values() {
+ let out = format_tsv(
+ &["id".to_string(), "note".to_string()],
+ &[vec![json!(1), Value::Null], vec![json!(2), json!("line1\n\"line2\"")]],
+ );
+ assert_eq!(out, "id\tnote\n1\t\n2\t\"line1\n\"\"line2\"\"\"");
+ }
+
use serde_json::Value;
}
diff --git a/crates/dbx-core/src/query_result_export.rs b/crates/dbx-core/src/query_result_export.rs
index d9d510bc49..f2651dca2a 100644
--- a/crates/dbx-core/src/query_result_export.rs
+++ b/crates/dbx-core/src/query_result_export.rs
@@ -8,7 +8,7 @@ use std::sync::{
use std::time::{Duration, Instant};
use crate::connection::{AppState, PoolKind};
-use crate::csv_export::{format_query_result_csv, format_query_result_csv_rows};
+use crate::csv_export::{format_query_result_csv, format_query_result_csv_rows, format_tsv, format_tsv_rows};
use crate::database_export::is_export_cancelled;
pub use crate::database_export::ExportStatus;
use crate::models::connection::DatabaseType;
@@ -110,6 +110,19 @@ fn xlsx_hard_limit_active(format: &str, request: &QueryResultExportRequest) -> b
format == "xlsx" && request.row_limit.map_or(true, |limit| limit > XLSX_MAX_DATA_ROWS)
}
+fn format_text_export_header(format: &str, columns: &[String]) -> String {
+ let content = if format == "csv" { format_query_result_csv(columns, &[]) } else { format_tsv(columns, &[]) };
+ content.strip_suffix('\n').unwrap_or(&content).to_string()
+}
+
+fn format_text_export_rows(format: &str, rows: &[Vec<Value>]) -> String {
+ if format == "csv" {
+ format_query_result_csv_rows(rows)
+ } else {
+ format_tsv_rows(rows)
+ }
+}
+
fn should_emit_stream_progress(
rows_exported: u64,
last_progress_rows: u64,
@@ -311,7 +324,7 @@ async fn export_query_result_core_inner(
session_id: &mut Option<String>,
) -> Result<(), String> {
let format = request.format.to_lowercase();
- if format != "csv" && format != "xlsx" {
+ if format != "csv" && format != "xlsx" && format != "txt" {
return Err(format!("Unsupported streaming query-result export format: {format}"));
}
@@ -351,12 +364,12 @@ async fn export_query_result_core_inner(
return Ok(());
}
- let mut csv_file = if format == "csv" {
+ let mut text_file = if format == "csv" || format == "txt" {
Some(BufWriter::new(File::create(&request.file_path).map_err(|e| format!("Failed to create file: {e}"))?))
} else {
None
};
- if let Some(file) = csv_file.as_mut() {
+ if let Some(file) = text_file.as_mut() {
file.write_all(b"\xEF\xBB\xBF").map_err(|e| format!("Failed to write BOM: {e}"))?;
}
@@ -365,7 +378,7 @@ async fn export_query_result_core_inner(
let mut column_types: Vec<String> = Vec::new();
let mut rows_exported: u64 = 0;
let mut offset: usize = 0;
- let mut wrote_csv_header = false;
+ let mut wrote_text_header = false;
let mut keyset_plan = build_keyset_plan(state, request).await;
if keyset_plan.is_none() && !request.use_agent_cursor && !supports_streaming_offset_pagination(request, page_size) {
return Err(STREAMING_PAGINATION_UNSUPPORTED_ERROR.to_string());
@@ -503,15 +516,19 @@ async fn export_query_result_core_inner(
}
let row_count = result.rows.len();
- if format == "csv" {
- if let Some(file) = csv_file.as_mut() {
- if !wrote_csv_header {
- let csv = format_query_result_csv(&columns, &result.rows);
- file.write_all(csv.as_bytes()).map_err(|e| format!("Failed to write CSV: {e}"))?;
- wrote_csv_header = true;
+ if format == "csv" || format == "txt" {
+ if let Some(file) = text_file.as_mut() {
+ if !wrote_text_header {
+ let header = format_text_export_header(&format, &columns);
+ file.write_all(header.as_bytes()).map_err(|e| format!("Failed to write export header: {e}"))?;
+ if row_count > 0 {
+ let rows = format_text_export_rows(&format, &result.rows);
+ write!(file, "\n{rows}").map_err(|e| format!("Failed to write export rows: {e}"))?;
+ }
+ wrote_text_header = true;
} else if row_count > 0 {
- let rows_csv = format_query_result_csv_rows(&result.rows);
- write!(file, "\n{rows_csv}").map_err(|e| format!("Failed to write CSV rows: {e}"))?;
+ let rows = format_text_export_rows(&format, &result.rows);
+ write!(file, "\n{rows}").map_err(|e| format!("Failed to write export rows: {e}"))?;
}
}
} else {
@@ -568,15 +585,15 @@ async fn export_query_result_core_inner(
on_progress(progress(request, rows_exported, ExportStatus::Writing, None));
- if format == "csv" {
- if !wrote_csv_header {
- let csv = format_query_result_csv(&columns, &[]);
- if let Some(file) = csv_file.as_mut() {
- file.write_all(csv.as_bytes()).map_err(|e| format!("Failed to write CSV: {e}"))?;
+ if format == "csv" || format == "txt" {
+ if !wrote_text_header {
+ let header = format_text_export_header(&format, &columns);
+ if let Some(file) = text_file.as_mut() {
+ file.write_all(header.as_bytes()).map_err(|e| format!("Failed to write export header: {e}"))?;
}
}
- if let Some(file) = csv_file.as_mut() {
- file.flush().map_err(|e| format!("Failed to flush CSV file: {e}"))?;
+ if let Some(file) = text_file.as_mut() {
+ file.flush().map_err(|e| format!("Failed to flush text export file: {e}"))?;
}
} else if let Some(writer) = xlsx {
let mut buf =
@@ -646,7 +663,7 @@ async fn try_export_postgres_query_result_stream(
let mut rows_exported = 0_u64;
let mut last_progress_rows = 0_u64;
let mut last_progress_at = Instant::now();
- let mut csv_file = if format == "csv" {
+ let mut text_file = if format == "csv" || format == "txt" {
let mut file =
BufWriter::new(File::create(&request.file_path).map_err(|e| format!("Failed to create file: {e}"))?);
file.write_all(b"\xEF\xBB\xBF").map_err(|e| format!("Failed to write BOM: {e}"))?;
@@ -670,10 +687,9 @@ async fn try_export_postgres_query_result_stream(
match item {
crate::db::postgres::PostgresQueryStreamItem::Columns { columns: stream_columns, column_types } => {
columns = stream_columns;
- if let Some(file) = csv_file.as_mut() {
- let csv = format_query_result_csv(&columns, &[]);
- let header = csv.strip_suffix('\n').unwrap_or(&csv);
- file.write_all(header.as_bytes()).map_err(|e| format!("Failed to write CSV: {e}"))?;
+ if let Some(file) = text_file.as_mut() {
+ let header = format_text_export_header(format, &columns);
+ file.write_all(header.as_bytes()).map_err(|e| format!("Failed to write export header: {e}"))?;
} else {
let xlsx_file =
File::create(&request.file_path).map_err(|e| format!("Failed to create XLSX file: {e}"))?;
@@ -689,9 +705,9 @@ async fn try_export_postgres_query_result_stream(
if xlsx_hard_limit_active && rows_exported as usize >= XLSX_MAX_DATA_ROWS {
return Err(XLSX_ROW_LIMIT_ERROR.to_string());
}
- if let Some(file) = csv_file.as_mut() {
- let rows_csv = format_query_result_csv_rows(std::slice::from_ref(&row));
- write!(file, "\n{rows_csv}").map_err(|e| format!("Failed to write CSV rows: {e}"))?;
+ if let Some(file) = text_file.as_mut() {
+ let rows = format_text_export_rows(format, std::slice::from_ref(&row));
+ write!(file, "\n{rows}").map_err(|e| format!("Failed to write export rows: {e}"))?;
} else if let Some(writer) = xlsx.as_mut() {
writer.write_row(&row).map_err(|e| format!("Failed to write XLSX row: {e}"))?;
} else {
@@ -730,8 +746,8 @@ async fn try_export_postgres_query_result_stream(
on_progress(progress(request, rows_exported, ExportStatus::Running, None));
}
on_progress(progress(request, rows_exported, ExportStatus::Writing, None));
- if let Some(file) = csv_file.as_mut() {
- file.flush().map_err(|e| format!("Failed to flush CSV file: {e}"))?;
+ if let Some(file) = text_file.as_mut() {
+ file.flush().map_err(|e| format!("Failed to flush text export file: {e}"))?;
}
if let Some(writer) = xlsx {
let mut buf =
@@ -813,7 +829,7 @@ async fn try_export_mysql_query_result_stream(
let mut rows_exported = 0_u64;
let mut last_progress_rows = 0_u64;
let mut last_progress_at = Instant::now();
- let mut csv_file = if format == "csv" {
+ let mut text_file = if format == "csv" || format == "txt" {
let mut file =
BufWriter::new(File::create(&request.file_path).map_err(|e| format!("Failed to create file: {e}"))?);
file.write_all(b"\xEF\xBB\xBF").map_err(|e| format!("Failed to write BOM: {e}"))?;
@@ -886,10 +902,9 @@ async fn try_export_mysql_query_result_stream(
match item {
crate::db::mysql::MySqlQueryStreamItem::Columns { columns: stream_columns, column_types } => {
columns = stream_columns;
- if let Some(file) = csv_file.as_mut() {
- let csv = format_query_result_csv(&columns, &[]);
- let header = csv.strip_suffix('\n').unwrap_or(&csv);
- file.write_all(header.as_bytes()).map_err(|e| format!("Failed to write CSV: {e}"))?;
+ if let Some(file) = text_file.as_mut() {
+ let header = format_text_export_header(format, &columns);
+ file.write_all(header.as_bytes()).map_err(|e| format!("Failed to write export header: {e}"))?;
} else {
let xlsx_file =
File::create(&request.file_path).map_err(|e| format!("Failed to create XLSX file: {e}"))?;
@@ -905,9 +920,9 @@ async fn try_export_mysql_query_result_stream(
if xlsx_hard_limit_active && rows_exported as usize >= XLSX_MAX_DATA_ROWS {
return Err(XLSX_ROW_LIMIT_ERROR.to_string());
}
- if let Some(file) = csv_file.as_mut() {
- let rows_csv = format_query_result_csv_rows(std::slice::from_ref(&row));
- write!(file, "\n{rows_csv}").map_err(|e| format!("Failed to write CSV rows: {e}"))?;
+ if let Some(file) = text_file.as_mut() {
+ let rows = format_text_export_rows(format, std::slice::from_ref(&row));
+ write!(file, "\n{rows}").map_err(|e| format!("Failed to write export rows: {e}"))?;
} else if let Some(writer) = xlsx.as_mut() {
writer.write_row(&row).map_err(|e| format!("Failed to write XLSX row: {e}"))?;
} else {
@@ -992,8 +1007,8 @@ async fn try_export_mysql_query_result_stream(
on_progress(progress(request, rows_exported, ExportStatus::Running, None));
}
on_progress(progress(request, rows_exported, ExportStatus::Writing, None));
- if let Some(file) = csv_file.as_mut() {
- file.flush().map_err(|e| format!("Failed to flush CSV file: {e}"))?;
+ if let Some(file) = text_file.as_mut() {
+ file.flush().map_err(|e| format!("Failed to flush text export file: {e}"))?;
}
if let Some(writer) = xlsx {
let mut buf =
@@ -1063,7 +1078,7 @@ async fn try_export_clickhouse_query_result_stream(
let mut rows_exported = 0_u64;
let mut last_progress_rows = 0_u64;
let mut last_progress_at = Instant::now();
- let mut csv_file = if format == "csv" {
+ let mut text_file = if format == "csv" || format == "txt" {
let mut file =
BufWriter::new(File::create(&request.file_path).map_err(|e| format!("Failed to create file: {e}"))?);
file.write_all(b"\xEF\xBB\xBF").map_err(|e| format!("Failed to write BOM: {e}"))?;
@@ -1087,10 +1102,9 @@ async fn try_export_clickhouse_query_result_stream(
column_types,
} => {
columns = stream_columns;
- if let Some(file) = csv_file.as_mut() {
- let csv = format_query_result_csv(&columns, &[]);
- let header = csv.strip_suffix('\n').unwrap_or(&csv);
- file.write_all(header.as_bytes()).map_err(|e| format!("Failed to write CSV: {e}"))?;
+ if let Some(file) = text_file.as_mut() {
+ let header = format_text_export_header(format, &columns);
+ file.write_all(header.as_bytes()).map_err(|e| format!("Failed to write export header: {e}"))?;
} else {
let xlsx_file =
File::create(&request.file_path).map_err(|e| format!("Failed to create XLSX file: {e}"))?;
@@ -1106,9 +1120,9 @@ async fn try_export_clickhouse_query_result_stream(
if xlsx_hard_limit_active && rows_exported as usize >= XLSX_MAX_DATA_ROWS {
return Err(XLSX_ROW_LIMIT_ERROR.to_string());
}
- if let Some(file) = csv_file.as_mut() {
- let rows_csv = format_query_result_csv_rows(std::slice::from_ref(&row));
- write!(file, "\n{rows_csv}").map_err(|e| format!("Failed to write CSV rows: {e}"))?;
+ if let Some(file) = text_file.as_mut() {
+ let rows = format_text_export_rows(format, std::slice::from_ref(&row));
+ write!(file, "\n{rows}").map_err(|e| format!("Failed to write export rows: {e}"))?;
} else if let Some(writer) = xlsx.as_mut() {
writer.write_row(&row).map_err(|e| format!("Failed to write XLSX row: {e}"))?;
} else {
@@ -1169,8 +1183,8 @@ async fn try_export_clickhouse_query_result_stream(
on_progress(progress(request, rows_exported, ExportStatus::Running, None));
}
on_progress(progress(request, rows_exported, ExportStatus::Writing, None));
- if let Some(file) = csv_file.as_mut() {
- file.flush().map_err(|e| format!("Failed to flush CSV file: {e}"))?;
+ if let Some(file) = text_file.as_mut() {
+ file.flush().map_err(|e| format!("Failed to flush text export file: {e}"))?;
}
if let Some(writer) = xlsx {
let mut buf =
@@ -1221,7 +1235,7 @@ async fn try_export_sqlserver_query_result_stream(
let mut last_progress_rows = 0_u64;
let mut last_progress_at = Instant::now();
let progress_row_interval = request.page_size.max(1) as u64;
- let mut csv_file = if format == "csv" {
+ let mut text_file = if format == "csv" || format == "txt" {
let mut file =
BufWriter::new(File::create(&request.file_path).map_err(|e| format!("Failed to create file: {e}"))?);
file.write_all(b"\xEF\xBB\xBF").map_err(|e| format!("Failed to write BOM: {e}"))?;
@@ -1251,10 +1265,9 @@ async fn try_export_sqlserver_query_result_stream(
match item {
crate::db::sqlserver::SqlServerStreamItem::Columns(stream_columns) => {
columns = stream_columns.to_vec();
- if let Some(file) = csv_file.as_mut() {
- let csv = format_query_result_csv(&columns, &[]);
- let header = csv.strip_suffix('\n').unwrap_or(&csv);
- file.write_all(header.as_bytes()).map_err(|e| format!("Failed to write CSV: {e}"))?;
+ if let Some(file) = text_file.as_mut() {
+ let header = format_text_export_header(format, &columns);
+ file.write_all(header.as_bytes()).map_err(|e| format!("Failed to write export header: {e}"))?;
} else {
let xlsx_file =
File::create(&request.file_path).map_err(|e| format!("Failed to create XLSX file: {e}"))?;
@@ -1270,9 +1283,9 @@ async fn try_export_sqlserver_query_result_stream(
if xlsx_hard_limit_active && rows_exported as usize >= XLSX_MAX_DATA_ROWS {
return Err(XLSX_ROW_LIMIT_ERROR.to_string());
}
- if let Some(file) = csv_file.as_mut() {
- let rows_csv = format_query_result_csv_rows(&[row.to_vec()]);
- write!(file, "\n{rows_csv}").map_err(|e| format!("Failed to write CSV rows: {e}"))?;
+ if let Some(file) = text_file.as_mut() {
+ let rows = format_text_export_rows(format, &[row.to_vec()]);
+ write!(file, "\n{rows}").map_err(|e| format!("Failed to write export rows: {e}"))?;
} else if let Some(writer) = xlsx.as_mut() {
writer.write_row(row).map_err(|e| format!("Failed to write XLSX row: {e}"))?;
} else {
@@ -1317,8 +1330,8 @@ async fn try_export_sqlserver_query_result_stream(
on_progress(progress(request, rows_exported, ExportStatus::Running, None));
}
on_progress(progress(request, rows_exported, ExportStatus::Writing, None));
- if let Some(file) = csv_file.as_mut() {
- file.flush().map_err(|e| format!("Failed to flush CSV file: {e}"))?;
+ if let Some(file) = text_file.as_mut() {
+ file.flush().map_err(|e| format!("Failed to flush text export file: {e}"))?;
}
if let Some(writer) = xlsx {
let mut buf =
@@ -1360,6 +1373,16 @@ mod tests {
assert_eq!(effective_row_limit("csv", &request("csv", None, None)), None);
}
+ #[test]
+ fn txt_unlimited_export_has_no_effective_row_limit() {
+ assert_eq!(effective_row_limit("txt", &request("txt", None, None)), None);
+ }
+
+ #[test]
+ fn txt_export_header_keeps_columns_for_empty_results() {
+ assert_eq!(format_text_export_header("txt", &["id".to_string(), "note".to_string()]), "id\tnote");
+ }
+
#[test]
fn xlsx_unlimited_export_uses_excel_hard_limit() {
assert_eq!(effective_row_limit("xlsx", &request("xlsx", None, None)), Some(XLSX_MAX_DATA_ROWS));
diff --git a/crates/dbx-core/src/table_export.rs b/crates/dbx-core/src/table_export.rs
index 15919bd2c7..fe84a71189 100644
--- a/crates/dbx-core/src/table_export.rs
+++ b/crates/dbx-core/src/table_export.rs
@@ -8,7 +8,7 @@ use tokio_util::sync::CancellationToken;
use crate::connection::MysqlMode;
use crate::connection::{task_client_session_id, AppState, PoolKind};
-use crate::csv_export::{escape_csv, format_csv, value_to_csv_text};
+use crate::csv_export::{escape_csv, format_csv, format_tsv, format_tsv_rows, value_to_csv_text};
pub use crate::database_export::ExportStatus;
use crate::database_export::{build_export_insert_statements, is_export_cancelled, BuildExportInsertStatementsOptions};
use crate::db::agent_driver::AgentTableReadStartParams;
@@ -36,7 +36,7 @@ pub struct TableExportRequest {
pub schema: Option<String>,
pub table_name: String,
pub file_path: String,
- /// "csv", "xlsx", "json", "markdown", or "sql"
+ /// "csv", "xlsx", "json", "markdown", "sql", or "txt"
pub format: String,
#[serde(default)]
pub columns: Option<Vec<String>>,
@@ -505,6 +505,45 @@ async fn try_export_native_table_stream(
}
result
}
+ "txt" => {
+ let mut file = BufWriter::new(
+ std::fs::File::create(&request.file_path).map_err(|e| format!("Failed to create file: {e}"))?,
+ );
+ let header = format_tsv(col_names, &[]);
+ let header = header.strip_suffix('\n').unwrap_or(&header);
+ file.write_all(header.as_bytes()).map_err(|e| format!("Failed to write TXT: {e}"))?;
+
+ let result = stream_native_table_rows(
+ state,
+ pool_key,
+ db_type,
+ &sql,
+ row_limit,
+ &cancelled,
+ cancel_token.clone(),
+ |row| {
+ let row_tsv = format_tsv_rows(&[row.to_vec()]);
+ write!(file, "\n{row_tsv}").map_err(|e| format!("Failed to write TXT rows: {e}"))?;
+ rows_exported += 1;
+ if rows_exported % progress_interval == 0 {
+ on_progress(TableExportProgress {
+ export_id: request.export_id.clone(),
+ table_name: request.table_name.clone(),
+ rows_exported,
+ total_rows,
+ status: ExportStatus::Running,
+ error_message: None,
+ });
+ }
+ Ok(())
+ },
+ )
+ .await;
+ if result.is_ok() {
+ file.flush().map_err(|e| format!("Failed to flush export file: {e}"))?;
+ }
+ result
+ }
"xlsx" => {
let column_types = export_column_types(request);
let xlsx_file =
@@ -979,6 +1018,85 @@ pub async fn export_table_data_core(
}
}
}
+ "txt" => {
+ let mut is_first_batch = true;
+ let header = format_tsv(&col_names, &[]);
+ let header = header.strip_suffix('\n').unwrap_or(&header);
+ file.write_all(header.as_bytes()).map_err(|e| format!("Failed to write TXT: {e}"))?;
+
+ loop {
+ if is_export_cancelled(&request.export_id).await {
+ on_progress(TableExportProgress {
+ export_id: request.export_id.clone(),
+ table_name: request.table_name.clone(),
+ rows_exported,
+ total_rows,
+ status: ExportStatus::Cancelled,
+ error_message: Some("Export cancelled".to_string()),
+ });
+ close_table_read_session_if_open(state, &pool_key, &mut table_read_session_id).await;
+ return Ok(());
+ }
+
+ let Some(active_batch_size) = next_export_batch_size(row_limit, rows_exported, batch_size) else {
+ break;
+ };
+ let result = fetch_table_export_batch(
+ state,
+ &pool_key,
+ request,
+ &db_type,
+ &col_names,
+ &primary_keys,
+ use_keyset,
+ &last_pk_values,
+ offset,
+ active_batch_size,
+ &mut table_read_session_id,
+ &mut table_read_attempted,
+ &mut table_read_completed,
+ )
+ .await?;
+ let row_count = result.rows.len();
+ if row_count == 0 {
+ break;
+ }
+
+ if is_first_batch {
+ let rows_tsv = format_tsv_rows(&result.rows);
+ write!(file, "\n{rows_tsv}").map_err(|e| format!("Failed to write TXT rows: {e}"))?;
+ is_first_batch = false;
+ } else {
+ let rows_tsv = format_tsv_rows(&result.rows);
+ if !rows_tsv.is_empty() {
+ write!(file, "\n{rows_tsv}").map_err(|e| format!("Failed to write TXT rows: {e}"))?;
+ }
+ }
+
+ rows_exported += row_count as u64;
+
+ if use_keyset {
+ if let Some(last_row) = result.rows.last() {
+ last_pk_values = pk_indices.iter().map(|&i| last_row[i].clone()).collect();
+ }
+ } else {
+ offset += row_count as u64;
+ }
+
+ on_progress(TableExportProgress {
+ export_id: request.export_id.clone(),
+ table_name: request.table_name.clone(),
+ rows_exported,
+ total_rows,
+ status: ExportStatus::Running,
+ error_message: None,
+ });
+
+ if row_count < active_batch_size {
+ break;
+ }
+ }
+ }
"xlsx" => {
let column_types = export_column_types(request);
// Create a dedicated file handle for the streaming XLSX writer
@@ -1403,6 +1521,44 @@ mod tests {
assert_eq!(out, "\"just\",\"one\"");
}
+ // -----------------------------------------------------------------------
+ // format_tsv (Navicat-style TXT export)
+ // -----------------------------------------------------------------------
+
+ #[test]
+ fn formats_tsv_with_header_and_tab_separated_values() {
+ let columns = vec!["id".to_string(), "name".to_string()];
+ let rows = vec![vec![json!(1), json!("Alice")], vec![json!(2), json!("Bob")]];
+ assert_eq!(format_tsv(&columns, &rows), "id\tname\n1\tAlice\n2\tBob");
+ }
+
+ #[test]
+ fn formats_tsv_renders_null_as_empty() {
+ let columns = vec!["id".to_string(), "note".to_string()];
+ let rows = vec![vec![json!(1), Value::Null]];
+ assert_eq!(format_tsv(&columns, &rows), "id\tnote\n1\t");
+ }
+
+ #[test]
+ fn formats_tsv_quotes_fields_containing_tab_or_newline() {
+ let columns = vec!["a".to_string(), "b".to_string()];
+ let rows = vec![vec![json!("x\ty"), json!("line1\nline2")]];
+ assert_eq!(format_tsv(&columns, &rows), "a\tb\n\"x\ty\"\t\"line1\nline2\"");
+ }
+
+ #[test]
+ fn formats_tsv_escapes_embedded_quotes() {
+ let columns = vec!["name".to_string()];
+ let rows = vec![vec![json!(r#"Bob "Builder""#)]];
+ assert_eq!(format_tsv(&columns, &rows), "name\n\"Bob \"\"Builder\"\"\"");
+ }
+
+ #[test]
+ fn formats_tsv_rows_returns_empty_for_empty_rows() {
+ let rows: Vec<Vec<Value>> = vec![];
+ assert_eq!(format_tsv_rows(&rows), "");
+ }
+
#[test]
fn export_batch_size_respects_row_limit_remaining_rows() {
assert_eq!(next_export_batch_size(None, 12_000, 10_000), Some(10_000));
diff --git a/src-tauri/src/commands/table_export.rs b/src-tauri/src/commands/table_export.rs
index 9cdde5ca5d..ca3d9c8cdd 100644
--- a/src-tauri/src/commands/table_export.rs
+++ b/src-tauri/src/commands/table_export.rs
@@ -1,4 +1,7 @@
-use std::sync::Arc;
+use std::sync::{
+ atomic::{AtomicBool, Ordering},
+ Arc,
+};
use tauri::{AppHandle, Emitter, State};
use crate::commands::connection::AppState;
@@ -9,6 +12,13 @@ fn emit_progress(app: &AppHandle, progress: TableExportProgress) {
let _ = app.emit("table-export-progress", progress);
}
+async fn remove_incomplete_export(file_path: &str, failed: bool, cancelled: bool) {
+ // A cancelled core export returns Ok, so cleanup must also follow the emitted terminal status.
+ if failed || cancelled {
+ let _ = tokio::fs::remove_file(file_path).await;
+ }
+}
+
#[tauri::command]
pub async fn start_table_export(
app: AppHandle,
@@ -17,16 +27,27 @@ pub async fn start_table_export(
) -> Result<(), String> {
let state = state.inner().clone();
let export_id = request.export_id.clone();
+ let file_path = request.file_path.clone();
tokio::spawn(async move {
- let result =
- dbx_core::table_export::export_table_data_core(&state, &request, |progress| emit_progress(&app, progress))
- .await;
+ let cancelled = Arc::new(AtomicBool::new(false));
+ let cancelled_progress = cancelled.clone();
+ let result = dbx_core::table_export::export_table_data_core(&state, &request, |progress| {
+ if matches!(progress.status, ExportStatus::Cancelled) {
+ cancelled_progress.store(true, Ordering::SeqCst);
+ }
+ emit_progress(&app, progress);
+ })
+ .await;
let client_session_id = dbx_core::table_export::table_export_client_session_id(&export_id);
let _ =
state.close_client_session_pool(&request.connection_id, Some(&request.database), &client_session_id).await;
+ let failed = result.is_err();
+ let was_cancelled = cancelled.load(Ordering::SeqCst);
+ remove_incomplete_export(&file_path, failed, was_cancelled).await;
+
if let Err(e) = result {
emit_progress(
&app,
@@ -52,3 +73,42 @@ pub async fn cancel_table_export(export_id: String) -> Result<(), String> {
dbx_core::database_export::set_export_cancelled(&export_id).await;
Ok(())
}
+
+#[cfg(test)]
+mod tests {
+ use super::remove_incomplete_export;
+
+ async fn create_export_file(name: &str) -> std::path::PathBuf {
+ let path = std::env::temp_dir().join(format!("dbx-table-export-{name}-{}", uuid::Uuid::new_v4()));
+ tokio::fs::write(&path, b"partial export").await.unwrap();
+ path
+ }
+
+ #[tokio::test]
+ async fn removes_export_file_after_cancellation() {
+ let path = create_export_file("cancelled").await;
+
+ remove_incomplete_export(path.to_str().unwrap(), false, true).await;
+
+ assert!(!path.exists());
+ }
+
+ #[tokio::test]
+ async fn removes_export_file_after_error() {
+ let path = create_export_file("failed").await;
+
+ remove_incomplete_export(path.to_str().unwrap(), true, false).await;
+
+ assert!(!path.exists());
+ }
+
+ #[tokio::test]
+ async fn preserves_successful_export_file() {
+ let path = create_export_file("completed").await;
+
+ remove_incomplete_export(path.to_str().unwrap(), false, false).await;
+
+ assert!(path.exists());
+ tokio::fs::remove_file(path).await.unwrap();
+ }
+}