A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
fix: select all on a searched table (#3993)
Shahmir Varqha8d176ca02baa
diff --git a/frontend/src/components/data-table/TableActions.tsx b/frontend/src/components/data-table/TableActions.tsxindex 235f9ca6ed..0c16f729ac 100644--- a/frontend/src/components/data-table/TableActions.tsx+++ b/frontend/src/components/data-table/TableActions.tsx@@ -8,6 +8,8 @@ import { SearchIcon } from "lucide-react";import { DataTablePagination } from "./pagination";import { DownloadAs, type DownloadActionProps } from "./download-actions";import type { Table, RowSelectionState } from "@tanstack/react-table";+import type { GetRowIds } from "@/plugins/impl/DataTablePlugin";+import { toast } from "../ui/use-toast";interface TableActionsProps<TData> {enableSearch: boolean;@@ -20,6 +22,7 @@ interface TableActionsProps<TData> {onRowSelectionChange?: (value: RowSelectionState) => void;table: Table<TData>;downloadAs?: DownloadActionProps["downloadAs"];+ getRowIds?: GetRowIds;}export const TableActions = <TData,>({@@ -33,7 +36,52 @@ export const TableActions = <TData,>({onRowSelectionChange,table,downloadAs,+ getRowIds,}: TableActionsProps<TData>) => {+ const handleSelectAllRows = (value: boolean) => {+ if (!onRowSelectionChange) {+ return;+ }++ // Clear all selections+ if (!value) {+ onRowSelectionChange({});+ return;+ }++ const selectAllRowsByIndex = () => {+ const allKeys = Array.from(+ { length: table.getRowCount() },+ (_, i) => [i, true] as const,+ );+ onRowSelectionChange(Object.fromEntries(allKeys));+ };++ if (!getRowIds) {+ selectAllRowsByIndex();+ return;+ }++ getRowIds({}).then((data) => {+ if (data.error) {+ toast({+ title: "Not available",+ description: data.error,+ variant: "danger",+ });+ return;+ }++ if (data.all_rows) {+ selectAllRowsByIndex();+ } else {+ onRowSelectionChange(+ Object.fromEntries(data.row_ids.map((id) => [id, true])),+ );+ }+ });+ };+return (<div className="flex items-center justify-between flex-shrink-0 pt-1">{onSearchQueryChange && enableSearch && (@@ -52,21 +100,7 @@ export const TableActions = <TData,>({<DataTablePaginationtotalColumns={totalColumns}selection={selection}- onSelectAllRowsChange={- onRowSelectionChange- ? (value: boolean) => {- if (value) {- const allKeys = Array.from(- { length: table.getRowCount() },- (_, i) => [i, true] as const,- );- onRowSelectionChange(Object.fromEntries(allKeys));- } else {- onRowSelectionChange({});- }- }- : undefined- }+ onSelectAllRowsChange={handleSelectAllRows}table={table}/>) : (diff --git a/frontend/src/components/data-table/data-table.tsx b/frontend/src/components/data-table/data-table.tsxindex 49c49d86b3..4224c08bfd 100644--- a/frontend/src/components/data-table/data-table.tsx+++ b/frontend/src/components/data-table/data-table.tsx@@ -30,6 +30,7 @@ import { TableActions } from "./TableActions";import { ColumnFormattingFeature } from "./column-formatting/feature";import { ColumnWrappingFeature } from "./column-wrapping/feature";import { INDEX_COLUMN_NAME } from "./types";+import type { GetRowIds } from "@/plugins/impl/DataTablePlugin";interface DataTableProps<TData> extends Partial<DownloadActionProps> {wrapperClassName?: string;@@ -51,6 +52,7 @@ interface DataTableProps<TData> extends Partial<DownloadActionProps> {selection?: "single" | "multi" | null;rowSelection?: RowSelectionState;onRowSelectionChange?: OnChangeFn<RowSelectionState>;+ getRowIds?: GetRowIds;// SearchenableSearch?: boolean;searchQuery?: string;@@ -82,6 +84,7 @@ const DataTableInternal = <TData,>({manualPagination = false,pagination = false,onRowSelectionChange,+ getRowIds,enableSearch = false,searchQuery,onSearchQueryChange,@@ -186,6 +189,7 @@ const DataTableInternal = <TData,>({onRowSelectionChange={onRowSelectionChange}table={table}downloadAs={downloadAs}+ getRowIds={getRowIds}/></div>);diff --git a/frontend/src/plugins/impl/DataTablePlugin.tsx b/frontend/src/plugins/impl/DataTablePlugin.tsxindex b4a89c1620..89d3d378a8 100644--- a/frontend/src/plugins/impl/DataTablePlugin.tsx+++ b/frontend/src/plugins/impl/DataTablePlugin.tsx@@ -54,6 +54,12 @@ interface ColumnSummaries<T = unknown> {is_disabled?: boolean;}+export type GetRowIds = (opts: {}) => Promise<{+ row_ids: number[];+ all_rows: boolean;+ error: string | null;+}>;+/*** Arguments for a data table*@@ -81,7 +87,7 @@ interface Data<T> {}// eslint-disable-next-line @typescript-eslint/consistent-type-definitions-type Functions = {+type DataTableFunctions = {download_as: (req: { format: "csv" | "json" }) => Promise<string>;get_column_summaries: <T>(opts: {}) => Promise<ColumnSummaries<T>>;search: <T>(req: {@@ -97,6 +103,7 @@ type Functions = {data: TableData<T>;total_rows: number;}>;+ get_row_ids?: GetRowIds;};type S = Array<string | number>;@@ -135,7 +142,7 @@ export const DataTablePlugin = createPlugin<S>("marimo-table")hasStableRowId: z.boolean().default(false),}),)- .withFunctions<Functions>({+ .withFunctions<DataTableFunctions>({download_as: rpc.input(z.object({ format: z.enum(["csv", "json"]) })).output(z.string()),@@ -176,6 +183,13 @@ export const DataTablePlugin = createPlugin<S>("marimo-table")total_rows: z.number(),}),),+ get_row_ids: rpc.input(z.object({}).passthrough()).output(+ z.object({+ row_ids: z.array(z.number()),+ all_rows: z.boolean(),+ error: z.string().nullable(),+ }),+ ),}).renderer((props) => {return (@@ -192,7 +206,7 @@ export const DataTablePlugin = createPlugin<S>("marimo-table"));});-interface DataTableProps<T> extends Data<T>, Functions {+interface DataTableProps<T> extends Data<T>, DataTableFunctions {className?: string;// Selectionvalue: S;@@ -455,6 +469,7 @@ const DataTableComponent = ({textJustifyColumns,wrappedColumns,totalColumns,+ get_row_ids,}: DataTableProps<unknown> &DataTableSearchProps & {data: unknown[];@@ -576,6 +591,7 @@ const DataTableComponent = ({onRowSelectionChange={handleRowSelectionChange}freezeColumnsLeft={freezeColumnsLeft}freezeColumnsRight={freezeColumnsRight}+ getRowIds={get_row_ids}/></Labeled></ColumnChartContext.Provider>diff --git a/marimo/_plugins/ui/_impl/table.py b/marimo/_plugins/ui/_impl/table.pyindex 946b87b030..b06a232202 100644--- a/marimo/_plugins/ui/_impl/table.py+++ b/marimo/_plugins/ui/_impl/table.py@@ -103,6 +103,13 @@ class SortArgs:descending: bool+@dataclass+class GetRowIdsResponse:+ row_ids: list[int]+ all_rows: bool+ error: Optional[str] = None++@mddocclass table(UIElement[@@ -416,6 +423,11 @@ class table(arg_cls=SearchTableArgs,function=self._search,),+ Function(+ name="get_row_ids",+ arg_cls=EmptyArgs,+ function=self._get_row_ids,+ ),),)@@ -649,6 +661,49 @@ class table(total_rows=result.get_num_rows(force=True) or 0,)+ def _get_row_ids(self, args: EmptyArgs) -> GetRowIdsResponse:+ """Get row IDs of a table. If searched, return searched rows else all rows."""+ del args++ total_rows = self._manager.get_num_rows()+ num_rows_searched = self._searched_manager.get_num_rows()++ if total_rows is None or num_rows_searched is None:+ return GetRowIdsResponse(+ row_ids=[],+ all_rows=False,+ error="Failed to get row IDs: number of rows is unknown",+ )++ # If no search has been applied, return with all_rows=True to avoid passing row IDs+ if total_rows == num_rows_searched:+ return GetRowIdsResponse(row_ids=[], all_rows=True)++ if num_rows_searched > 1_000_000:+ return GetRowIdsResponse(+ row_ids=[],+ all_rows=False,+ error="Select all with search is not supported for large datasets. Please filter to less than 1,000,000 rows",+ )++ # For dictionary data, return sequential indices+ if isinstance(self.data, dict):+ return GetRowIdsResponse(+ row_ids=list(range(num_rows_searched)),+ all_rows=False,+ )++ # For dataframes+ try:+ row_ids = self._searched_manager.data[INDEX_COLUMN_NAME].to_list()+ return GetRowIdsResponse(row_ids=row_ids, all_rows=False)+ except Exception as e:+ return GetRowIdsResponse(+ row_ids=[],+ all_rows=False,+ error=f"Failed to get row IDs: {str(e)}",+ )+def _repr_markdown_(self) -> str:"""Return a markdown representation of the table.diff --git a/tests/_plugins/ui/_impl/test_table.py b/tests/_plugins/ui/_impl/test_table.pyindex 9f8eb12862..245864c114 100644--- a/tests/_plugins/ui/_impl/test_table.py+++ b/tests/_plugins/ui/_impl/test_table.py@@ -444,6 +444,82 @@ def test_search_sort_nonexistent_columns() -> None:assert table._convert_value(["0"]) == ["banana"]+def test_get_row_ids() -> None:+ data = {+ "id": [1, 2, 3] * 3,+ "fruits": ["banana", "apple", "cherry"] * 3,+ "quantity": [10, 20, 30] * 3,+ }+ table = ui.table(data)++ initial_response = table._get_row_ids(EmptyArgs())+ assert initial_response.all_rows is True+ assert initial_response.row_ids == []+ assert initial_response.error is None++ table._search(+ SearchTableArgs(+ query="cherry",+ page_size=10,+ page_number=0,+ )+ )++ response = table._get_row_ids(EmptyArgs())+ # For dicts, we do not need to find row_id, we just return the index+ assert response.row_ids == [0, 1, 2]+ assert response.all_rows is False+ assert response.error is None+++ "df",+ create_dataframes(+ {+ "id": [1, 2, 3] * 3,+ "fruits": ["banana", "apple", "cherry"] * 3,+ "quantity": [10, 20, 30] * 3,+ },+ exclude=["ibis", "duckdb", "pyarrow"],+ ),+)+def test_get_row_ids_with_df(df: any) -> None:+ table = ui.table(df)++ initial_response = table._get_row_ids(EmptyArgs())+ assert initial_response.all_rows is True+ assert initial_response.row_ids == []+ assert initial_response.error is None++ # Test with search+ table._search(+ SearchTableArgs(+ query="cherry",+ page_size=10,+ page_number=0,+ )+ )++ response = table._get_row_ids(EmptyArgs())+ assert response.row_ids == [2, 5, 8]+ assert response.all_rows is False+ assert response.error is None++ # Test with no search+ table._search(+ SearchTableArgs(+ query="",+ page_size=10,+ page_number=0,+ )+ )++ response = table._get_row_ids(EmptyArgs())+ assert response.all_rows is True+ assert response.row_ids == []+ assert response.error is None++def test_table_with_too_many_columns_passes() -> None:data = {str(i): [1] for i in range(101)}assert ui.table(data) is not None