fix(export): use page sql for current-page xlsx export

This commit is contained in:
lxk955 authored and GitHub committed 2026-10-03 00:21:12 +08:00
1 parent 7e732a985a
commit 06918c06c8
16 files changed
+310 -43

No files matched your search

@@ -555,6 +555,7 @@ interface DataGridProps {
/** Column names captured with a document-store local-filter snapshot. */
localColumnFilterColumns?: string[];
exportSql?: string;
pageSql?: string;
onExecuteSql?: (sql: string) => Promise<void>;
fullExportResult?: (onProgress?: (info: { rowsExported: number; totalRows: number | null }) => void) => Promise<QueryResult | undefined>;
queryResultExportRequest?: (options: {
@@ -8059,7 +8060,7 @@ function sqlWithDisplayDatabaseName(sql: string): string {
async function syncUserFacingSql() {
const generation = ++userFacingSqlGeneration;
const executionSql = props.sql?.trim() ?? "";
const executionSql = (props.pageSql || props.sql)?.trim() ?? "";
const includeDatabaseName = settingsStore.editorSettings.generateSqlIncludeDatabaseName;
const shouldRebuildSql = executionSql.includes("__DBX_LARGE_VALUE_BYTES_") || includeDatabaseName;
if (props.context !== "table-data" || !shouldRebuildSql || !props.tableMeta?.tableName) {
@@ -8101,7 +8102,7 @@ async function syncUserFacingSql() {
}
watch(
() => [props.sql, props.context, props.tableMeta, props.pageLimit, props.pageOffset, props.executedPageLimit, props.executedPageOffset, currentWhereInput(), effectiveOrderBy(), settingsStore.editorSettings.generateSqlIncludeDatabaseName],
() => [props.sql, props.pageSql, props.context, props.tableMeta, props.pageLimit, props.pageOffset, props.executedPageLimit, props.executedPageOffset, currentWhereInput(), effectiveOrderBy(), settingsStore.editorSettings.generateSqlIncludeDatabaseName],
() => void syncUserFacingSql(),
{ immediate: true },
);
@@ -8150,6 +8151,7 @@ const {
extractorOptions: computed(() => settingsStore.editorSettings.dataGridExtractorOptions),
sql: computed(() => props.sql),
exportSql: computed(() => props.exportSql),
pageSql: computed(() => props.pageSql),
tableMeta: computed(() => (props.tableMeta ? { ...props.tableMeta } : undefined)),
includeDatabaseName: computed(() => settingsStore.editorSettings.generateSqlIncludeDatabaseName),
copyInsertTargetLabel: computed(() => props.tableMeta?.tableName ?? props.customSaveHandler?.targetLabel),
@@ -2456,6 +2456,7 @@ defineExpose({
:initial-order-by-input="activeTab.orderByInput"
:sql="activeResultSql"
:export-sql="activeResultExportSql"
:page-sql="activeTab.resultPageSql"
:loading="activeResultIsLoading"
:editable="!hasNeo4jNodes && (!!activeTab.queryAnalysis || !!mongoQueryResultSaveHandler)"
:source-columns="hasNeo4jNodes ? undefined : activeTab.querySourceColumns"
@@ -2936,6 +2937,7 @@ defineExpose({
:sort-mode="activeTab.resultSortMode"
:initial-order-by-input="activeTab.orderByInput"
:sql="activeTab.sql"
:page-sql="activeTab.resultPageSql || activeTab.sql"
:loading="activeTab.isExecuting"
:editable="!activeTab.tableMetaPending && (isTableDataEditable(activeEffectiveDatabaseType, activeTableMeta?.primaryKeys ?? [], activeTableMeta?.tableType) || !!influxDbV1DeleteSaveHandler)"
:custom-save-handler="influxDbV1DeleteSaveHandler"
@@ -83,6 +83,7 @@ export interface UseDataGridExportOptions {
extractorOptions?: ComputedRef<DataGridExtractorOptions>;
sql: ComputedRef<string | undefined>;
exportSql?: ComputedRef<string | undefined>;
pageSql?: ComputedRef<string | undefined>;
tableMeta: ComputedRef<DataGridTableMeta | undefined>;
/** Editor setting "Include database name in generated SQL" — passed through to SQL extractors. */
includeDatabaseName?: ComputedRef<boolean>;
@@ -189,6 +190,7 @@ export function useDataGridExport(options: UseDataGridExportOptions) {
extractorOptions: extractorOptionsOption,
sql,
exportSql: resultExportSql,
pageSql: resultPageSql,
tableMeta,
copyInsertTargetLabel,
sourceColumns,
@@ -520,8 +522,13 @@ export function useDataGridExport(options: UseDataGridExportOptions) {
return resultExportSql?.value || sql.value;
}
async function writeXlsxResult(outputPath: string, result: { columns: string[]; columnTypes: string[]; columnComments?: (string | null)[]; rows: CellValue[][] }, includeSqlSheet: boolean, autoFilter: boolean) {
const sqlWorksheet = includeSqlSheet ? buildXlsxSqlWorksheet([{ sql: currentExportSql() || "" }]) : undefined;
function currentPageExportSql(): string | undefined {
return resultPageSql?.value || currentExportSql();
}
async function writeXlsxResult(outputPath: string, result: { columns: string[]; columnTypes: string[]; columnComments?: (string | null)[]; rows: CellValue[][] }, includeSqlSheet: boolean, autoFilter: boolean, sqlOverride?: string) {
const effectiveSql = sqlOverride ?? currentExportSql();
const sqlWorksheet = includeSqlSheet ? buildXlsxSqlWorksheet([{ sql: effectiveSql || "" }]) : undefined;
const rightAlign = useSettingsStore().editorSettings.numericColumnRightAlign;
// The rows are already rendered with the global export pattern, but the
// workbook still needs the pattern itself so its numFmt matches; without it
@@ -543,7 +550,7 @@ export function useDataGridExport(options: UseDataGridExportOptions) {
numericColumnRightAlign: rightAlign,
autoFilter,
},
{ ...sqlWorksheet, autoFilter },
{ ...sqlWorksheet, autoFilter: false },
],
autoFilter,
dateTimeFormat,
@@ -1243,7 +1250,7 @@ export function useDataGridExport(options: UseDataGridExportOptions) {
outputPath = path as string;
}
const result = await resultToExport(undefined, undefined, false, true, exportOptions.headerMode);
await writeXlsxResult(outputPath, result, includeSqlSheet, exportOptions.autoFilter);
await writeXlsxResult(outputPath, result, includeSqlSheet, exportOptions.autoFilter, currentPageExportSql());
toast(t("grid.exported"));
} catch (e: any) {
toast(t("grid.exportFailed", { message: translateBackendError(t, e) }), 5000);
@@ -1291,7 +1298,7 @@ export function useDataGridExport(options: UseDataGridExportOptions) {
autoFilter: exportOptions.autoFilter,
}));
const sqlWorksheet = includeSqlSheet ? buildXlsxSqlWorksheet(sheets.map((sheet) => ({ resultName: sheet.sheetName, sql: sheet.sql || sheet.result.sourceStatement || "" }))) : undefined;
await api.exportQueryResultsXlsx(outputPath, sqlWorksheet ? [...worksheets, { ...sqlWorksheet, autoFilter: exportOptions.autoFilter }] : worksheets, exportOptions.autoFilter, exportPattern || undefined);
await api.exportQueryResultsXlsx(outputPath, sqlWorksheet ? [...worksheets, { ...sqlWorksheet, autoFilter: false }] : worksheets, exportOptions.autoFilter, exportPattern || undefined);
toast(t("grid.exported"));
} catch (e: any) {
toast(t("grid.exportFailed", { message: translateBackendError(t, e) }), 5000);
+27 -7
View File
@@ -117,9 +117,23 @@ function normalizeUniqueSheetNames(sheets: readonly { sheetName?: string }[]): s
function estimateColumnWidths(columns: readonly string[], rows: readonly (readonly XlsxCellValue[])[], rowStart: number, rowEnd: number, columnComments?: readonly (string | null)[]): number[] {
return columns.map((column, colIndex) => {
const headerText = columnComments?.[colIndex] || column;
const isSqlCol = column.toUpperCase() === "SQL";
const maxClamp = isSqlCol ? 100 : 60;
const values = Array.from({ length: Math.min(100, rowEnd - rowStart) }, (_, index) => rows[rowStart + index]?.[colIndex]);
const maxLen = [headerText, ...values.map((value) => (value == null ? "" : String(value)))].map((value) => Math.min(value.length, 60)).reduce((max, length) => Math.max(max, length), 8);
return Math.max(10, Math.min(60, maxLen + 2));
const maxLen = [
headerText,
...values.map((value) => {
if (value == null) return "";
const str = String(value);
if (isSqlCol || str.includes("\n")) {
return str.split("\n").reduce((max, line) => Math.max(max, line.length), 0);
}
return str.length;
}),
]
.map((value) => Math.min(typeof value === "number" ? value : value.length, maxClamp))
.reduce((max, length) => Math.max(max, length), 8);
return Math.max(isSqlCol ? 40 : 10, Math.min(maxClamp, maxLen + 2));
});
}
@@ -133,15 +147,20 @@ function safeExcelNumber(value: string): string | undefined {
const NUMERIC_RIGHT_ALIGN_STYLE_INDEX = 2;
const NUMERIC_LEFT_ALIGN_STYLE_INDEX = 3;
const XLSX_WRAP_TEXT_STYLE_INDEX = 4;
function numericColumnStyle(columnType?: string, enabled = true): number | undefined {
if (!isNumericColumnType(columnType)) return undefined;
return enabled ? NUMERIC_RIGHT_ALIGN_STYLE_INDEX : NUMERIC_LEFT_ALIGN_STYLE_INDEX;
}
function cellXml(value: XlsxCellValue, rowIndex: number, colIndex: number, style?: number, columnType?: string): string {
function cellXml(value: XlsxCellValue, rowIndex: number, colIndex: number, style?: number, columnType?: string, columnName?: string): string {
const ref = cellRef(rowIndex, colIndex);
const styleAttr = style == null ? "" : ` s="${style}"`;
const isSqlCol = columnName?.toLowerCase() === "sql";
const strVal = typeof value === "string" ? value : undefined;
const isMultiline = strVal !== undefined && (strVal.includes("\n") || strVal.includes("\r"));
const effectiveStyle = isSqlCol || isMultiline ? XLSX_WRAP_TEXT_STYLE_INDEX : style;
const styleAttr = effectiveStyle == null ? "" : ` s="${effectiveStyle}"`;
if (value == null) return `<c r="${ref}"${styleAttr}/>`;
if (typeof value === "number" && Number.isFinite(value)) {
return `<c r="${ref}"${styleAttr}><v>${value}</v></c>`;
@@ -155,7 +174,8 @@ function cellXml(value: XlsxCellValue, rowIndex: number, colIndex: number, style
const number = safeExcelNumber(value);
if (number !== undefined) return `<c r="${ref}"${styleAttr}><v>${number}</v></c>`;
}
return `<c r="${ref}" t="inlineStr"${styleAttr}><is><t>${escapeXml(String(value))}</t></is></c>`;
const spaceAttr = typeof value === "string" && /^\s|\s$|[\r\n\t]/.test(value) ? ' xml:space="preserve"' : "";
return `<c r="${ref}" t="inlineStr"${styleAttr}><is><t${spaceAttr}>${escapeXml(String(value))}</t></is></c>`;
}
function worksheetXml(segment: XlsxWorksheetSegment): string {
@@ -171,7 +191,7 @@ function worksheetXml(segment: XlsxWorksheetSegment): string {
const bodyXml = Array.from({ length: segment.rowEnd - segment.rowStart }, (_, rowIndex) => {
const row = rows[segment.rowStart + rowIndex]!;
const excelRowIndex = rowIndex + 2;
const cells = columns.map((_, colIndex) => cellXml(row[colIndex], excelRowIndex - 1, colIndex, numericColumnStyle(data.columnTypes?.[colIndex], rightAlignEnabled), data.columnTypes?.[colIndex])).join("");
const cells = columns.map((colName, colIndex) => cellXml(row[colIndex], excelRowIndex - 1, colIndex, numericColumnStyle(data.columnTypes?.[colIndex], rightAlignEnabled), data.columnTypes?.[colIndex], colName)).join("");
return `<row r="${excelRowIndex}">${cells}</row>`;
}).join("");
@@ -254,7 +274,7 @@ function stylesXml(): string {
<fills count="2"><fill><patternFill patternType="none"/></fill><fill><patternFill patternType="gray125"/></fill></fills>
<borders count="1"><border><left/><right/><top/><bottom/><diagonal/></border></borders>
<cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellStyleXfs>
<cellXfs count="4"><xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/><xf numFmtId="0" fontId="1" fillId="0" borderId="0" xfId="0" applyFont="1"/><xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0" applyAlignment="1"><alignment horizontal="right"/></xf><xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0" applyAlignment="1"><alignment horizontal="left"/></xf></cellXfs>
<cellXfs count="5"><xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/><xf numFmtId="0" fontId="1" fillId="0" borderId="0" xfId="0" applyFont="1"/><xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0" applyAlignment="1"><alignment horizontal="right"/></xf><xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0" applyAlignment="1"><alignment horizontal="left"/></xf><xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0" applyAlignment="1"><alignment wrapText="1" vertical="top"/></xf></cellXfs>
<cellStyles count="1"><cellStyle name="Normal" xfId="0" builtinId="0"/></cellStyles>
</styleSheet>`;
}
@@ -9,6 +9,7 @@ export interface XlsxSqlWorksheet {
sheetName: "SQL";
columns: string[];
rows: Array<Array<string>>;
autoFilter?: boolean;
}
function splitExcelCellText(value: string): string[] {