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::>>(); - identity.filter(|columns| !columns.is_empty()).unwrap_or_else(|| context.request.columns.iter().collect()) - } else { - context.selected_columns.clone() - }; + 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::>>(); + let predicate_columns = + identity.filter(|columns| !columns.is_empty()).unwrap_or_else(|| context.request.columns.iter().collect()); if predicate_columns.is_empty() { return Err(DataGridExtractError::new( DataGridExtractErrorCode::InvalidColumnMapping, @@ -407,14 +432,6 @@ pub(super) fn write_sql_select( context.request.identifier_quote.as_deref(), )); } - 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(), - ); write_bytes(output, format!("SELECT * FROM {table} WHERE {};", predicates.join(" AND ")).as_bytes()) } diff --git a/crates/dbx-core/src/data_grid_extractors/tests.rs b/crates/dbx-core/src/data_grid_extractors/tests.rs index 569a0fdc71..6eaa99a67e 100644 --- a/crates/dbx-core/src/data_grid_extractors/tests.rs +++ b/crates/dbx-core/src/data_grid_extractors/tests.rs @@ -616,10 +616,30 @@ fn select_row_falls_back_to_all_columns_without_usable_identity() { } } +#[test] +fn select_cells_joins_multiple_columns_and_rows() { + // A genuine multi-cell selection (same-row columns AND'd, multi-row + // selections OR'd) is allowed for SELECT and reuses the WHERE predicate + // builder, matching "Copy as WHERE clause" for the same selection. + let mut request = request(DataGridExtractorId::SqlSelect); + request.table_meta = Some(DataGridTableMeta { + catalog: None, + database: None, + schema: None, + table_name: "users".to_string(), + primary_keys: vec!["id".to_string()], + columns: None, + }); + + let result = extract_data_grid_selection(request).expect("multi-cell SELECT extraction"); + + assert_eq!(result.text, "SELECT * FROM \"users\" WHERE (\"id\" = 1 AND \"name\" = 'Ada') OR (\"id\" = 2 AND \"name\" = 'Grace, Hopper');"); +} + #[test] fn select_rejects_ambiguous_selection_and_missing_target() { let error = extract_data_grid_selection(request(DataGridExtractorId::SqlSelect)) - .expect_err("multiple cells without a table must fail"); + .expect_err("cells without a table must fail"); assert_eq!(error.code, DataGridExtractErrorCode::MissingTableMetadata); let mut request = request(DataGridExtractorId::SqlSelect); @@ -631,7 +651,12 @@ fn select_rejects_ambiguous_selection_and_missing_target() { primary_keys: Vec::new(), columns: None, }); - let error = extract_data_grid_selection(request).expect_err("multiple cells must fail"); + request.selection_kind = DataGridSelectionKind::Columns; + let error = extract_data_grid_selection(request.clone()).expect_err("column selection must fail"); + assert_eq!(error.code, DataGridExtractErrorCode::InvalidSelectSelection); + + request.selection_kind = DataGridSelectionKind::Rows; + let error = extract_data_grid_selection(request).expect_err("multiple selected rows must fail"); assert_eq!(error.code, DataGridExtractErrorCode::InvalidSelectSelection); } @@ -668,12 +693,55 @@ fn where_clause_applies_mysql_json_cast() { }, ]), }); + let mut select_request = request.clone(); + select_request.extractor = DataGridExtractorId::SqlSelect; let result = extract_data_grid_selection(request).expect("WHERE extraction"); assert!( result.text.contains("CAST(") && result.text.contains(" AS JSON)"), "expected MySQL JSON CAST predicate, got: {}", result.text ); + + let select_result = extract_data_grid_selection(select_request).expect("SELECT extraction"); + assert!( + select_result.text.starts_with("SELECT * FROM `t` WHERE ") + && select_result.text.contains("CAST(") + && select_result.text.contains(" AS JSON)"), + "expected MySQL JSON CAST predicate in SELECT, got: {}", + select_result.text + ); +} + +#[test] +fn select_cells_falls_back_to_display_name_like_where_clause() { + // SELECT built from a cell selection reuses write_where_clause, so a + // missing source_name must fall back to display_name exactly like WHERE + // does, instead of erroring — the two must stay in lockstep for the + // identical selection. + let mut request = request(DataGridExtractorId::SqlSelect); + request.table_meta = Some(DataGridTableMeta { + catalog: None, + database: None, + schema: None, + table_name: "users".to_string(), + primary_keys: vec!["id".to_string()], + columns: None, + }); + request.columns = vec![ + DataGridExtractColumn { display_name: "id".to_string(), source_name: None, source_index: 0 }, + column("name", 1), + ]; + let mut where_request = request.clone(); + where_request.extractor = DataGridExtractorId::WhereClause; + + let result = extract_data_grid_selection(request).expect("SELECT extraction with missing source_name"); + assert_eq!( + result.text, + "SELECT * FROM \"users\" WHERE (\"id\" = 1 AND \"name\" = 'Ada') OR (\"id\" = 2 AND \"name\" = 'Grace, Hopper');" + ); + + let where_result = extract_data_grid_selection(where_request).expect("WHERE extraction with missing source_name"); + assert_eq!(where_result.text, "(\"id\" = 1 AND \"name\" = 'Ada') OR (\"id\" = 2 AND \"name\" = 'Grace, Hopper')"); } #[test]