diff --git a/apps/desktop/src/composables/__tests__/useDataGridExport.spec.ts b/apps/desktop/src/composables/__tests__/useDataGridExport.spec.ts
index bd05193514..1846bfa5eb 100644
--- a/apps/desktop/src/composables/__tests__/useDataGridExport.spec.ts
+++ b/apps/desktop/src/composables/__tests__/useDataGridExport.spec.ts
@@ -325,6 +325,112 @@ describe("useDataGridExport prepared row statements", () => {
);
});
+ // Regression test for https://github.com/t8y2/dbx/issues/6519
+ it("uses every selected cell for a WHERE clause when right-clicking inside an existing multi-cell selection", async () => {
+ const matrix: CellSelectionMatrix = {
+ rowIndexes: [0],
+ columnIndexes: [0, 1],
+ columns: ["id", "name"],
+ rows: [[7, "Ada"]],
+ };
+ // isSyntheticContext=false mirrors onCellContext(): right-clicking a cell that is
+ // already part of the current multi-cell selection leaves the selection intact.
+ const state = createExportState(editableTable, ["id", "name"], matrix, [7, "Ada"], undefined, undefined, [], DEFAULT_DATA_GRID_EXTRACTOR_OPTIONS, false, undefined, false, 1, 1);
+ vi.mocked(extractDataGridSelection).mockResolvedValueOnce({ text: "id = 7 AND name = 'Ada'", mimeType: "application/sql", fileExtension: "sql", rowCount: 1, columnCount: 2 });
+
+ expect(state.canCopyWithExtractor("where-clause")).toBe(true);
+ await state.copyWithExtractor("where-clause");
+
+ expect(extractDataGridSelection).toHaveBeenCalledWith(
+ expect.objectContaining({
+ extractor: "where-clause",
+ columns: [expect.objectContaining({ sourceName: "id" }), expect.objectContaining({ sourceName: "name" })],
+ selectedColumnIndexes: [0, 1],
+ rows: [[7, "Ada"]],
+ selectionKind: "cells",
+ }),
+ );
+ });
+
+ // Regression test: a whole-column selection (via the column header) fills
+ // the matrix with every loaded row, which is a different affordance from a
+ // genuine multi-cell range selection. Right-clicking inside it must not
+ // silently OR a WHERE predicate across every loaded row.
+ it("disables WHERE copy when right-clicking inside a whole-column selection", () => {
+ const rowDataList = [
+ [7, "Ada"],
+ [8, "Grace"],
+ ];
+ const matrix: CellSelectionMatrix = {
+ rowIndexes: [0, 1],
+ columnIndexes: [1],
+ columns: ["name"],
+ rows: [["Ada"], ["Grace"]],
+ };
+ const state = createExportState(editableTable, ["id", "name"], matrix, undefined, undefined, rowDataList, [], DEFAULT_DATA_GRID_EXTRACTOR_OPTIONS, true, undefined, false, 1, 1);
+
+ expect(state.canCopyWithExtractor("where-clause")).toBe(false);
+ });
+
+ // Regression test for https://github.com/t8y2/dbx/issues/6519
+ it("uses every selected cell for a SELECT when right-clicking inside an existing multi-cell selection", async () => {
+ const matrix: CellSelectionMatrix = {
+ rowIndexes: [0],
+ columnIndexes: [0, 1],
+ columns: ["id", "name"],
+ rows: [[7, "Ada"]],
+ };
+ const state = createExportState(editableTable, ["id", "name"], matrix, [7, "Ada"], undefined, undefined, [], DEFAULT_DATA_GRID_EXTRACTOR_OPTIONS, false, undefined, false, 1, 1);
+ vi.mocked(extractDataGridSelection).mockResolvedValueOnce({ text: "SELECT * FROM users WHERE id = 7 AND name = 'Ada';", mimeType: "application/sql", fileExtension: "sql", rowCount: 1, columnCount: 2 });
+
+ expect(state.canCopyWithExtractor("sql-select")).toBe(true);
+ await state.copyWithExtractor("sql-select");
+
+ expect(extractDataGridSelection).toHaveBeenCalledWith(
+ expect.objectContaining({
+ extractor: "sql-select",
+ columns: [expect.objectContaining({ sourceName: "id" }), expect.objectContaining({ sourceName: "name" })],
+ selectedColumnIndexes: [0, 1],
+ rows: [[7, "Ada"]],
+ selectionKind: "cells",
+ }),
+ );
+ });
+
+ // Regression test for https://github.com/t8y2/dbx/issues/6519
+ it("joins a same-column multi-row SELECT selection with OR", async () => {
+ const selectedRows = [
+ [7, "Ada"],
+ [8, "Grace"],
+ ];
+ const matrix: CellSelectionMatrix = {
+ rowIndexes: [0, 1],
+ columnIndexes: [0, 1],
+ columns: ["id", "name"],
+ rows: selectedRows,
+ };
+ const state = createExportState(editableTable, ["id", "name"], matrix, undefined, undefined, selectedRows);
+ vi.mocked(extractDataGridSelection).mockResolvedValueOnce({
+ text: "SELECT * FROM users WHERE (id = 7 AND name = 'Ada') OR (id = 8 AND name = 'Grace');",
+ mimeType: "application/sql",
+ fileExtension: "sql",
+ rowCount: 2,
+ columnCount: 2,
+ });
+
+ expect(state.canCopyWithExtractor("sql-select")).toBe(true);
+ await state.copyWithExtractor("sql-select");
+
+ expect(extractDataGridSelection).toHaveBeenCalledWith(
+ expect.objectContaining({
+ extractor: "sql-select",
+ selectedColumnIndexes: [0, 1],
+ rows: selectedRows,
+ selectionKind: "cells",
+ }),
+ );
+ });
+
it("includes hidden identity support columns in a selected-row SELECT request", async () => {
const item = row([7, "Ada"]);
const options: UseDataGridExportOptions = {
@@ -390,15 +496,14 @@ describe("useDataGridExport prepared row statements", () => {
);
});
- it("disables SELECT copy for multiple cells or a missing table target", () => {
+ it("disables SELECT copy for a missing table target", () => {
const matrix: CellSelectionMatrix = {
rowIndexes: [0],
- columnIndexes: [0, 1],
- columns: ["id", "name"],
- rows: [[7, "Ada"]],
+ columnIndexes: [1],
+ columns: ["name"],
+ rows: [["Ada"]],
};
- expect(createExportState(editableTable, ["id", "name"], matrix, [7, "Ada"]).canCopyWithExtractor("sql-select")).toBe(false);
- expect(createExportState({ ...editableTable, tableName: "" }, ["id", "name"], { ...matrix, columnIndexes: [1], columns: ["name"], rows: [["Ada"]] }, [7, "Ada"]).canCopyWithExtractor("sql-select")).toBe(false);
+ expect(createExportState({ ...editableTable, tableName: "" }, ["id", "name"], matrix, [7, "Ada"]).canCopyWithExtractor("sql-select")).toBe(false);
});
// Regression tests for https://github.com/t8y2/dbx/issues/6272
diff --git a/apps/desktop/src/composables/useDataGridExtractor.ts b/apps/desktop/src/composables/useDataGridExtractor.ts
index e6a16091a6..2361b5ee10 100644
--- a/apps/desktop/src/composables/useDataGridExtractor.ts
+++ b/apps/desktop/src/composables/useDataGridExtractor.ts
@@ -100,9 +100,15 @@ export function useDataGridExtractor(options: UseDataGridExtractorOptions) {
// harness and non-right-click paths leave it at -1.
const hasRightClickContext = !!contextCell && options.contextSelectionIsSynthetic.value;
// SQL predicates generated from the context menu must describe the cell the
- // user right-clicked, even when an existing row or range selection remains
- // active underneath that menu.
- const contextPredicateCell = hasContextPredicateTarget(extractor) ? contextCell : null;
+ // user right-clicked, even when an existing row selection remains active
+ // underneath that menu. But when the right-click lands inside an existing
+ // *multi-cell* selection (matrix has more than one row/column and the
+ // selection wasn't just synthesized by this right-click), the predicate
+ // must cover the whole selection, not collapse to the single cell the
+ // mouse happened to land on — otherwise copying a 2+ cell selection as
+ // SQL SELECT/WHERE silently drops every cell but the last one clicked.
+ const contextCellIsInsideMultiCellSelection = isMultiCellSelection && !options.contextSelectionIsSynthetic.value;
+ const contextPredicateCell = hasContextPredicateTarget(extractor) && !contextCellIsInsideMultiCellSelection ? contextCell : null;
// When the user already has a single-cell selection and right-clicks the same
// cell, contextSelectionIsSynthetic is false but we still have a valid context
// cell. For INSERT/UPDATE extractors, we include all visible non-PK columns
@@ -269,19 +275,28 @@ export function useDataGridExtractor(options: UseDataGridExtractorOptions) {
// The context-menu target is validated by buildRequest below.
} else if (options.hasRowSelection.value) {
if (options.selectedRowIds.value.size !== 1) return false;
- } else if (matrix) {
- if (matrix.rowIndexes.length !== 1 || matrix.columnIndexes.length !== 1) return false;
- } else if (!options.contextCell.value || !options.contextSelectionIsSynthetic.value) {
+ } else if (!matrix && (!options.contextCell.value || !options.contextSelectionIsSynthetic.value)) {
return false;
}
const request = buildRequest(extractor, extractorOptions);
- if (!request?.tableMeta?.tableName.trim() || request.rows.length !== 1) return false;
+ // A genuine multi-cell selection is allowed to span multiple rows/columns
+ // (same-row columns AND together, same-column rows OR together — see
+ // write_sql_select), but row-checkbox selection still targets exactly one
+ // row: there's no well-defined single predicate for multiple whole rows.
+ if (!request?.tableMeta?.tableName.trim() || request.rows.length === 0) return false;
if (request.selectionKind === "columns") return false;
- if (request.selectionKind === "cells" && request.selectedColumnIndexes.length !== 1) return false;
+ if (request.selectionKind === "rows" && request.rows.length !== 1) return false;
+ if (request.selectionKind === "cells" && request.selectedColumnIndexes.length === 0) return false;
return request.columns.length > 0 && request.columns.every((column) => !!(column.sourceName ?? column.displayName)?.trim());
}
if (extractor === "where-clause" && contextPredicateTarget) {
- return buildRequest(extractor, extractorOptions) !== null;
+ // A whole-column selection (selected via the column header) fills the
+ // matrix with every loaded row, which is a different affordance from a
+ // genuine multi-cell range selection. Right-clicking inside it must not
+ // silently OR a predicate across every loaded row — sql-select already
+ // guards this via the "columns" selectionKind check above.
+ const request = buildRequest(extractor, extractorOptions);
+ return request !== null && request.selectionKind !== "columns";
}
if (extractor === "raw") {
const request = buildRequest(extractor, extractorOptions);
diff --git a/crates/dbx-core/src/data_grid_extractors/sql.rs b/crates/dbx-core/src/data_grid_extractors/sql.rs
index f387c27a1b..6d2058976d 100644
--- a/crates/dbx-core/src/data_grid_extractors/sql.rs
+++ b/crates/dbx-core/src/data_grid_extractors/sql.rs
@@ -147,8 +147,14 @@ fn ensure_sql_builder_budget(context: &ExtractContext<'_>) -> Result<(), DataGri
size.saturating_add(column.display_name.len())
.saturating_add(column.source_name.as_deref().map_or(0, str::len))
}));
+ // WHERE-clause output (and SELECT built from a cell selection, which reuses
+ // the same predicate builder) repeats every selected column's identifier
+ // once per row via OR'd row groups, just like SqlUpdates/row-by-row insert.
let repeats_identifiers_per_row = context.request.extractor == super::DataGridExtractorId::SqlUpdates
- || context.request.options.sql.insert_mode == crate::data_grid_sql::DataGridCopyInsertMode::RowByRow;
+ || context.request.options.sql.insert_mode == crate::data_grid_sql::DataGridCopyInsertMode::RowByRow
+ || context.request.extractor == super::DataGridExtractorId::WhereClause
+ || (context.request.extractor == super::DataGridExtractorId::SqlSelect
+ && context.request.selection_kind == super::DataGridSelectionKind::Cells);
let statement_overhead = identifier_bytes
.saturating_mul(4)
.saturating_add(256)
@@ -340,37 +346,56 @@ pub(super) fn write_sql_select(
"SELECT extraction requires one resolved table target.",
)
})?;
- if context.request.rows.len() != 1
+ if context.request.rows.is_empty()
|| matches!(context.request.selection_kind, super::DataGridSelectionKind::Columns)
- || (context.request.selection_kind == super::DataGridSelectionKind::Cells
- && context.selected_columns.len() != 1)
+ || (context.request.selection_kind == super::DataGridSelectionKind::Rows && context.request.rows.len() != 1)
{
return Err(DataGridExtractError::new(
DataGridExtractErrorCode::InvalidSelectSelection,
- "SELECT extraction supports exactly one selected cell or row.",
+ "SELECT extraction supports cell selections or exactly one selected row.",
));
}
+ let table = data_grid_qualified_table_name(
+ context.request.database_type,
+ table_meta.catalog.as_deref(),
+ table_meta.schema.as_deref(),
+ table_meta.database.as_deref(),
+ &table_meta.table_name,
+ context.request.identifier_quote.as_deref(),
+ );
+
+ if context.request.selection_kind == super::DataGridSelectionKind::Cells {
+ // A cell-selection SELECT reuses the WHERE-clause predicate builder so a
+ // multi-cell selection (same-row columns AND'd, multi-row selections
+ // OR'd) produces the same predicate as "Copy as WHERE clause" for the
+ // identical selection — including its fallback to display_name when a
+ // column has no resolved source_name. build_context() already rejects
+ // an empty column selection before this function runs.
+ write_bytes(output, format!("SELECT * FROM {table} WHERE ").as_bytes())?;
+ write_where_clause(context, output)?;
+ return write_bytes(output, b";");
+ }
+
+ // Only the single-row identity path (row-checkbox selection) reaches here;
+ // cell selections returned above via the write_where_clause path.
let row = &context.request.rows[0];
- let predicate_columns = if context.request.selection_kind == super::DataGridSelectionKind::Rows {
- let identity = table_meta
- .primary_keys
- .iter()
- .map(|primary_key| {
- context
- .request
- .columns
- .iter()
- .find(|column| {
- normalized_name_eq(column.source_name.as_deref().unwrap_or(&column.display_name), primary_key)
- })
- .filter(|column| row.get(column.source_index).is_some_and(|value| !value.is_null()))
- })
- .collect::