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。

fix(export): stream full table exports correctly

t8y2388873213fb9
diff --git a/apps/desktop/src/components/grid/DataGrid.vue b/apps/desktop/src/components/grid/DataGrid.vue
index e7c11ddc7f..64a70908a0 100644
--- a/apps/desktop/src/components/grid/DataGrid.vue
+++ b/apps/desktop/src/components/grid/DataGrid.vue
@@ -3547,7 +3547,13 @@ const {
sql: computed(() => props.sql),
tableMeta: computed(() => (props.tableMeta ? { ...props.tableMeta } : undefined)),
databaseType: computed(() => props.databaseType),
+ connectionId: computed(() => props.connectionId),
+ database: computed(() => props.database),
+ context: computed(() => props.context),
sourceColumns: visibleSourceColumns,
+ whereInput: computed(() => currentWhereInput()),
+ orderBy: computed(() => currentOrderBy()),
+ exportBatchSize: computed(() => settingsStore.editorSettings.exportBatchSize),
hasCellSelection,
selectedCells,
selectedRange,
diff --git a/apps/desktop/src/composables/useDataGridExport.ts b/apps/desktop/src/composables/useDataGridExport.ts
index f35c7bd296..62df03d052 100644
--- a/apps/desktop/src/composables/useDataGridExport.ts
+++ b/apps/desktop/src/composables/useDataGridExport.ts
@@ -16,6 +16,7 @@ import { tryStartExclusiveActivation, type ActionActivationGuard } from "@/lib/a
import { copyToClipboard } from "@/lib/clipboard";
import { buildDataGridCopyInsertStatement, buildDataGridCopyUpdateStatements } from "@/lib/dataGridSql";
import { formatSqlInsert } from "@/lib/exportFormats";
+import { uuid } from "@/lib/utils";
import type { DatabaseType, QueryResult } from "@/types/database";
interface RowItem {
@@ -35,7 +36,13 @@ export interface UseDataGridExportOptions {
sql: ComputedRef<string | undefined>;
tableMeta: ComputedRef<{ schema?: string; tableName: string; primaryKeys: string[] } | undefined>;
databaseType: ComputedRef<DatabaseType | undefined>;
+ connectionId: ComputedRef<string | undefined>;
+ database: ComputedRef<string | undefined>;
+ context: ComputedRef<"results" | "table-data" | undefined>;
sourceColumns: ComputedRef<Array<string | undefined> | undefined>;
+ whereInput: ComputedRef<string | undefined>;
+ orderBy: ComputedRef<string | undefined>;
+ exportBatchSize: ComputedRef<number>;
hasCellSelection: ComputedRef<boolean>;
selectedCells: ComputedRef<SelectionData>;
selectedRange: ComputedRef<CellSelectionRange | null>;
@@ -95,6 +102,12 @@ export function useDataGridExport(options: UseDataGridExportOptions) {
tableMeta,
sourceColumns,
databaseType,
+ connectionId,
+ database,
+ context,
+ whereInput,
+ orderBy,
+ exportBatchSize,
hasCellSelection,
selectedCells,
selectedRange,
@@ -453,6 +466,8 @@ export function useDataGridExport(options: UseDataGridExportOptions) {
async function exportCsv(rowIds?: number[]) {
await runExclusiveExport(async () => {
try {
+ if (await exportFullTableDataViaBackend("csv", rowIds)) return;
+
const needsFullExport = !rowIds?.length && !!fullExportResult;
if (needsFullExport && exportProgressDialog && exportProgressState) {
exportProgressState.value = {
@@ -514,6 +529,8 @@ export function useDataGridExport(options: UseDataGridExportOptions) {
async function exportJson(rowIds?: number[]) {
await runExclusiveExport(async () => {
try {
+ if (await exportFullTableDataViaBackend("json", rowIds)) return;
+
let outputPath = "export.json";
if (isTauriRuntime()) {
const { save } = await import("@tauri-apps/plugin-dialog");
@@ -536,6 +553,8 @@ export function useDataGridExport(options: UseDataGridExportOptions) {
async function exportMarkdown(rowIds?: number[]) {
await runExclusiveExport(async () => {
try {
+ if (await exportFullTableDataViaBackend("markdown", rowIds)) return;
+
let outputPath = "export.md";
if (isTauriRuntime()) {
const { save } = await import("@tauri-apps/plugin-dialog");
@@ -558,6 +577,8 @@ export function useDataGridExport(options: UseDataGridExportOptions) {
async function exportXlsx(rowIds?: number[]) {
await runExclusiveExport(async () => {
try {
+ if (await exportFullTableDataViaBackend("xlsx", rowIds)) return;
+
let outputPath = "export.xlsx";
if (isTauriRuntime()) {
const { save } = await import("@tauri-apps/plugin-dialog");
@@ -617,9 +638,88 @@ export function useDataGridExport(options: UseDataGridExportOptions) {
});
}
+ async function exportFullTableDataViaBackend(
+ format: "csv" | "xlsx" | "json" | "markdown" | "sql",
+ rowIds?: number[],
+ ): Promise<boolean> {
+ const meta = tableMeta.value;
+ if (rowIds?.length || context.value !== "table-data" || !meta || !connectionId.value || !database.value) {
+ return false;
+ }
+
+ const extension = format === "markdown" ? "md" : format;
+ const filterName =
+ format === "csv"
+ ? "CSV"
+ : format === "xlsx"
+ ? "Excel"
+ : format === "json"
+ ? "JSON"
+ : format === "markdown"
+ ? "Markdown"
+ : "SQL";
+ let outputPath = `${meta.tableName || "export"}.${extension}`;
+ if (isTauriRuntime()) {
+ const { save } = await import("@tauri-apps/plugin-dialog");
+ const path = await save({
+ defaultPath: outputPath,
+ filters: [{ name: filterName, extensions: [extension] }],
+ });
+ if (!path) return true;
+ outputPath = path as string;
+ }
+
+ if (exportProgressState) {
+ exportProgressState.value = {
+ title: t("exportProgress.title"),
+ tableName: meta.tableName,
+ format,
+ rowsExported: 0,
+ totalRows: null,
+ status: "Running",
+ errorMessage: null,
+ };
+ }
+ if (exportProgressDialog) exportProgressDialog.value = true;
+
+ await api.startTableExport(
+ {
+ exportId: uuid(),
+ connectionId: connectionId.value,
+ database: database.value,
+ schema: meta.schema,
+ tableName: meta.tableName,
+ filePath: outputPath,
+ format,
+ columns: columns.value,
+ primaryKeys: meta.primaryKeys,
+ whereInput: whereInput.value,
+ orderBy: orderBy.value,
+ skipCount: true,
+ batchSize: exportBatchSize.value,
+ },
+ (progress) => {
+ if (exportProgressState) {
+ exportProgressState.value = {
+ ...exportProgressState.value,
+ tableName: progress.tableName || meta.tableName,
+ rowsExported: progress.rowsExported,
+ totalRows: progress.totalRows,
+ status: progress.status,
+ errorMessage: progress.errorMessage || null,
+ };
+ }
+ },
+ );
+ toast(t("grid.exported"));
+ return true;
+ }
+
async function exportSql(rowIds?: number[]) {
await runExclusiveExport(async () => {
try {
+ if (await exportFullTableDataViaBackend("sql", rowIds)) return;
+
const result = await resultToExport(rowIds);
const exportData = sqlInsertExportData(result);
const content = await formatSqlInsert({
diff --git a/apps/desktop/src/lib/http.ts b/apps/desktop/src/lib/http.ts
index 5fc7ba8d40..d71341f774 100644
--- a/apps/desktop/src/lib/http.ts
+++ b/apps/desktop/src/lib/http.ts
@@ -1137,7 +1137,7 @@ export async function startTableExport(
}
function downloadTableExportFile(exportId: string, format: string): void {
- const ext = format === "csv" ? "csv" : "xlsx";
+ const ext = format === "markdown" || format === "md" ? "md" : format;
const a = document.createElement("a");
a.href = `/api/export/table/download/${exportId}`;
a.download = `table_export_${exportId}.${ext}`;
diff --git a/apps/desktop/src/lib/tauri.ts b/apps/desktop/src/lib/tauri.ts
index d1c0adb2e7..d7914b9214 100644
--- a/apps/desktop/src/lib/tauri.ts
+++ b/apps/desktop/src/lib/tauri.ts
@@ -1517,8 +1517,12 @@ export interface TableExportRequest {
schema?: string;
tableName: string;
filePath: string;
- format: "csv" | "xlsx";
+ format: "csv" | "xlsx" | "json" | "markdown" | "sql";
columns?: string[];
+ primaryKeys?: string[];
+ whereInput?: string;
+ orderBy?: string;
+ skipCount?: boolean;
batchSize?: number;
}
diff --git a/apps/desktop/src/stores/queryStore.ts b/apps/desktop/src/stores/queryStore.ts
index 42f3222b29..b7b723593c 100644
--- a/apps/desktop/src/stores/queryStore.ts
+++ b/apps/desktop/src/stores/queryStore.ts
@@ -1,6 +1,6 @@
import { defineStore } from "pinia";
import { uuid } from "@/lib/utils";
-import { ref, watch, computed } from "vue";
+import { markRaw, ref, watch, computed } from "vue";
import { useI18n } from "vue-i18n";
import type { DatabaseType, QueryResult, QueryTab } from "@/types/database";
import { orderPinnedFirst } from "@/lib/pinnedItems";
@@ -28,6 +28,8 @@ import {
import { AGENT_DRIVER_TYPES } from "@/lib/databaseCapabilities";
import { editablePrimaryKeys } from "@/lib/tableEditing";
import { TABLE_DATA_EXPORT_PAGE_SIZE } from "@/lib/tableDataExport";
+import { tableMetaForDataTab } from "@/lib/tableDataTabMeta";
+import { quoteTableIdentifier } from "@/lib/tableSelectSql";
import { queryTimeoutSecsForConnection } from "@/lib/queryTimeout";
import * as api from "@/lib/api";
import { useConnectionStore } from "@/stores/connectionStore";
@@ -38,6 +40,16 @@ const STORAGE_KEY = "dbx-open-tabs";
const ACTIVE_TAB_KEY = "dbx-active-tab";
const ORACLE_LIKE_METADATA_TYPES = new Set<string>(["oracle", "dameng", "oceanbase-oracle"]);
+function markQueryResultRowsRaw(result: QueryResult): QueryResult {
+ markRaw(result.rows);
+ return result;
+}
+
+function markQueryResultsRowsRaw(results: QueryResult[]): QueryResult[] {
+ for (const result of results) markQueryResultRowsRaw(result);
+ return results;
+}
+
async function withFrontendQueryTimeout<T>(promise: Promise<T>, timeoutSecs: number, message: string): Promise<T> {
if (timeoutSecs === 0) return promise;
@@ -540,12 +552,12 @@ export const useQueryStore = defineStore("query", () => {
function toErrorResult(e: any): NonNullable<QueryTab["result"]> {
const message = e instanceof Error ? e.message : String(e);
- return {
+ return markQueryResultRowsRaw({
columns: ["Error"],
rows: [[message]],
affected_rows: 0,
execution_time_ms: 0,
- };
+ });
}
function setErrorResult(id: string, e: any) {
@@ -834,7 +846,9 @@ export const useQueryStore = defineStore("query", () => {
if (current?.executionId === executionId) {
current.results = undefined;
current.activeResultIndex = undefined;
- current.result = mongoDocumentsToQueryResult(result.documents, performance.now() - startedAt, result.total);
+ current.result = markQueryResultRowsRaw(
+ mongoDocumentsToQueryResult(result.documents, performance.now() - startedAt, result.total),
+ );
touchResult(current);
current.queryAnalysis = undefined;
current.querySourceColumns = undefined;
@@ -866,7 +880,7 @@ export const useQueryStore = defineStore("query", () => {
if (current?.executionId === executionId) {
current.results = undefined;
current.activeResultIndex = undefined;
- current.result = mongoCountToQueryResult(result.total, performance.now() - startedAt);
+ current.result = markQueryResultRowsRaw(mongoCountToQueryResult(result.total, performance.now() - startedAt));
touchResult(current);
current.queryAnalysis = undefined;
current.querySourceColumns = undefined;
@@ -903,7 +917,9 @@ export const useQueryStore = defineStore("query", () => {
if (current?.executionId === executionId) {
current.results = undefined;
current.activeResultIndex = undefined;
- current.result = mongoDocumentsToQueryResult(result.documents, performance.now() - startedAt, result.total);
+ current.result = markQueryResultRowsRaw(
+ mongoDocumentsToQueryResult(result.documents, performance.now() - startedAt, result.total),
+ );
touchResult(current);
current.queryAnalysis = undefined;
current.querySourceColumns = undefined;
@@ -961,7 +977,7 @@ export const useQueryStore = defineStore("query", () => {
if (current?.executionId === executionId) {
current.results = undefined;
current.activeResultIndex = undefined;
- current.result = mongoWriteToQueryResult(affectedRows, performance.now() - startedAt);
+ current.result = markQueryResultRowsRaw(mongoWriteToQueryResult(affectedRows, performance.now() - startedAt));
touchResult(current);
current.queryAnalysis = undefined;
current.querySourceColumns = undefined;
@@ -999,10 +1015,12 @@ export const useQueryStore = defineStore("query", () => {
executionOptions,
);
const frontendTimeoutSecs = Math.max(queryTimeoutSecs * 2, 60);
- const results = await withFrontendQueryTimeout(
- executionPromise,
- queryTimeoutSecs === 0 ? 0 : frontendTimeoutSecs,
- t("editor.queryTimeoutError", { seconds: frontendTimeoutSecs }),
+ const results = markQueryResultsRowsRaw(
+ await withFrontendQueryTimeout(
+ executionPromise,
+ queryTimeoutSecs === 0 ? 0 : frontendTimeoutSecs,
+ t("editor.queryTimeoutError", { seconds: frontendTimeoutSecs }),
+ ),
);
console.info("[DBX][executeTabSql:execute-multi:done]", {
traceId,
@@ -1267,6 +1285,70 @@ export const useQueryStore = defineStore("query", () => {
async function fetchTabResultForExport(id: string): Promise<QueryResult | undefined> {
const tab = tabs.value.find((t) => t.id === id);
if (!tab?.result) return undefined;
+
+ if (tab.mode === "data") {
+ const connStore = useConnectionStore();
+ await connStore.ensureConnected(tab.connectionId);
+ const conn = connStore.getConfig(tab.connectionId);
+ const tableMeta = tableMetaForDataTab(tab);
+ if (!tableMeta?.tableName) return tab.result;
+
+ const pageLimit = TABLE_DATA_EXPORT_PAGE_SIZE;
+ const primaryKeys = tab.tableMeta
+ ? editablePrimaryKeys(conn?.db_type, tab.tableMeta.columns)
+ : tableMeta.primaryKeys;
+ const fallbackOrderColumns =
+ conn?.db_type === "sqlserver" && !primaryKeys.length
+ ? tableMeta.columns.slice(0, 1).map((column) => column.name)
+ : undefined;
+ const sortOrder =
+ tab.resultSortColumn && tab.resultSortDirection
+ ? `${quoteTableIdentifier(conn?.db_type, tab.resultSortColumn)} ${tab.resultSortDirection.toUpperCase()}`
+ : undefined;
+ const orderBy = tab.orderByInput?.trim() || sortOrder;
+ const queryTimeoutSecs = queryTimeoutSecsForConnection(conn);
+ const rows: QueryResult["rows"] = [];
+ let columns: string[] = [];
+ let executionTimeMs = 0;
+ let offset = 0;
+
+ while (true) {
+ const sql = await api.buildTableSelectSql({
+ databaseType: conn?.db_type,
+ schema: tableMeta.schema,
+ tableName: tableMeta.tableName,
+ columns: tableMeta.columns.map((column) => column.name),
+ primaryKeys,
+ fallbackOrderColumns,
+ whereInput: tab.whereInput,
+ orderBy,
+ limit: pageLimit,
+ offset,
+ });
+ const results = await api.executeMulti(tab.connectionId, tab.database, sql, undefined, undefined, {
+ maxRows: pageLimit,
+ fetchSize: pageLimit,
+ timeoutSecs: queryTimeoutSecs,
+ });
+ const result = results[0];
+ if (!result) break;
+ if (columns.length === 0) columns = result.columns;
+ rows.push(...result.rows);
+ executionTimeMs += result.execution_time_ms ?? 0;
+ if (result.rows.length < pageLimit) break;
+ offset += result.rows.length;
+ }
+
+ return {
+ columns: columns.length ? columns : tab.result.columns,
+ rows,
+ affected_rows: 0,
+ execution_time_ms: executionTimeMs,
+ truncated: false,
+ has_more: false,
+ };
+ }
+
if (tab.mode !== "query") return tab.result;
const sql = tab.resultSortedSql ?? tab.resultBaseSql ?? tab.lastExecutedSql ?? tab.sql;
diff --git a/apps/desktop/src/stores/settingsStore.ts b/apps/desktop/src/stores/settingsStore.ts
index ec3e1b71db..7d7db8d548 100644
--- a/apps/desktop/src/stores/settingsStore.ts
+++ b/apps/desktop/src/stores/settingsStore.ts
@@ -278,7 +278,7 @@ export const DEFAULT_EDITOR_SETTINGS: EditorSettings = {
columnFormatters: {},
customColumnFormatters: {},
snippets: DEFAULT_SQL_SNIPPETS,
- exportBatchSize: 2000,
+ exportBatchSize: 10000,
};
export const STORAGE_KEY = "dbx-editor-settings";
diff --git a/crates/dbx-core/src/table_export.rs b/crates/dbx-core/src/table_export.rs
index 5f5595a6f8..292cb39f2a 100644
--- a/crates/dbx-core/src/table_export.rs
+++ b/crates/dbx-core/src/table_export.rs
@@ -1,15 +1,18 @@
use serde::{Deserialize, Serialize};
use serde_json::Value;
-use std::io::Write;
+use std::io::{BufWriter, Write};
use crate::connection::AppState;
use crate::csv_export::{escape_csv, format_csv, value_to_csv_text};
-use crate::database_export::is_export_cancelled;
pub use crate::database_export::ExportStatus;
-use crate::transfer::{count_sql, execute_on_pool, keyset_pagination_sql, pagination_sql};
+use crate::database_export::{build_export_insert_statements, is_export_cancelled, BuildExportInsertStatementsOptions};
+use crate::transfer::{
+ count_sql_with_where, execute_on_pool, execute_on_pool_with_max_rows, keyset_pagination_sql,
+ pagination_sql_with_filter_order,
+};
use crate::xlsx_export::{build_xlsx_workbook, XlsxWorksheetData};
-const DEFAULT_BATCH_SIZE: usize = 2000;
+const DEFAULT_BATCH_SIZE: usize = 10_000;
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
@@ -20,10 +23,18 @@ pub struct TableExportRequest {
pub schema: Option<String>,
pub table_name: String,
pub file_path: String,
- /// "csv" or "xlsx"
+ /// "csv", "xlsx", "json", "markdown", or "sql"
pub format: String,
#[serde(default)]
pub columns: Option<Vec<String>>,
+ #[serde(default)]
+ pub primary_keys: Option<Vec<String>>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub where_input: Option<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub order_by: Option<String>,
+ #[serde(default)]
+ pub skip_count: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub batch_size: Option<usize>,
}
@@ -49,6 +60,90 @@ fn format_csv_rows(rows: &[Vec<Value>]) -> String {
.join("\n")
}
+fn write_json_row_object<W: Write>(writer: &mut W, columns: &[String], row: &[Value]) -> Result<(), String> {
+ writer.write_all(b"{\n").map_err(|e| format!("Failed to write JSON: {e}"))?;
+ let mut first = true;
+ for (index, column) in columns.iter().enumerate() {
+ let Some(value) = row.get(index) else {
+ continue;
+ };
+ if !first {
+ writer.write_all(b",\n").map_err(|e| format!("Failed to write JSON: {e}"))?;
+ }
+ writer.write_all(b" ").map_err(|e| format!("Failed to write JSON: {e}"))?;
+ serde_json::to_writer(&mut *writer, column).map_err(|e| format!("Failed to write JSON: {e}"))?;
+ writer.write_all(b": ").map_err(|e| format!("Failed to write JSON: {e}"))?;
+ serde_json::to_writer(&mut *writer, value).map_err(|e| format!("Failed to write JSON: {e}"))?;
+ first = false;
+ }
+ writer.write_all(b"\n}").map_err(|e| format!("Failed to write JSON: {e}"))
+}
+
+fn display_cell(value: &Value) -> String {
+ match value {
+ Value::Null => "NULL".to_string(),
+ Value::Bool(value) => value.to_string(),
+ Value::Number(value) => value.to_string(),
+ Value::String(value) => value.clone(),
+ other => other.to_string(),
+ }
+}
+
+fn markdown_cell(value: &str) -> String {
+ value.replace('|', "\\|").replace("\r\n", "<br>").replace('\n', "<br>")
+}
+
+fn format_markdown_header(columns: &[String]) -> String {
+ let header = columns.iter().map(|column| markdown_cell(column)).collect::<Vec<_>>().join(" | ");
+ let separator = columns.iter().map(|_| "---").collect::<Vec<_>>().join(" | ");
+ format!("| {header} |\n| {separator} |\n")
+}
+
+fn format_markdown_rows(rows: &[Vec<Value>]) -> String {
+ rows.iter()
+ .map(|row| {
+ let cells = row.iter().map(|cell| markdown_cell(&display_cell(cell))).collect::<Vec<_>>().join(" | ");
+ format!("| {cells} |")
+ })
+ .collect::<Vec<_>>()
+ .join("\n")
+}
+
+fn table_page_sql(
+ request: &TableExportRequest,
+ db_type: &crate::models::connection::DatabaseType,
+ col_names: &[String],
+ primary_keys: &[String],
+ use_keyset: bool,
+ last_pk_values: &[Value],
+ offset: u64,
+ batch_size: usize,
+) -> String {
+ if use_keyset {
+ keyset_pagination_sql(
+ col_names,
+ &request.table_name,
+ request.schema.as_deref().unwrap_or(""),
+ db_type,
+ primary_keys,
+ last_pk_values,
+ batch_size,
+ )
+ } else {
+ pagination_sql_with_filter_order(
+ col_names,
+ &request.table_name,
+ request.schema.as_deref().unwrap_or(""),
+ db_type,
+ offset,
+ batch_size,
+ request.where_input.as_deref(),
+ request.order_by.as_deref(),
+ primary_keys,
+ )
+ }
+}
+
pub async fn export_table_data_core(
state: &AppState,
request: &TableExportRequest,
@@ -66,34 +161,24 @@ pub async fn export_table_data_core(
// 2. Get pool
let pool_key = state.get_or_create_pool(&request.connection_id, Some(&request.database)).await?;
- // 3. Get columns
- let columns = crate::schema::get_columns_core(
- state,
- &request.connection_id,
- &request.database,
- request.schema.as_deref().unwrap_or(""),
- &request.table_name,
- )
- .await?;
-
- let col_names: Vec<String> = columns.iter().map(|c| c.name.clone()).collect();
-
- // 4. Extract primary keys from column metadata (before column filtering)
- let primary_keys: Vec<String> = columns.iter().filter(|c| c.is_primary_key).map(|c| c.name.clone()).collect();
-
- // 5. Optionally filter to requested columns
- let col_names = if let Some(requested_cols) = &request.columns {
- if requested_cols.is_empty() {
- col_names
- } else {
- let filtered: Vec<String> = requested_cols.iter().filter(|c| col_names.contains(c)).cloned().collect();
- if filtered.is_empty() {
- return Err("None of the requested columns exist in the table".to_string());
- }
- filtered
- }
+ // 3. Resolve columns. Data grid exports can provide columns/primary keys
+ // directly, which avoids expensive metadata round-trips on JDBC drivers.
+ let requested_columns = request.columns.as_ref().filter(|columns| !columns.is_empty());
+ let (col_names, primary_keys) = if let Some(requested_columns) = requested_columns {
+ let primary_keys = request.primary_keys.clone().unwrap_or_default();
+ (requested_columns.clone(), primary_keys)
} else {
- col_names
+ let columns = crate::schema::get_columns_core(
+ state,
+ &request.connection_id,
+ &request.database,
+ request.schema.as_deref().unwrap_or(""),
+ &request.table_name,
+ )
+ .await?;
+ let col_names: Vec<String> = columns.iter().map(|c| c.name.clone()).collect();
+ let primary_keys: Vec<String> = columns.iter().filter(|c| c.is_primary_key).map(|c| c.name.clone()).collect();
+ (col_names, primary_keys)
};
if col_names.is_empty() {
@@ -103,7 +188,10 @@ pub async fn export_table_data_core(
// Use keyset pagination when all PKs are in the selected (filtered) columns.
// This avoids the OFFSET performance penalty for large tables.
// When no PK is available, falls back to offset-based pagination.
- let use_keyset = !primary_keys.is_empty() && primary_keys.iter().all(|pk| col_names.contains(pk));
+ let has_custom_filter_or_order = request.where_input.as_ref().is_some_and(|value| !value.trim().is_empty())
+ || request.order_by.as_ref().is_some_and(|value| !value.trim().is_empty());
+ let use_keyset =
+ !has_custom_filter_or_order && !primary_keys.is_empty() && primary_keys.iter().all(|pk| col_names.contains(pk));
// PK column indices within result rows (for extracting last-row values)
let pk_indices: Vec<usize> = if use_keyset {
@@ -112,15 +200,26 @@ pub async fn export_table_data_core(
Vec::new()
};
- // 6. Get total row count for progress estimation
- let count_query = count_sql(&request.table_name, request.schema.as_deref().unwrap_or(""), &db_type);
- let total_rows = match execute_on_pool(state, &pool_key, &count_query).await {
- Ok(result) => result.rows.first().and_then(|r| r.first()).and_then(|v| match v {
- Value::Number(n) => n.as_u64(),
- Value::String(s) => s.parse::<u64>().ok(),
- _ => None,
- }),
- Err(_) => None,
+ // 6. Get total row count for progress estimation when requested. Data
+ // grid exports skip this by default because COUNT can be the slowest query
+ // on large HANA/JDBC tables, especially with filters.
+ let total_rows = if request.skip_count {
+ None
+ } else {
+ let count_query = count_sql_with_where(
+ &request.table_name,
+ request.schema.as_deref().unwrap_or(""),
+ &db_type,
+ request.where_input.as_deref(),
+ );
+ match execute_on_pool(state, &pool_key, &count_query).await {
+ Ok(result) => result.rows.first().and_then(|r| r.first()).and_then(|v| match v {
+ Value::Number(n) => n.as_u64(),
+ Value::String(s) => s.parse::<u64>().ok(),
+ _ => None,
+ }),
+ Err(_) => None,
+ }
};
// 7. Emit initial Running progress
@@ -134,7 +233,8 @@ pub async fn export_table_data_core(
});
// 8. Create output file
- let mut file = std::fs::File::create(&request.file_path).map_err(|e| format!("Failed to create file: {e}"))?;
+ let file = std::fs::File::create(&request.file_path).map_err(|e| format!("Failed to create file: {e}"))?;
+ let mut file = BufWriter::new(file);
let mut rows_exported: u64 = 0;
let batch_size = request.batch_size.unwrap_or(DEFAULT_BATCH_SIZE).max(1);
@@ -164,28 +264,18 @@ pub async fn export_table_data_core(
return Ok(());
}
- let sql = if use_keyset {
- keyset_pagination_sql(
- &col_names,
- &request.table_name,
- request.schema.as_deref().unwrap_or(""),
- &db_type,
- &primary_keys,
- &last_pk_values,
- batch_size,
- )
- } else {
- pagination_sql(
- &col_names,
- &request.table_name,
- request.schema.as_deref().unwrap_or(""),
- &db_type,
- offset,
- batch_size,
- )
- };
-
- let result = execute_on_pool(state, &pool_key, &sql).await?;
+ let sql = table_page_sql(
+ request,
+ &db_type,
+ &col_names,
+ &primary_keys,
+ use_keyset,
+ &last_pk_values,
+ offset,
+ batch_size,
+ );
+
+ let result = execute_on_pool_with_max_rows(state, &pool_key, &sql, Some(batch_size)).await?;
let row_count = result.rows.len();
if row_count == 0 {
break;
@@ -246,28 +336,18 @@ pub async fn export_table_data_core(
return Ok(());
}
- let sql = if use_keyset {
- keyset_pagination_sql(
- &col_names,
- &request.table_name,
- request.schema.as_deref().unwrap_or(""),
- &db_type,
- &primary_keys,
- &last_pk_values,
- batch_size,
- )
- } else {
- pagination_sql(
- &col_names,
- &request.table_name,
- request.schema.as_deref().unwrap_or(""),
- &db_type,
- offset,
- batch_size,
- )
- };
-
- let result = execute_on_pool(state, &pool_key, &sql).await?;
+ let sql = table_page_sql(
+ request,
+ &db_type,
+ &col_names,
+ &primary_keys,
+ use_keyset,
+ &last_pk_values,
+ offset,
+ batch_size,
+ );
+
+ let result = execute_on_pool_with_max_rows(state, &pool_key, &sql, Some(batch_size)).await?;
let row_count = result.rows.len();
if row_count == 0 {
break;
@@ -315,11 +395,224 @@ pub async fn export_table_data_core(
let xlsx_bytes = build_xlsx_workbook(&workbook_data)?;
file.write_all(&xlsx_bytes).map_err(|e| format!("Failed to write XLSX file: {e}"))?;
}
+ "json" => {
+ file.write_all(b"[\n").map_err(|e| format!("Failed to write JSON: {e}"))?;
+ let mut is_first_row = true;
+
+ 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()),
+ });
+ return Ok(());
+ }
+
+ let sql = table_page_sql(
+ request,
+ &db_type,
+ &col_names,
+ &primary_keys,
+ use_keyset,
+ &last_pk_values,
+ offset,
+ batch_size,
+ );
+ let result = execute_on_pool_with_max_rows(state, &pool_key, &sql, Some(batch_size)).await?;
+ let row_count = result.rows.len();
+ if row_count == 0 {
+ break;
+ }
+
+ for row in &result.rows {
+ if !is_first_row {
+ file.write_all(b",\n").map_err(|e| format!("Failed to write JSON: {e}"))?;
+ }
+ write_json_row_object(&mut file, &col_names, row)?;
+ is_first_row = false;
+ }
+
+ 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 < batch_size {
+ break;
+ }
+ }
+
+ file.write_all(b"\n]\n").map_err(|e| format!("Failed to write JSON: {e}"))?;
+ }
+ "markdown" | "md" => {
+ file.write_all(format_markdown_header(&col_names).as_bytes())
+ .map_err(|e| format!("Failed to write Markdown: {e}"))?;
+ let mut wrote_rows = false;
+
+ 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()),
+ });
+ return Ok(());
+ }
+
+ let sql = table_page_sql(
+ request,
+ &db_type,
+ &col_names,
+ &primary_keys,
+ use_keyset,
+ &last_pk_values,
+ offset,
+ batch_size,
+ );
+ let result = execute_on_pool_with_max_rows(state, &pool_key, &sql, Some(batch_size)).await?;
+ let row_count = result.rows.len();
+ if row_count == 0 {
+ break;
+ }
+
+ let rows_markdown = format_markdown_rows(&result.rows);
+ if !rows_markdown.is_empty() {
+ if wrote_rows {
+ file.write_all(b"\n").map_err(|e| format!("Failed to write Markdown: {e}"))?;
+ }
+ file.write_all(rows_markdown.as_bytes()).map_err(|e| format!("Failed to write Markdown: {e}"))?;
+ wrote_rows = true;
+ }
+
+ 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 < batch_size {
+ break;
+ }
+ }
+
+ file.write_all(b"\n").map_err(|e| format!("Failed to write Markdown: {e}"))?;
+ }
+ "sql" => {
+ let mut wrote_statements = false;
+
+ 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()),
+ });
+ return Ok(());
+ }
+
+ let sql = table_page_sql(
+ request,
+ &db_type,
+ &col_names,
+ &primary_keys,
+ use_keyset,
+ &last_pk_values,
+ offset,
+ batch_size,
+ );
+ let result = execute_on_pool_with_max_rows(state, &pool_key, &sql, Some(batch_size)).await?;
+ let row_count = result.rows.len();
+ if row_count == 0 {
+ break;
+ }
+
+ let statements = build_export_insert_statements(BuildExportInsertStatementsOptions {
+ database_type: Some(db_type),
+ schema: request.schema.clone(),
+ table_name: Some(request.table_name.clone()),
+ qualified_table_name: None,
+ columns: col_names.clone(),
+ rows: result.rows.clone(),
+ batch_size: Some(100),
+ })?;
+ if !statements.is_empty() {
+ if wrote_statements {
+ file.write_all(b"\n").map_err(|e| format!("Failed to write SQL: {e}"))?;
+ }
+ file.write_all(statements.join("\n").as_bytes())
+ .map_err(|e| format!("Failed to write SQL: {e}"))?;
+ wrote_statements = true;
+ }
+
+ 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 < batch_size {
+ break;
+ }
+ }
+
+ if wrote_statements {
+ file.write_all(b"\n").map_err(|e| format!("Failed to write SQL: {e}"))?;
+ }
+ }
other => {
return Err(format!("Unsupported export format: {other}"));
}
}
+ file.flush().map_err(|e| format!("Failed to flush export file: {e}"))?;
+
// 8. Emit Done progress
on_progress(TableExportProgress {
export_id: request.export_id.clone(),
@@ -387,6 +680,19 @@ mod tests {
assert_eq!(out, "\"just\",\"one\"");
}
+ #[test]
+ fn writes_json_row_without_allocating_object_map() {
+ let mut out = Vec::new();
+ write_json_row_object(
+ &mut out,
+ &["id".to_string(), "name".to_string(), "missing".to_string()],
+ &[json!(1), json!("Ada")],
+ )
+ .unwrap();
+
+ assert_eq!(String::from_utf8(out).unwrap(), "{\n \"id\": 1,\n \"name\": \"Ada\"\n}");
+ }
+
#[test]
fn formats_csv_rows_escapes_embedded_commas_and_newlines() {
let rows = vec![vec![json!("hello,world"), json!("line1\nline2")]];
diff --git a/crates/dbx-core/src/transfer.rs b/crates/dbx-core/src/transfer.rs
index 6848988dee..5f13321484 100644
--- a/crates/dbx-core/src/transfer.rs
+++ b/crates/dbx-core/src/transfer.rs
@@ -1248,9 +1248,50 @@ pub fn pagination_sql_with_order(
}
}
+pub fn pagination_sql_with_filter_order(
+ columns: &[String],
+ table: &str,
+ schema: &str,
+ db_type: &DatabaseType,
+ offset: u64,
+ limit: usize,
+ where_input: Option<&str>,
+ order_by: Option<&str>,
+ default_order_columns: &[String],
+) -> String {
+ let full_table = qualified_table(table, schema, db_type);
+ let col_list = columns.iter().map(|c| quote_identifier(c, db_type)).collect::<Vec<_>>().join(", ");
+ let predicate = crate::sql_dialect::normalize_where_input(where_input);
+ let where_clause = if predicate.is_empty() { String::new() } else { format!(" WHERE ({predicate})") };
+ let order_expression = order_by
+ .map(str::trim)
+ .filter(|value| !value.is_empty())
+ .map(str::to_string)
+ .or_else(|| postgres_order_by_expression(default_order_columns, db_type));
+
+ match db_type {
+ DatabaseType::SqlServer | DatabaseType::Oracle => {
+ let order_by = order_expression.unwrap_or_else(|| "(SELECT NULL)".to_string());
+ format!(
+ "SELECT {col_list} FROM {full_table}{where_clause} ORDER BY {order_by} OFFSET {offset} ROWS FETCH NEXT {limit} ROWS ONLY"
+ )
+ }
+ _ => {
+ let order_by = order_expression.map(|value| format!(" ORDER BY {value}")).unwrap_or_default();
+ format!("SELECT {col_list} FROM {full_table}{where_clause}{order_by} LIMIT {limit} OFFSET {offset}")
+ }
+ }
+}
+
pub fn count_sql(table: &str, schema: &str, db_type: &DatabaseType) -> String {
+ count_sql_with_where(table, schema, db_type, None)
+}
+
+pub fn count_sql_with_where(table: &str, schema: &str, db_type: &DatabaseType, where_input: Option<&str>) -> String {
let full_table = qualified_table(table, schema, db_type);
- format!("SELECT COUNT(*) FROM {full_table}")
+ let predicate = crate::sql_dialect::normalize_where_input(where_input);
+ let where_clause = if predicate.is_empty() { String::new() } else { format!(" WHERE ({predicate})") };
+ format!("SELECT COUNT(*) FROM {full_table}{where_clause}")
}
pub fn keyset_pagination_sql(
@@ -1335,6 +1376,15 @@ fn value_to_sql_literal(value: &serde_json::Value, _db_type: &DatabaseType) -> S
}
pub async fn execute_on_pool(state: &AppState, pool_key: &str, sql: &str) -> Result<db::QueryResult, String> {
+ execute_on_pool_with_max_rows(state, pool_key, sql, None).await
+}
+
+pub async fn execute_on_pool_with_max_rows(
+ state: &AppState,
+ pool_key: &str,
+ sql: &str,
+ max_rows: Option<usize>,
+) -> Result<db::QueryResult, String> {
let connections = state.connections.read().await;
let pool = connections.get(pool_key).ok_or("Connection not found")?;
@@ -1343,29 +1393,29 @@ pub async fn execute_on_pool(state: &AppState, pool_key: &str, sql: &str) -> Res
let p = p.clone();
let bare = *mode == crate::connection::MysqlMode::Bare;
drop(connections);
- db::mysql::execute_query(&p, sql, bare).await
+ db::mysql::execute_query_with_max_rows(&p, sql, bare, max_rows, Default::default()).await
}
PoolKind::Postgres(p) => {
let p = p.clone();
drop(connections);
- db::postgres::execute_query(&p, sql).await
+ db::postgres::execute_query_with_max_rows(&p, sql, max_rows).await
}
PoolKind::Sqlite(p) => {
let p = p.clone();
drop(connections);
- db::sqlite::execute_query(&p, sql).await
+ db::sqlite::execute_query_with_max_rows(&p, sql, max_rows).await
}
PoolKind::ClickHouse(client) => {
let client = client.clone();
let database = database_from_pool_key(pool_key).unwrap_or("default").to_string();
drop(connections);
- db::clickhouse_driver::execute_query(&client, &database, sql).await
+ db::clickhouse_driver::execute_query_with_max_rows(&client, &database, sql, max_rows).await
}
PoolKind::SqlServer(client) => {
let client = client.clone();
drop(connections);
let mut client = client.lock().await;
- db::sqlserver::execute_query(&mut client, sql).await
+ db::sqlserver::execute_query_with_max_rows(&mut client, sql, max_rows).await
}
PoolKind::Agent(client) => {
let client = client.clone();
@@ -1377,7 +1427,7 @@ pub async fn execute_on_pool(state: &AppState, pool_key: &str, sql: &str) -> Res
&sql,
database.as_deref(),
None,
- QueryExecutionOptions { max_rows: None, ..QueryExecutionOptions::default() },
+ QueryExecutionOptions { max_rows, fetch_size: max_rows, ..QueryExecutionOptions::default() },
);
client.execute_query(params).await
}
@@ -1387,6 +1437,11 @@ pub async fn execute_on_pool(state: &AppState, pool_key: &str, sql: &str) -> Res
drop(connections);
tokio::task::spawn_blocking(move || {
let con = con.lock().map_err(|e| e.to_string())?;
+ if max_rows.is_some()
+ && starts_with_executable_sql_keyword(&sql, &["SELECT", "SHOW", "DESCRIBE", "WITH", "PRAGMA"])
+ {
+ return crate::query::duckdb_execute_with_max_rows(&con, &sql, max_rows);
+ }
let start = std::time::Instant::now();
if starts_with_executable_sql_keyword(&sql, &["SELECT", "SHOW", "DESCRIBE", "WITH", "PRAGMA"]) {
let mut stmt = con.prepare(&sql).map_err(|e| e.to_string())?;
@@ -1447,7 +1502,7 @@ pub async fn execute_on_pool(state: &AppState, pool_key: &str, sql: &str) -> Res
drop(connections);
tokio::task::spawn_blocking(move || {
let con = con.lock().map_err(|e| e.to_string())?;
- crate::query::duckdb_execute(&con, &sql)
+ crate::query::duckdb_execute_with_max_rows(&con, &sql, max_rows)
})
.await
.map_err(|e| e.to_string())?
@@ -2827,6 +2882,33 @@ mod tests {
assert_eq!(sql, "SELECT \"id\", \"name\" FROM \"public\".\"users\" ORDER BY \"id\" LIMIT 100 OFFSET 200");
}
+ #[test]
+ fn filtered_pagination_preserves_where_and_order() {
+ let sql = pagination_sql_with_filter_order(
+ &[String::from("id"), String::from("status")],
+ "users",
+ "public",
+ &DatabaseType::SapHana,
+ 10_000,
+ 2_000,
+ Some("WHERE status = 'active'"),
+ Some("\"id\" DESC"),
+ &[String::from("id")],
+ );
+
+ assert_eq!(
+ sql,
+ "SELECT \"id\", \"status\" FROM \"public\".\"users\" WHERE (status = 'active') ORDER BY \"id\" DESC LIMIT 2000 OFFSET 10000"
+ );
+ }
+
+ #[test]
+ fn filtered_count_preserves_where() {
+ let sql = count_sql_with_where("users", "public", &DatabaseType::SapHana, Some("WHERE status = 'active'"));
+
+ assert_eq!(sql, "SELECT COUNT(*) FROM \"public\".\"users\" WHERE (status = 'active')");
+ }
+
#[test]
fn sqlserver_keyset_pagination_includes_offset_fetch() {
let sql = keyset_pagination_sql(
diff --git a/crates/dbx-web/src/routes/table_export.rs b/crates/dbx-web/src/routes/table_export.rs
index 1944ac5bee..589fefabc4 100644
--- a/crates/dbx-web/src/routes/table_export.rs
+++ b/crates/dbx-web/src/routes/table_export.rs
@@ -43,6 +43,9 @@ pub async fn start_table_export(
let ext = match req.format.as_str() {
"csv" => "csv",
"xlsx" => "xlsx",
+ "json" => "json",
+ "markdown" | "md" => "md",
+ "sql" => "sql",
_ => return Err(AppError(format!("Unsupported export format: {}", req.format))),
};
let tmp_file = tmp_dir.join(format!("table_export_{export_id}.{ext}"));
@@ -138,6 +141,9 @@ pub async fn table_export_download(
let (content_type, file_ext) = match format.as_str() {
"csv" => ("text/csv; charset=utf-8", "csv"),
"xlsx" => ("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "xlsx"),
+ "json" => ("application/json; charset=utf-8", "json"),
+ "markdown" | "md" => ("text/markdown; charset=utf-8", "md"),
+ "sql" => ("application/sql; charset=utf-8", "sql"),
_ => return Err(AppError(format!("Unknown format: {format}"))),
};
diff --git a/packages/app-tests/queryStore.test.ts b/packages/app-tests/queryStore.test.ts
index 32ef4e909c..5aeb9191e9 100644
--- a/packages/app-tests/queryStore.test.ts
+++ b/packages/app-tests/queryStore.test.ts
@@ -1,6 +1,7 @@
import { strict as assert } from "node:assert";
import test from "node:test";
import { createPinia, setActivePinia } from "pinia";
+import { isReactive } from "vue";
import { useConnectionStore } from "../../apps/desktop/src/stores/connectionStore.ts";
import { useQueryStore } from "../../apps/desktop/src/stores/queryStore.ts";
import type { ConnectionConfig } from "../../apps/desktop/src/types/database.ts";
@@ -947,6 +948,124 @@ test("query result export fetches every paginated page", async () => {
}
});
+test("table data export fetches every filtered page", async () => {
+ const restoreStorage = installMemoryStorage();
+ setActivePinia(createPinia());
+ const connectionStore = useConnectionStore();
+ const store = useQueryStore();
+ const originalFetch = globalThis.fetch;
+ const buildRequests: unknown[] = [];
+ const executedSqls: string[] = [];
+
+ connectionStore.addEphemeralConnection({ ...conn("conn-1"), db_type: "saphana" });
+ const tabId = store.createTab("conn-1", "db", "users", "data", "public");
+ const tab = store.tabs.find((item) => item.id === tabId);
+ assert.ok(tab);
+ tab.whereInput = "status = 'active'";
+ tab.orderByInput = '"id" DESC';
+ tab.result = {
+ columns: ["id", "status"],
+ rows: [[1, "active"]],
+ affected_rows: 0,
+ execution_time_ms: 1,
+ truncated: false,
+ has_more: true,
+ };
+ tab.tableMeta = {
+ schema: "public",
+ tableName: "users",
+ columns: [
+ {
+ name: "id",
+ data_type: "integer",
+ is_nullable: false,
+ column_default: null,
+ is_primary_key: true,
+ extra: null,
+ },
+ {
+ name: "status",
+ data_type: "varchar",
+ is_nullable: true,
+ column_default: null,
+ is_primary_key: false,
+ extra: null,
+ },
+ ],
+ primaryKeys: ["id"],
+ };
+
+ globalThis.fetch = (async (input, init) => {
+ const url = String(input);
+ if (url === "/api/query/build-table-select-sql") {
+ const body = JSON.parse(String(init?.body ?? "{}"));
+ buildRequests.push(body.options);
+ const { limit, offset } = body.options;
+ return new Response(
+ JSON.stringify(`SELECT * FROM "public"."users" WHERE (status = 'active') ORDER BY "id" DESC LIMIT ${limit} OFFSET ${offset ?? 0};`),
+ { status: 200, headers: { "Content-Type": "application/json" } },
+ );
+ }
+ if (url === "/api/query/execute-multi") {
+ const body = JSON.parse(String(init?.body ?? "{}"));
+ executedSqls.push(body.sql);
+ const rows = String(body.sql).includes("OFFSET 0")
+ ? Array.from({ length: 10_000 }, (_, index) => [index + 1, "active"])
+ : [[10_001, "active"], [10_002, "active"]];
+ return new Response(JSON.stringify([{ columns: ["id", "status"], rows, affected_rows: 0, execution_time_ms: 1 }]), {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ });
+ }
+ return new Response("unexpected request", { status: 500 });
+ }) as typeof fetch;
+
+ try {
+ const exported = await store.fetchTabResultForExport(tabId);
+
+ assert.deepEqual(
+ buildRequests.map((request) => ({
+ databaseType: (request as any).databaseType,
+ schema: (request as any).schema,
+ tableName: (request as any).tableName,
+ whereInput: (request as any).whereInput,
+ orderBy: (request as any).orderBy,
+ limit: (request as any).limit,
+ offset: (request as any).offset,
+ })),
+ [
+ {
+ databaseType: "saphana",
+ schema: "public",
+ tableName: "users",
+ whereInput: "status = 'active'",
+ orderBy: '"id" DESC',
+ limit: 10_000,
+ offset: 0,
+ },
+ {
+ databaseType: "saphana",
+ schema: "public",
+ tableName: "users",
+ whereInput: "status = 'active'",
+ orderBy: '"id" DESC',
+ limit: 10_000,
+ offset: 10_000,
+ },
+ ],
+ );
+ assert.deepEqual(executedSqls, [
+ 'SELECT * FROM "public"."users" WHERE (status = \'active\') ORDER BY "id" DESC LIMIT 10000 OFFSET 0;',
+ 'SELECT * FROM "public"."users" WHERE (status = \'active\') ORDER BY "id" DESC LIMIT 10000 OFFSET 10000;',
+ ]);
+ assert.equal(exported?.rows.length, 10_002);
+ assert.deepEqual(exported?.rows.at(-1), [10_002, "active"]);
+ } finally {
+ globalThis.fetch = originalFetch;
+ restoreStorage();
+ }
+});
+
test("query execution finishes without waiting for metadata analysis", async () => {
const restoreStorage = installMemoryStorage();
setActivePinia(createPinia());
@@ -1091,6 +1210,9 @@ test("multi statement execution shows the first result set by default", async ()
assert.equal(tab?.activeResultIndex, 1);
assert.deepEqual(tab?.result?.columns, ["@id"]);
assert.deepEqual(tab?.result?.rows, [[1]]);
+ assert.equal(isReactive(tab?.result?.rows), false);
+ assert.equal(isReactive(tab?.result?.rows[0]), false);
+ assert.equal(tab?.results?.every((result) => !isReactive(result.rows)), true);
} finally {
globalThis.fetch = originalFetch;
restoreStorage();
diff --git a/packages/app-tests/settingsStore.test.ts b/packages/app-tests/settingsStore.test.ts
index bc2e90b35c..8a1ee24639 100644
--- a/packages/app-tests/settingsStore.test.ts
+++ b/packages/app-tests/settingsStore.test.ts
@@ -23,6 +23,12 @@ test("normalizes saved query result page size", () => {
assert.equal(normalizeEditorSettings({ pageSize: 0 }).pageSize, 100);
});
+test("defaults export batch size to 10000 rows", () => {
+ assert.equal(DEFAULT_EDITOR_SETTINGS.exportBatchSize, 10000);
+ assert.equal(normalizeEditorSettings({}).exportBatchSize, 10000);
+ assert.equal(normalizeEditorSettings({ exportBatchSize: 2000 }).exportBatchSize, 2000);
+});
+
test("normalizes editor theme settings", () => {
assert.equal(DEFAULT_EDITOR_SETTINGS.theme, "app");
assert.equal(normalizeEditorSettings({}).theme, "app");