A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
feat: sql datasources (#1808)
Myles Scolnick208d66992e53
diff --git a/frontend/src/components/editor/chrome/panels/datasources-panel.tsx b/frontend/src/components/editor/chrome/panels/datasources-panel.tsxindex 687488b829..92cd7ea82f 100644--- a/frontend/src/components/editor/chrome/panels/datasources-panel.tsx+++ b/frontend/src/components/editor/chrome/panels/datasources-panel.tsx@@ -42,6 +42,8 @@ import type {} from "@/core/kernel/messages";import { variablesAtom } from "@/core/variables/state";import { sortBy } from "lodash-es";+import { logNever } from "@/utils/assertNever";+import { Objects } from "@/utils/objects";const sortedTablesAtom = atom((get) => {const tables = get(datasetTablesAtom);@@ -90,7 +92,9 @@ export const DataSourcesPanel: React.FC = () => {}const handleAddColumn = (chartCode: string) => {- maybeAddAltairImport(autoInstantiate, createNewCell, lastFocusedCellId);+ if (chartCode.includes("alt")) {+ maybeAddAltairImport(autoInstantiate, createNewCell, lastFocusedCellId);+ }createNewCell({code: chartCode,before: false,@@ -100,8 +104,20 @@ export const DataSourcesPanel: React.FC = () => {const handleAddTable = (table: DataTable) => {maybeAddMarimoImport(autoInstantiate, createNewCell, lastFocusedCellId);+ let code = "";+ switch (table.source_type) {+ case "local":+ code = `mo.data.table(${table.name})`;+ break;+ case "duckdb":+ code = `_df = mo.sql(f"SELECT * FROM ${table.name} LIMIT 100")`;+ break;+ default:+ logNever(table.source_type);+ break;+ }createNewCell({- code: `mo.ui.table(${table.name})`,+ code: code,before: false,cellId: lastFocusedCellId ?? "__end__",});@@ -151,6 +167,7 @@ export const DataSourcesPanel: React.FC = () => {source: table.source,tableName: table.name,columnName: column.name,+ sourceType: table.source_type,});}}}@@ -198,53 +215,96 @@ const TableList: React.FC<{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>- );- }),+ let groupedBySource = Object.entries(+ Objects.groupBy(+ tables,+ (table) => table.source,+ (table) => table,+ ),+ );+ // Sort by `memory` first, then by alphabet+ groupedBySource = sortBy(groupedBySource, ([source]) => {+ if (source === "memory") {+ return 0;+ }+ return 1;+ });++ const renderTable = (table: DataTable): React.ReactNode => {+ 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+ table={table}+ column={column}+ onAddColumnChart={onAddColumnChart}+ preview={columnPreviews.get(+ `${table.name}:${column.name}`,+ )}+ />+ </ErrorBoundary>+ </div>+ )}+ </React.Fragment>);- }+ }),+ );+ }- return items;- })}+ return items;+ };++ const renderTableWithHeaders = () => {+ if (groupedBySource.length === 0) {+ return null;+ }+ if (groupedBySource.length === 1) {+ return groupedBySource[0][1].flatMap(renderTable);+ }++ return groupedBySource.flatMap(([source, tables], idx) => {+ return [+ <div+ className={cn(+ "font-bold px-2 py-1 text-muted-foreground bg-[var(--slate-2)] border-t text-sm",+ idx > 0 && "border-t",+ )}+ key={source}+ >+ {source === "memory" ? "In-Memory" : source}+ </div>,+ ...tables.flatMap(renderTable),+ ];+ });+ };++ return (+ <CommandList className="flex flex-col overflow-auto">+ {renderTableWithHeaders()}</CommandList>);};@@ -257,11 +317,17 @@ const DatasetTableItem: React.FC<{isExpanded: boolean;}> = ({ table, onExpand, onAddTable, isExpanded }) => {const renderRowsByColumns = () => {- if (table.num_rows == null && table.num_columns == null) {- return null;+ const label: string[] = [];+ if (table.num_rows != null) {+ label.push(`${table.num_rows} rows`);+ }+ if (table.num_columns != null) {+ label.push(`${table.num_columns} columns`);}- const label = [`${table.num_rows} rows`, `${table.num_columns} columns`];+ if (label.length === 0) {+ return null;+ }return (<div className="flex flex-row gap-2 items-center pl-6 group-hover:hidden">@@ -349,11 +415,29 @@ const LazyVegaLite = React.lazy(() =>);const DatasetColumnPreview: React.FC<{+ table: DataTable;+ column: DataTableColumn;onAddColumnChart: (code: string) => void;preview: DataColumnPreview | undefined;-}> = ({ preview, onAddColumnChart }) => {+}> = ({ table, column, preview, onAddColumnChart }) => {const { theme } = useTheme();+ if (table.source_type === "duckdb") {+ return (+ <Button+ variant="text"+ className="z-10"+ size="xs"+ onClick={Events.stopPropagation(() => {+ const code = `_df = mo.sql(f"SELECT '${column.name}' FROM ${table.name} LIMIT 100")`;+ onAddColumnChart(code);+ })}+ >+ <PlusSquareIcon className="h-4 w-4 mr-2" /> Add cell+ </Button>+ );+ }+if (!preview) {return <span className="text-xs text-muted-foreground">Loading...</span>;}diff --git a/frontend/src/core/datasets/state.ts b/frontend/src/core/datasets/state.tsindex c8fbc07cda..4fc9fae056 100644--- a/frontend/src/core/datasets/state.ts+++ b/frontend/src/core/datasets/state.ts@@ -3,8 +3,11 @@import { createReducerAndAtoms } from "@/utils/createReducer";import type { DatasetsState } from "./types";import { atom, useAtomValue } from "jotai";-import { VariableName } from "../variables/types";-import { DataColumnPreview } from "../kernel/messages";+import type { VariableName } from "../variables/types";+import type {+ DataColumnPreview,+ OperationMessageData,+} from "../kernel/messages";import { previewDatasetColumn } from "../network/requests";function initialState(): DatasetsState {@@ -22,7 +25,7 @@ const {valueAtom: datasetsAtom,useActions,} = createReducerAndAtoms(initialState, {- addDatasets: (state, datasets: Pick<DatasetsState, "tables">) => {+ addDatasets: (state, datasets: OperationMessageData<"datasets">) => {// Quietly in the background make requests to get the previews for// opened columns, in the new tablesfor (const table of datasets.tables) {@@ -34,13 +37,22 @@ const {tableName: table.name,columnName: column.name,source: table.source,+ sourceType: table.source_type,});}}}+ // Prev tables+ let prevTables = state.tables;+ if (datasets.clear_channel) {+ prevTables = prevTables.filter((table) => {+ return table.source !== datasets.clear_channel;+ });+ }+// Put new tables at the top- const newTables = [...datasets.tables, ...state.tables];+ const newTables = [...datasets.tables, ...prevTables];// Dedupe by name and sourceconst seen = new Set();@@ -52,9 +64,11 @@ const {seen.add(key);return true;});+const sortedTables = dedupedTables.sort((a, b) => {return a.name.localeCompare(b.name);});+return {...state,tables: sortedTables,@@ -64,9 +78,11 @@ const {const names = new Set(variableNames);// Filter out tables that come from variables that are not in the listconst tables = state.tables.filter((table) => {- return (- table.variable_name && names.has(table.variable_name as VariableName)- );+ // If there's no variable name, it's not a variable and we should keep it+ if (!table.variable_name) {+ return true;+ }+ return names.has(table.variable_name as VariableName);});return { ...state, tables };},diff --git a/marimo/_ast/cell.py b/marimo/_ast/cell.pyindex 77faf9574e..711ea5a31a 100644--- a/marimo/_ast/cell.py+++ b/marimo/_ast/cell.py@@ -1,17 +1,18 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations+import astimport dataclassesimport inspectfrom typing import TYPE_CHECKING, Any, Literal, Mapping, Optionalfrom marimo._ast.visitor import ImportData, Name, VariableData+from marimo._data.sql_visitor import SQLVisitorfrom marimo._utils.deep_merge import deep_mergeCellId_t = strif TYPE_CHECKING:- import astfrom collections.abc import Awaitable, Iterablefrom types import CodeType@@ -123,6 +124,17 @@ class CellImpl:def status(self) -> Optional[CellStatusType]:return self._status.state+ @property+ def sqls(self) -> list[str]:+ """Return a list of SQL statements for this cell."""+ try:+ visitor = SQLVisitor()+ visitor.visit(ast.parse(self.code))+ sqls = visitor.get_sqls()+ return sqls+ except Exception:+ return []+@propertydef stale(self) -> bool:return self._stale.statediff --git a/marimo/_ast/visitor.py b/marimo/_ast/visitor.pyindex 896b508460..59494faf51 100644--- a/marimo/_ast/visitor.py+++ b/marimo/_ast/visitor.py@@ -7,6 +7,7 @@ from dataclasses import dataclass, fieldfrom typing import Literal, Optionalfrom uuid import uuid4+from marimo._data.sql_visitor import normalize_sql_f_stringfrom marimo._dependencies.dependencies import DependencyManagerfrom marimo._utils.variables import is_local@@ -366,9 +367,11 @@ class ScopedVisitor(ast.NodeVisitor):# Add all tables in the query to the ref scopetry:- tables = duckdb.get_table_names(sql)- for table in tables:- self._add_ref(table, deleted=False)+ statements = duckdb.extract_statements(sql)+ for statement in statements:+ tables = duckdb.get_table_names(statement.query)+ for table in tables:+ self._add_ref(table, deleted=False)except (duckdb.ParserException, duckdb.InvalidInputException):# The user's sql query may have a syntax errorpass@@ -653,18 +656,3 @@ class ScopedVisitor(ast.NodeVisitor):kind="variable", required_refs=self.ref_stack[-1]),)---def normalize_sql_f_string(node: ast.JoinedStr) -> str:- def print_part(part: ast.expr) -> str:- if isinstance(part, ast.FormattedValue):- return print_part(part.value)- elif isinstance(part, ast.JoinedStr):- return normalize_sql_f_string(part)- elif isinstance(part, ast.Constant):- return str(part.s)- else:- # Just add '_' as a placeholder for {...} expressions- return "'_'"-- return "".join(print_part(part) for part in node.values)diff --git a/marimo/_data/get_datasets.py b/marimo/_data/get_datasets.pyindex e0d32915a3..69e4d77075 100644--- a/marimo/_data/get_datasets.py+++ b/marimo/_data/get_datasets.py@@ -1,10 +1,10 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations-from typing import List, Optional+from typing import List, Optional, castfrom marimo import _loggers-from marimo._data.models import DataTable, DataTableColumn+from marimo._data.models import DataTable, DataTableColumn, DataTypefrom marimo._plugins.ui._impl.tables.utils import get_table_manager_or_noneLOGGER = _loggers.marimo_logger()@@ -41,7 +41,8 @@ def _get_data_table(value: object, variable_name: str) -> Optional[DataTable]:variable_name=variable_name,num_rows=table.get_num_rows(force=False),num_columns=table.get_num_columns(),- source=f"Local ({table.type})",+ source_type="local",+ source="memory",columns=columns,)except Exception as e:@@ -51,3 +52,106 @@ def _get_data_table(value: object, variable_name: str) -> Optional[DataTable]:exc_info=e,)return None+++def has_updates_to_datasource(query: str) -> bool:+ import duckdb # type: ignore[import-not-found,import-untyped,unused-ignore] # noqa: E501++ try:+ statements = duckdb.extract_statements(query)+ except Exception:+ # May not be valid SQL+ return False++ return any(+ statement.type == duckdb.StatementType.ATTACH+ or statement.type == duckdb.StatementType.DETACH+ or statement.type == duckdb.StatementType.ALTER+ # This may catch some false positives for other CREATE statements+ or statement.type == duckdb.StatementType.CREATE+ for statement in statements+ )+++def get_datasets_from_duckdb() -> List[DataTable]:+ try:+ return _get_datasets_from_duckdb_internal()+ except Exception as e:+ LOGGER.error(e)+ return []+++def _get_datasets_from_duckdb_internal() -> List[DataTable]:+ import duckdb # type: ignore[import-not-found,import-untyped,unused-ignore] # noqa: E501++ # Columns+ # 0:"database"+ # 1:"schema"+ # 2:"name"+ # 3:"column_names"+ # 4:"column_types"+ # 5:"temporary"+ databases = duckdb.execute("SHOW ALL TABLES").fetchall()+ if not len(databases):+ # No tables+ return []++ tables: list[DataTable] = []++ for (+ database,+ schema,+ name,+ column_names,+ column_types,+ *_rest,+ ) in databases:+ assert len(column_names) == len(column_types)+ assert isinstance(column_names, list)+ assert isinstance(column_types, list)++ columns = [+ DataTableColumn(+ name=column_name,+ type=_db_type_to_data_type(column_type),+ external_type=column_type,+ )+ for column_name, column_type in zip(+ cast(list[str], column_names),+ cast(list[str], column_types),+ )+ ]++ tables.append(+ DataTable(+ source_type="duckdb",+ source=database,+ name=f"{database}.{schema}.{name}",+ num_rows=None,+ num_columns=len(columns),+ variable_name=None,+ columns=columns,+ )+ )++ return tables+++def _db_type_to_data_type(db_type: str) -> DataType:+ if db_type == "INTEGER":+ return "integer"+ if db_type == "FLOAT":+ return "number"+ if db_type == "BOOLEAN":+ return "boolean"+ if db_type == "VARCHAR":+ return "string"+ if db_type == "DATE":+ return "date"+ if db_type == "DATETIME":+ return "date"+ if db_type == "TIMESTAMP":+ return "date"+ if db_type == "TIME":+ return "date"+ return "unknown"diff --git a/marimo/_data/models.py b/marimo/_data/models.pyindex 6c9ff8aea9..995f6719a9 100644--- a/marimo/_data/models.py+++ b/marimo/_data/models.py@@ -27,6 +27,9 @@ class DataTableColumn:external_type: ExternalDataType+DataTableSource = Literal["local", "duckdb"]++@dataclassclass DataTable:"""@@ -42,6 +45,7 @@ class DataTable:columns (List[DataTableColumn]): The list of columns in the data table."""+ source_type: DataTableSourcesource: strname: strnum_rows: Optional[int]diff --git a/marimo/_data/sql_visitor.py b/marimo/_data/sql_visitor.pynew file mode 100644index 0000000000..dc2c79fdef--- /dev/null+++ b/marimo/_data/sql_visitor.py@@ -0,0 +1,65 @@+# Copyright 2024 Marimo. All rights reserved.+from __future__ import annotations++import ast+from typing import Optional+++class SQLVisitor(ast.NodeVisitor):+ """+ Find any SQL queries in the AST.+ This should be inside a function called `.execute` or `.sql`.+ """++ def __init__(self) -> None:+ super().__init__()+ self._sqls: list[str] = []++ def visit_Call(self, node: ast.Call) -> None:+ # Check if the call is a method call and the method is named+ # either 'execute' or 'sql'+ if isinstance(node.func, ast.Attribute) and node.func.attr in (+ "execute",+ "sql",+ ):+ # Check if there are arguments and the first argument is a+ # string or f-string+ if node.args:+ first_arg = node.args[0]+ sql: Optional[str] = None+ if isinstance(first_arg, ast.Constant):+ sql = first_arg.s+ elif isinstance(first_arg, ast.JoinedStr):+ sql = normalize_sql_f_string(first_arg)++ if sql is not None:+ # Append the SQL query to the list+ self._sqls.append(sql)+ # Continue walking through the AST+ self.generic_visit(node)++ def get_sqls(self) -> list[str]:+ return self._sqls+++def normalize_sql_f_string(node: ast.JoinedStr) -> str:+ """+ Normalize a f-string to a string by joining the parts.++ We add placeholder for {...} expressions in the f-string.+ This is so we can create a valid SQL query to be passed to+ other utilities.+ """++ def print_part(part: ast.expr) -> str:+ if isinstance(part, ast.FormattedValue):+ return print_part(part.value)+ elif isinstance(part, ast.JoinedStr):+ return normalize_sql_f_string(part)+ elif isinstance(part, ast.Constant):+ return str(part.s)+ else:+ # Just add '_' as a placeholder for {...} expressions+ return "'_'"++ return "".join(print_part(part) for part in node.values)diff --git a/marimo/_messaging/ops.py b/marimo/_messaging/ops.pyindex 89b7edcac5..0b3fcaa341 100644--- a/marimo/_messaging/ops.py+++ b/marimo/_messaging/ops.py@@ -27,7 +27,7 @@ from typing import (from marimo import _loggers as loggersfrom marimo._ast.app import _AppConfigfrom marimo._ast.cell import CellConfig, CellId_t, CellStatusType-from marimo._data.models import ColumnSummary, DataTable+from marimo._data.models import ColumnSummary, DataTable, DataTableSourcefrom marimo._dependencies.dependencies import DependencyManagerfrom marimo._messaging.cell_output import CellChannel, CellOutputfrom marimo._messaging.completion_option import CompletionOption@@ -501,6 +501,7 @@ class Datasets(Op):name: ClassVar[str] = "datasets"tables: List[DataTable]+ clear_channel: Optional[DataTableSource] = None@dataclassdiff --git a/marimo/_runtime/requests.py b/marimo/_runtime/requests.pyindex b32c8177ed..aaed3157aa 100644--- a/marimo/_runtime/requests.py+++ b/marimo/_runtime/requests.py@@ -7,6 +7,7 @@ from uuid import uuid4from marimo._ast.cell import CellId_tfrom marimo._config.config import MarimoConfig+from marimo._data.models import DataTableSourceUIElementId = strCompletionRequestId = str@@ -143,6 +144,8 @@ class InstallMissingPackagesRequest:@dataclassclass PreviewDatasetColumnRequest:+ # The source type of the dataset+ source_type: DataTableSource# The source of the datasetsource: str# The name of the datasetdiff --git a/marimo/_runtime/runner/hooks_post_execution.py b/marimo/_runtime/runner/hooks_post_execution.pyindex 20c861bd0e..c1ce242389 100644--- a/marimo/_runtime/runner/hooks_post_execution.py+++ b/marimo/_runtime/runner/hooks_post_execution.py@@ -5,7 +5,12 @@ from typing import Callablefrom marimo import _loggersfrom marimo._ast.cell import CellImpl-from marimo._data.get_datasets import get_datasets_from_variables+from marimo._data.get_datasets import (+ get_datasets_from_duckdb,+ get_datasets_from_variables,+ has_updates_to_datasource,+)+from marimo._dependencies.dependencies import DependencyManagerfrom marimo._messaging.cell_output import CellChannelfrom marimo._messaging.errors import (MarimoExceptionRaisedError,@@ -79,6 +84,35 @@ def _broadcast_datasets(Datasets(tables=tables).broadcast()+def _broadcast_duckdb_tables(+ cell: CellImpl,+ runner: cell_runner.Runner,+ run_result: cell_runner.RunResult,+) -> None:+ del run_result+ del runner+ if not DependencyManager.has_duckdb():+ return++ try:+ sqls = cell.sqls+ if not sqls:+ return+ modifies_datasources = any(+ has_updates_to_datasource(sql) for sql in sqls+ )+ if not modifies_datasources:+ return++ tables = get_datasets_from_duckdb()+ if not tables:+ return++ Datasets(tables=tables, clear_channel="duckdb").broadcast()+ except Exception:+ return++def _store_reference_to_output(cell: CellImpl,runner: cell_runner.Runner,@@ -200,6 +234,7 @@ POST_EXECUTION_HOOKS: list[PostExecutionHookType] = [_store_reference_to_output,_broadcast_variables,_broadcast_datasets,+ _broadcast_duckdb_tables,_broadcast_outputs,_reset_matplotlib_context,]diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.pyindex 699f664ea8..1531d75da2 100644--- a/marimo/_runtime/runtime.py+++ b/marimo/_runtime/runtime.py@@ -15,7 +15,14 @@ import threadingimport timeimport tracebackfrom multiprocessing import connection-from typing import TYPE_CHECKING, Any, Callable, Iterator, Optional, cast+from typing import (+ TYPE_CHECKING,+ Any,+ Callable,+ Iterator,+ Optional,+ cast,+)from uuid import uuid4from marimo import _loggers@@ -119,6 +126,7 @@ from marimo._runtime.utils.set_ui_element_request_manager import (from marimo._runtime.validate_graph import check_for_errorsfrom marimo._runtime.win32_interrupt_handler import Win32InterruptHandlerfrom marimo._server.types import QueueType+from marimo._utils.assert_never import assert_neverfrom marimo._utils.platform import is_pyodidefrom marimo._utils.signals import restore_signalsfrom marimo._utils.typed_connection import TypedConnection@@ -1487,23 +1495,35 @@ class Kernel: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:++ if request.source_type == "duckdb":DataColumnPreview(- error=str(e),column_name=request.column_name,table_name=request.table_name,).broadcast()+ return++ if request.source_type == "local":+ 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()+ return++ assert_never(request.source_type)async def handle_message(self, request: ControlRequest) -> None:"""Handle a message from the client.diff --git a/marimo/_server/session/session_view.py b/marimo/_server/session/session_view.pyindex 66ea04d5a2..bd39ab5bb3 100644--- a/marimo/_server/session/session_view.py+++ b/marimo/_server/session/session_view.py@@ -139,7 +139,16 @@ class SessionView: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}+ # If clear_channel is set, clear those tables+ prev_tables = self.datasets.tables+ if operation.clear_channel is not None:+ prev_tables = [+ t+ for t in prev_tables+ if t.source_type != operation.clear_channel+ ]++ tables = {t.name: t for t in prev_tables}for table in operation.tables:tables[table.name] = tableself.datasets = Datasets(tables=list(tables.values()))diff --git a/openapi/api.yaml b/openapi/api.yamlindex c3c3d24ded..318c8c3ba6 100644--- a/openapi/api.yaml+++ b/openapi/api.yaml@@ -360,10 +360,16 @@ components:type: integersource:type: string+ source_type:+ enum:+ - local+ - duckdb+ type: stringvariable_name:nullable: truetype: stringrequired:+ - source_type- source- name- columns@@ -392,6 +398,12 @@ components:type: stringDatasets:properties:+ clear_channel:+ enum:+ - local+ - duckdb+ nullable: true+ type: stringname:enum:- datasets@@ -1289,9 +1301,15 @@ components:type: stringsource:type: string+ sourceType:+ enum:+ - local+ - duckdb+ type: stringtableName:type: stringrequired:+ - sourceType- source- tableName- columnNamediff --git a/openapi/src/api.ts b/openapi/src/api.tsindex 3c828540ef..5112691a4c 100644--- a/openapi/src/api.ts+++ b/openapi/src/api.ts@@ -895,6 +895,8 @@ export interface components {num_columns?: number | null;num_rows?: number | null;source: string;+ /** @enum {string} */+ source_type: "local" | "duckdb";variable_name?: string | null;};DataTableColumn: {@@ -905,6 +907,8 @@ export interface components {/** @enum {string} */DataType: "string" | "boolean" | "integer" | "number" | "date" | "unknown";Datasets: {+ /** @enum {string|null} */+ clear_channel?: "local" | "duckdb" | null;/** @enum {string} */name: "datasets";tables: components["schemas"]["DataTable"][];@@ -1281,6 +1285,8 @@ export interface components {PreviewDatasetColumnRequest: {columnName: string;source: string;+ /** @enum {string} */+ sourceType: "local" | "duckdb";tableName: string;};QueryParamsAppend: {diff --git a/tests/_ast/test_codegen.py b/tests/_ast/test_codegen.pyindex 1a2269077a..c970a03789 100644--- a/tests/_ast/test_codegen.py+++ b/tests/_ast/test_codegen.py@@ -6,6 +6,7 @@ import osimport tempfilefrom functools import partialfrom inspect import cleandoc+from textwrap import dedentfrom typing import Optionalimport codegen_data.test_main as mod@@ -561,3 +562,15 @@ def test_get_header_comments_invalid() -> None:comments = codegen.get_header_comments(filepath)assert comments is None, "Comments found when there should be none"+++def test_sqls() -> None:+ code = dedent(+ """+ db.sql("SELECT * FROM foo")+ db.sql("ATTACH TABLE bar")+ """+ )+ cell = compile_cell(code)+ sqls = cell.sqls+ assert sqls == ["SELECT * FROM foo", "ATTACH TABLE bar"]diff --git a/tests/_data/test_get_datasets.py b/tests/_data/test_get_datasets.pynew file mode 100644index 0000000000..ffe78ba963--- /dev/null+++ b/tests/_data/test_get_datasets.py@@ -0,0 +1,16 @@+from __future__ import annotations++import pytest++from marimo._data.get_datasets import has_updates_to_datasource+from marimo._dependencies.dependencies import DependencyManager++HAS_DEPS = DependencyManager.has_duckdb()++[email protected](not HAS_DEPS, reason="optional dependencies not installed")+def test_has_updates_to_datasource() -> None:+ assert has_updates_to_datasource("hello") is False+ assert has_updates_to_datasource("ATTACH 'marimo.db'") is True+ assert has_updates_to_datasource("DETACH marimo") is True+ assert has_updates_to_datasource("CREATE TABLE cars (name TEXT)") is Truediff --git a/tests/_data/test_preview_column.py b/tests/_data/test_preview_column.pyindex b66d77c509..daacd6d31d 100644--- a/tests/_data/test_preview_column.py+++ b/tests/_data/test_preview_column.py@@ -41,7 +41,10 @@ def test_get_column_preview() -> None:result = get_column_preview(df,request=PreviewDatasetColumnRequest(- source="source", table_name="table", column_name="A"+ source="source",+ table_name="table",+ column_name="A",+ source_type="local",),)@@ -57,7 +60,10 @@ def test_get_column_preview() -> None:result = get_column_preview(df,request=PreviewDatasetColumnRequest(- source="source", table_name="table", column_name="date_col"+ source="source",+ table_name="table",+ column_name="date_col",+ source_type="local",),)diff --git a/tests/_data/test_sql_visitor.py b/tests/_data/test_sql_visitor.pynew file mode 100644index 0000000000..3c578efd5a--- /dev/null+++ b/tests/_data/test_sql_visitor.py@@ -0,0 +1,77 @@+from __future__ import annotations++import ast+from textwrap import dedent++from marimo._data.sql_visitor import SQLVisitor+++def test_execute_with_string_literal():+ source_code = "db.execute('SELECT * FROM users')"+ tree = ast.parse(source_code)+ visitor = SQLVisitor()+ visitor.visit(tree)+ assert visitor.get_sqls() == ["SELECT * FROM users"]+++def test_sql_with_string_literal():+ source_code = "db.sql('UPDATE users SET name = \\'Alice\\' WHERE id = 1')"+ tree = ast.parse(source_code)+ visitor = SQLVisitor()+ visitor.visit(tree)+ assert visitor.get_sqls() == [+ "UPDATE users SET name = 'Alice' WHERE id = 1"+ ]+++def test_execute_with_f_string():+ source_code = 'db.execute(f"SELECT * FROM users WHERE name = {name}")'+ tree = ast.parse(source_code)+ visitor = SQLVisitor()+ visitor.visit(tree)+ assert visitor.get_sqls() == ["SELECT * FROM users WHERE name = '_'"]+++def test_no_sql_calls():+ source_code = "print('Hello, world!')"+ tree = ast.parse(source_code)+ visitor = SQLVisitor()+ visitor.visit(tree)+ assert visitor.get_sqls() == []+++def test_sql_with_multiple_arguments():+ source_code = (+ "db.sql('SELECT * FROM users', 'This should not be captured')"+ )+ tree = ast.parse(source_code)+ visitor = SQLVisitor()+ visitor.visit(tree)+ assert visitor.get_sqls() == ["SELECT * FROM users"]+++def test_multiple_sql_calls():+ source_code = dedent("""+ a = db.sql('SELECT * FROM users', 'This should not be captured')+ b = db.sql('ALTER TABLE users ADD COLUMN name TEXT')+ c = db.sql('UPDATE users SET name = \\'Alice\\' WHERE id = 1')+ """)+ tree = ast.parse(source_code)+ visitor = SQLVisitor()+ visitor.visit(tree)+ assert visitor.get_sqls() == [+ "SELECT * FROM users",+ "ALTER TABLE users ADD COLUMN name TEXT",+ "UPDATE users SET name = 'Alice' WHERE id = 1",+ ]+++def test_sql_with_variable():+ source_code = dedent("""+ var = f"SELECT * FROM users WHERE name = {name}"+ db.sql(var)+ """)+ tree = ast.parse(source_code)+ visitor = SQLVisitor()+ visitor.visit(tree)+ assert visitor.get_sqls() == []diff --git a/tests/_server/session/test_session_view.py b/tests/_server/session/test_session_view.pyindex 327ec456ef..62c5350e35 100644--- a/tests/_server/session/test_session_view.py+++ b/tests/_server/session/test_session_view.py@@ -241,7 +241,8 @@ def test_add_datasets() -> None:Datasets(tables=[DataTable(- source="Local",+ source_type="local",+ source="df",name="table1",columns=[DataTableColumn(@@ -255,7 +256,8 @@ def test_add_datasets() -> None:variable_name="df1",),DataTable(- source="Local",+ source_type="local",+ source="df",name="table2",columns=[DataTableColumn(@@ -285,7 +287,8 @@ def test_add_datasets() -> None:Datasets(tables=[DataTable(- source="Local",+ source_type="local",+ source="df",name="table2",columns=[DataTableColumn(@@ -299,7 +302,8 @@ def test_add_datasets() -> None:variable_name="df2",),DataTable(- source="Local",+ source_type="local",+ source="df",name="table3",columns=[],num_rows=3,@@ -337,6 +341,67 @@ def test_add_datasets() -> None:assert session_view.datasets.tables[0].name == "table2"+def test_add_datasets_clear_channel() -> None:+ session_view = SessionView()+ session_view.add_raw_operation(+ serialize(+ Datasets(+ tables=[+ DataTable(+ source_type="duckdb",+ source="db",+ name="db.table1",+ columns=[],+ num_rows=1,+ num_columns=1,+ variable_name=None,+ ),+ DataTable(+ source_type="local",+ source="memory",+ name="df1",+ columns=[],+ num_rows=1,+ num_columns=1,+ variable_name="df1",+ ),+ ],+ clear_channel="duckdb",+ )+ )+ )++ assert len(session_view.datasets.tables) == 2+ names = [t.name for t in session_view.datasets.tables]+ assert "db.table1" in names+ assert "df1" in names++ session_view.add_raw_operation(+ serialize(+ Datasets(+ tables=[+ DataTable(+ source_type="local",+ source="db",+ name="db.table2",+ columns=[],+ num_rows=1,+ num_columns=1,+ variable_name=None,+ )+ ],+ clear_channel="duckdb",+ )+ )+ )++ assert len(session_view.datasets.tables) == 2+ names = [t.name for t in session_view.datasets.tables]+ assert "db.table1" not in names+ assert "df1" in names+ assert "db.table2" in names++def test_add_cell_op() -> None:session_view = SessionView()session_view.add_raw_operation(