A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
fix: sql case with function (#2869)
Myles Scolnick8b66670abf52
diff --git a/marimo/_ast/visitor.py b/marimo/_ast/visitor.pyindex c2c11206d6..cb22ac248f 100644--- a/marimo/_ast/visitor.py+++ b/marimo/_ast/visitor.py@@ -6,11 +6,12 @@ import itertoolsimport sysfrom collections import defaultdictfrom dataclasses import dataclass, field-from typing import Callable, Literal, Optional, Union+from typing import Callable, Literal, Optional, Set, Unionfrom uuid import uuid4from marimo import _loggersfrom marimo._ast.sql_visitor import (+ SQLDefs,find_sql_defs,find_sql_refs,normalize_sql_f_string,@@ -489,20 +490,28 @@ class ScopedVisitor(ast.NodeVisitor):return nodefor statement in statements:+ tables: Set[str] = set()+ from_targets: list[str] = []# Parse the refs and defs of each statementtry:tables = duckdb.get_table_names(statement.query)+ except (duckdb.ProgrammingError, duckdb.IOException):+ LOGGER.debug(+ "Error parsing SQL statement: %s", statement.query+ )+ except BaseException as e:+ LOGGER.warning("Unexpected duckdb error %s", e)+ try:# TODO(akshayka): more comprehensive parsing# of the statement -- schemas can show up in# joins, queries, ...from_targets = find_sql_refs(statement.query)except (duckdb.ProgrammingError, duckdb.IOException):- self.generic_visit(node)- continue+ LOGGER.debug(+ "Error parsing SQL statement: %s", statement.query+ )except BaseException as e:LOGGER.warning("Unexpected duckdb error %s", e)- self.generic_visit(node)- continuefor name in itertools.chain(tables, from_targets):# Name (table, db) may be a URL or something else that@@ -514,12 +523,10 @@ class ScopedVisitor(ast.NodeVisitor):try:sql_defs = find_sql_defs(sql)except duckdb.ProgrammingError:- self.generic_visit(node)- continue+ sql_defs = SQLDefs()except BaseException as e:LOGGER.warning("Unexpected duckdb error %s", e)- self.generic_visit(node)- continue+ sql_defs = SQLDefs()for _table in sql_defs.tables:self._define(None, _table, VariableData("table"))diff --git a/tests/_ast/test_sql_visitor.py b/tests/_ast/test_sql_visitor.pyindex 51e461daa8..aa888892e3 100644--- a/tests/_ast/test_sql_visitor.py+++ b/tests/_ast/test_sql_visitor.py@@ -484,6 +484,23 @@ class TestFindSQLRefs:"""assert find_sql_refs(sql) == ["table1", "table2"]+ @staticmethod+ def test_find_sql_refs_without_duplicates() -> None:+ sql = """+ SELECT * FROM table1;+ SELECT * FROM table2;+ SELECT * FROM table1;+ """+ assert find_sql_refs(sql) == ["table1", "table2"]++ @staticmethod+ def test_find_sql_refs_with_function() -> None:+ sql = """+ SELECT *, embedding(text) as text_embedding+ FROM prompts;+ """+ assert find_sql_refs(sql) == ["prompts"]+@staticmethoddef test_find_sql_refs_with_schema() -> None:sql = "SELECT * FROM my_schema.my_table;"diff --git a/tests/_ast/test_visitor.py b/tests/_ast/test_visitor.pyindex eb986b5c74..d4cdc97f58 100644--- a/tests/_ast/test_visitor.py+++ b/tests/_ast/test_visitor.py@@ -3,6 +3,7 @@ from __future__ import annotationsimport astfrom inspect import cleandoc+from textwrap import dedentimport pytest@@ -1098,6 +1099,23 @@ def test_sql_statement_with_url() -> None:assert v.refs == set(["mo"])[email protected](not HAS_DEPS, reason="Requires duckdb")+def test_sql_statement_with_function() -> None:+ code = dedent('''+ prompt_embeddings = mo.sql(+ f"""+ SELECT *, embedding(text) as text_embedding+ FROM prompts;+ """+ )+ ''')+ v = visitor.ScopedVisitor()+ mod = ast.parse(code)+ v.visit(mod)+ assert v.defs == set(["prompt_embeddings"])+ assert v.refs == set(["mo", "prompts"])++@pytest.mark.skipif(not HAS_DEPS, reason="Requires duckdb")def test_unparsable_sql_doesnt_fail() -> None:code = "\n".join(