Skip to content

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.

feat: datasets panel (#1427)

Myles Scolnick590e1743ea04
diff --git a/frontend/src/components/datasets/icons.tsx b/frontend/src/components/datasets/icons.tsx
new file mode 100644
index 0000000000..97eb55ca94
--- /dev/null
+++ b/frontend/src/components/datasets/icons.tsx
@@ -0,0 +1,30 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+
+import {
+ ToggleLeftIcon,
+ CalendarIcon,
+ HashIcon,
+ TypeIcon,
+ ListOrderedIcon,
+ type LucideIcon,
+} from "lucide-react";
+
+export type DataType =
+ | "string"
+ | "boolean"
+ | "integer"
+ | "number"
+ | "date"
+ | "unknown";
+
+/**
+ * Maps a data type to an icon.
+ */
+export const DATA_TYPE_ICON: Record<DataType, LucideIcon> = {
+ boolean: ToggleLeftIcon,
+ date: CalendarIcon,
+ number: HashIcon,
+ string: TypeIcon,
+ integer: ListOrderedIcon,
+ unknown: TypeIcon,
+};
diff --git a/frontend/src/components/editor/RecoveryButton.tsx b/frontend/src/components/editor/RecoveryButton.tsx
index ce39d77f4d..dd6b3109ff 100644
--- a/frontend/src/components/editor/RecoveryButton.tsx
+++ b/frontend/src/components/editor/RecoveryButton.tsx
@@ -122,7 +122,7 @@ export const RecoveryButton = (props: {
className="rectangle"
color={needsSave ? "yellow" : "gray"}
>
- <SaveIcon strokeWidth={1.5} size={18}/>
+ <SaveIcon strokeWidth={1.5} size={18} />
</EditorButton>
</Tooltip>
);
diff --git a/frontend/src/components/editor/chrome/panels/datasources-panel.tsx b/frontend/src/components/editor/chrome/panels/datasources-panel.tsx
new file mode 100644
index 0000000000..18704acab9
--- /dev/null
+++ b/frontend/src/components/editor/chrome/panels/datasources-panel.tsx
@@ -0,0 +1,392 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import React from "react";
+import {
+ ChevronRightIcon,
+ DatabaseIcon,
+ PlusSquareIcon,
+ XIcon,
+} from "lucide-react";
+import type { DataTable, DataTableColumn } from "@/core/network/types";
+import { Command, CommandInput, CommandItem } from "@/components/ui/command";
+import { CommandList } from "cmdk";
+
+import { cn } from "@/utils/cn";
+import { useDatasets, useDatasetsActions } from "@/core/datasets/state";
+import { DATA_TYPE_ICON } from "@/components/datasets/icons";
+import { Button } from "@/components/ui/button";
+import { useCellActions } from "@/core/cells/cells";
+import { lastFocusedCellIdAtom } from "@/core/cells/focus";
+import { useAtomValue } from "jotai";
+import { Tooltip } from "@/components/ui/tooltip";
+import { PanelEmptyState } from "./empty-state";
+import { previewDatasetColumn } from "@/core/network/requests";
+import type { ColumnPreviewMap } from "@/core/datasets/types";
+import { prettyNumber } from "@/utils/numbers";
+import { Events } from "@/utils/events";
+import { CopyClipboardIcon } from "@/components/icons/copy-icon";
+import { ErrorBoundary } from "../../boundary/ErrorBoundary";
+import type { TopLevelFacetedUnitSpec } from "@/plugins/impl/data-explorer/queries/types";
+import { useTheme } from "@/theme/useTheme";
+import {
+ maybeAddAltairImport,
+ maybeAddMarimoImport,
+} from "@/core/cells/add-missing-import";
+import { autoInstantiateAtom } from "@/core/config/config";
+import { DataColumnPreview } from "@/core/kernel/messages";
+
+export const DataSourcesPanel: React.FC = () => {
+ const [searchValue, setSearchValue] = React.useState<string>("");
+
+ const autoInstantiate = useAtomValue(autoInstantiateAtom);
+ const lastFocusedCellId = useAtomValue(lastFocusedCellIdAtom);
+ const { tables, expandedColumns, expandedTables, columnsPreviews } =
+ useDatasets();
+ const { toggleTable, toggleColumn, closeAllColumns } = useDatasetsActions();
+ const { createNewCell } = useCellActions();
+
+ if (tables.length === 0) {
+ return (
+ <PanelEmptyState
+ title="No tables found"
+ description="Any datasets/dataframes in the global scope will be shown here."
+ icon={<DatabaseIcon />}
+ />
+ );
+ }
+
+ const handleAddColumn = (chartCode: string) => {
+ maybeAddAltairImport(autoInstantiate, createNewCell, lastFocusedCellId);
+ createNewCell({
+ code: chartCode,
+ before: false,
+ cellId: lastFocusedCellId ?? "__end__",
+ });
+ };
+
+ const handleAddTable = (table: DataTable) => {
+ maybeAddMarimoImport(autoInstantiate, createNewCell, lastFocusedCellId);
+ createNewCell({
+ code: `mo.ui.table(${table.name})`,
+ before: false,
+ cellId: lastFocusedCellId ?? "__end__",
+ });
+ };
+
+ const hasSearch = !!searchValue.trim();
+
+ return (
+ <div className="flex-1 overflow-hidden">
+ <Command className={cn("border-b bg-background rounded-none", "h-full")}>
+ <div className="flex items-center w-full">
+ <CommandInput
+ placeholder="Search tables..."
+ className="h-6 m-1"
+ value={searchValue}
+ onValueChange={(value) => {
+ // If searching, remove open previews
+ if (value.length > 0) {
+ closeAllColumns();
+ }
+ setSearchValue(value);
+ }}
+ rootClassName="flex-1 border-r"
+ />
+ {hasSearch && (
+ <button
+ type="button"
+ className="float-right border-b px-2 m-0 h-full hover:bg-accent hover:text-accent-foreground"
+ onClick={() => setSearchValue("")}
+ >
+ <XIcon className="h-4 w-4" />
+ </button>
+ )}
+ </div>
+
+ <TableList
+ onAddColumnChart={handleAddColumn}
+ onAddTable={handleAddTable}
+ onExpandColumn={(table, column) => {
+ const tableColumn = `${table.name}:${column.name}` as const;
+ toggleColumn({
+ table: table.name,
+ column: column.name,
+ });
+ if (!columnsPreviews.has(tableColumn)) {
+ previewDatasetColumn({
+ source: table.source,
+ tableName: table.name,
+ columnName: column.name,
+ });
+ }
+ }}
+ onExpandTable={(table) => {
+ toggleTable(table.name);
+ }}
+ columnPreviews={columnsPreviews}
+ tables={tables}
+ isSearching={hasSearch}
+ isTableExpanded={(table) => {
+ // Always show tables if there is a search value
+ if (hasSearch) {
+ return true;
+ }
+ return expandedTables.has(table.name);
+ }}
+ isColumnExpanded={(table, column) => {
+ const tableColumn = `${table.name}:${column.name}` as const;
+ return expandedColumns.has(tableColumn);
+ }}
+ />
+ </Command>
+ </div>
+ );
+};
+
+const TableList: React.FC<{
+ onAddColumnChart: (chartCode: string) => void;
+ onAddTable: (table: DataTable) => void;
+ onExpandTable: (table: DataTable) => void;
+ onExpandColumn: (table: DataTable, column: DataTableColumn) => void;
+ isTableExpanded: (table: DataTable) => boolean;
+ isColumnExpanded: (table: DataTable, column: DataTableColumn) => boolean;
+ columnPreviews: ColumnPreviewMap;
+ isSearching: boolean;
+ tables: DataTable[];
+}> = ({
+ tables,
+ isSearching,
+ columnPreviews,
+ onAddColumnChart,
+ onAddTable,
+ onExpandTable,
+ onExpandColumn,
+ isTableExpanded,
+ isColumnExpanded,
+}) => {
+ return (
+ <CommandList className="flex flex-col overflow-auto">
+ {tables.flatMap((table) => {
+ const expanded = isTableExpanded(table);
+ const items = [
+ <DatasetTableItem
+ key={table.name}
+ table={table}
+ forceMount={isSearching}
+ onExpand={() => onExpandTable(table)}
+ onAddTable={() => onAddTable(table)}
+ isExpanded={expanded}
+ />,
+ ];
+
+ if (expanded) {
+ items.push(
+ ...table.columns.map((column) => {
+ return (
+ <React.Fragment key={`${table.name}.${column.name}`}>
+ <DatasetColumnItem
+ key={`${table.name}.${column.name}`}
+ table={table}
+ column={column}
+ onExpandColumn={onExpandColumn}
+ isExpanded={isColumnExpanded(table, column)}
+ />
+ {isColumnExpanded(table, column) && (
+ <div className="pl-10 pr-2 py-2 bg-[var(--slate-1)] shadow-inner border-b">
+ <ErrorBoundary>
+ <DatasetColumnPreview
+ onAddColumnChart={onAddColumnChart}
+ preview={columnPreviews.get(
+ `${table.name}:${column.name}`,
+ )}
+ />
+ </ErrorBoundary>
+ </div>
+ )}
+ </React.Fragment>
+ );
+ }),
+ );
+ }
+
+ return items;
+ })}
+ </CommandList>
+ );
+};
+
+const DatasetTableItem: React.FC<{
+ table: DataTable;
+ onExpand: () => void;
+ forceMount?: boolean;
+ onAddTable: (table: DataTable) => void;
+ isExpanded: boolean;
+}> = ({ table, onExpand, onAddTable, isExpanded }) => {
+ const renderRowsByColumns = () => {
+ if (table.num_rows == null || table.num_columns == null) {
+ return null;
+ }
+
+ return (
+ <div className="flex flex-row gap-2 items-center pl-6 group-hover:hidden">
+ <span className="text-xs text-muted-foreground">
+ {table.num_rows} rows, {table.num_columns} columns
+ </span>
+ </div>
+ );
+ };
+
+ return (
+ <CommandItem
+ className="rounded-none py-1 group min-h-9 border-t"
+ value={table.name}
+ aria-selected={isExpanded}
+ forceMount={true}
+ onSelect={onExpand}
+ >
+ <div className="flex gap-1 items-center flex-1">
+ <ChevronRightIcon
+ className={cn(
+ "h-3 w-3 transition-transform",
+ isExpanded && "rotate-90",
+ )}
+ />
+ <span className="text-sm">{table.name}</span>
+ </div>
+ {renderRowsByColumns()}
+ <Tooltip content="Add table to notebook" delayDuration={400}>
+ <Button
+ className="group-hover:inline-flex hidden"
+ variant="text"
+ size="icon"
+ onClick={Events.stopPropagation(() => onAddTable(table))}
+ >
+ <PlusSquareIcon className="h-3 w-3" />
+ </Button>
+ </Tooltip>
+ </CommandItem>
+ );
+};
+
+const DatasetColumnItem: React.FC<{
+ table: DataTable;
+ column: DataTableColumn;
+ onExpandColumn: (table: DataTable, column: DataTableColumn) => void;
+ // onAddColumnChart: (code: string) => void;
+ isExpanded: boolean;
+}> = ({ table, column, onExpandColumn }) => {
+ const Icon = DATA_TYPE_ICON[column.type];
+
+ return (
+ <CommandItem
+ className="rounded-none py-1 group"
+ key={`${table.name}.${column.name}`}
+ value={`${table.name}.${column.name}`}
+ onSelect={() => onExpandColumn(table, column)}
+ >
+ <div className="flex flex-row gap-2 items-center pl-6 flex-1">
+ <Icon className="h-3 w-3" strokeWidth={1.5} />
+ <span>{column.name}</span>
+ </div>
+ <Tooltip content="Copy column name" delayDuration={400}>
+ <Button
+ variant="text"
+ size="icon"
+ className="group-hover:opacity-100 opacity-0 hover:bg-muted text-muted-foreground hover:text-foreground"
+ >
+ <CopyClipboardIcon
+ tooltip={false}
+ value={column.name}
+ className="h-3 w-3"
+ />
+ </Button>
+ </Tooltip>
+ </CommandItem>
+ );
+};
+
+const LazyVegaLite = React.lazy(() =>
+ import("react-vega").then((m) => ({ default: m.VegaLite })),
+);
+
+const DatasetColumnPreview: React.FC<{
+ onAddColumnChart: (code: string) => void;
+ preview: DataColumnPreview | undefined;
+}> = ({ preview, onAddColumnChart }) => {
+ const { theme } = useTheme();
+
+ if (!preview) {
+ return <span className="text-xs text-muted-foreground">Loading...</span>;
+ }
+
+ const error = preview.error && (
+ <span className="text-xs text-muted-foreground">{preview.error}</span>
+ );
+
+ const summary = preview.summary && (
+ <div className="gap-x-16 gap-y-1 grid grid-cols-2-fit border rounded p-2 empty:hidden">
+ {Object.entries(preview.summary).map(([key, value]) => {
+ if (value == null) {
+ return null;
+ }
+
+ return (
+ <div key={key} className="flex items-center gap-1 group">
+ <CopyClipboardIcon
+ className="h-3 w-3 invisible group-hover:visible"
+ value={value}
+ />
+ <span className="text-xs min-w-[60px] uppercase">{key}</span>
+ <span className="text-xs font-bold text-muted-foreground tracking-wide">
+ {prettyNumber(value)}
+ </span>
+ </div>
+ );
+ })}
+ </div>
+ );
+
+ const chart = preview.chart_spec && (
+ <LazyVegaLite
+ spec={JSON.parse(preview.chart_spec) as TopLevelFacetedUnitSpec}
+ width={"container" as unknown as number}
+ height={100}
+ actions={false}
+ theme={theme === "dark" ? "dark" : "vox"}
+ />
+ );
+
+ const addChart = preview.chart_code && (
+ <Tooltip content="Add chart to notebook" delayDuration={400}>
+ <Button
+ variant="outline"
+ size="icon"
+ className="z-10 bg-background absolute right-1 top-0"
+ onClick={Events.stopPropagation(() =>
+ onAddColumnChart(preview.chart_code || ""),
+ )}
+ >
+ <PlusSquareIcon className="h-3 w-3" />
+ </Button>
+ </Tooltip>
+ );
+
+ const chartMaxRowsWarning = preview.chart_max_rows_errors && (
+ <span className="text-xs text-muted-foreground">
+ Too many rows to render the chart.
+ </span>
+ );
+
+ if (!error && !summary && !chart && !chartMaxRowsWarning) {
+ return <span className="text-xs text-muted-foreground">No data</span>;
+ }
+
+ return (
+ <div className="flex flex-col gap-2 relative">
+ {error}
+ {addChart}
+ {chartMaxRowsWarning}
+ {chart}
+ {summary}
+ </div>
+ );
+};
diff --git a/frontend/src/components/editor/chrome/panels/snippets-panel.tsx b/frontend/src/components/editor/chrome/panels/snippets-panel.tsx
index 3ac6a8d339..075e966001 100644
--- a/frontend/src/components/editor/chrome/panels/snippets-panel.tsx
+++ b/frontend/src/components/editor/chrome/panels/snippets-panel.tsx
@@ -4,7 +4,7 @@ import { BetweenHorizontalStartIcon, PlusIcon } from "lucide-react";
import { PanelEmptyState } from "./empty-state";
import { useAsyncData } from "@/hooks/useAsyncData";
import { ErrorBanner } from "@/plugins/impl/common/error-banner";
-import { Snippet } from "@/core/network/types";
+import type { Snippet } from "@/core/network/types";
import { renderHTML } from "@/plugins/core/RenderHTML";
import { readSnippets } from "@/core/network/requests";
import {
diff --git a/frontend/src/components/editor/chrome/types.ts b/frontend/src/components/editor/chrome/types.ts
index 2f63f40438..654241b600 100644
--- a/frontend/src/components/editor/chrome/types.ts
+++ b/frontend/src/components/editor/chrome/types.ts
@@ -8,8 +8,9 @@ import {
ScrollTextIcon,
TextSearchIcon,
FileTextIcon,
- LucideIcon,
+ type LucideIcon,
SquareDashedBottomCodeIcon,
+ DatabaseIcon,
} from "lucide-react";
export type PanelType =
@@ -20,12 +21,14 @@ export type PanelType =
| "dependencies"
| "documentation"
| "snippets"
+ | "datasources"
| "logs";
export const PANEL_ICONS: Record<PanelType, LucideIcon> = {
errors: XCircleIcon,
files: FolderTreeIcon,
variables: FunctionSquareIcon,
+ datasources: DatabaseIcon,
dependencies: NetworkIcon,
outline: ScrollTextIcon,
documentation: TextSearchIcon,
diff --git a/frontend/src/components/editor/chrome/wrapper/app-chrome.tsx b/frontend/src/components/editor/chrome/wrapper/app-chrome.tsx
index 8ea6b5773a..8c656c2021 100644
--- a/frontend/src/components/editor/chrome/wrapper/app-chrome.tsx
+++ b/frontend/src/components/editor/chrome/wrapper/app-chrome.tsx
@@ -23,6 +23,7 @@ import { DocumentationPanel } from "../panels/documentation-panel";
import { FileExplorerPanel } from "../panels/file-explorer-panel";
import { SnippetsPanel } from "../panels/snippets-panel";
import { ErrorBoundary } from "../../boundary/ErrorBoundary";
+import { DataSourcesPanel } from "../panels/datasources-panel";
export const AppChrome: React.FC<PropsWithChildren> = ({ children }) => {
const { isOpen, selectedPanel } = useChromeState();
@@ -100,6 +101,7 @@ export const AppChrome: React.FC<PropsWithChildren> = ({ children }) => {
{selectedPanel === "variables" && <VariablePanel />}
{selectedPanel === "dependencies" && <DependencyGraphPanel />}
{selectedPanel === "outline" && <OutlinePanel />}
+ {selectedPanel === "datasources" && <DataSourcesPanel />}
{selectedPanel === "documentation" && <DocumentationPanel />}
{selectedPanel === "snippets" && <SnippetsPanel />}
{selectedPanel === "logs" && <LogsPanel />}
diff --git a/frontend/src/components/editor/chrome/wrapper/sidebar.tsx b/frontend/src/components/editor/chrome/wrapper/sidebar.tsx
index 658805bb78..b4c305478e 100644
--- a/frontend/src/components/editor/chrome/wrapper/sidebar.tsx
+++ b/frontend/src/components/editor/chrome/wrapper/sidebar.tsx
@@ -32,6 +32,13 @@ export const Sidebar: React.FC = () => {
>
{renderIcon("variables")}
</SidebarItem>
+ <SidebarItem
+ tooltip="Explore data sources"
+ selected={selectedPanel === "datasources"}
+ onClick={() => openApplication("datasources")}
+ >
+ {renderIcon("datasources")}
+ </SidebarItem>
<SidebarItem
tooltip="Explore dependencies"
selected={selectedPanel === "dependencies"}
diff --git a/frontend/src/components/icons/copy-icon.tsx b/frontend/src/components/icons/copy-icon.tsx
new file mode 100644
index 0000000000..8eec5d6705
--- /dev/null
+++ b/frontend/src/components/icons/copy-icon.tsx
@@ -0,0 +1,51 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { CheckIcon, Copy } from "lucide-react";
+import type React from "react";
+import { useState } from "react";
+import { Tooltip } from "../ui/tooltip";
+import { cn } from "@/utils/cn";
+import { Events } from "@/utils/events";
+
+interface Props {
+ value: string;
+ className?: string;
+ tooltip?: string | false;
+}
+
+export const CopyClipboardIcon: React.FC<Props> = ({
+ value,
+ className,
+ tooltip,
+}) => {
+ const [isCopied, setIsCopied] = useState(false);
+
+ const handleCopy = Events.stopPropagation(() => {
+ navigator.clipboard.writeText(value).then(() => {
+ setIsCopied(true);
+ setTimeout(() => setIsCopied(false), 2000);
+ });
+ });
+
+ const button = (
+ <span onClick={handleCopy}>
+ {isCopied ? (
+ <CheckIcon className={cn(className, "text-[var(--grass-11)]")} />
+ ) : (
+ <Copy className={className} />
+ )}
+ </span>
+ );
+
+ if (tooltip === false) {
+ return button;
+ }
+
+ return (
+ <Tooltip
+ content={isCopied ? "Copied!" : tooltip ?? "Copy to clipboard"}
+ delayDuration={400}
+ >
+ {button}
+ </Tooltip>
+ );
+};
diff --git a/frontend/src/core/cells/add-missing-import.ts b/frontend/src/core/cells/add-missing-import.ts
index 6e18031156..64487d5d11 100644
--- a/frontend/src/core/cells/add-missing-import.ts
+++ b/frontend/src/core/cells/add-missing-import.ts
@@ -44,19 +44,41 @@ export function maybeAddMissingImport(
export function maybeAddMarimoImport(
autoRun: boolean,
createNewCell: CellActions["createNewCell"],
+ fromCellId?: CellId | null,
): boolean {
return maybeAddMissingImport("marimo", "mo", (importStatement) => {
- const cellId = CellId.create();
+ const newCellId = CellId.create();
createNewCell({
- cellId: "__end__",
+ cellId: fromCellId ?? "__end__",
before: false,
code: importStatement,
lastCodeRun: autoRun ? importStatement : undefined,
- newCellId: cellId,
+ newCellId: newCellId,
autoFocus: false,
});
if (autoRun) {
- void sendRun([cellId], [importStatement]);
+ void sendRun([newCellId], [importStatement]);
+ }
+ });
+}
+
+export function maybeAddAltairImport(
+ autoRun: boolean,
+ createNewCell: CellActions["createNewCell"],
+ fromCellId?: CellId | null,
+): boolean {
+ return maybeAddMissingImport("altair", "alt", (importStatement) => {
+ const newCellId = CellId.create();
+ createNewCell({
+ cellId: fromCellId ?? "__end__",
+ before: false,
+ code: importStatement,
+ lastCodeRun: autoRun ? importStatement : undefined,
+ newCellId: newCellId,
+ autoFocus: false,
+ });
+ if (autoRun) {
+ void sendRun([newCellId], [importStatement]);
}
});
}
diff --git a/frontend/src/core/cells/focus.ts b/frontend/src/core/cells/focus.ts
index 00aba79afe..89c35a233d 100644
--- a/frontend/src/core/cells/focus.ts
+++ b/frontend/src/core/cells/focus.ts
@@ -1,9 +1,9 @@
/* Copyright 2024 Marimo. All rights reserved. */
import { atom } from "jotai";
-import { CellId } from "./ids";
-import { NotebookState, notebookAtom } from "./cells";
-import { EditorView } from "@codemirror/view";
-import { CellConfig, CellStatus } from "./types";
+import type { CellId } from "./ids";
+import { type NotebookState, notebookAtom } from "./cells";
+import type { EditorView } from "@codemirror/view";
+import type { CellConfig, CellStatus } from "./types";
/**
* Holds state for the last focused cell.
diff --git a/frontend/src/core/datasets/state.ts b/frontend/src/core/datasets/state.ts
new file mode 100644
index 0000000000..32fecd776c
--- /dev/null
+++ b/frontend/src/core/datasets/state.ts
@@ -0,0 +1,96 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+
+import { createReducerAndAtoms } from "@/utils/createReducer";
+import type { DatasetsState } from "./types";
+import { useAtomValue } from "jotai";
+import { VariableName } from "../variables/types";
+import { DataColumnPreview } from "../kernel/messages";
+
+function initialState(): DatasetsState {
+ return {
+ tables: [],
+ expandedTables: new Set(),
+ expandedColumns: new Set(),
+ columnsPreviews: new Map(),
+ };
+}
+
+const {
+ reducer,
+ createActions,
+ valueAtom: datasetsAtom,
+ useActions,
+} = createReducerAndAtoms(initialState, {
+ addDatasets: (state, datasets: Pick<DatasetsState, "tables">) => {
+ // Put new tables at the top
+ const newTables = [...datasets.tables, ...state.tables];
+ // Dedupe by name and source
+ const seen = new Set();
+ const dedupedTables = newTables.filter((table) => {
+ const key = `${table.name}:${table.source}`;
+ if (seen.has(key)) {
+ return false;
+ }
+ seen.add(key);
+ return true;
+ });
+ return {
+ ...state,
+ tables: dedupedTables,
+ };
+ },
+ filterDatasetsFromVariables: (state, variableNames: VariableName[]) => {
+ const names = new Set(variableNames);
+ // Filter out tables that come from variables that are not in the list
+ const tables = state.tables.filter((table) => {
+ return table.variable_name && names.has(table.variable_name);
+ });
+ return { ...state, tables };
+ },
+ toggleTable: (state, tableName: string) => {
+ const expandedTables = new Set(state.expandedTables);
+ if (expandedTables.has(tableName)) {
+ expandedTables.delete(tableName);
+ } else {
+ expandedTables.add(tableName);
+ }
+ return { ...state, expandedTables };
+ },
+ toggleColumn: (state, opts: { table: string; column: string }) => {
+ const tableColumn = `${opts.table}:${opts.column}` as const;
+ const expandedColumns = new Set(state.expandedColumns);
+ if (expandedColumns.has(tableColumn)) {
+ expandedColumns.delete(tableColumn);
+ } else {
+ expandedColumns.add(tableColumn);
+ }
+ return { ...state, expandedColumns };
+ },
+ closeAllColumns: (state) => {
+ return { ...state, expandedColumns: new Set() };
+ },
+ addColumnPreview: (state, preview: DataColumnPreview) => {
+ const tableColumn = `${preview.table_name}:${preview.column_name}` as const;
+ const columnsPreviews = new Map(state.columnsPreviews);
+ columnsPreviews.set(tableColumn, preview);
+ return { ...state, columnsPreviews };
+ },
+});
+
+/**
+ * React hook to get the datasets state.
+ */
+export const useDatasets = () => useAtomValue(datasetsAtom);
+
+/**
+ * React hook to get the datasets actions.
+ */
+export function useDatasetsActions() {
+ return useActions();
+}
+
+export const exportedForTesting = {
+ reducer,
+ createActions,
+ initialState,
+};
diff --git a/frontend/src/core/datasets/types.ts b/frontend/src/core/datasets/types.ts
new file mode 100644
index 0000000000..9179a94602
--- /dev/null
+++ b/frontend/src/core/datasets/types.ts
@@ -0,0 +1,39 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import type { DataTable } from "../network/types";
+import { DataColumnPreview } from "../kernel/messages";
+
+/**
+ * A qualified column name, e.g. `table:column`.
+ */
+export type QualifiedColumn = `${string}:${string}`;
+
+/**
+ * A summary of a column's statistics.
+ */
+export interface ColumnPreviewSummary {
+ error?: string;
+ total?: number;
+ nulls?: number;
+ unique?: number;
+ min?: number;
+ max?: number;
+ mean?: number;
+ median?: number;
+ std?: number;
+ p5?: number;
+ p25?: number;
+ p75?: number;
+ p95?: number;
+}
+
+export type ColumnPreviewMap = ReadonlyMap<QualifiedColumn, DataColumnPreview>;
+
+/**
+ * The datasets state.
+ */
+export interface DatasetsState {
+ tables: DataTable[];
+ expandedTables: ReadonlySet<string>;
+ expandedColumns: ReadonlySet<QualifiedColumn>;
+ columnsPreviews: ColumnPreviewMap;
+}
diff --git a/frontend/src/core/edit-app.tsx b/frontend/src/core/edit-app.tsx
index 9f3a26d926..591e00388c 100644
--- a/frontend/src/core/edit-app.tsx
+++ b/frontend/src/core/edit-app.tsx
@@ -115,11 +115,11 @@ export const EditApp: React.FC<AppProps> = ({ userConfig, appConfig }) => {
}
});
- return sendRename(name)
+ return sendRename(name)
.then(() => {
setFilename(name);
- // Set document title: app_title takes precedence, then filename, then default
- document.title = appConfig.app_title || name || "Untitled Notebook";
+ // Set document title: app_title takes precedence, then filename, then default
+ document.title = appConfig.app_title || name || "Untitled Notebook";
return name;
})
.catch((error) => {
@@ -128,10 +128,10 @@ export const EditApp: React.FC<AppProps> = ({ userConfig, appConfig }) => {
});
});
- // Update document title whenever filename or app_title changes
+ // Update document title whenever filename or app_title changes
useEffect(() => {
// Set document title: app_title takes precedence, then filename, then default
- document.title = appConfig.app_title || filename || "Untitled Notebook";
+ document.title = appConfig.app_title || filename || "Untitled Notebook";
}, [appConfig.app_title, filename]);
const cells = notebookCells(notebook);
diff --git a/frontend/src/core/functions/FunctionRegistry.ts b/frontend/src/core/functions/FunctionRegistry.ts
index c880366f2a..97de03ddc6 100644
--- a/frontend/src/core/functions/FunctionRegistry.ts
+++ b/frontend/src/core/functions/FunctionRegistry.ts
@@ -1,9 +1,9 @@
/* Copyright 2024 Marimo. All rights reserved. */
import { sendFunctionRequest } from "@/core/network/requests";
-import { FunctionCallResultMessage } from "../kernel/messages";
+import type { FunctionCallResultMessage } from "../kernel/messages";
import { DeferredRequestRegistry } from "../network/DeferredRequestRegistry";
-import { SendFunctionRequest } from "../network/types";
+import type { SendFunctionRequest } from "../network/types";
export const FUNCTIONS_REGISTRY = new DeferredRequestRegistry<
Omit<SendFunctionRequest, "functionCallId">,
diff --git a/frontend/src/core/islands/bridge.ts b/frontend/src/core/islands/bridge.ts
index f9514ffef8..99033babc4 100644
--- a/frontend/src/core/islands/bridge.ts
+++ b/frontend/src/core/islands/bridge.ts
@@ -147,6 +147,7 @@ export class IslandsPyodideBridge implements RunRequests, EditRequests {
sendRestart = throwNotImplemented;
readCode = throwNotImplemented;
readSnippets = throwNotImplemented;
+ previewDatasetColumn = throwNotImplemented;
openFile = throwNotImplemented;
sendListFiles = throwNotImplemented;
sendCreateFileOrFolder = throwNotImplemented;
diff --git a/frontend/src/core/islands/main.ts b/frontend/src/core/islands/main.ts
index 4b6bde0c7c..472b015abe 100644
--- a/frontend/src/core/islands/main.ts
+++ b/frontend/src/core/islands/main.ts
@@ -89,6 +89,8 @@ export async function initialize() {
return;
case "variables":
case "variable-values":
+ case "data-column-preview":
+ case "datasets":
return;
case "alert":
// TODO: support toast with islands
diff --git a/frontend/src/core/kernel/messages.ts b/frontend/src/core/kernel/messages.ts
index 977d14e0c7..6c99837039 100644
--- a/frontend/src/core/kernel/messages.ts
+++ b/frontend/src/core/kernel/messages.ts
@@ -1,12 +1,15 @@
/* Copyright 2024 Marimo. All rights reserved. */
-import { LayoutType } from "@/components/editor/renderers/types";
+import type { LayoutType } from "@/components/editor/renderers/types";
import type { CellConfig, CellStatus } from "../cells/types";
-import { CellId, UIElementId } from "../cells/ids";
-import { VariableName } from "../variables/types";
-import { RequestId } from "../network/DeferredRequestRegistry";
-import { Seconds } from "@/utils/time";
-import { AppConfig } from "../config/config-schema";
+import type { CellId, UIElementId } from "../cells/ids";
+import type { VariableName } from "../variables/types";
+import type { RequestId } from "../network/DeferredRequestRegistry";
+import type { Seconds } from "@/utils/time";
+import type { AppConfig } from "../config/config-schema";
+import type { DataTable } from "../network/types";
+import type { ColumnPreviewSummary } from "../datasets/types";
+import type { JsonString } from "@/utils/json/base64";
export type OutputChannel =
| "output"
@@ -167,6 +170,16 @@ export interface PackageInstallationStatus {
[key: string]: "queued" | "installing" | "installed" | "failed";
}
+export interface DataColumnPreview {
+ table_name: string;
+ column_name: string;
+ chart_max_rows_errors: boolean;
+ chart_spec?: JsonString;
+ chart_code?: string;
+ error?: string;
+ summary?: ColumnPreviewSummary;
+}
+
/**
* Message sent from the frontend to the kernel via the websocket.
*/
@@ -275,6 +288,16 @@ export type OperationMessage =
}>;
};
}
+ | {
+ op: "datasets";
+ data: {
+ tables: DataTable[];
+ };
+ }
+ | {
+ op: "data-column-preview";
+ data: DataColumnPreview;
+ }
| {
op: "query-params-set";
data: {
diff --git a/frontend/src/core/network/requests-network.ts b/frontend/src/core/network/requests-network.ts
index 4f17f53e93..fb3fb58fe0 100644
--- a/frontend/src/core/network/requests-network.ts
+++ b/frontend/src/core/network/requests-network.ts
@@ -35,6 +35,7 @@ import type {
UsageResponse,
ExportAsMarkdownRequest,
WorkspaceFilesRequest,
+ PreviewDatasetColumnRequest,
} from "./types";
import { invariant } from "@/utils/invariant";
@@ -155,6 +156,12 @@ export function createNetworkRequests(): EditRequests & RunRequests {
readSnippets: () => {
return API.get<SnippetsResponse>("/documentation/snippets", {});
},
+ previewDatasetColumn: (request: PreviewDatasetColumnRequest) => {
+ return API.post<PreviewDatasetColumnRequest>(
+ "/datasources/preview_column",
+ request,
+ );
+ },
openFile: async (request) => {
await API.post<{ path: string }>("/kernel/open", request);
await API.post("/kernel/restart_session", {});
diff --git a/frontend/src/core/network/requests-static.ts b/frontend/src/core/network/requests-static.ts
index b84abedc71..0a4be3a0e1 100644
--- a/frontend/src/core/network/requests-static.ts
+++ b/frontend/src/core/network/requests-static.ts
@@ -51,6 +51,7 @@ export function createStaticRequests(): EditRequests & RunRequests {
sendStdin: throwNotInEditMode,
readCode: throwNotInEditMode,
readSnippets: throwNotInEditMode,
+ previewDatasetColumn: throwNotInEditMode,
openFile: throwNotInEditMode,
getUsageStats: throwNotInEditMode,
sendListFiles: throwNotInEditMode,
diff --git a/frontend/src/core/network/requests-toasting.ts b/frontend/src/core/network/requests-toasting.ts
index 41b573dc99..24a9b3b6ef 100644
--- a/frontend/src/core/network/requests-toasting.ts
+++ b/frontend/src/core/network/requests-toasting.ts
@@ -27,6 +27,7 @@ export function createErrorToastingRequests(
sendStdin: "Failed to send stdin",
readCode: "Failed to read code",
readSnippets: "Failed to fetch snippets",
+ previewDatasetColumn: "Failed to fetch data sources",
openFile: "Failed to open file",
getUsageStats: "", // Empty string because we don't show a toast for this
sendListFiles: "Failed to list files",
diff --git a/frontend/src/core/network/requests.ts b/frontend/src/core/network/requests.ts
index 7bda5bc14b..d62a35eaff 100644
--- a/frontend/src/core/network/requests.ts
+++ b/frontend/src/core/network/requests.ts
@@ -45,6 +45,7 @@ export const {
sendInstallMissingPackages,
readCode,
readSnippets,
+ previewDatasetColumn,
openFile,
getUsageStats,
sendListFiles,
diff --git a/frontend/src/core/network/types.ts b/frontend/src/core/network/types.ts
index 468273afed..a96ef9db45 100644
--- a/frontend/src/core/network/types.ts
+++ b/frontend/src/core/network/types.ts
@@ -1,12 +1,13 @@
/* Copyright 2024 Marimo. All rights reserved. */
-import { AppConfig, UserConfig } from "../config/config-schema";
-import { LayoutType } from "@/components/editor/renderers/types";
-import { CellId } from "../cells/ids";
-import { CellConfig } from "../cells/types";
-import { RequestId } from "./DeferredRequestRegistry";
-import { FilePath } from "@/utils/paths";
-import { PackageManagerName } from "../config/config-schema";
-import { SessionId } from "@/core/kernel/session";
+import type { AppConfig, UserConfig } from "../config/config-schema";
+import type { LayoutType } from "@/components/editor/renderers/types";
+import type { CellId } from "../cells/ids";
+import type { CellConfig } from "../cells/types";
+import type { RequestId } from "./DeferredRequestRegistry";
+import type { FilePath } from "@/utils/paths";
+import type { PackageManagerName } from "../config/config-schema";
+import type { SessionId } from "@/core/kernel/session";
+import { VariableName } from "../variables/types";
// Ideally this would be generated from server.py, but for now we just
// manually keep them in sync.
@@ -172,6 +173,29 @@ export interface SnippetsResponse {
snippets: Snippet[];
}
+export interface PreviewDatasetColumnRequest {
+ source: string;
+ tableName: string;
+ columnName: string;
+}
+
+export interface DataTableColumn {
+ name: string;
+ type: "string" | "boolean" | "integer" | "number" | "date" | "unknown";
+}
+
+export interface DataTable {
+ name: string;
+ source: string;
+ /**
+ * The variable name if this is a variable in the notebook.
+ */
+ variable_name: VariableName | null;
+ num_rows: number;
+ num_columns: number;
+ columns: DataTableColumn[];
+}
+
interface MarimoNotebook {
name: string;
path: string;
@@ -255,6 +279,7 @@ export interface EditRequests {
) => Promise<null>;
readCode: () => Promise<{ contents: string }>;
readSnippets: () => Promise<SnippetsResponse>;
+ previewDatasetColumn: (request: PreviewDatasetColumnRequest) => Promise<null>;
openFile: (request: { path: string }) => Promise<null>;
getUsageStats: () => Promise<UsageResponse>;
// File explorer requests
diff --git a/frontend/src/core/pyodide/bridge.ts b/frontend/src/core/pyodide/bridge.ts
index 40584034b4..831fca53e5 100644
--- a/frontend/src/core/pyodide/bridge.ts
+++ b/frontend/src/core/pyodide/bridge.ts
@@ -412,6 +412,7 @@ export class PyodideBridge implements RunRequests, EditRequests {
return response as string;
};
+ previewDatasetColumn = throwNotImplemented;
getUsageStats = throwNotImplemented;
getRecentFiles = throwNotImplemented;
getWorkspaceFiles = throwNotImplemented;
diff --git a/frontend/src/core/websocket/useMarimoWebSocket.tsx b/frontend/src/core/websocket/useMarimoWebSocket.tsx
index 38542ad546..d55f36d016 100644
--- a/frontend/src/core/websocket/useMarimoWebSocket.tsx
+++ b/frontend/src/core/websocket/useMarimoWebSocket.tsx
@@ -32,6 +32,7 @@ import {
} from "../kernel/handlers";
import { queryParamHandlers } from "../kernel/queryParamHandlers";
import type { JsonString } from "@/utils/json/base64";
+import { useDatasetsActions } from "../datasets/state";
/**
* WebSocket that connects to the Marimo kernel and handles incoming messages.
@@ -49,6 +50,8 @@ export function useMarimoWebSocket(opts: {
const { handleCellMessage } = useCellActions();
const setAppConfig = useSetAppConfig();
const { setVariables, setMetadata } = useVariablesActions();
+ const { addColumnPreview } = useDatasetsActions();
+ const { addDatasets, filterDatasetsFromVariables } = useDatasetsActions();
const { setLayoutData } = useLayoutActions();
const [connection, setConnection] = useAtom(connectionAtom);
const { addBanner } = useBannersActions();
@@ -97,6 +100,7 @@ export function useMarimoWebSocket(opts: {
usedBy: v.used_by,
})),
);
+ filterDatasetsFromVariables(msg.data.variables.map((v) => v.name));
return;
case "variable-values":
setMetadata(
@@ -150,6 +154,13 @@ export function useMarimoWebSocket(opts: {
queryParamHandlers.clear();
return;
+ case "datasets":
+ addDatasets(msg.data);
+ return;
+ case "data-column-preview":
+ addColumnPreview(msg.data);
+ return;
+
default:
logNever(msg);
}
diff --git a/frontend/src/plugins/impl/vega/vega-component.tsx b/frontend/src/plugins/impl/vega/vega-component.tsx
index 98687e5317..1243127420 100644
--- a/frontend/src/plugins/impl/vega/vega-component.tsx
+++ b/frontend/src/plugins/impl/vega/vega-component.tsx
@@ -3,7 +3,7 @@ import { VegaLite, type SignalListeners, type View } from "react-vega";
import { makeSelectable } from "./make-selectable";
import { useMemo, useRef, useState } from "react";
import { getSelectionParamNames } from "./params";
-import { VegaLiteSpec } from "./types";
+import type { VegaLiteSpec } from "./types";
import { Alert, AlertTitle } from "@/components/ui/alert";
import { useDeepCompareMemoize } from "@/hooks/useDeepCompareMemoize";
import { useDebugMounting, usePropsDidChange } from "@/hooks/debug";
@@ -16,6 +16,7 @@ import { useTheme } from "@/theme/useTheme";
import { Objects } from "@/utils/objects";
import { resolveVegaSpecData } from "./resolve-data";
import { Events } from "@/utils/events";
+import { ErrorBanner } from "../common/error-banner";
export interface Data {
spec: VegaLiteSpec;
@@ -49,7 +50,7 @@ const VegaComponent = ({
fieldSelection,
spec,
}: VegaComponentProps<VegaComponentState>) => {
- const { data: resolvedSpec } = useAsyncData(async () => {
+ const { data: resolvedSpec, error } = useAsyncData(async () => {
// We try to resolve the data before passing it to Vega
// otherwise it will try to load it internally and flicker
// Instead we can handle the loading state ourselves,
@@ -57,6 +58,10 @@ const VegaComponent = ({
return resolveVegaSpecData(spec);
}, [spec]);
+ if (error) {
+ return <ErrorBanner error={error} />;
+ }
+
if (!resolvedSpec) {
return null;
}
diff --git a/frontend/src/utils/json/base64.ts b/frontend/src/utils/json/base64.ts
index 1ed0a7ebf0..532ec113d4 100644
--- a/frontend/src/utils/json/base64.ts
+++ b/frontend/src/utils/json/base64.ts
@@ -1,7 +1,7 @@
/* Copyright 2024 Marimo. All rights reserved. */
-import { TypedString } from "../typed";
+import type { TypedString } from "../typed";
-export type JsonString<T> = TypedString<"Json"> & {
+export type JsonString<T = unknown> = TypedString<"Json"> & {
_of_: T;
};
diff --git a/frontend/src/utils/numbers.ts b/frontend/src/utils/numbers.ts
index e677259b93..2bd53c6077 100644
--- a/frontend/src/utils/numbers.ts
+++ b/frontend/src/utils/numbers.ts
@@ -1,6 +1,10 @@
/* Copyright 2024 Marimo. All rights reserved. */
-export function prettyNumber(value: number): string {
+export function prettyNumber(value: number | string): string {
+ if (typeof value === "string") {
+ return value;
+ }
+
return value.toLocaleString(undefined, {
minimumFractionDigits: 0,
maximumFractionDigits: 2,
diff --git a/frontend/tailwind.config.js b/frontend/tailwind.config.js
index 85fd5c4796..71205a1967 100644
--- a/frontend/tailwind.config.js
+++ b/frontend/tailwind.config.js
@@ -130,11 +130,18 @@ module.exports = {
"delayed-show-200": "delayed-show 200ms ease-out",
"delayed-show-400": "delayed-show 400ms ease-out",
},
+ gridTemplateColumns: {
+ "auto-fit": "repeat(auto-fit, minmax(0, 1fr))",
+ "auto-fill": "repeat(auto-fill, minmax(0, 1fr))",
+ "auto-fill-200": "repeat(auto-fill, minmax(200px, 1fr))",
+ "2-fit": "repeat(2, minmax(0, max-content))",
+ "3-fit": "repeat(3, minmax(0, max-content))",
+ },
},
},
plugins: [
require("tailwindcss-animate"),
- plugin(function ({ addUtilities }) {
+ plugin(({ addUtilities }) => {
const newUtilities = {
".increase-pointer-area-x": {
border: "none",
diff --git a/frontend/vite.config.mts b/frontend/vite.config.mts
index 80ca54c687..630efe3301 100644
--- a/frontend/vite.config.mts
+++ b/frontend/vite.config.mts
@@ -84,7 +84,8 @@ const htmlDevPlugin = (): Plugin => {
copyElements.forEach((id) => {
const element = devDoc.querySelector(id);
if (!element) {
- throw new Error(`Element ${id} not found.`);
+ console.warn(`Element ${id} not found.`);
+ return;
}
element.remove();
});
@@ -93,7 +94,8 @@ const htmlDevPlugin = (): Plugin => {
copyElements.forEach((id) => {
const element = serverDoc.querySelector(id);
if (!element) {
- throw new Error(`Element ${id} not found.`);
+ console.warn(`Element ${id} not found.`);
+ return;
}
devDoc.head.append(element);
});
diff --git a/marimo/_cli/config/utils.py b/marimo/_cli/config/utils.py
index c0d9d0b650..5584cc791e 100644
--- a/marimo/_cli/config/utils.py
+++ b/marimo/_cli/config/utils.py
@@ -1,3 +1,4 @@
+# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
from marimo._cli.print import orange
diff --git a/marimo/_config/manager.py b/marimo/_config/manager.py
index becaf81c5d..06067c2a6d 100644
--- a/marimo/_config/manager.py
+++ b/marimo/_config/manager.py
@@ -2,6 +2,7 @@
from __future__ import annotations
import os
+from typing import Optional
from marimo import _loggers
from marimo._config.config import (
@@ -17,7 +18,8 @@ LOGGER = _loggers.marimo_logger()
class UserConfigManager:
- def __init__(self) -> None:
+ def __init__(self, config_path: Optional[str] = None) -> None:
+ self._config_path = config_path
self.config = load_config()
def save_config(self, config: MarimoConfig) -> MarimoConfig:
diff --git a/marimo/_data/charts.py b/marimo/_data/charts.py
new file mode 100644
index 0000000000..15bc8aca54
--- /dev/null
+++ b/marimo/_data/charts.py
@@ -0,0 +1,280 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+import abc
+from dataclasses import dataclass
+from textwrap import dedent
+from typing import Any, cast
+
+from marimo._data.models import DataType
+
+
+class ChartBuilder:
+ @abc.abstractmethod
+ def altair(self, data: Any, column: str) -> Any:
+ raise NotImplementedError
+
+ def altair_json(self, data: Any, column: str) -> str:
+ return cast(str, self.altair(data, column).to_json())
+
+ @abc.abstractmethod
+ def altair_code(self, data: str, column: str) -> str:
+ raise NotImplementedError
+
+
+@dataclass
+class ChartParams:
+ table_name: str
+ column: str
+
+
+class NumberChartBuilder(ChartBuilder):
+ def altair(self, data: Any, column: str) -> Any:
+ import altair as alt # type: ignore[import-not-found,import-untyped,unused-ignore] # noqa: E501
+
+ return (
+ alt.Chart(data)
+ .mark_bar()
+ .encode(
+ x=alt.X(column, type="quantitative", bin=True),
+ y=alt.Y("count()", type="quantitative"),
+ )
+ .properties(width="container")
+ )
+
+ def altair_code(self, data: str, column: str) -> str:
+ return f"""
+ _chart = (
+ alt.Chart({data})
+ .mark_bar()
+ .encode(
+ x=alt.X("{column}", type="quantitative", bin=True),
+ y=alt.Y("count()", type="quantitative"),
+ )
+ .properties(width="container")
+ )
+ _chart
+ """
+
+
+class StringChartBuilder(ChartBuilder):
+ def __init__(self, should_limit_to_10_items: bool) -> None:
+ self.should_limit_to_10_items = should_limit_to_10_items
+ super().__init__()
+
+ def altair(self, data: Any, column: str) -> Any:
+ import altair as alt # type: ignore[import-not-found,import-untyped,unused-ignore] # noqa: E501
+
+ if self.should_limit_to_10_items:
+ return (
+ alt.Chart(data)
+ .transform_aggregate(count="count()", groupby=[column])
+ .transform_window(
+ rank="rank()",
+ sort=[
+ alt.SortField("count", order="descending"),
+ alt.SortField(column, order="ascending"),
+ ],
+ )
+ .transform_filter(alt.datum.rank <= 10)
+ .mark_bar()
+ .encode(
+ y=alt.Y(column, type="nominal", sort="-x"),
+ x=alt.X("count", type="quantitative"),
+ )
+ .properties(title=f"Top 10 {column}", width="container")
+ )
+
+ return (
+ alt.Chart(data)
+ .mark_bar()
+ .encode(
+ y=alt.Y(column, type="nominal"),
+ x=alt.X("count()", type="quantitative"),
+ )
+ .properties(width="container")
+ )
+
+ def altair_code(self, data: str, column: str) -> str:
+ if self.should_limit_to_10_items:
+ return f"""
+ _chart = (
+ alt.Chart({data})
+ .transform_aggregate(count="count()", groupby=["{column}"])
+ .transform_window(
+ rank="rank()",
+ sort=[
+ alt.SortField("count", order="descending"),
+ alt.SortField("{column}", order="ascending"),
+ ],
+ )
+ .transform_filter(alt.datum.rank <= 10)
+ .mark_bar()
+ .encode(
+ y=alt.Y("{column}", type="nominal", sort="-x"),
+ x=alt.X("count", type="quantitative"),
+ )
+ .properties(title="Top 10 {column}", width="container")
+ )
+ _chart
+ """
+
+ return f"""
+ _chart = (
+ alt.Chart({data})
+ .mark_bar()
+ .encode(
+ y=alt.Y("{column}", type="nominal"),
+ x=alt.X("count()", type="quantitative"),
+ )
+ .properties(width="container")
+ )
+ _chart
+ """
+
+
+class DateChartBuilder(ChartBuilder):
+ def altair(self, data: Any, column: str) -> Any:
+ import altair as alt # type: ignore[import-not-found,import-untyped,unused-ignore] # noqa: E501
+
+ return (
+ alt.Chart(data)
+ .mark_line(point={"filled": False, "fill": "white"})
+ .encode(
+ x=alt.X(column, type="temporal"),
+ y=alt.Y("count()", type="quantitative"),
+ )
+ .properties(width="container")
+ )
+
+ def altair_code(self, data: str, column: str) -> str:
+ return f"""
+ _chart = (
+ alt.Chart({data})
+ .mark_line(point={{"filled": False, "fill": "white"}})
+ .encode(
+ x=alt.X("{column}", type="temporal"),
+ y=alt.Y("count()", type="quantitative"),
+ )
+ .properties(width="container")
+ )
+ _chart
+ """
+
+
+class BooleanChartBuilder(ChartBuilder):
+ def altair(self, data: Any, column: str) -> Any:
+ import altair as alt # type: ignore[import-not-found,import-untyped,unused-ignore] # noqa: E501
+
+ return (
+ alt.Chart(data)
+ .mark_bar()
+ .encode(
+ x=alt.X(column, type="nominal"),
+ y=alt.Y("count()", type="quantitative"),
+ )
+ .properties(width="container")
+ )
+
+ def altair_code(self, data: str, column: str) -> str:
+ return f"""
+ _chart = (
+ alt.Chart({data})
+ .mark_bar()
+ .encode(
+ x=alt.X("{column}", type="nominal"),
+ y=alt.Y("count()", type="quantitative"),
+ )
+ .properties(width="container")
+ )
+ _chart
+ """
+
+
+class IntegerChartBuilder(ChartBuilder):
+ def altair(self, data: Any, column: str) -> Any:
+ import altair as alt # type: ignore[import-not-found,import-untyped,unused-ignore] # noqa: E501
+
+ return (
+ alt.Chart(data)
+ .mark_bar()
+ .encode(
+ x=alt.X(column, type="quantitative", bin=True),
+ y=alt.Y("count()", type="quantitative"),
+ )
+ .properties(width="container")
+ )
+
+ def altair_code(self, data: str, column: str) -> str:
+ return f"""
+ _chart = (
+ alt.Chart({data})
+ .mark_bar()
+ .encode(
+ x=alt.X("{column}", type="quantitative", bin=True),
+ y=alt.Y("count()", type="quantitative"),
+ )
+ .properties(width="container")
+ )
+ _chart
+ """
+
+
+class UnknownChartBuilder(ChartBuilder):
+ def altair(self, data: Any, column: str) -> Any:
+ import altair as alt # type: ignore[import-not-found,import-untyped,unused-ignore] # noqa: E501
+
+ return (
+ alt.Chart(data)
+ .mark_bar()
+ .encode(
+ x=alt.X(column, type="nominal"),
+ y=alt.Y("count()", type="quantitative"),
+ )
+ .properties(width="container")
+ )
+
+ def altair_code(self, data: str, column: str) -> str:
+ return f"""
+ _chart = (
+ alt.Chart({data})
+ .mark_bar()
+ .encode(
+ x=alt.X("{column}", type="nominal"),
+ y=alt.Y("count()", type="quantitative"),
+ )
+ .properties(width="container")
+ )
+ _chart
+ """
+
+
+class WrapperChartBuilder(ChartBuilder):
+ def __init__(self, delegate: ChartBuilder):
+ self.delegate = delegate
+
+ def altair(self, data: Any, column: str) -> Any:
+ return self.delegate.altair(data, column)
+
+ def altair_code(self, data: str, column: str) -> str:
+ return dedent(self.delegate.altair_code(data, column)).strip()
+
+
+def get_chart_builder(
+ column_type: DataType, should_limit_to_10_items: bool = False
+) -> ChartBuilder:
+ if column_type == "number":
+ return WrapperChartBuilder(NumberChartBuilder())
+ if column_type == "string":
+ return WrapperChartBuilder(
+ StringChartBuilder(should_limit_to_10_items)
+ )
+ if column_type == "date":
+ return WrapperChartBuilder(DateChartBuilder())
+ if column_type == "boolean":
+ return WrapperChartBuilder(BooleanChartBuilder())
+ if column_type == "integer":
+ return WrapperChartBuilder(IntegerChartBuilder())
+ if column_type == "unknown":
+ return WrapperChartBuilder(UnknownChartBuilder())
diff --git a/marimo/_data/get_datasets.py b/marimo/_data/get_datasets.py
new file mode 100644
index 0000000000..1a825a7ea4
--- /dev/null
+++ b/marimo/_data/get_datasets.py
@@ -0,0 +1,37 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+from typing import List, Optional
+
+from marimo._data.models import DataTable, DataTableColumn
+from marimo._plugins.ui._impl.tables.utils import get_table_manager_or_none
+
+
+def get_datasets_from_variables(
+ variables: List[tuple[str, object]],
+) -> List[DataTable]:
+ tables: List[DataTable] = []
+ for variable_name, value in variables:
+ table = get_data_table(value, variable_name)
+ if table is not None:
+ tables.append(table)
+
+ return tables
+
+
+def get_data_table(value: object, variable_name: str) -> Optional[DataTable]:
+ table = get_table_manager_or_none(value)
+ if table is not None:
+ return DataTable(
+ name=variable_name,
+ variable_name=variable_name,
+ num_rows=table.get_num_rows(),
+ num_columns=table.get_num_columns(),
+ source=f"Local ({table.type})",
+ columns=[
+ DataTableColumn(name=column_name, type=column_type)
+ for column_name, column_type in table.get_field_types().items()
+ ],
+ )
+
+ return None
diff --git a/marimo/_data/models.py b/marimo/_data/models.py
new file mode 100644
index 0000000000..0d5f3db3bb
--- /dev/null
+++ b/marimo/_data/models.py
@@ -0,0 +1,75 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+from dataclasses import dataclass
+from datetime import date, datetime, time, timedelta # noqa: TCH003
+from decimal import Decimal
+from typing import List, Literal, Optional, Union
+
+DataType = Literal["string", "boolean", "integer", "number", "date", "unknown"]
+
+
+@dataclass
+class DataTableColumn:
+ """
+ Represents a column in a data table.
+
+ Attributes:
+ name (str): The name of the column.
+ type (DataType): The data type of the column.
+ """
+
+ name: str
+ type: DataType
+
+
+@dataclass
+class DataTable:
+ """
+ Represents a data table.
+
+ Attributes:
+ source (str): The source of the data table.
+ name (str): The name of the data table.
+ num_rows (Optional[int]): The number of rows in the data table.
+ num_columns (Optional[int]): The number of columns in the data table.
+ variable_name (Optional[str]): The variable name associated with
+ the data table.
+ columns (List[DataTableColumn]): The list of columns in the data table.
+ """
+
+ source: str
+ name: str
+ num_rows: Optional[int]
+ num_columns: Optional[int]
+ variable_name: Optional[str]
+ columns: List[DataTableColumn]
+
+
+NumericLiteral = Union[int, float, Decimal]
+TemporalLiteral = Union[date, time, datetime, timedelta]
+NonNestedLiteral = Union[NumericLiteral, TemporalLiteral, str, bool, bytes]
+
+
+@dataclass
+class ColumnSummary:
+ """
+ Represents a summary of a column in a data table.
+
+ """
+
+ total: Optional[int] = None
+ nulls: Optional[int] = None
+ unique: Optional[int] = None
+ min: Optional[NonNestedLiteral] = None
+ max: Optional[NonNestedLiteral] = None
+ mean: Optional[NonNestedLiteral] = None
+ median: Optional[NonNestedLiteral] = None
+ std: Optional[NonNestedLiteral] = None
+ true: Optional[NonNestedLiteral] = None
+ false: Optional[NonNestedLiteral] = None
+ p5: Optional[NonNestedLiteral] = None
+ p25: Optional[NonNestedLiteral] = None
+ # p50 is the median
+ p75: Optional[NonNestedLiteral] = None
+ p95: Optional[NonNestedLiteral] = None
diff --git a/marimo/_data/preview_column.py b/marimo/_data/preview_column.py
new file mode 100644
index 0000000000..d7f7220dcc
--- /dev/null
+++ b/marimo/_data/preview_column.py
@@ -0,0 +1,132 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+from typing import Any, Optional
+
+from marimo import _loggers
+from marimo._data.charts import get_chart_builder
+from marimo._data.models import ColumnSummary
+from marimo._dependencies.dependencies import DependencyManager
+from marimo._messaging.ops import DataColumnPreview
+from marimo._plugins.ui._impl.tables.table_manager import TableManager
+from marimo._plugins.ui._impl.tables.utils import get_table_manager_or_none
+from marimo._runtime.requests import PreviewDatasetColumnRequest
+
+LOGGER = _loggers.marimo_logger()
+
+
+def get_column_preview(
+ item: object,
+ request: PreviewDatasetColumnRequest,
+) -> DataColumnPreview | None:
+ """
+ Get a preview of the column in the dataset.
+
+ This may return a chart and a aggregation summary of the column.
+ """
+ try:
+ table = get_table_manager_or_none(item)
+ if table is None:
+ return None
+
+ # Get the summary of the column
+ try:
+ summary = table.get_summary(request.column_name)
+ except Exception as e:
+ LOGGER.warning(
+ "Failed to get summary for column %s in table %s",
+ request.column_name,
+ request.table_name,
+ exc_info=e,
+ )
+ summary = ColumnSummary()
+
+ # We require altair to render the chart
+ error = None
+ if not DependencyManager.has_altair():
+ error = (
+ "Altair is required to render charts. "
+ "Install it with `pip install altair`."
+ )
+
+ # Get the chart for the column
+ try:
+ chart_spec, chart_code, chart_max_rows_errors = _get_altair_chart(
+ request, table, summary
+ )
+ except Exception as e:
+ LOGGER.warning(
+ "Failed to get chart for column %s in table %s",
+ request.column_name,
+ request.table_name,
+ exc_info=e,
+ )
+ chart_max_rows_errors = False
+ chart_spec = None
+ chart_code = None
+
+ return DataColumnPreview(
+ table_name=request.table_name,
+ column_name=request.column_name,
+ chart_max_rows_errors=chart_max_rows_errors,
+ chart_spec=chart_spec,
+ chart_code=chart_code,
+ summary=summary,
+ error=error,
+ )
+ except Exception as e:
+ LOGGER.warning(
+ "Failed to get preview for column %s in table %s",
+ request.column_name,
+ request.table_name,
+ exc_info=e,
+ )
+ return DataColumnPreview(
+ table_name=request.table_name,
+ column_name=request.column_name,
+ error=str(e),
+ )
+
+
+def _get_altair_chart(
+ request: PreviewDatasetColumnRequest,
+ table: TableManager[Any],
+ summary: ColumnSummary,
+) -> tuple[Optional[str], Optional[str], bool]:
+ # We require altair to render the chart
+ if not DependencyManager.has_altair() or not table.supports_altair():
+ return None, None, False
+
+ from altair import ( # type: ignore[import-not-found,import-untyped,unused-ignore] # noqa: E501
+ MaxRowsError,
+ )
+
+ column_type = table.get_field_types()[request.column_name]
+
+ # For categorical columns with more than 10 unique values,
+ # we limit the chart to 10 items
+ should_limit_to_10_items = False
+ if (
+ column_type == "string"
+ and summary.unique is not None
+ and summary.unique > 10
+ ):
+ should_limit_to_10_items = True
+
+ chart_builder = get_chart_builder(column_type, should_limit_to_10_items)
+ code = chart_builder.altair_code(
+ request.table_name,
+ request.column_name,
+ )
+
+ chart_max_rows_errors = False
+ try:
+ chart_json = chart_builder.altair_json(
+ table.data,
+ request.column_name,
+ )
+ except MaxRowsError:
+ chart_json = None
+ chart_max_rows_errors = True
+
+ return chart_json, code, chart_max_rows_errors
diff --git a/marimo/_messaging/ops.py b/marimo/_messaging/ops.py
index a4a68e52ae..d657a06aff 100644
--- a/marimo/_messaging/ops.py
+++ b/marimo/_messaging/ops.py
@@ -26,6 +26,7 @@ from typing import (
from marimo import _loggers as loggers
from marimo._ast.app import _AppConfig
from marimo._ast.cell import CellConfig, CellId_t, CellStatusType
+from marimo._data.models import ColumnSummary, DataTable
from marimo._messaging.cell_output import CellChannel, CellOutput
from marimo._messaging.completion_option import CompletionOption
from marimo._messaging.errors import Error
@@ -421,6 +422,28 @@ class VariableValues(Op):
variables: List[VariableValue]
+@dataclass
+class Datasets(Op):
+ """List of datasets."""
+
+ name: ClassVar[str] = "datasets"
+ tables: List[DataTable]
+
+
+@dataclass
+class DataColumnPreview(Op):
+ """Preview of a column in a dataset."""
+
+ name: ClassVar[str] = "data-column-preview"
+ table_name: str
+ column_name: str
+ chart_spec: Optional[str] = None
+ chart_max_rows_errors: bool = False
+ chart_code: Optional[str] = None
+ error: Optional[str] = None
+ summary: Optional[ColumnSummary] = None
+
+
@dataclass
class QueryParamsSet(Op):
"""Set query parameters."""
@@ -478,4 +501,7 @@ MessageOperation = Union[
QueryParamsAppend,
QueryParamsDelete,
QueryParamsClear,
+ # Datasets
+ Datasets,
+ DataColumnPreview,
]
diff --git a/marimo/_plugins/ui/_impl/altair_chart.py b/marimo/_plugins/ui/_impl/altair_chart.py
index 735bb60042..7faa61a8b9 100644
--- a/marimo/_plugins/ui/_impl/altair_chart.py
+++ b/marimo/_plugins/ui/_impl/altair_chart.py
@@ -18,6 +18,9 @@ from marimo import _loggers
from marimo._dependencies.dependencies import DependencyManager
from marimo._output.rich_help import mddoc
from marimo._plugins.ui._core.ui_element import UIElement
+from marimo._plugins.ui._impl.charts.altair_transformer import (
+ register_transformers,
+)
from marimo._utils import flatten
LOGGER = _loggers.marimo_logger()
@@ -198,6 +201,8 @@ class altair_chart(UIElement[ChartSelection, "pd.DataFrame"]):
import altair as alt
+ register_transformers()
+
if not isinstance(chart, (alt.TopLevelMixin)):
raise ValueError(
"Invalid type for chart: "
diff --git a/marimo/_plugins/ui/_impl/charts/altair_transformer.py b/marimo/_plugins/ui/_impl/charts/altair_transformer.py
index 4db431ef10..24759c9b22 100644
--- a/marimo/_plugins/ui/_impl/charts/altair_transformer.py
+++ b/marimo/_plugins/ui/_impl/charts/altair_transformer.py
@@ -1,4 +1,6 @@
# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
import json
from typing import TYPE_CHECKING, Any, Dict, Literal, TypedDict, Union
diff --git a/marimo/_plugins/ui/_impl/tables/default_table.py b/marimo/_plugins/ui/_impl/tables/default_table.py
index 21fba6e5bb..f2eadcec7d 100644
--- a/marimo/_plugins/ui/_impl/tables/default_table.py
+++ b/marimo/_plugins/ui/_impl/tables/default_table.py
@@ -10,6 +10,7 @@ from typing import (
cast,
)
+from marimo._data.models import ColumnSummary
from marimo._dependencies.dependencies import DependencyManager
from marimo._output.mime import MIME
from marimo._plugins.core.web_component import JSONType
@@ -30,6 +31,8 @@ JsonTableData = Union[
class DefaultTableManager(TableManager[JsonTableData]):
+ type = "dictionary"
+
def __init__(self, data: JsonTableData):
self.data = data
@@ -77,6 +80,20 @@ class DefaultTableManager(TableManager[JsonTableData]):
raise ValueError("No supported table libraries found.")
+ def get_summary(self, column: str) -> ColumnSummary:
+ del column
+ return ColumnSummary()
+
+ def get_num_rows(self) -> int:
+ if isinstance(self.data, dict):
+ return len(next(iter(self.data.values()), []))
+ return len(self.data)
+
+ def get_num_columns(self) -> int:
+ if isinstance(self.data, dict):
+ return len(self.data)
+ return 1
+
@staticmethod
def is_type(value: Any) -> bool:
return isinstance(value, (list, tuple, dict))
diff --git a/marimo/_plugins/ui/_impl/tables/pandas_table.py b/marimo/_plugins/ui/_impl/tables/pandas_table.py
index 8cb94fd7ce..74c9673075 100644
--- a/marimo/_plugins/ui/_impl/tables/pandas_table.py
+++ b/marimo/_plugins/ui/_impl/tables/pandas_table.py
@@ -3,6 +3,7 @@ from __future__ import annotations
from typing import Any
+from marimo._data.models import ColumnSummary
from marimo._plugins.ui._impl.tables.table_manager import (
FieldType,
FieldTypes,
@@ -21,6 +22,8 @@ class PandasTableManagerFactory(TableManagerFactory):
import pandas as pd
class PandasTableManager(TableManager[pd.DataFrame]):
+ type = "pandas"
+
def to_csv(self) -> bytes:
return self.data.to_csv(
index=False,
@@ -150,4 +153,59 @@ class PandasTableManagerFactory(TableManagerFactory):
return "unknown"
return "unknown"
+ def get_summary(self, column: str) -> ColumnSummary:
+ # If column is not in the dataframe, return an empty summary
+ if column not in self.data.columns:
+ return ColumnSummary()
+ col = self.data[column]
+
+ if col.dtype == "object":
+ return ColumnSummary(
+ total=col.count(),
+ nulls=col.isnull().sum(),
+ unique=col.nunique(),
+ )
+
+ if col.dtype == "bool":
+ return ColumnSummary(
+ total=col.count(),
+ nulls=col.isnull().sum(),
+ true=col.sum(),
+ false=col.count() - col.sum(),
+ )
+
+ if col.dtype == "datetime64[ns]":
+ return ColumnSummary(
+ total=col.count(),
+ nulls=col.isnull().sum(),
+ min=col.min(),
+ max=col.max(),
+ mean=col.mean(),
+ median=col.median(),
+ p5=col.quantile(0.05),
+ p25=col.quantile(0.25),
+ p75=col.quantile(0.75),
+ p95=col.quantile(0.95),
+ )
+
+ return ColumnSummary(
+ total=col.count(),
+ nulls=col.isnull().sum(),
+ min=col.min(),
+ max=col.max(),
+ mean=col.mean(),
+ median=col.median(),
+ std=col.std(),
+ p5=col.quantile(0.05),
+ p25=col.quantile(0.25),
+ p75=col.quantile(0.75),
+ p95=col.quantile(0.95),
+ )
+
+ def get_num_rows(self) -> int:
+ return self.data.shape[0]
+
+ def get_num_columns(self) -> int:
+ return self.data.shape[1]
+
return PandasTableManager
diff --git a/marimo/_plugins/ui/_impl/tables/polars_table.py b/marimo/_plugins/ui/_impl/tables/polars_table.py
index 116edf6273..7b1bf8cdeb 100644
--- a/marimo/_plugins/ui/_impl/tables/polars_table.py
+++ b/marimo/_plugins/ui/_impl/tables/polars_table.py
@@ -1,8 +1,9 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
-from typing import Any
+from typing import Any, cast
+from marimo._data.models import ColumnSummary, NonNestedLiteral
from marimo._plugins.ui._impl.tables.table_manager import (
FieldType,
FieldTypes,
@@ -21,6 +22,8 @@ class PolarsTableManagerFactory(TableManagerFactory):
import polars as pl
class PolarsTableManager(TableManager[pl.DataFrame]):
+ type = "polars"
+
def to_csv(self) -> bytes:
return self.data.write_csv().encode("utf-8")
@@ -54,6 +57,59 @@ class PolarsTableManagerFactory(TableManagerFactory):
raise ValueError("Limit must be a positive integer")
return PolarsTableManager(self.data.head(num))
+ def get_summary(self, column: str) -> ColumnSummary:
+ # If column is not in the dataframe, return an empty summary
+ if column not in self.data.columns:
+ return ColumnSummary()
+ col = self.data[column]
+ total = len(col)
+ if col.is_utf8():
+ return ColumnSummary(
+ total=total,
+ nulls=col.null_count(),
+ unique=col.n_unique(),
+ )
+ if col.is_boolean():
+ return ColumnSummary(
+ total=total,
+ nulls=col.null_count(),
+ true=col.sum(),
+ false=total - col.sum(),
+ )
+ if col.is_temporal():
+ return ColumnSummary(
+ total=total,
+ nulls=col.null_count(),
+ min=cast(NonNestedLiteral, col.min()),
+ max=cast(NonNestedLiteral, col.max()),
+ mean=cast(NonNestedLiteral, col.mean()),
+ median=cast(NonNestedLiteral, col.median()),
+ p5=col.quantile(0.05),
+ p25=col.quantile(0.25),
+ p75=col.quantile(0.75),
+ p95=col.quantile(0.95),
+ )
+ return ColumnSummary(
+ total=total,
+ nulls=col.null_count(),
+ unique=col.n_unique() if col.is_integer() else None,
+ min=cast(NonNestedLiteral, col.min()),
+ max=cast(NonNestedLiteral, col.max()),
+ mean=cast(NonNestedLiteral, col.mean()),
+ median=cast(NonNestedLiteral, col.median()),
+ std=col.std(),
+ p5=col.quantile(0.05),
+ p25=col.quantile(0.25),
+ p75=col.quantile(0.75),
+ p95=col.quantile(0.95),
+ )
+
+ def get_num_rows(self) -> int:
+ return self.data.height
+
+ def get_num_columns(self) -> int:
+ return self.data.width
+
@staticmethod
def _get_field_type(column: pl.Series) -> FieldType:
if column.is_utf8():
diff --git a/marimo/_plugins/ui/_impl/tables/pyarrow_table.py b/marimo/_plugins/ui/_impl/tables/pyarrow_table.py
index a42b93411e..89131cb949 100644
--- a/marimo/_plugins/ui/_impl/tables/pyarrow_table.py
+++ b/marimo/_plugins/ui/_impl/tables/pyarrow_table.py
@@ -4,6 +4,7 @@ from __future__ import annotations
import io
from typing import Any, Union, cast
+from marimo._data.models import ColumnSummary
from marimo._plugins.ui._impl.tables.table_manager import (
FieldType,
FieldTypes,
@@ -20,10 +21,13 @@ class PyArrowTableManagerFactory(TableManagerFactory):
@staticmethod
def create() -> type[TableManager[Any]]:
import pyarrow as pa # type: ignore
+ import pyarrow.compute as pc # type: ignore
class PyArrowTableManager(
TableManager[Union[pa.Table, pa.RecordBatch]]
):
+ type = "pyarrow"
+
def to_csv(self) -> bytes:
import pyarrow.csv as csv # type: ignore
@@ -72,6 +76,63 @@ class PyArrowTableManagerFactory(TableManagerFactory):
raise ValueError("Limit must be a positive integer")
return PyArrowTableManager(self.data.take(list(range(num))))
+ def get_summary(self, column: str) -> ColumnSummary:
+ # If column is not in the dataframe, return an empty summary
+ if column not in self.data.schema.names:
+ return ColumnSummary()
+ idx = self.data.schema.get_field_index(column)
+ col: Any = self.data.column(idx)
+
+ field_type = self._get_field_type(col)
+ if field_type == "unknown":
+ return ColumnSummary()
+ if field_type == "string":
+ return ColumnSummary(
+ total=self.data.num_rows,
+ nulls=col.null_count,
+ unique=pc.count_distinct(col).as_py(), # type: ignore[attr-defined]
+ )
+ if field_type == "boolean":
+ return ColumnSummary(
+ total=self.data.num_rows,
+ nulls=col.null_count,
+ true=pc.sum(col).as_py(), # type: ignore[attr-defined]
+ false=self.data.num_rows
+ - pc.sum(col).as_py() # type: ignore[attr-defined]
+ - col.null_count,
+ )
+ if field_type == "integer":
+ return ColumnSummary(
+ total=self.data.num_rows,
+ nulls=col.null_count,
+ unique=pc.count_distinct(col).as_py(), # type: ignore[attr-defined]
+ min=pc.min(col).as_py(), # type: ignore[attr-defined]
+ max=pc.max(col).as_py(), # type: ignore[attr-defined]
+ mean=pc.mean(col).as_py(), # type: ignore[attr-defined]
+ )
+ if field_type == "number":
+ return ColumnSummary(
+ total=self.data.num_rows,
+ nulls=col.null_count,
+ min=pc.min(col).as_py(), # type: ignore[attr-defined]
+ max=pc.max(col).as_py(), # type: ignore[attr-defined]
+ mean=pc.mean(col).as_py(), # type: ignore[attr-defined]
+ )
+ if field_type == "date":
+ return ColumnSummary(
+ total=self.data.num_rows,
+ nulls=col.null_count,
+ min=pc.min(col).as_py(), # type: ignore[attr-defined]
+ max=pc.max(col).as_py(), # type: ignore[attr-defined]
+ )
+ return ColumnSummary()
+
+ def get_num_rows(self) -> int:
+ return self.data.num_rows
+
+ def get_num_columns(self) -> int:
+ return self.data.num_columns
+
@staticmethod
def _get_field_type(column: pa.Array[Any, Any]) -> FieldType:
if isinstance(column, pa.NullArray):
diff --git a/marimo/_plugins/ui/_impl/tables/table_manager.py b/marimo/_plugins/ui/_impl/tables/table_manager.py
index 7bda07f2d5..f79c8c60eb 100644
--- a/marimo/_plugins/ui/_impl/tables/table_manager.py
+++ b/marimo/_plugins/ui/_impl/tables/table_manager.py
@@ -2,23 +2,22 @@
from __future__ import annotations
import abc
-from typing import Any, Dict, Generic, Literal, TypeVar
+from typing import Any, Dict, Generic, TypeVar
import marimo._output.data.data as mo_data
+from marimo._data.models import ColumnSummary, DataType
from marimo._plugins.core.web_component import JSONType
T = TypeVar("T")
-# This is the frontend type for how the frontend should parse the data
-FieldType = Literal[
- "string", "boolean", "integer", "number", "date", "unknown"
-]
+FieldType = DataType
FieldTypes = Dict[str, FieldType]
class TableManager(abc.ABC, Generic[T]):
DEFAULT_LIMIT = 10_000
+ type: str = ""
def __init__(self, data: T) -> None:
self.data = data
@@ -62,6 +61,21 @@ class TableManager(abc.ABC, Generic[T]):
def is_type(value: Any) -> bool:
raise NotImplementedError
+ @abc.abstractmethod
+ def get_summary(self, column: str) -> ColumnSummary:
+ raise NotImplementedError
+
+ @abc.abstractmethod
+ def get_num_rows(self) -> int:
+ raise NotImplementedError
+
+ @abc.abstractmethod
+ def get_num_columns(self) -> int:
+ raise NotImplementedError
+
+ def supports_altair(self) -> bool:
+ return True
+
class TableManagerFactory(abc.ABC):
@staticmethod
diff --git a/marimo/_plugins/ui/_impl/tables/utils.py b/marimo/_plugins/ui/_impl/tables/utils.py
index 95e2570203..da006806df 100644
--- a/marimo/_plugins/ui/_impl/tables/utils.py
+++ b/marimo/_plugins/ui/_impl/tables/utils.py
@@ -27,10 +27,14 @@ MANAGERS: List[TableManagerFactory] = [
def get_table_manager(data: Any) -> TableManager[Any]:
+ return get_table_manager_or_none(data) or DefaultTableManager(data)
+
+
+def get_table_manager_or_none(data: Any) -> TableManager[Any] | None:
for manager_factory in MANAGERS:
if DependencyManager.has(manager_factory.package_name()):
manager = manager_factory.create()
if manager.is_type(data):
return manager(data)
- return DefaultTableManager(data)
+ return None
diff --git a/marimo/_runtime/requests.py b/marimo/_runtime/requests.py
index 27cb3216de..275b85a926 100644
--- a/marimo/_runtime/requests.py
+++ b/marimo/_runtime/requests.py
@@ -101,6 +101,17 @@ class InstallMissingPackagesRequest:
manager: str
+@dataclass
+class PreviewDatasetColumnRequest:
+ # The source of the dataset
+ source: str
+ # The name of the dataset
+ # This currently corresponds to the variable name
+ table_name: str
+ # The name of the column
+ column_name: str
+
+
ControlRequest = Union[
ExecuteMultipleRequest,
ExecuteStaleRequest,
@@ -112,4 +123,5 @@ ControlRequest = Union[
SetUIElementValueRequest,
StopRequest,
InstallMissingPackagesRequest,
+ PreviewDatasetColumnRequest,
]
diff --git a/marimo/_runtime/runner/hooks_post_execution.py b/marimo/_runtime/runner/hooks_post_execution.py
index 3f1a76e143..47e15510c0 100644
--- a/marimo/_runtime/runner/hooks_post_execution.py
+++ b/marimo/_runtime/runner/hooks_post_execution.py
@@ -1,12 +1,20 @@
# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
from marimo import _loggers
from marimo._ast.cell import CellImpl
+from marimo._data.get_datasets import get_datasets_from_variables
from marimo._messaging.cell_output import CellChannel
from marimo._messaging.errors import (
MarimoExceptionRaisedError,
MarimoInterruptionError,
)
-from marimo._messaging.ops import CellOp, VariableValue, VariableValues
+from marimo._messaging.ops import (
+ CellOp,
+ Datasets,
+ VariableValue,
+ VariableValues,
+)
from marimo._messaging.tracebacks import write_traceback
from marimo._output import formatting
from marimo._plugins.ui._core.ui_element import UIElement
@@ -47,6 +55,23 @@ def _broadcast_variables(
VariableValues(variables=values).broadcast()
+def _broadcast_datasets(
+ cell: CellImpl,
+ runner: cell_runner.Runner,
+ run_result: cell_runner.RunResult,
+) -> None:
+ del run_result
+ tables = get_datasets_from_variables(
+ [
+ (variable, runner.glbls[variable])
+ for variable in cell.defs
+ if variable in runner.glbls
+ ]
+ )
+ if tables:
+ Datasets(tables=tables).broadcast()
+
+
def _store_reference_to_output(
cell: CellImpl,
runner: cell_runner.Runner,
@@ -161,6 +186,7 @@ POST_EXECUTION_HOOKS = [
_set_status_idle,
_store_reference_to_output,
_broadcast_variables,
+ _broadcast_datasets,
_broadcast_outputs,
_reset_matplotlib_context,
]
diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.py
index 8c2ceadf53..a2b5ad3fbb 100644
--- a/marimo/_runtime/runtime.py
+++ b/marimo/_runtime/runtime.py
@@ -23,12 +23,14 @@ from marimo._ast.cell import CellConfig, CellId_t
from marimo._ast.compiler import compile_cell
from marimo._ast.visitor import Name, is_local
from marimo._config.config import MarimoConfig, OnCellChangeType
+from marimo._data.preview_column import get_column_preview
from marimo._messaging.cell_output import CellChannel
from marimo._messaging.errors import Error, MarimoSyntaxError, UnknownError
from marimo._messaging.ops import (
Alert,
CellOp,
CompletedRun,
+ DataColumnPreview,
FunctionCallResult,
HumanReadableStatus,
InstallingPackageAlert,
@@ -86,6 +88,7 @@ from marimo._runtime.requests import (
ExecutionRequest,
FunctionCallRequest,
InstallMissingPackagesRequest,
+ PreviewDatasetColumnRequest,
SetCellConfigRequest,
SetUIElementValueRequest,
SetUserConfigRequest,
@@ -1304,6 +1307,31 @@ class Kernel:
else:
self.graph.set_stale(cells_to_run)
+ async def preview_dataset_column(
+ self, request: PreviewDatasetColumnRequest
+ ) -> None:
+ """Preview a column of a dataset.
+
+ The dataset is loaded, and the column is displayed in the frontend.
+ """
+ try:
+ dataset = self.globals[request.table_name]
+ column_preview = get_column_preview(dataset, request)
+ if column_preview is None:
+ DataColumnPreview(
+ error=f"Column {request.column_name} not found",
+ column_name=request.column_name,
+ table_name=request.table_name,
+ ).broadcast()
+ else:
+ column_preview.broadcast()
+ except Exception as e:
+ DataColumnPreview(
+ error=str(e),
+ column_name=request.column_name,
+ table_name=request.table_name,
+ ).broadcast()
+
async def handle_message(self, request: ControlRequest) -> None:
"""Handle a message from the client.
@@ -1337,6 +1365,8 @@ class Kernel:
elif isinstance(request, InstallMissingPackagesRequest):
await self.install_missing_packages(request)
CompletedRun().broadcast()
+ elif isinstance(request, PreviewDatasetColumnRequest):
+ await self.preview_dataset_column(request)
elif isinstance(request, StopRequest):
return None
else:
diff --git a/marimo/_server/api/endpoints/datasources.py b/marimo/_server/api/endpoints/datasources.py
new file mode 100644
index 0000000000..1d1f678bd8
--- /dev/null
+++ b/marimo/_server/api/endpoints/datasources.py
@@ -0,0 +1,32 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+from starlette.authentication import requires
+
+from marimo import _loggers
+from marimo._runtime.requests import PreviewDatasetColumnRequest
+from marimo._server.api.deps import AppState
+from marimo._server.api.utils import parse_request
+from marimo._server.models.models import BaseResponse, SuccessResponse
+from marimo._server.router import APIRouter
+
+if TYPE_CHECKING:
+ from starlette.requests import Request
+
+LOGGER = _loggers.marimo_logger()
+
+# Router for data source endpoints
+router = APIRouter()
+
+
[email protected]("/preview_column")
+@requires("edit")
+async def preview_column(
+ request: Request,
+) -> BaseResponse:
+ app_state = AppState(request)
+ body = await parse_request(request, PreviewDatasetColumnRequest)
+ app_state.require_current_session().put_control_request(body)
+ return SuccessResponse()
diff --git a/marimo/_server/api/router.py b/marimo/_server/api/router.py
index 37e1575da4..d0ad966aa1 100644
--- a/marimo/_server/api/router.py
+++ b/marimo/_server/api/router.py
@@ -6,6 +6,9 @@ from typing import TYPE_CHECKING, List
from marimo._server.api.endpoints.ai import router as ai_router
from marimo._server.api.endpoints.assets import router as assets_router
from marimo._server.api.endpoints.config import router as config_router
+from marimo._server.api.endpoints.datasources import (
+ router as datasources_router,
+)
from marimo._server.api.endpoints.documentation import (
router as documentation_router,
)
@@ -45,6 +48,9 @@ def build_routes(base_url: str = "") -> List[BaseRoute]:
app_router.include_router(
documentation_router, prefix="/api/documentation", name="documentation"
)
+ app_router.include_router(
+ datasources_router, prefix="/api/datasources", name="datasources"
+ )
app_router.include_router(ai_router, prefix="/api/ai", name="ai")
app_router.include_router(home_router, prefix="/api/home", name="home")
app_router.include_router(login_router, prefix="/auth", name="auth")
diff --git a/marimo/_server/api/status.py b/marimo/_server/api/status.py
index 2347e678eb..4b9c314598 100644
--- a/marimo/_server/api/status.py
+++ b/marimo/_server/api/status.py
@@ -12,6 +12,7 @@ class HTTPStatus(IntEnum):
NOT_FOUND = 404
METHOD_NOT_ALLOWED = 405
UNSUPPORTED_MEDIA_TYPE = 415
+ PRECONDITION_REQUIRED = 428
SERVER_ERROR = 500
diff --git a/marimo/_server/session/session_view.py b/marimo/_server/session/session_view.py
index 16fdae538e..5845a34b3a 100644
--- a/marimo/_server/session/session_view.py
+++ b/marimo/_server/session/session_view.py
@@ -5,9 +5,11 @@ from dataclasses import dataclass
from typing import Any, Optional, Union
from marimo._ast.cell import CellId_t
+from marimo._data.models import DataTable
from marimo._messaging.cell_output import CellChannel, CellOutput
from marimo._messaging.ops import (
CellOp,
+ Datasets,
Interrupted,
MessageOperation,
Variables,
@@ -34,6 +36,8 @@ class SessionView:
def __init__(self) -> None:
# List of operations we care about keeping track of.
self.cell_operations: dict[CellId_t, CellOp] = {}
+ # The most recent datasets operation.
+ self.datasets: Datasets = Datasets(tables=[])
# The most recent Variables operation.
self.variable_operations: Variables = Variables(variables=[])
# Map of variable name to value.
@@ -97,16 +101,25 @@ class SessionView:
elif isinstance(operation, Variables):
self.variable_operations = operation
- # Remove any variable values that are no longer in scope.
- names: set[str] = set(
+ # Set of variable names that are in scope.
+ variable_names: set[str] = set(
[v.name for v in self.variable_operations.variables]
)
+
+ # Remove any variable values that are no longer in scope.
next_values: dict[str, VariableValue] = {}
for name, value in self.variable_values.items():
- if name in names:
+ if name in variable_names:
next_values[name] = value
self.variable_values = next_values
+ # Remove any table values that are no longer in scope.
+ next_tables: dict[str, DataTable] = {}
+ for table in self.datasets.tables:
+ if table.variable_name in variable_names:
+ next_tables[table.name] = table
+ self.datasets = Datasets(tables=list(next_tables.values()))
+
elif isinstance(operation, VariableValues):
for value in operation.variables:
self.variable_values[value.name] = value
@@ -114,6 +127,12 @@ class SessionView:
elif isinstance(operation, Interrupted):
# Resolve stdin
self.add_stdin("")
+ elif isinstance(operation, Datasets):
+ # Merge datasets, dedupe by table name and keep the latest.
+ tables = {t.name: t for t in self.datasets.tables}
+ for table in operation.tables:
+ tables[table.name] = table
+ self.datasets = Datasets(tables=list(tables.values()))
def get_cell_outputs(
self, ids: list[CellId_t]
@@ -142,6 +161,7 @@ class SessionView:
all_ops: list[MessageOperation] = [
self.variable_operations,
VariableValues(variables=list(self.variable_values.values())),
+ self.datasets,
]
all_ops.extend(self.cell_operations.values())
return all_ops
diff --git a/marimo/_smoke_tests/bugs/1510.py b/marimo/_smoke_tests/bugs/1510.py
index e2cedb8c07..b44e97593c 100644
--- a/marimo/_smoke_tests/bugs/1510.py
+++ b/marimo/_smoke_tests/bugs/1510.py
@@ -1,3 +1,4 @@
+# Copyright 2024 Marimo. All rights reserved.
import marimo
__generated_with = "0.6.11"
diff --git a/marimo/_smoke_tests/datasources.py b/marimo/_smoke_tests/datasources.py
new file mode 100644
index 0000000000..0151d647b1
--- /dev/null
+++ b/marimo/_smoke_tests/datasources.py
@@ -0,0 +1,46 @@
+# Copyright 2024 Marimo. All rights reserved.
+
+import marimo
+
+__generated_with = "0.6.11"
+app = marimo.App(width="full")
+
+
+def __():
+ import marimo as mo
+ from vega_datasets import data
+ return data, mo
+
+
+def __(data, mo):
+ options = data.list_datasets()
+ dropdown = mo.ui.dropdown(options)
+ dropdown
+ return dropdown, options
+
+
+def __(data, dropdown, mo):
+ mo.stop(not dropdown.value)
+ df = data.__call__(dropdown.value)
+ return df,
+
+
+def __(df):
+ import polars as pl
+ polars_df = pl.DataFrame(df)
+ return pl, polars_df
+
+
+def __(df):
+ import pyarrow as pa
+ pyarrow_df = pa.Table.from_pandas(df)
+ return pa, pyarrow_df
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/pyproject.toml b/pyproject.toml
index 11757e52f2..be9ecb118a 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -88,7 +88,7 @@ dev = [
"types-Pillow~=10.2.0.20240311",
# polars 0.19.13 requires building maturn from source, but we don't
# have the rust toolchain installed on CI
- "polars==0.19.12",
+ "polars==0.20.30",
"pytest~=7.4.0",
"pytest-codecov~=0.5.1",
"pytest-asyncio~=0.23.4",
@@ -130,7 +130,7 @@ testoptional = [
"types-Pillow~=10.2.0.20240311",
# polars 0.19.13 requires building maturn from source, but we don't
# have the rust toolchain installed on CI
- "polars==0.19.12",
+ "polars==0.20.30",
"anywidget~=0.9.3",
"ipython~=8.12.3",
"openai~=1.12.0",
diff --git a/tests/_data/snapshots/charts.txt b/tests/_data/snapshots/charts.txt
new file mode 100644
index 0000000000..aeca02ec21
--- /dev/null
+++ b/tests/_data/snapshots/charts.txt
@@ -0,0 +1,92 @@
+# boolean
+_chart = (
+ alt.Chart(df)
+ .mark_bar()
+ .encode(
+ x=alt.X("some_column", type="nominal"),
+ y=alt.Y("count()", type="quantitative"),
+ )
+ .properties(width="container")
+)
+_chart
+
+# date
+_chart = (
+ alt.Chart(df)
+ .mark_line(point={"filled": False, "fill": "white"})
+ .encode(
+ x=alt.X("some_column", type="temporal"),
+ y=alt.Y("count()", type="quantitative"),
+ )
+ .properties(width="container")
+)
+_chart
+
+# integer
+_chart = (
+ alt.Chart(df)
+ .mark_bar()
+ .encode(
+ x=alt.X("some_column", type="quantitative", bin=True),
+ y=alt.Y("count()", type="quantitative"),
+ )
+ .properties(width="container")
+)
+_chart
+
+# number
+_chart = (
+ alt.Chart(df)
+ .mark_bar()
+ .encode(
+ x=alt.X("some_column", type="quantitative", bin=True),
+ y=alt.Y("count()", type="quantitative"),
+ )
+ .properties(width="container")
+)
+_chart
+
+# string
+_chart = (
+ alt.Chart(df)
+ .mark_bar()
+ .encode(
+ y=alt.Y("some_column", type="nominal"),
+ x=alt.X("count()", type="quantitative"),
+ )
+ .properties(width="container")
+)
+_chart
+
+# string (limit to 10 items)
+_chart = (
+ alt.Chart(df)
+ .transform_aggregate(count="count()", groupby=["some_column"])
+ .transform_window(
+ rank="rank()",
+ sort=[
+ alt.SortField("count", order="descending"),
+ alt.SortField("some_column", order="ascending"),
+ ],
+ )
+ .transform_filter(alt.datum.rank <= 10)
+ .mark_bar()
+ .encode(
+ y=alt.Y("some_column", type="nominal", sort="-x"),
+ x=alt.X("count", type="quantitative"),
+ )
+ .properties(title="Top 10 some_column", width="container")
+)
+_chart
+
+# unknown
+_chart = (
+ alt.Chart(df)
+ .mark_bar()
+ .encode(
+ x=alt.X("some_column", type="nominal"),
+ y=alt.Y("count()", type="quantitative"),
+ )
+ .properties(width="container")
+)
+_chart
\ No newline at end of file
diff --git a/tests/_data/snapshots/charts_json.txt b/tests/_data/snapshots/charts_json.txt
new file mode 100644
index 0000000000..b4eac8a7c0
--- /dev/null
+++ b/tests/_data/snapshots/charts_json.txt
@@ -0,0 +1,329 @@
+# boolean
+{
+ "$schema": "https://vega.github.io/schema/vega-lite/v5.17.0.json",
+ "config": {
+ "view": {
+ "continuousHeight": 300,
+ "continuousWidth": 300
+ }
+ },
+ "data": {
+ "name": "data-afce120bec1de31b50bc39eae2fedbed"
+ },
+ "datasets": {
+ "data-afce120bec1de31b50bc39eae2fedbed": [
+ {
+ "some_column": 1
+ },
+ {
+ "some_column": 2
+ },
+ {
+ "some_column": 3
+ }
+ ]
+ },
+ "encoding": {
+ "x": {
+ "field": "some_column",
+ "type": "nominal"
+ },
+ "y": {
+ "aggregate": "count",
+ "type": "quantitative"
+ }
+ },
+ "mark": {
+ "type": "bar"
+ },
+ "width": "container"
+}
+
+# date
+{
+ "$schema": "https://vega.github.io/schema/vega-lite/v5.17.0.json",
+ "config": {
+ "view": {
+ "continuousHeight": 300,
+ "continuousWidth": 300
+ }
+ },
+ "data": {
+ "name": "data-afce120bec1de31b50bc39eae2fedbed"
+ },
+ "datasets": {
+ "data-afce120bec1de31b50bc39eae2fedbed": [
+ {
+ "some_column": 1
+ },
+ {
+ "some_column": 2
+ },
+ {
+ "some_column": 3
+ }
+ ]
+ },
+ "encoding": {
+ "x": {
+ "field": "some_column",
+ "type": "temporal"
+ },
+ "y": {
+ "aggregate": "count",
+ "type": "quantitative"
+ }
+ },
+ "mark": {
+ "point": {
+ "fill": "white",
+ "filled": false
+ },
+ "type": "line"
+ },
+ "width": "container"
+}
+
+# integer
+{
+ "$schema": "https://vega.github.io/schema/vega-lite/v5.17.0.json",
+ "config": {
+ "view": {
+ "continuousHeight": 300,
+ "continuousWidth": 300
+ }
+ },
+ "data": {
+ "name": "data-afce120bec1de31b50bc39eae2fedbed"
+ },
+ "datasets": {
+ "data-afce120bec1de31b50bc39eae2fedbed": [
+ {
+ "some_column": 1
+ },
+ {
+ "some_column": 2
+ },
+ {
+ "some_column": 3
+ }
+ ]
+ },
+ "encoding": {
+ "x": {
+ "bin": true,
+ "field": "some_column",
+ "type": "quantitative"
+ },
+ "y": {
+ "aggregate": "count",
+ "type": "quantitative"
+ }
+ },
+ "mark": {
+ "type": "bar"
+ },
+ "width": "container"
+}
+
+# number
+{
+ "$schema": "https://vega.github.io/schema/vega-lite/v5.17.0.json",
+ "config": {
+ "view": {
+ "continuousHeight": 300,
+ "continuousWidth": 300
+ }
+ },
+ "data": {
+ "name": "data-afce120bec1de31b50bc39eae2fedbed"
+ },
+ "datasets": {
+ "data-afce120bec1de31b50bc39eae2fedbed": [
+ {
+ "some_column": 1
+ },
+ {
+ "some_column": 2
+ },
+ {
+ "some_column": 3
+ }
+ ]
+ },
+ "encoding": {
+ "x": {
+ "bin": true,
+ "field": "some_column",
+ "type": "quantitative"
+ },
+ "y": {
+ "aggregate": "count",
+ "type": "quantitative"
+ }
+ },
+ "mark": {
+ "type": "bar"
+ },
+ "width": "container"
+}
+
+# string
+{
+ "$schema": "https://vega.github.io/schema/vega-lite/v5.17.0.json",
+ "config": {
+ "view": {
+ "continuousHeight": 300,
+ "continuousWidth": 300
+ }
+ },
+ "data": {
+ "name": "data-afce120bec1de31b50bc39eae2fedbed"
+ },
+ "datasets": {
+ "data-afce120bec1de31b50bc39eae2fedbed": [
+ {
+ "some_column": 1
+ },
+ {
+ "some_column": 2
+ },
+ {
+ "some_column": 3
+ }
+ ]
+ },
+ "encoding": {
+ "x": {
+ "aggregate": "count",
+ "type": "quantitative"
+ },
+ "y": {
+ "field": "some_column",
+ "type": "nominal"
+ }
+ },
+ "mark": {
+ "type": "bar"
+ },
+ "width": "container"
+}
+
+# string (limit to 10 items)
+{
+ "$schema": "https://vega.github.io/schema/vega-lite/v5.17.0.json",
+ "config": {
+ "view": {
+ "continuousHeight": 300,
+ "continuousWidth": 300
+ }
+ },
+ "data": {
+ "name": "data-afce120bec1de31b50bc39eae2fedbed"
+ },
+ "datasets": {
+ "data-afce120bec1de31b50bc39eae2fedbed": [
+ {
+ "some_column": 1
+ },
+ {
+ "some_column": 2
+ },
+ {
+ "some_column": 3
+ }
+ ]
+ },
+ "encoding": {
+ "x": {
+ "field": "count",
+ "type": "quantitative"
+ },
+ "y": {
+ "field": "some_column",
+ "sort": "-x",
+ "type": "nominal"
+ }
+ },
+ "mark": {
+ "type": "bar"
+ },
+ "title": "Top 10 some_column",
+ "transform": [
+ {
+ "aggregate": [
+ {
+ "as": "count",
+ "op": "count"
+ }
+ ],
+ "groupby": [
+ "some_column"
+ ]
+ },
+ {
+ "sort": [
+ {
+ "field": "count",
+ "order": "descending"
+ },
+ {
+ "field": "some_column",
+ "order": "ascending"
+ }
+ ],
+ "window": [
+ {
+ "as": "rank",
+ "field": "",
+ "op": "rank"
+ }
+ ]
+ },
+ {
+ "filter": "(datum.rank <= 10)"
+ }
+ ],
+ "width": "container"
+}
+
+# unknown
+{
+ "$schema": "https://vega.github.io/schema/vega-lite/v5.17.0.json",
+ "config": {
+ "view": {
+ "continuousHeight": 300,
+ "continuousWidth": 300
+ }
+ },
+ "data": {
+ "name": "data-afce120bec1de31b50bc39eae2fedbed"
+ },
+ "datasets": {
+ "data-afce120bec1de31b50bc39eae2fedbed": [
+ {
+ "some_column": 1
+ },
+ {
+ "some_column": 2
+ },
+ {
+ "some_column": 3
+ }
+ ]
+ },
+ "encoding": {
+ "x": {
+ "field": "some_column",
+ "type": "nominal"
+ },
+ "y": {
+ "aggregate": "count",
+ "type": "quantitative"
+ }
+ },
+ "mark": {
+ "type": "bar"
+ },
+ "width": "container"
+}
\ No newline at end of file
diff --git a/tests/_data/test_charts.py b/tests/_data/test_charts.py
new file mode 100644
index 0000000000..5d7589e8f0
--- /dev/null
+++ b/tests/_data/test_charts.py
@@ -0,0 +1,68 @@
+from __future__ import annotations
+
+import ast
+from typing import List, Tuple
+
+import pytest
+
+from marimo._data.charts import ChartBuilder, get_chart_builder
+from marimo._data.models import DataType
+from marimo._dependencies.dependencies import DependencyManager
+from tests.mocks import snapshotter
+
+TYPES: List[Tuple[DataType, bool]] = [
+ ("boolean", False),
+ ("date", False),
+ ("integer", False),
+ ("number", False),
+ ("string", False),
+ ("string", True),
+ ("unknown", False),
+]
+
+snapshot = snapshotter(__file__)
+
+HAS_DEPS = DependencyManager.has_pandas() and DependencyManager.has_altair()
+
+
+def test_get_chart_builder():
+ for t, should_limit_to_10_items in TYPES:
+ assert isinstance(
+ get_chart_builder(t, should_limit_to_10_items), ChartBuilder
+ )
+
+
+def test_charts_altair_code():
+ outputs: List[str] = []
+
+ for t, should_limit_to_10_items in TYPES:
+ builder = get_chart_builder(t, should_limit_to_10_items)
+ code = builder.altair_code("df", "some_column")
+ # Validate it is valid Python code
+ try:
+ ast.parse(code)
+ except SyntaxError as e:
+ raise SyntaxError(f"Invalid Python code for {t}") from e
+ title = f"{t} (limit to 10 items)" if should_limit_to_10_items else t
+ outputs.append(f"# {title}\n{code}")
+
+ snapshot("charts.txt", "\n\n".join(outputs))
+
+
[email protected](not HAS_DEPS, reason="optional dependencies not installed")
+def test_charts_altair_json():
+ outputs: List[str] = []
+ import altair as alt
+ import pandas as pd
+
+ data = pd.DataFrame({"some_column": [1, 2, 3]})
+
+ for t, should_limit_to_10_items in TYPES:
+ builder = get_chart_builder(t, should_limit_to_10_items)
+ code = builder.altair_json(data, "some_column")
+ # Validate it is valid JSON
+ alt.Chart.from_json(code)
+ title = f"{t} (limit to 10 items)" if should_limit_to_10_items else t
+ outputs.append(f"# {title}\n{code}")
+
+ snapshot("charts_json.txt", "\n\n".join(outputs))
diff --git a/tests/_plugins/ui/_impl/tables/test_pandas_table.py b/tests/_plugins/ui/_impl/tables/test_pandas_table.py
index 7b21636698..3dc301e9d8 100644
--- a/tests/_plugins/ui/_impl/tables/test_pandas_table.py
+++ b/tests/_plugins/ui/_impl/tables/test_pandas_table.py
@@ -1,9 +1,11 @@
from __future__ import annotations
+import datetime
import unittest
import pytest
+from marimo._data.models import ColumnSummary
from marimo._dependencies.dependencies import DependencyManager
from marimo._plugins.ui._impl.tables.pandas_table import (
PandasTableManagerFactory,
@@ -18,7 +20,24 @@ class TestPandasTableManager(unittest.TestCase):
import pandas as pd
self.factory = PandasTableManagerFactory()
- self.data = pd.DataFrame({"A": [1, 2, 3], "B": ["a", "b", "c"]})
+ self.data = pd.DataFrame(
+ {
+ # Integer
+ "A": [1, 2, 3],
+ # String
+ "B": ["a", "b", "c"],
+ # Float
+ "C": [1.0, 2.0, 3.0],
+ # Boolean
+ "D": [True, False, True],
+ # DateTime
+ "E": [
+ datetime.datetime(2021, 1, 1),
+ datetime.datetime(2021, 1, 2),
+ datetime.datetime(2021, 1, 3),
+ ],
+ }
+ )
self.manager = self.factory.create()(self.data)
def test_package_name(self) -> None:
@@ -42,7 +61,7 @@ class TestPandasTableManager(unittest.TestCase):
def test_select_rows_empty(self) -> None:
selected_manager = self.manager.select_rows([])
- assert selected_manager.data.shape == (0, 2)
+ assert selected_manager.data.shape == (0, 5)
def test_get_row_headers(self) -> None:
expected_headers = []
@@ -112,6 +131,9 @@ class TestPandasTableManager(unittest.TestCase):
expected_field_types = {
"A": "integer",
"B": "string",
+ "C": "number",
+ "D": "boolean",
+ "E": "date",
}
assert self.manager.get_field_types() == expected_field_types
@@ -216,3 +238,79 @@ class TestPandasTableManager(unittest.TestCase):
limited_manager = self.manager.limit(limit)
expected_data = self.data.head(limit)
pd.testing.assert_frame_equal(limited_manager.data, expected_data)
+
+ def test_summary_integer(self) -> None:
+ column = "A"
+ summary = self.manager.get_summary(column)
+ assert summary == ColumnSummary(
+ total=3,
+ nulls=0,
+ unique=None,
+ min=1,
+ max=3,
+ mean=2.0,
+ median=2.0,
+ std=1.0,
+ p5=1.1,
+ p25=1.5,
+ p75=2.5,
+ p95=2.9,
+ )
+
+ def test_summary_string(self) -> None:
+ column = "B"
+ summary = self.manager.get_summary(column)
+ assert summary == ColumnSummary(
+ total=3,
+ nulls=0,
+ unique=3,
+ )
+
+ def test_summary_number(self) -> None:
+ column = "C"
+ summary = self.manager.get_summary(column)
+ assert summary == ColumnSummary(
+ total=3,
+ nulls=0,
+ min=1.0,
+ max=3.0,
+ mean=2.0,
+ median=2.0,
+ std=1.0,
+ p5=1.1,
+ p25=1.5,
+ p75=2.5,
+ p95=2.9,
+ )
+
+ def test_summary_boolean(self) -> None:
+ column = "D"
+ summary = self.manager.get_summary(column)
+ assert summary == ColumnSummary(
+ total=3,
+ nulls=0,
+ true=2,
+ false=1,
+ )
+
+ def test_summary_date(self) -> None:
+ column = "E"
+ summary = self.manager.get_summary(column)
+ import pandas as pd
+
+ assert summary == ColumnSummary(
+ total=3,
+ nulls=0,
+ unique=None,
+ min=pd.Timestamp("2021-01-01 00:00:00"),
+ max=pd.Timestamp("2021-01-03 00:00:00"),
+ mean=pd.Timestamp("2021-01-02 00:00:00"),
+ median=pd.Timestamp("2021-01-02 00:00:00"),
+ std=None,
+ true=None,
+ false=None,
+ p5=pd.Timestamp("2021-01-01 02:24:00"),
+ p25=pd.Timestamp("2021-01-01 12:00:00"),
+ p75=pd.Timestamp("2021-01-02 12:00:00"),
+ p95=pd.Timestamp("2021-01-02 21:36:00"),
+ )
diff --git a/tests/_plugins/ui/_impl/tables/test_polars_table.py b/tests/_plugins/ui/_impl/tables/test_polars_table.py
index d78e24354a..eeca5d5997 100644
--- a/tests/_plugins/ui/_impl/tables/test_polars_table.py
+++ b/tests/_plugins/ui/_impl/tables/test_polars_table.py
@@ -1,9 +1,11 @@
from __future__ import annotations
+import datetime
import unittest
import pytest
+from marimo._data.models import ColumnSummary
from marimo._dependencies.dependencies import DependencyManager
from marimo._plugins.ui._impl.tables.polars_table import (
PolarsTableManagerFactory,
@@ -18,7 +20,24 @@ class TestPolarsTableManagerFactory(unittest.TestCase):
import polars as pl
self.factory = PolarsTableManagerFactory()
- self.data = pl.DataFrame({"A": [1, 2, 3], "B": ["a", "b", "c"]})
+ self.data = pl.DataFrame(
+ {
+ # Integer
+ "A": [1, 2, 3],
+ # String
+ "B": ["a", "b", "c"],
+ # Float
+ "C": [1.0, 2.0, 3.0],
+ # Boolean
+ "D": [True, False, True],
+ # DateTime
+ "E": [
+ datetime.datetime(2021, 1, 1),
+ datetime.datetime(2021, 1, 2),
+ datetime.datetime(2021, 1, 3),
+ ],
+ }
+ )
self.manager = self.factory.create()(self.data)
def test_package_name(self) -> None:
@@ -34,7 +53,7 @@ class TestPolarsTableManagerFactory(unittest.TestCase):
indices = [0, 2]
selected_manager = self.manager.select_rows(indices)
expected_data = self.data[indices]
- assert selected_manager.data.frame_equal(expected_data)
+ assert selected_manager.data.equals(expected_data)
def test_select_rows_empty(self) -> None:
selected_manager = self.manager.select_rows([])
@@ -55,6 +74,9 @@ class TestPolarsTableManagerFactory(unittest.TestCase):
expected_field_types = {
"A": "integer",
"B": "string",
+ "C": "number",
+ "D": "boolean",
+ "E": "date",
}
assert self.manager.get_field_types() == expected_field_types
@@ -68,19 +90,19 @@ class TestPolarsTableManagerFactory(unittest.TestCase):
"F": [None, None, None],
"G": [set([1, 2]), set([3, 4]), set([5, 6])],
"H": [
- pl.Date(2021, 1, 1),
- pl.Date(2021, 1, 2),
- pl.Date(2021, 1, 3),
+ datetime.datetime(2021, 1, 1),
+ datetime.datetime(2021, 1, 2),
+ datetime.datetime(2021, 1, 3),
],
"I": [
- pl.Time(0, 0, 0),
- pl.Time(1, 0, 0),
- pl.Time(2, 0, 0),
+ "1 days",
+ "2 days",
+ "3 days",
],
"J": [
- pl.Duration("ms"),
- pl.Duration("ms"),
- pl.Duration("ms"),
+ "0-5",
+ "5-10",
+ "10-15",
],
}
)
@@ -90,11 +112,11 @@ class TestPolarsTableManagerFactory(unittest.TestCase):
"C": "number",
"D": "boolean",
"E": "unknown",
- "F": "number",
+ "F": "unknown",
"G": "unknown",
- "H": "unknown",
- "I": "unknown",
- "J": "unknown",
+ "H": "date",
+ "I": "string",
+ "J": "string",
}
assert (
self.factory.create()(complex_data).get_field_types()
@@ -104,4 +126,70 @@ class TestPolarsTableManagerFactory(unittest.TestCase):
def test_limit(self) -> None:
limited_manager = self.manager.limit(1)
expected_data = self.data.head(1)
- assert limited_manager.data.frame_equal(expected_data)
+ assert limited_manager.data.equals(expected_data)
+
+ def test_summary_integer(self) -> None:
+ column = "A"
+ summary = self.manager.get_summary(column)
+ assert summary == ColumnSummary(
+ total=3,
+ nulls=0,
+ unique=3,
+ min=1,
+ max=3,
+ mean=2.0,
+ median=2.0,
+ std=1.0,
+ p5=1.0,
+ p25=2.0,
+ p75=3.0,
+ p95=3.0,
+ )
+
+ def test_summary_string(self) -> None:
+ column = "B"
+ summary = self.manager.get_summary(column)
+ assert summary == ColumnSummary(
+ total=3,
+ nulls=0,
+ unique=3,
+ )
+
+ def test_summary_number(self) -> None:
+ column = "C"
+ summary = self.manager.get_summary(column)
+ assert summary == ColumnSummary(
+ total=3,
+ nulls=0,
+ min=1.0,
+ max=3.0,
+ mean=2.0,
+ median=2.0,
+ std=1.0,
+ p5=1.0,
+ p25=2.0,
+ p75=3.0,
+ p95=3.0,
+ )
+
+ def test_summary_boolean(self) -> None:
+ column = "D"
+ summary = self.manager.get_summary(column)
+ assert summary == ColumnSummary(
+ total=3,
+ nulls=0,
+ true=2,
+ false=1,
+ )
+
+ def test_summary_date(self) -> None:
+ column = "E"
+ summary = self.manager.get_summary(column)
+ assert summary == ColumnSummary(
+ total=3,
+ nulls=0,
+ min=datetime.datetime(2021, 1, 1, 0, 0),
+ max=datetime.datetime(2021, 1, 3, 0, 0),
+ mean=datetime.datetime(2021, 1, 2, 0, 0),
+ median=datetime.datetime(2021, 1, 2, 0, 0),
+ )
diff --git a/tests/_plugins/ui/_impl/tables/test_pyarrow.py b/tests/_plugins/ui/_impl/tables/test_pyarrow.py
index 55709206d5..838f38589a 100644
--- a/tests/_plugins/ui/_impl/tables/test_pyarrow.py
+++ b/tests/_plugins/ui/_impl/tables/test_pyarrow.py
@@ -1,9 +1,11 @@
from __future__ import annotations
+import datetime
import unittest
import pytest
+from marimo._data.models import ColumnSummary
from marimo._dependencies.dependencies import DependencyManager
from marimo._plugins.ui._impl.tables.pyarrow_table import (
PyArrowTableManagerFactory,
@@ -18,7 +20,24 @@ class TestPyArrowTableManagerFactory(unittest.TestCase):
import pyarrow as pa
self.factory = PyArrowTableManagerFactory()
- self.data = pa.table({"A": [1, 2, 3], "B": ["a", "b", "c"]}) # type: ignore
+ self.data = pa.table(
+ { # type: ignore
+ # Integer
+ "A": [1, 2, 3],
+ # String
+ "B": ["a", "b", "c"],
+ # Float
+ "C": [1.0, 2.0, 3.0],
+ # Boolean
+ "D": [True, False, True],
+ # DateTime
+ "E": [
+ datetime.datetime(2021, 1, 1),
+ datetime.datetime(2021, 1, 2),
+ datetime.datetime(2021, 1, 3),
+ ],
+ }
+ )
self.manager = self.factory.create()(self.data)
def test_package_name(self) -> None:
@@ -54,6 +73,9 @@ class TestPyArrowTableManagerFactory(unittest.TestCase):
expected_field_types = {
"A": "integer",
"B": "string",
+ "C": "number",
+ "D": "boolean",
+ "E": "date",
}
assert self.manager.get_field_types() == expected_field_types
@@ -82,3 +104,55 @@ class TestPyArrowTableManagerFactory(unittest.TestCase):
limited_manager = self.manager.limit(1)
expected_data = self.data.take([0])
assert limited_manager.data == expected_data
+
+ def test_summary_integer(self) -> None:
+ column = "A"
+ summary = self.manager.get_summary(column)
+ assert summary == ColumnSummary(
+ total=3,
+ nulls=0,
+ unique=3,
+ min=1,
+ max=3,
+ mean=2.0,
+ )
+
+ def test_summary_string(self) -> None:
+ column = "B"
+ summary = self.manager.get_summary(column)
+ assert summary == ColumnSummary(
+ total=3,
+ nulls=0,
+ unique=3,
+ )
+
+ def test_summary_number(self) -> None:
+ column = "C"
+ summary = self.manager.get_summary(column)
+ assert summary == ColumnSummary(
+ total=3,
+ nulls=0,
+ min=1.0,
+ max=3.0,
+ mean=2.0,
+ )
+
+ def test_summary_boolean(self) -> None:
+ column = "D"
+ summary = self.manager.get_summary(column)
+ assert summary == ColumnSummary(
+ total=3,
+ nulls=0,
+ true=2,
+ false=1,
+ )
+
+ def test_summary_date(self) -> None:
+ column = "E"
+ summary = self.manager.get_summary(column)
+ assert summary == ColumnSummary(
+ total=3,
+ nulls=0,
+ min=datetime.datetime(2021, 1, 1, 0, 0),
+ max=datetime.datetime(2021, 1, 3, 0, 0),
+ )
diff --git a/tests/_server/conftest.py b/tests/_server/conftest.py
index ffe1e8fe63..ec0fd5f70d 100644
--- a/tests/_server/conftest.py
+++ b/tests/_server/conftest.py
@@ -1,7 +1,9 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
+import os
import sys
+from tempfile import TemporaryDirectory
from typing import Generator, Iterator
import pytest
@@ -9,6 +11,7 @@ import uvicorn
from starlette.testclient import TestClient
from marimo._config.manager import UserConfigManager
+from marimo._config.utils import CONFIG_FILENAME
from marimo._server.main import create_starlette_app
from marimo._server.sessions import SessionManager
from marimo._server.utils import initialize_asyncio
@@ -30,10 +33,20 @@ def client_with_lifespans() -> Generator[TestClient, None, None]:
@pytest.fixture
-def client() -> Iterator[TestClient]:
+def user_config_manager() -> UserConfigManager:
+ class TestUserConfigManager(UserConfigManager):
+ def _get_config_path(self) -> str:
+ tmp = TemporaryDirectory()
+ return os.path.join(tmp.name, CONFIG_FILENAME)
+
+ return TestUserConfigManager()
+
+
+def client(user_config_manager: UserConfigManager) -> Iterator[TestClient]:
main = sys.modules["__main__"]
app.state.session_manager = get_mock_session_manager()
- app.state.config_manager = UserConfigManager()
+ app.state.config_manager = user_config_manager
client = TestClient(app)
# Mock out the server
diff --git a/tests/_server/session/test_session_view.py b/tests/_server/session/test_session_view.py
index d9ec5ff1e4..4ca3454438 100644
--- a/tests/_server/session/test_session_view.py
+++ b/tests/_server/session/test_session_view.py
@@ -5,9 +5,11 @@ from typing import Any
from unittest.mock import patch
from marimo._ast.cell import CellId_t, CellStatusType
+from marimo._data.models import DataTable, DataTableColumn
from marimo._messaging.cell_output import CellChannel, CellOutput
from marimo._messaging.ops import (
CellOp,
+ Datasets,
VariableDeclaration,
Variables,
VariableValue,
@@ -232,6 +234,94 @@ def test_add_variables() -> None:
assert session_view.variable_values["var2"].datatype == "str"
+def test_add_datasets() -> None:
+ session_view = SessionView()
+
+ session_view.add_raw_operation(
+ serialize(
+ Datasets(
+ tables=[
+ DataTable(
+ source="Local",
+ name="table1",
+ columns=[DataTableColumn(name="col1", type="boolean")],
+ num_rows=1,
+ num_columns=1,
+ variable_name="df1",
+ ),
+ DataTable(
+ source="Local",
+ name="table2",
+ columns=[DataTableColumn(name="col2", type="integer")],
+ num_rows=2,
+ num_columns=2,
+ variable_name="df2",
+ ),
+ ]
+ )
+ )
+ )
+
+ assert session_view.datasets.tables[0].name == "table1"
+ assert session_view.datasets.tables[1].name == "table2"
+ assert session_view.datasets.tables[0].variable_name == "df1"
+ assert session_view.datasets.tables[1].variable_name == "df2"
+
+ # Can add a new table and overwrite an existing table
+
+ session_view.add_raw_operation(
+ serialize(
+ Datasets(
+ tables=[
+ DataTable(
+ source="Local",
+ name="table2",
+ columns=[
+ DataTableColumn(name="new_col", type="boolean")
+ ],
+ num_rows=20,
+ num_columns=20,
+ variable_name="df2",
+ ),
+ DataTable(
+ source="Local",
+ name="table3",
+ columns=[],
+ num_rows=3,
+ num_columns=3,
+ variable_name="df3",
+ ),
+ ]
+ )
+ )
+ )
+
+ assert session_view.datasets.tables[0].name == "table1"
+ # Updated
+ assert session_view.datasets.tables[1].name == "table2"
+ assert session_view.datasets.tables[1].columns[0].name == "new_col"
+ assert session_view.datasets.tables[1].num_rows == 20
+ # Added
+ assert session_view.datasets.tables[2].name == "table3"
+ assert session_view.datasets.tables[2].variable_name == "df3"
+
+ # Can filter out tables from new variables
+ session_view.add_raw_operation(
+ serialize(
+ Variables(
+ variables=[
+ VariableDeclaration(
+ name="df2", declared_by=[cell_id], used_by=[]
+ ),
+ ]
+ )
+ )
+ )
+
+ assert len(session_view.datasets.tables) == 1
+ assert session_view.datasets.tables[0].name == "table2"
+
+
def test_add_cell_op() -> None:
session_view = SessionView()
session_view.add_raw_operation(