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.

improvement: parse sql CREATE table names (#2031)

Myles Scolnick7b9a76bcc578
diff --git a/marimo/_ast/cell.py b/marimo/_ast/cell.py
index 95c99346c6..26093233c8 100644
--- a/marimo/_ast/cell.py
+++ b/marimo/_ast/cell.py
@@ -6,8 +6,8 @@ import dataclasses
import inspect
from typing import TYPE_CHECKING, Any, Literal, Mapping, Optional
-from marimo._ast.visitor import ImportData, Name, VariableData
-from marimo._data.sql_visitor import SQLVisitor
+from marimo._ast.sql_visitor import SQLVisitor
+from marimo._ast.visitor import ImportData, Language, Name, VariableData
from marimo._utils.deep_merge import deep_merge
CellId_t = str
@@ -136,6 +136,8 @@ class CellImpl:
deleted_refs: set[Name]
body: Optional[CodeType]
last_expr: Optional[CodeType]
+ # whether this cell is Python or SQL
+ language: Language
# unique id
cell_id: CellId_t
diff --git a/marimo/_ast/compiler.py b/marimo/_ast/compiler.py
index 488837fadc..4a6c564fe1 100644
--- a/marimo/_ast/compiler.py
+++ b/marimo/_ast/compiler.py
@@ -119,6 +119,7 @@ def compile_cell(
refs=set(),
variable_data={},
deleted_refs=set(),
+ language="python",
body=None,
last_expr=None,
cell_id=cell_id,
@@ -199,6 +200,7 @@ def compile_cell(
imported_defs=imported_defs,
),
deleted_refs=v.deleted_refs,
+ language=v.language,
body=body,
last_expr=last_expr,
cell_id=cell_id,
diff --git a/marimo/_ast/sql_visitor.py b/marimo/_ast/sql_visitor.py
new file mode 100644
index 0000000000..a06f8435ff
--- /dev/null
+++ b/marimo/_ast/sql_visitor.py
@@ -0,0 +1,262 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+import ast
+import re
+from dataclasses import dataclass
+from typing import Any, Optional
+
+from marimo._dependencies.dependencies import DependencyManager
+
+
+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 "'_'"
+
+ result = "".join(print_part(part) for part in node.values)
+ # remove any double '' created by the f-string
+ return result.replace("''", "'")
+
+
+class TokenExtractor:
+ def __init__(self, sql_statement: str, tokens: list[Any]) -> None:
+ self.sql_statement = sql_statement
+ self.tokens = tokens
+
+ def token_str(self, i: int) -> str:
+ sql_statement, tokens = self.sql_statement, self.tokens
+ token = tokens[i]
+ start = token[0]
+
+ # If it starts with a quote, find the matching end quote
+ if sql_statement[start] == '"':
+ end = sql_statement.find('"', start + 1) + 1
+ elif sql_statement[start] == "'":
+ end = sql_statement.find("'", start + 1) + 1
+ else:
+ # For non-quoted tokens, find until space or comment
+ maybe_end = re.search(r"[\s\-/]", sql_statement[start:])
+ end = (
+ start + maybe_end.start() if maybe_end else len(sql_statement)
+ )
+ if i + 1 < len(tokens):
+ # For tokens squashed together e.g. '(select' or 'x);;'
+ # in (select * from x);;
+ end = min(end, tokens[i + 1][0])
+
+ return sql_statement[start:end]
+
+ def is_keyword(self, i: int, match: str) -> bool:
+ import duckdb
+
+ if self.tokens[i][1] != duckdb.token_type.keyword:
+ return False
+ return self.token_str(i).lower() == match
+
+ def strip_quotes(self, token: str) -> str:
+ if token.startswith('"') and token.endswith('"'):
+ return token.strip('"')
+ elif token.startswith("'") and token.endswith("'"):
+ return token.strip("'")
+ return token
+
+
+@dataclass
+class SQLDefs:
+ tables: list[str]
+ views: list[str]
+ schemas: list[str]
+
+
+def find_sql_defs(sql_statement: str) -> SQLDefs:
+ """
+ Find the tables, views, and schemas created/attached in a SQL statement.
+
+ This function uses the DuckDB tokenizer to find the tables created
+ and schemas attached in a SQL statement. It returns a list of the table
+ names created and schemas attached in the statement.
+
+ Args:
+ sql_statement: The SQL statement to parse.
+
+ Returns:
+ SQLDefs
+ """
+ if not DependencyManager.duckdb.has():
+ return SQLDefs([], [], [])
+
+ import duckdb
+
+ tokens = duckdb.tokenize(sql_statement)
+ token_extractor = TokenExtractor(
+ sql_statement=sql_statement, tokens=tokens
+ )
+ created_tables: list[str] = []
+ created_views: list[str] = []
+ created_schemas: list[str] = []
+ i = 0
+
+ # See
+ #
+ # https://duckdb.org/docs/sql/statements/create_table#syntax
+ # https://duckdb.org/docs/sql/statements/create_view#syntax
+ #
+ # for the CREATE syntax, and
+ #
+ # https://duckdb.org/docs/sql/statements/attach#attach-syntax
+ #
+ # for ATTACH syntax
+ while i < len(tokens):
+ if token_extractor.is_keyword(i, "create"):
+ # CREATE TABLE and CREATE VIEW have the same syntax
+ i += 1
+ if i < len(tokens) and token_extractor.is_keyword(i, "or"):
+ i += 2 # Skip 'OR REPLACE'
+ if i < len(tokens) and (
+ token_extractor.is_keyword(i, "temporary")
+ or token_extractor.is_keyword(i, "temp")
+ ):
+ i += 1 # Skip 'TEMPORARY' or 'TEMP'
+ if i < len(tokens) and (
+ (is_table := token_extractor.is_keyword(i, "table"))
+ or token_extractor.is_keyword(i, "view")
+ ):
+ i += 1
+ if i < len(tokens) and token_extractor.is_keyword(i, "if"):
+ i += 3 # Skip 'IF NOT EXISTS'
+ if i < len(tokens):
+ table_name = token_extractor.strip_quotes(
+ token_extractor.token_str(i)
+ )
+ if is_table:
+ created_tables.append(table_name)
+ else:
+ created_views.append(table_name)
+ elif token_extractor.is_keyword(i, "attach"):
+ schema_name = None
+ i += 1
+ if i < len(tokens) and token_extractor.is_keyword(i, "database"):
+ i += 1 # Skip 'DATABASE'
+ if i < len(tokens) and token_extractor.is_keyword(i, "if"):
+ i += 3 # Skip "IF NOT EXISTS"
+ if i < len(tokens):
+ schema_name = token_extractor.strip_quotes(
+ token_extractor.token_str(i)
+ )
+ if "." in schema_name:
+ # strip the extension from the name
+ schema_name = schema_name.split(".")[0]
+ if i + 1 < len(tokens) and token_extractor.is_keyword(i + 1, "as"):
+ # Skip over database-path 'AS'
+ i += 2
+ # AS clause gets precedence in creating database
+ if i < len(tokens):
+ schema_name = token_extractor.strip_quotes(
+ token_extractor.token_str(i)
+ )
+ if schema_name is not None:
+ created_schemas.append(schema_name)
+
+ i += 1
+
+ return SQLDefs(
+ tables=created_tables, views=created_views, schemas=created_schemas
+ )
+
+
+# TODO(akshayka): there are other kinds of refs to find; this should be
+# find_sql_refs
+def find_from_targets(
+ sql_statement: str,
+) -> list[str]:
+ """
+ Find tokens following the FROM keyword, which may be tables or schemas.
+
+ Args:
+ sql_statement: The SQL statement to parse.
+
+ Returns:
+ A list of names following the FROM keyword.
+ """
+ if not DependencyManager.duckdb.has():
+ return []
+
+ import duckdb
+
+ tokens = duckdb.tokenize(sql_statement)
+ token_extractor = TokenExtractor(
+ sql_statement=sql_statement, tokens=tokens
+ )
+ refs: list[str] = []
+ i = 0
+
+ while i < len(tokens):
+ if token_extractor.is_keyword(i, "from"):
+ i += 1
+ if i < len(tokens):
+ # TODO(akshayka): this is maybe a name, but it's totally
+ # possible that it's not a name -- could be a function (such as
+ # range), or the start of a subquery, ...
+ name = token_extractor.strip_quotes(
+ token_extractor.token_str(i)
+ )
+ if "." in name:
+ # get the schema
+ name = name.split(".")[0]
+ refs.append(name)
+ i += 1
+
+ return refs
diff --git a/marimo/_ast/visitor.py b/marimo/_ast/visitor.py
index fb68326a84..b66d308499 100644
--- a/marimo/_ast/visitor.py
+++ b/marimo/_ast/visitor.py
@@ -2,6 +2,7 @@
from __future__ import annotations
import ast
+import itertools
import sys
from collections import defaultdict
from dataclasses import dataclass, field
@@ -9,7 +10,11 @@ from typing import Literal, Optional
from uuid import uuid4
from marimo import _loggers
-from marimo._data.sql_visitor import normalize_sql_f_string
+from marimo._ast.sql_visitor import (
+ find_from_targets,
+ find_sql_defs,
+ normalize_sql_f_string,
+)
from marimo._dependencies.dependencies import DependencyManager
from marimo._utils.variables import is_local
@@ -17,6 +22,8 @@ LOGGER = _loggers.marimo_logger()
Name = str
+Language = Literal["python", "sql"]
+
@dataclass
class ImportData:
@@ -37,7 +44,10 @@ class ImportData:
@dataclass
class VariableData:
- kind: Literal["function", "class", "import", "variable"] = "variable"
+ # "table", "view", and "schema" are SQL variables, not Python.
+ kind: Literal[
+ "function", "class", "import", "variable", "table", "view", "schema"
+ ] = "variable"
# If kind == function or class, it may be dependent on externally defined
# variables.
@@ -54,6 +64,18 @@ class VariableData:
# For kind == import
import_data: Optional[ImportData] = None
+ @property
+ def language(self) -> Language:
+ return (
+ "sql"
+ if (
+ self.kind == "table"
+ or self.kind == "schema"
+ or self.kind == "view"
+ )
+ else "python"
+ )
+
@dataclass
class Block:
@@ -109,6 +131,7 @@ class ScopedVisitor(ast.NodeVisitor):
else mangle_prefix
)
self.is_local = (lambda _: False) if ignore_local else is_local
+ self.language: Language = "python"
@property
def defs(self) -> set[Name]:
@@ -356,6 +379,10 @@ class ScopedVisitor(ast.NodeVisitor):
# If the call name is sql and has one argument, and the argument is
# a string literal, then it's likely to be a SQL query.
# It must also come from the `mo` module.
+ #
+ # This check is brittle, since we can't detect at parse time whether
+ # 'mo'/'marimo' actually refer to the marimo library, but it gets
+ # the job done.
if (
isinstance(node.func, ast.Attribute)
and isinstance(node.func.value, ast.Name)
@@ -363,6 +390,7 @@ class ScopedVisitor(ast.NodeVisitor):
and node.func.attr == "sql"
and len(node.args) == 1
):
+ self.language = "sql"
first_arg = node.args[0]
sql: Optional[str] = None
if isinstance(first_arg, ast.Constant):
@@ -381,6 +409,13 @@ class ScopedVisitor(ast.NodeVisitor):
# Add all tables in the query to the ref scope
try:
+ # TODO: This function raises a CatalogError on CREATE VIEW
+ # statements that reference tables that are not yet
+ # defined, such
+ #
+ # as CREATE OR REPLACE VIEW my_view as SELECT * from my_df
+ #
+ # This breaks dependency parsing.
statements = duckdb.extract_statements(sql)
except duckdb.ProgrammingError:
# The user's sql query may have a syntax error,
@@ -397,21 +432,44 @@ class ScopedVisitor(ast.NodeVisitor):
return
for statement in statements:
+ # Parse the refs and defs of each statement
try:
tables = duckdb.get_table_names(statement.query)
+ # TODO(akshayka): more comprehensive parsing
+ # of the statement -- schemas can show up in
+ # joins, queries, ...
+ from_targets = find_from_targets(statement.query)
except duckdb.ProgrammingError:
self.generic_visit(node)
- return
+ continue
except BaseException as e:
LOGGER.warning("Unexpected duckdb error %s", e)
self.generic_visit(node)
- return
+ continue
- for table in tables:
- # Table may be a URL or something else that
+ for name in itertools.chain(tables, from_targets):
+ # Name (table, db) may be a URL or something else that
# isn't a Python variable
- if table.isidentifier():
- self._add_ref(table, deleted=False)
+ if name.isidentifier():
+ self._add_ref(name, deleted=False)
+
+ # Add all tables/dbs created in the query to the defs
+ try:
+ sql_defs = find_sql_defs(sql)
+ except duckdb.ProgrammingError:
+ self.generic_visit(node)
+ continue
+ except BaseException as e:
+ LOGGER.warning("Unexpected duckdb error %s", e)
+ self.generic_visit(node)
+ continue
+
+ for _table in sql_defs.tables:
+ self._define(_table, VariableData("table"))
+ for _view in sql_defs.views:
+ self._define(_view, VariableData("view"))
+ for _schema in sql_defs.schemas:
+ self._define(_schema, VariableData("schema"))
# Visit arguments, keyword args, etc.
self.generic_visit(node)
diff --git a/marimo/_cli/convert/ipynb.py b/marimo/_cli/convert/ipynb.py
index 0a8256c756..bc9702d5cf 100644
--- a/marimo/_cli/convert/ipynb.py
+++ b/marimo/_cli/convert/ipynb.py
@@ -38,7 +38,7 @@ def fixup_multiple_definitions(sources: list[str]) -> list[str]:
name_transformations = {}
for name in multiply_defined_names:
- if not graph.get_referring_cells(name):
+ if not graph.get_referring_cells(name, language="python"):
name_transformations[name] = (
"_" + name if not name.startswith("_") else name
)
diff --git a/marimo/_cli/sandbox.py b/marimo/_cli/sandbox.py
index 4246f9a12b..8baf1aa085 100644
--- a/marimo/_cli/sandbox.py
+++ b/marimo/_cli/sandbox.py
@@ -1,3 +1,4 @@
+# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
import os
diff --git a/marimo/_data/sql_visitor.py b/marimo/_data/sql_visitor.py
deleted file mode 100644
index b85794a272..0000000000
--- a/marimo/_data/sql_visitor.py
+++ /dev/null
@@ -1,67 +0,0 @@
-# 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 "'_'"
-
- result = "".join(print_part(part) for part in node.values)
- # remove any double '' created by the f-string
- return result.replace("''", "'")
diff --git a/marimo/_runtime/dataflow.py b/marimo/_runtime/dataflow.py
index 3529b7cbfa..5263cac2e8 100644
--- a/marimo/_runtime/dataflow.py
+++ b/marimo/_runtime/dataflow.py
@@ -3,7 +3,7 @@ from __future__ import annotations
import threading
from dataclasses import dataclass, field
-from typing import TYPE_CHECKING, Any, Callable, List, Tuple
+from typing import TYPE_CHECKING, Any, Callable, List, Literal, Tuple
from marimo import _loggers
from marimo._ast.cell import (
@@ -69,6 +69,7 @@ class DirectedGraph:
cell_id in self.cells and code_key(code) == self.cells[cell_id].key
)
+ # TODO: language type?
def get_defining_cells(self, name: Name) -> set[CellId_t]:
"""Get all cells that define name.
@@ -76,9 +77,24 @@ class DirectedGraph:
"""
return self.definitions[name]
- def get_referring_cells(self, name: Name) -> set[CellId_t]:
- """Get all cells that have a ref to `name`."""
- return set([cid for cid in self.cells if name in self.cells[cid].refs])
+ def get_referring_cells(
+ self, name: Name, language: Literal["python", "sql"]
+ ) -> set[CellId_t]:
+ """Get all cells that have a ref to `name`.
+
+ The variable can be either a Python variable or a SQL variable (table).
+ """
+ children = set()
+ for cid, cell in self.cells.items():
+ if name not in cell.refs:
+ continue
+ elif language == "sql" and cell.language == "python":
+ # SQL variables don't leak to Python cells, but
+ # Python variables do leak to SQL cells
+ continue
+ children.add(cid)
+
+ return children
def get_path(self, source: CellId_t, dst: CellId_t) -> list[Edge]:
"""Get a path from `source` to `dst`, if any."""
@@ -123,18 +139,20 @@ class DirectedGraph:
self.children[cell_id] = children
self.siblings[cell_id] = siblings
self.parents[cell_id] = parents
- for name in cell.defs:
+ for name, variable_data in cell.variable_data.items():
self.definitions.setdefault(name, set()).add(cell_id)
for sibling in self.definitions[name]:
+ # TODO(akshayka): Distinguish between Python/SQL?
if sibling != cell_id:
siblings.add(sibling)
self.siblings[sibling].add(cell_id)
# a cell can refer to its own defs, but that doesn't add an
# edge to the dependency graph
- referring_cells = self.get_referring_cells(name) - set(
- (cell_id,)
- )
+ referring_cells = self.get_referring_cells(
+ name,
+ language=variable_data[-1].language,
+ ) - set((cell_id,))
# we will add an edge (cell_id, v) for each v in
# referring_cells; if there is a path from v to cell_id, then
# the new edge will form a cycle
@@ -148,7 +166,7 @@ class DirectedGraph:
self.parents[child].add(cell_id)
for name in cell.refs:
- other_ids = (
+ other_ids_defining_name = (
self.definitions[name]
if name in self.definitions
else set()
@@ -156,7 +174,13 @@ class DirectedGraph:
# if other is empty, this means that the user is going to
# get a NameError once the cell is run, unless the symbol
# is say a builtin
- for other_id in other_ids:
+ for other_id in other_ids_defining_name:
+ language = (
+ self.cells[other_id].variable_data[name][-1].language
+ )
+ if language == "sql" and cell.language == "python":
+ # SQL table/db def -> Python ref is not an edge
+ continue
parents.add(other_id)
# we are adding an edge (other_id, cell_id). If there
# is a path from cell_id to other_id, then the new
@@ -381,8 +405,9 @@ def transitive_closure(
cell_ids: set[CellId_t],
children: bool = True,
inclusive: bool = True,
- relatives: Callable[[DirectedGraph, CellId_t, bool], set[CellId_t]]
- | None = None,
+ relatives: (
+ Callable[[DirectedGraph, CellId_t, bool], set[CellId_t]] | None
+ ) = None,
predicate: Callable[[CellImpl], bool] | None = None,
) -> set[CellId_t]:
"""Return a set of the passed-in cells and their descendants or ancestors
@@ -482,7 +507,10 @@ def import_block_relatives(
# definitions used to find the descendants of this cell.
unimported_defs = cell.defs - cell.import_workspace.imported_defs
children_ids = set().union(
- *[graph.get_referring_cells(name) for name in unimported_defs]
+ *[
+ graph.get_referring_cells(name, language="python")
+ for name in unimported_defs
+ ]
)
# If children haven't been executed, then still use imported defs;
@@ -490,7 +518,7 @@ def import_block_relatives(
# exception or user interrupt, so that a module is imported but the
# cell's children haven't run.
for name in cell.import_workspace.imported_defs:
- for child_id in graph.get_referring_cells(name):
+ for child_id in graph.get_referring_cells(name, language="python"):
if graph.cells[child_id].run_result_status in (
"interrupted",
"cancelled",
diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.py
index 51ddc4afc7..f5fa30e22f 100644
--- a/marimo/_runtime/runtime.py
+++ b/marimo/_runtime/runtime.py
@@ -22,9 +22,10 @@ from uuid import uuid4
from marimo import _loggers
from marimo._ast.cell import CellConfig, CellId_t, CellImpl
from marimo._ast.compiler import compile_cell
-from marimo._ast.visitor import ImportData, Name
+from marimo._ast.visitor import ImportData, Name, VariableData
from marimo._config.config import ExecutionType, MarimoConfig, OnCellChangeType
from marimo._data.preview_column import get_column_preview
+from marimo._dependencies.dependencies import DependencyManager
from marimo._messaging.cell_output import CellChannel
from marimo._messaging.errors import (
Error,
@@ -131,7 +132,7 @@ from marimo._utils.typed_connection import TypedConnection
from marimo._utils.variables import is_local
if TYPE_CHECKING:
- from collections.abc import Iterable, Sequence
+ from collections.abc import Sequence
from types import ModuleType
from marimo._plugins.ui._core.ui_element import UIElement
@@ -692,22 +693,42 @@ class Kernel:
children = self.graph.children.get(cell_id, set())
return previous_children - children, error
- def _delete_names(
- self, names: Iterable[Name], exclude_defs: set[Name]
+ def _delete_variables(
+ self,
+ variables: dict[Name, list[VariableData]],
+ exclude_defs: set[Name],
) -> None:
"""Delete `names` from kernel, except for `exclude_defs`"""
- for name in names:
+ for name, variable_data in variables.items():
+ # Take the last definition of the variable
+ variable = variable_data[-1]
if name in exclude_defs:
continue
- if name in self.globals:
- del self.globals[name]
+ if variable.kind == "table" and DependencyManager.duckdb.has():
+ import duckdb
- if (
- "__annotations__" in self.globals
- and name in self.globals["__annotations__"]
- ):
- del self.globals["__annotations__"][name]
+ # We only drop in-memory tables: we don't want to drop tables
+ # on databases!
+ duckdb.execute(f"DROP TABLE IF EXISTS memory.main.{name}")
+ elif variable.kind == "view" and DependencyManager.duckdb.has():
+ import duckdb
+
+ # We only drop in-memory views for the same reason.
+ duckdb.execute(f"DROP VIEW IF EXISTS memory.main.{name}")
+ elif variable.kind == "schema" and DependencyManager.duckdb.has():
+ import duckdb
+
+ duckdb.execute(f"DETACH DATABASE IF EXISTS {name}")
+ else:
+ if name in self.globals:
+ del self.globals[name]
+
+ if (
+ "__annotations__" in self.globals
+ and name in self.globals["__annotations__"]
+ ):
+ del self.globals["__annotations__"][name]
def _invalidate_cell_state(
self,
@@ -726,9 +747,9 @@ class Kernel:
missing_modules_before_deletion = (
self.module_registry.missing_modules()
)
- defs_to_delete = cell.defs
- self._delete_names(
- defs_to_delete, exclude_defs if exclude_defs is not None else set()
+ self._delete_variables(
+ cell.variable_data,
+ exclude_defs if exclude_defs is not None else set(),
)
missing_modules_after_deletion = (
@@ -990,7 +1011,11 @@ class Kernel:
VariableDeclaration(
name=variable,
declared_by=list(declared_by),
- used_by=list(self.graph.get_referring_cells(variable)),
+ used_by=list(
+ self.graph.get_referring_cells(
+ variable, language="python"
+ )
+ ),
)
for variable, declared_by in self.graph.definitions.items()
]
@@ -1348,7 +1373,9 @@ class Kernel:
]
for binding in bindings:
referring_cells.update(
- self.graph.get_referring_cells(binding)
+ self.graph.get_referring_cells(
+ binding, language="python"
+ )
)
# KeyError: Trying to access an unnamed UIElement
@@ -1424,7 +1451,7 @@ class Kernel:
# subtracting self.graph.definitions[name]: never rerun the
# cell that created the name
referring_cells.update(
- self.graph.get_referring_cells(name)
+ self.graph.get_referring_cells(name, language="python")
- self.graph.get_defining_cells(name)
)
except Exception:
diff --git a/marimo/_smoke_tests/bugs/2019-sql-refs.py b/marimo/_smoke_tests/bugs/2019-sql-refs.py
new file mode 100644
index 0000000000..9c9a739b70
--- /dev/null
+++ b/marimo/_smoke_tests/bugs/2019-sql-refs.py
@@ -0,0 +1,60 @@
+import marimo
+
+__generated_with = "0.8.4"
+app = marimo.App(width="medium")
+
+
+def __(mo, my_table):
+ _df = mo.sql(
+ f"""
+ SELECT * FROM my_table
+ """
+ )
+ [mo.refs(), mo.defs()]
+ return
+
+
+def __(mo, my_view):
+ _df = mo.sql(
+ f"""
+ SELECT * FROM my_view
+ """
+ )
+ [mo.refs(), mo.defs()]
+ return
+
+
+def __(mo):
+ _df = mo.sql(
+ f"""
+ CREATE OR REPlACE TABLE my_table (a text);
+ INSERT INTO my_table (VALUES ('foo'), ('bar'));
+ """
+ )
+ [mo.refs(), mo.defs()]
+ return my_table,
+
+
+def __(mo):
+ _df = mo.sql(
+ f"""
+ CREATE OR REPLACE VIEW my_view AS (SELECT * FROM my_table WHERE a LIKE 'f%o')
+ """
+ )
+ [mo.refs(), mo.defs()]
+ return
+
+
[email protected](hide_code=True)
+def __():
+ import marimo as mo
+ import pandas as pd
+ return mo, pd
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/marimo/_smoke_tests/sql/duckdb_tokenize.py b/marimo/_smoke_tests/sql/duckdb_tokenize.py
new file mode 100644
index 0000000000..7819a4daf4
--- /dev/null
+++ b/marimo/_smoke_tests/sql/duckdb_tokenize.py
@@ -0,0 +1,130 @@
+# Copyright 2024 Marimo. All rights reserved.
+import marimo
+
+__generated_with = "0.7.20"
+app = marimo.App(width="medium")
+
+
+def __():
+ import marimo as mo
+ import duckdb
+ import re
+ return duckdb, mo, re
+
+
+def __(mo):
+ default_code = """
+ CREATE TABLE
+ -- This is a comment
+ IF NOT EXISTS
+ -- This is another comment
+ table1 (id INT)
+ """
+ code = mo.ui.code_editor(language="sql", value=default_code.strip())
+ code
+ return code, default_code
+
+
+def __(code, duckdb):
+ statements = duckdb.extract_statements(code.value)
+ print("Number of statements: " + str(len(statements)))
+
+ print(duckdb.tokenize(code.value))
+ return statements,
+
+
+def __(code, find_created_tables):
+ find_created_tables(code.value)
+ return
+
+
+def __(re):
+ def find_created_tables(sql_statement: str) -> list[str]:
+ """
+ Find the tables created in a SQL statement.
+
+ This function uses the DuckDB tokenizer to find the tables created
+ in a SQL statement. It returns a list of the table names created
+ in the statement.
+
+ Args:
+ sql_statement: The SQL statement to parse.
+
+ Returns:
+ A list of the table names created in the statement.
+ """
+
+ import duckdb
+
+ def remove_comments(sql):
+ # Function to replace comments with spaces, preserving newlines
+ def replace_with_spaces(match):
+ return " " * len(match.group())
+
+ # Split the SQL into strings and non-strings
+ parts = re.split(r'(\'(?:\'\'|[^\'])*\'|"(?:""|[^"])*")', sql)
+
+ for i in range(0, len(parts), 2):
+ # Remove single-line comments
+ parts[i] = re.sub(
+ r"--.*$", replace_with_spaces, parts[i], flags=re.MULTILINE
+ )
+
+ # Remove multi-line comments
+ parts[i] = re.sub(r"/\*[\s\S]*?\*/", replace_with_spaces, parts[i])
+
+ # Join the parts back together
+ return "".join(parts)
+
+ sql_statement = remove_comments(sql_statement)
+
+ tokens = duckdb.tokenize(sql_statement)
+ created_tables: list[str] = []
+ i = 0
+
+ def token_str(i: int) -> str:
+ token = tokens[i]
+ start = token[0]
+ end = len(sql_statement) - 1
+ if i + 1 < len(tokens):
+ end = tokens[i + 1][0]
+ return sql_statement[start:end].strip()
+
+ def keyword_token_str(i: int) -> str:
+ return token_str(i).lower()
+
+ def token_type(i: int) -> str:
+ return tokens[i][1]
+
+ while i < len(tokens):
+ if (
+ keyword_token_str(i) == "create"
+ and token_type(i) == duckdb.token_type.keyword
+ ):
+ i += 1
+ if i < len(tokens) and keyword_token_str(i) == "or":
+ i += 2 # Skip 'OR REPLACE'
+ if i < len(tokens) and keyword_token_str(i) in (
+ "temporary",
+ "temp",
+ ):
+ i += 1 # Skip 'TEMPORARY' or 'TEMP'
+ if i < len(tokens) and keyword_token_str(i) == "table":
+ i += 1
+ if i < len(tokens) and keyword_token_str(i) == "if":
+ i += 3 # Skip 'IF NOT EXISTS'
+ if i < len(tokens):
+ created_tables.append(token_str(i))
+ i += 1
+
+ return created_tables
+ return find_created_tables,
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/marimo/_smoke_tests/table_urls.py b/marimo/_smoke_tests/table_urls.py
index 6b571df5c7..7d829edf32 100644
--- a/marimo/_smoke_tests/table_urls.py
+++ b/marimo/_smoke_tests/table_urls.py
@@ -14,11 +14,20 @@ def __():
@app.cell
def __(mo):
mo.ui.table(
- [
- { "title": 'New York', "url": 'https://en.wikipedia.org/wiki/New_York_City', },
- { "title": 'London', "url": 'https://en.wikipedia.org/wiki/London', },
- { "title": 'Paris', "url": 'https://en.wikipedia.org/wiki/Paris', },
- ],
+ [
+ {
+ "title": "New York",
+ "url": "https://en.wikipedia.org/wiki/New_York_City",
+ },
+ {
+ "title": "London",
+ "url": "https://en.wikipedia.org/wiki/London",
+ },
+ {
+ "title": "Paris",
+ "url": "https://en.wikipedia.org/wiki/Paris",
+ },
+ ],
)
return
diff --git a/pyproject.toml b/pyproject.toml
index f2851359ed..685dd0dd2d 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -82,8 +82,10 @@ dev = [
"build~=0.10.0",
"types-Pygments~=2.18.0.20240506",
"types-psutil~=5.9.5.20240516",
- # for server testing
+ # For server testing
"httpx~=0.27.0",
+ # For SQL
+ "duckdb~=1.0.0",
# For testing mo.ui.chart, dataframes, tables
"pandas>=1.5.3",
"pandas-stubs>=1.5.3.230321",
diff --git a/tests/_ast/test_compiler.py b/tests/_ast/test_compiler.py
index 320fcdf12a..1073fe4bbf 100644
--- a/tests/_ast/test_compiler.py
+++ b/tests/_ast/test_compiler.py
@@ -3,12 +3,17 @@ from __future__ import annotations
from functools import partial
+import pytest
+
from marimo._ast import compiler
from marimo._ast.app import CellManager
-from marimo._ast.visitor import ImportData
+from marimo._ast.visitor import ImportData, VariableData
+from marimo._dependencies.dependencies import DependencyManager
compile_cell = partial(compiler.compile_cell, cell_id="0")
+HAS_DUCKDB = DependencyManager.duckdb.has()
+
class TestParseCell:
@staticmethod
@@ -244,6 +249,31 @@ class TestImportWorkspace:
assert not cell.import_workspace.imported_defs
[email protected](not HAS_DUCKDB, reason="Missing DuckDB")
+class TestParseSQLCell:
+ @staticmethod
+ def test_table_definition() -> None:
+ code = 'mo.sql("CREATE TABLE t1 (i INTEGER, j INTEGER)")'
+ cell = compile_cell(code)
+ assert cell.key == hash(code)
+ assert cell.code == code
+ assert cell.defs == set(["t1"])
+ assert cell.refs == set(["mo"])
+ assert cell.language == "sql"
+ assert cell.variable_data == {"t1": [VariableData("table")]}
+
+ @staticmethod
+ def test_table_reference() -> None:
+ code = 'mo.sql("SELECT * from t1")'
+ cell = compile_cell(code)
+ assert cell.key == hash(code)
+ assert cell.code == code
+ assert not cell.defs
+ assert cell.refs == set(["mo", "t1"])
+ assert cell.language == "sql"
+ assert not cell.variable_data
+
+
class TestCellFactory:
@staticmethod
def test_defs() -> None:
diff --git a/tests/_ast/test_sql_visitor.py b/tests/_ast/test_sql_visitor.py
new file mode 100644
index 0000000000..cfd824e926
--- /dev/null
+++ b/tests/_ast/test_sql_visitor.py
@@ -0,0 +1,418 @@
+from __future__ import annotations
+
+import ast
+from textwrap import dedent
+
+import pytest
+
+from marimo._ast.sql_visitor import (
+ SQLDefs,
+ SQLVisitor,
+ find_sql_defs,
+)
+from marimo._dependencies.dependencies import DependencyManager
+
+HAS_DUCKDB = DependencyManager.duckdb.has()
+
+
+def test_execute_with_string_literal() -> None:
+ 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() -> None:
+ 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() -> None:
+ 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() -> None:
+ 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() -> None:
+ 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() -> None:
+ 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() -> None:
+ 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() == []
+
+
[email protected](not HAS_DUCKDB, reason="Missing DuckDB")
+class TestFindCreatedTables:
+ @staticmethod
+ def test_find_sql_defs_simple() -> None:
+ sql = "CREATE TABLE test_table (id INT, name VARCHAR(255));"
+ assert find_sql_defs(sql) == SQLDefs(
+ ["test_table"],
+ [],
+ [],
+ )
+
+ sql = "CREATE VIEW test_view (id INT, name VARCHAR(255));"
+ assert find_sql_defs(sql) == SQLDefs(
+ [],
+ ["test_view"],
+ [],
+ )
+
+ @staticmethod
+ def test_find_sql_defs_multiple() -> None:
+ sql = """
+ CREATE TABLE table1 (id INT);
+ CREATE TABLE table2 (name VARCHAR(255));
+ """
+ assert find_sql_defs(sql) == SQLDefs(
+ [
+ "table1",
+ "table2",
+ ],
+ [],
+ [],
+ )
+
+ sql = """
+ CREATE VIEW table1 (id INT);
+ CREATE VIEW table2 (name VARCHAR(255));
+ """
+ assert find_sql_defs(sql) == SQLDefs(
+ [],
+ [
+ "table1",
+ "table2",
+ ],
+ [],
+ )
+
+ @staticmethod
+ def test_find_sql_defs_with_comments() -> None:
+ sql = """
+ CREATE TABLE
+ -- This is a comment
+ IF NOT EXISTS
+ -- This is another comment
+ table1 (id INT);
+ -- This is a comment
+ CREATE TABLE table2 (name VARCHAR(255));
+ """
+ assert find_sql_defs(sql) == SQLDefs(
+ [
+ "table1",
+ "table2",
+ ],
+ [],
+ [],
+ )
+
+ sql = """
+ CREATE VIEW
+ -- This is a comment
+ IF NOT EXISTS
+ -- This is another comment
+ table1 (id INT);
+ -- This is a comment
+ CREATE VIEW table2 (name VARCHAR(255));
+ """
+ assert find_sql_defs(sql) == SQLDefs(
+ [],
+ [
+ "table1",
+ "table2",
+ ],
+ [],
+ )
+
+ @staticmethod
+ def test_find_sql_defs_with_or_replace() -> None:
+ sql = "CREATE OR REPLACE TABLE test_table (id INT);"
+ assert find_sql_defs(sql) == SQLDefs(
+ ["test_table"],
+ [],
+ [],
+ )
+
+ sql = "CREATE OR REPLACE VIEW test_view (id INT);"
+ assert find_sql_defs(sql) == SQLDefs(
+ [],
+ ["test_view"],
+ [],
+ )
+
+ @staticmethod
+ def test_find_sql_defs_temporary() -> None:
+ sql = "CREATE TEMPORARY TABLE temp_table (id INT);"
+ assert find_sql_defs(sql) == SQLDefs(
+ ["temp_table"],
+ [],
+ [],
+ )
+
+ sql = "CREATE TEMPORARY VIEW temp_table (id INT);"
+ assert find_sql_defs(sql) == SQLDefs(
+ [],
+ ["temp_table"],
+ [],
+ )
+
+ @staticmethod
+ def test_find_sql_defs_if_not_exists() -> None:
+ sql = "CREATE TABLE IF NOT EXISTS new_table (id INT);"
+ assert find_sql_defs(sql) == SQLDefs(
+ ["new_table"],
+ [],
+ [],
+ )
+
+ sql = "CREATE VIEW IF NOT EXISTS new_table (id INT);"
+ assert find_sql_defs(sql) == SQLDefs(
+ [],
+ ["new_table"],
+ [],
+ )
+
+ @staticmethod
+ def test_find_sql_defs_complex() -> None:
+ sql = """
+ CREATE TABLE table1 (id INT);
+ CREATE OR REPLACE TEMPORARY TABLE IF NOT EXISTS table2 (name VARCHAR(255));
+ CREATE TABLE table3 (date DATE);
+ """ # noqa: E501
+ assert find_sql_defs(sql) == SQLDefs(
+ [
+ "table1",
+ "table2",
+ "table3",
+ ],
+ [],
+ [],
+ )
+
+ sql = """
+ CREATE VIEW table1 (id INT);
+ CREATE OR REPLACE TEMPORARY VIEW IF NOT EXISTS table2 (name VARCHAR(255));
+ CREATE VIEW table3 (date DATE);
+ """ # noqa: E501
+ assert find_sql_defs(sql) == SQLDefs(
+ [],
+ [
+ "table1",
+ "table2",
+ "table3",
+ ],
+ [],
+ )
+
+ @staticmethod
+ def test_find_sql_defs_no_create() -> None:
+ sql = "SELECT * FROM existing_table;"
+ assert find_sql_defs(sql) == SQLDefs([], [], [])
+
+ @staticmethod
+ def test_find_sql_defs_case_insensitive() -> None:
+ sql = "create TABLE Test_Table (id INT);"
+ assert find_sql_defs(sql) == SQLDefs(
+ ["Test_Table"],
+ [],
+ [],
+ )
+
+ sql = "create VIEW Test_Table (id INT);"
+ assert find_sql_defs(sql) == SQLDefs(
+ [],
+ ["Test_Table"],
+ [],
+ )
+
+ @staticmethod
+ @pytest.mark.parametrize(
+ "query",
+ [
+ "",
+ " ",
+ ";",
+ ],
+ )
+ def test_find_sql_defs_empty_input(
+ query: str,
+ ) -> None:
+ assert find_sql_defs(query) == SQLDefs(
+ [],
+ [],
+ [],
+ )
+
+ @staticmethod
+ @pytest.mark.parametrize(
+ "query",
+ [
+ """
+ -- This is a comment
+ CREATE TABLE my_table (
+ my_column INT, -- Inline comment
+ my_other_column INT
+ )
+ """,
+ """
+ /* Multi-line
+ comment */
+ CREATE OR REPLACE TABLE my_table (
+ my_column INT,
+ my_other_column INT
+ )
+ """,
+ """
+ CREATE TABLE IF NOT EXISTS my_table
+ -- Comment before AS
+ AS
+ /* Comment
+ before SELECT */
+ SELECT * FROM read_csv()
+ """,
+ """
+ CREATE TEMPORARY TABLE my_table AS
+ -- Comment in the middle
+ SELECT * FROM existing_table
+ """,
+ """
+ -- Comment at the start
+ CREATE OR REPLACE TEMP TABLE IF NOT EXISTS my_table (
+ id INT, -- Comment after column
+ name VARCHAR
+ ) -- Comment at the end
+ """,
+ ],
+ )
+ def test_find_sql_defs_many_comments(
+ query: str,
+ ) -> None:
+ assert find_sql_defs(query) == SQLDefs(
+ ["my_table"],
+ [],
+ [],
+ )
+
+ @staticmethod
+ def test_find_sql_defs_weird_names() -> None:
+ sql = """
+ CREATE TABLE "my--table" (
+ "column/*with*/comment" INT,
+ "another--column" VARCHAR
+ );
+
+ CREATE TABLE my_table_with_select AS
+ SELECT *
+ FROM (
+ VALUES
+ ('a', 1),
+ ('b', 2)
+ ) AS t("col--1", "col--2");
+
+ CREATE TABLE "my/*weird*/table" (id INT);
+
+ CREATE TABLE "with a space" (id INT);
+ """
+ assert find_sql_defs(sql) == SQLDefs(
+ [
+ "my--table",
+ "my_table_with_select",
+ "my/*weird*/table",
+ "with a space",
+ ],
+ [],
+ [],
+ )
+
+ @staticmethod
+ def test_find_created_database() -> None:
+ sql = "ATTACH 'Chinook.sqlite';"
+ assert find_sql_defs(sql) == SQLDefs(
+ [],
+ [],
+ ["Chinook"],
+ )
+
+ sql = "ATTACH 'Chinook.sqlite' AS my_db;"
+ assert find_sql_defs(sql) == SQLDefs(
+ [],
+ [],
+ ["my_db"],
+ )
+ sql = "ATTACH DATABASE 'Chinook.sqlite';"
+ assert find_sql_defs(sql) == SQLDefs(
+ [],
+ [],
+ ["Chinook"],
+ )
+
+ sql = "ATTACH DATABASE IF NOT EXISTS 'Chinook.sqlite';"
+ assert find_sql_defs(sql) == SQLDefs(
+ [],
+ [],
+ ["Chinook"],
+ )
+
+ sql = "ATTACH DATABASE IF NOT EXISTS 'Chinook.sqlite' AS my_db;"
+ assert find_sql_defs(sql) == SQLDefs(
+ [],
+ [],
+ ["my_db"],
+ )
+
+
+ HAS_DUCKDB, reason="Test requires DuckDB to be unavailable"
+)
+def test_find_sql_defs_duckdb_not_available() -> None:
+ assert find_sql_defs("CREATE TABLE test (id INT);") == SQLDefs([], [], [])
diff --git a/tests/_ast/test_visitor.py b/tests/_ast/test_visitor.py
index 6334801b76..175359bfae 100644
--- a/tests/_ast/test_visitor.py
+++ b/tests/_ast/test_visitor.py
@@ -1026,7 +1026,8 @@ def test_sql_statement_with_url() -> None:
v = visitor.ScopedVisitor()
mod = ast.parse(code)
v.visit(mod)
- assert v.defs == set()
+ assert v.defs == set(["cars"])
+ assert v.variable_data == {"cars": [VariableData("table")]}
assert v.refs == set(["mo"])
diff --git a/tests/_data/test_sql_visitor.py b/tests/_data/test_sql_visitor.py
deleted file mode 100644
index 3c578efd5a..0000000000
--- a/tests/_data/test_sql_visitor.py
+++ /dev/null
@@ -1,77 +0,0 @@
-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/_runtime/test_dataflow.py b/tests/_runtime/test_dataflow.py
index 693911343c..1bbe0da0b8 100644
--- a/tests/_runtime/test_dataflow.py
+++ b/tests/_runtime/test_dataflow.py
@@ -3,11 +3,16 @@ from __future__ import annotations
from functools import partial
+import pytest
+
from marimo._ast import compiler
+from marimo._dependencies.dependencies import DependencyManager
from marimo._runtime import dataflow
parse_cell = partial(compiler.compile_cell, cell_id="0")
+HAS_DUCKDB = DependencyManager.duckdb.has()
+
def test_graph_single_node() -> None:
code = "x = 0"
@@ -220,3 +225,153 @@ def test_register_with_stale_ancestor() -> None:
third_cell = parse_cell(code)
graph.register_cell("3", third_cell)
assert graph.get_stale() == set(["0", "1"])
+
+
[email protected](not HAS_DUCKDB, reason="duckdb is required")
+class TestSQL:
+ def test_sql_chain(self) -> None:
+ graph = dataflow.DirectedGraph()
+ code = 'mo.sql("CREATE TABLE t1 (i INTEGER, j INTEGER)")'
+ first_cell = parse_cell(code)
+ graph.register_cell("0", first_cell)
+
+ assert graph.cells == {"0": first_cell}
+ assert graph.parents == {"0": set()}
+ assert graph.children == {"0": set()}
+
+ code = 'mo.sql("SELECT * from t1")'
+ second_cell = parse_cell(code)
+ graph.register_cell("1", second_cell)
+
+ assert graph.cells == {"0": first_cell, "1": second_cell}
+ assert graph.parents == {"0": set(), "1": set(["0"])}
+ assert graph.children == {"0": set(["1"]), "1": set()}
+
+ def test_sql_tree_with_declared_df(self) -> None:
+ graph = dataflow.DirectedGraph()
+ code = 'df = mo.sql("CREATE TABLE t1 (i INTEGER, j INTEGER)")'
+ first_cell = parse_cell(code)
+ graph.register_cell("0", first_cell)
+
+ assert graph.cells == {"0": first_cell}
+ assert graph.parents == {"0": set()}
+ assert graph.children == {"0": set()}
+
+ code = 'mo.sql("SELECT * from t1")'
+ second_cell = parse_cell(code)
+ graph.register_cell("1", second_cell)
+
+ assert graph.cells == {"0": first_cell, "1": second_cell}
+ assert graph.parents == {"0": set(), "1": set(["0"])}
+ assert graph.children == {"0": set(["1"]), "1": set()}
+
+ code = 'mo.sql("SELECT * from df")'
+ third_cell = parse_cell(code)
+ graph.register_cell("2", third_cell)
+
+ assert graph.cells == {
+ "0": first_cell,
+ "1": second_cell,
+ "2": third_cell,
+ }
+ assert graph.parents == {"0": set(), "1": set(["0"]), "2": set(["0"])}
+ assert graph.children == {"0": set(["1", "2"]), "1": set(), "2": set()}
+
+ code = "df"
+ fourth_cell = parse_cell(code)
+ graph.register_cell("3", fourth_cell)
+
+ assert graph.cells == {
+ "0": first_cell,
+ "1": second_cell,
+ "2": third_cell,
+ "3": fourth_cell,
+ }
+ assert graph.parents == {
+ "0": set(),
+ "1": set(["0"]),
+ "2": set(["0"]),
+ "3": set(["0"]),
+ }
+ assert graph.children == {
+ "0": set(["1", "2", "3"]),
+ "1": set(),
+ "2": set(),
+ "3": set(),
+ }
+
+ def test_no_sql_table_to_python_ref(self):
+ graph = dataflow.DirectedGraph()
+ code = 'df = mo.sql("CREATE TABLE t1 (i INTEGER, j INTEGER)")'
+ first_cell = parse_cell(code)
+ graph.register_cell("0", first_cell)
+
+ # not a child of first_cell because t1 is a sql table not Python
+ # variable
+ code = "t1"
+ second_cell = parse_cell(code)
+ graph.register_cell("1", second_cell)
+
+ # is a child of first_cell because df is a Python variable
+ code = "df"
+ third_cell = parse_cell(code)
+ graph.register_cell("2", third_cell)
+
+ assert graph.cells == {
+ "0": first_cell,
+ "1": second_cell,
+ "2": third_cell,
+ }
+ assert graph.parents == {"0": set(), "1": set([]), "2": set(["0"])}
+ assert graph.children == {"0": set(["2"]), "1": set(), "2": set([])}
+
+ assert second_cell.language == "python"
+ assert graph.get_referring_cells("t1", language="sql") == set([])
+ assert graph.get_referring_cells("df", language="python") == set(["2"])
+
+ def test_python_to_sql_ref(self):
+ graph = dataflow.DirectedGraph()
+ code = "df = 123"
+ first_cell = parse_cell(code)
+ graph.register_cell("0", first_cell)
+
+ # not a child of first_cell because t1 is a sql table not Python
+ # variable
+ code = "mo.sql('SELECT * from df')"
+ second_cell = parse_cell(code)
+ graph.register_cell("1", second_cell)
+
+ assert graph.cells == {
+ "0": first_cell,
+ "1": second_cell,
+ }
+ assert graph.parents == {"0": set(), "1": set(["0"])}
+ assert graph.children == {"0": set(["1"]), "1": set([])}
+
+ assert graph.get_referring_cells("df", language="python") == set(["1"])
+
+ def test_attached_db(self):
+ graph = dataflow.DirectedGraph()
+ code = "mo.sql(\"ATTACH 'my_db.db'\")"
+ first_cell = parse_cell(code)
+ graph.register_cell("0", first_cell)
+
+ code = "mo.sql('SELECT * FROM my_db.my_table')"
+ second_cell = parse_cell(code)
+ graph.register_cell("1", second_cell)
+
+ code = "my_db"
+ third_cell = parse_cell(code)
+ graph.register_cell("2", third_cell)
+
+ assert graph.cells == {
+ "0": first_cell,
+ "1": second_cell,
+ "2": third_cell,
+ }
+ assert graph.parents == {"0": set(), "1": set(["0"]), "2": set([])}
+ assert graph.children == {"0": set(["1"]), "1": set([]), "2": set([])}
+
+ # cell 2 shouldn't count as a referring cell because it isn't a SQL
+ # cell
+ assert graph.get_referring_cells("my_db", language="sql") == set(["1"])
diff --git a/tests/_runtime/test_runtime.py b/tests/_runtime/test_runtime.py
index 1aeb5919a5..9488ccc4f0 100644
--- a/tests/_runtime/test_runtime.py
+++ b/tests/_runtime/test_runtime.py
@@ -8,6 +8,7 @@ from typing import TYPE_CHECKING, Sequence
import pytest
from marimo._config.config import DEFAULT_CONFIG
+from marimo._dependencies.dependencies import DependencyManager
from marimo._messaging.errors import (
CycleError,
DeleteNonlocalError,
@@ -45,6 +46,9 @@ def _check_edges(error: Error, expected_edges: Sequence[EdgeWithVar]) -> None:
assert edge in error.edges_with_vars
+HAS_SQL = DependencyManager.duckdb.has() and DependencyManager.polars.has()
+
+
class TestExecution:
async def test_expected_gloals(self, any_kernel: Kernel):
k = any_kernel
@@ -2018,6 +2022,80 @@ class TestAsyncIO:
assert k.globals["res"] == "done"
[email protected](not HAS_SQL, reason="SQL deps not available")
+class TestSQL:
+ async def test_sql_table(self, k: Kernel) -> None:
+ await k.run(
+ [
+ ExecutionRequest(
+ cell_id="0",
+ code="import marimo as mo",
+ ),
+ ExecutionRequest(
+ cell_id="1", code="df = mo.sql('SELECT * from t1')"
+ ),
+ ]
+ )
+ assert "df" not in k.globals
+
+ await k.run(
+ [
+ ExecutionRequest(
+ cell_id="2",
+ code="import polars as pl; t1_df = pl.from_dict({'a': [42]})", # noqa: E501
+ ),
+ # cell 1 should automatically execute due to the definition of
+ # t1
+ ExecutionRequest(
+ cell_id="3",
+ code="mo.sql('CREATE OR REPLACE TABLE t1 as SELECT * FROM t1_df')", # noqa: E501
+ ),
+ ]
+ )
+
+ # make sure cell 1 executed, defining df
+ assert k.globals["df"].to_dict(as_series=False) == {"a": [42]}
+
+ await k.delete_cell(DeleteCellRequest(cell_id="3"))
+ # t1 should be dropped since it's an in-memory table;
+ # cell 1 should re-run but will fail to find t1
+ assert "df" not in k.globals
+
+ async def test_sql_view(self, k: Kernel) -> None:
+ await k.run(
+ [
+ ExecutionRequest(
+ cell_id="0",
+ code="import marimo as mo",
+ ),
+ ExecutionRequest(
+ cell_id="1", code="df = mo.sql('SELECT * from view')"
+ ),
+ ]
+ )
+ assert "df" not in k.globals
+
+ await k.run(
+ [
+ # cell 1 should automatically execute due to the definition of
+ # t1
+ ExecutionRequest(
+ cell_id="2",
+ code="mo.sql('CREATE OR REPLACE VIEW view as SELECT 42')", # noqa: E501
+ ),
+ ]
+ )
+
+ assert not k.errors
+ # make sure cell 1 executed, defining df
+ assert "df" in k.globals
+
+ await k.delete_cell(DeleteCellRequest(cell_id="2"))
+ # view should be dropped since it's an in-memory table;
+ # cell 1 should re-run but will fail to find t1
+ assert "df" not in k.globals
+
+
class TestStateTransitions:
async def test_statuses_not_repeated_ok_run(
self, mocked_kernel: MockedKernel, exec_req: ExecReqProvider