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: handle some sql edge cases for catalogs (#2825)
Myles Scolnick4b3f1e3776cc
diff --git a/marimo/_ast/sql_visitor.py b/marimo/_ast/sql_visitor.pyindex e97d4d63cb..b9dc01958e 100644--- a/marimo/_ast/sql_visitor.py+++ b/marimo/_ast/sql_visitor.py@@ -4,10 +4,13 @@ from __future__ import annotationsimport astimport refrom dataclasses import dataclass-from typing import Any, Optional+from typing import Any, List, Optional+from marimo import _loggersfrom marimo._dependencies.dependencies import DependencyManager+LOGGER = _loggers.marimo_logger()+class SQLVisitor(ast.NodeVisitor):"""@@ -222,17 +225,17 @@ def find_sql_defs(sql_statement: str) -> SQLDefs:# TODO(akshayka): there are other kinds of refs to find; this should be# find_sql_refs-def find_from_targets(+def find_sql_refs(sql_statement: str,) -> list[str]:"""- Find tokens following the FROM keyword, which may be tables or schemas.+ Find table and schema references in a SQL statement.Args:sql_statement: The SQL statement to parse.Returns:- A list of names following the FROM keyword.+ A list of table and schema names referenced in the statement."""if not DependencyManager.duckdb.has():return []@@ -244,22 +247,95 @@ def find_from_targets(sql_statement=sql_statement, tokens=tokens)refs: list[str] = []+ cte_names: set[str] = set()i = 0+ # First pass - collect CTE nameswhile i < len(tokens):- if token_extractor.is_keyword(i, "from"):+ if token_extractor.is_keyword(i, "with"):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(+ # Handle optional parenthesis after WITH+ if token_extractor.token_str(i) == "(":+ i += 1+ while i < len(tokens):+ if token_extractor.is_keyword(i, "select"):+ break+ if (+ token_extractor.token_str(i) == ","+ or token_extractor.token_str(i) == "("+ ):+ i += 1+ continue+ cte_name = token_extractor.strip_quotes(token_extractor.token_str(i))- if "." in name:- # get the schema- name = name.split(".")[0]- refs.append(name)+ if not token_extractor.is_keyword(i, "as"):+ cte_names.add(cte_name)+ i += 1+ if token_extractor.is_keyword(i, "as"):+ break+ i += 1++ # Second pass - collect references excluding CTEs+ i = 0+ while i < len(tokens):+ if token_extractor.is_keyword(i, "from") or token_extractor.is_keyword(+ i, "join"+ ):+ i += 1+ if i < len(tokens):+ # Skip over opening parenthesis for subqueries+ if token_extractor.token_str(i) == "(":+ continue++ parts: List[str] = []+ while i < len(tokens):+ part = token_extractor.strip_quotes(+ token_extractor.token_str(i)+ )+ if part in (+ "on",+ "as",+ "where",+ "group",+ "order",+ "limit",+ "offset",+ ")",+ ):+ break+ if part not in (",", "("):+ if part not in cte_names:+ parts.append(part)++ i += 1+ if i >= len(tokens) or token_extractor.token_str(i) != ".":+ break+ i += 1++ if len(parts) == 3:+ if parts[0] == "memory":+ # Skip catalog and schema, if its the default+ # in-memory catalog+ refs.append(parts[2])+ else:+ # Just add the catalog and table, skip schema+ refs.extend([parts[0], parts[2]])+ elif len(parts) == 2:+ # It's a schema and table+ refs.extend(parts)+ elif len(parts) == 1:+ # It's a table, make sure it's not a CTE+ if parts[0] not in cte_names:+ refs.append(parts[0])+ else:+ LOGGER.warning(+ "Unexpected number of parts in SQL reference: %s",+ parts,+ )++ i -= 1 # Compensate for outer loop incrementi += 1- return refs+ # Remove duplicates while preserving order+ return list(dict.fromkeys(refs))diff --git a/marimo/_ast/visitor.py b/marimo/_ast/visitor.pyindex f13171f8b5..ea9949f1da 100644--- a/marimo/_ast/visitor.py+++ b/marimo/_ast/visitor.py@@ -11,8 +11,8 @@ from uuid import uuid4from marimo import _loggersfrom marimo._ast.sql_visitor import (- find_from_targets,find_sql_defs,+ find_sql_refs,normalize_sql_f_string,)from marimo._dependencies.dependencies import DependencyManager@@ -487,7 +487,7 @@ class ScopedVisitor(ast.NodeVisitor):# TODO(akshayka): more comprehensive parsing# of the statement -- schemas can show up in# joins, queries, ...- from_targets = find_from_targets(statement.query)+ from_targets = find_sql_refs(statement.query)except (duckdb.ProgrammingError, duckdb.IOException):self.generic_visit(node)continuediff --git a/tests/_ast/test_sql_visitor.py b/tests/_ast/test_sql_visitor.pyindex 66ba0c6e59..212b6958eb 100644--- a/tests/_ast/test_sql_visitor.py+++ b/tests/_ast/test_sql_visitor.py@@ -9,6 +9,7 @@ from marimo._ast.sql_visitor import (SQLDefs,SQLVisitor,find_sql_defs,+ find_sql_refs,)from marimo._dependencies.dependencies import DependencyManager@@ -91,7 +92,7 @@ def test_sql_with_variable() -> None:@pytest.mark.skipif(not HAS_DUCKDB, reason="Missing DuckDB")-class TestFindCreatedTables:+class TestFindSQLDefs:@staticmethoddef test_find_sql_defs_simple() -> None:sql = "CREATE TABLE test_table (id INT, name VARCHAR(255));"@@ -421,3 +422,133 @@ class TestFindCreatedTables:)def test_find_sql_defs_duckdb_not_available() -> None:assert find_sql_defs("CREATE TABLE test (id INT);") == SQLDefs([], [], [])++[email protected](not HAS_DUCKDB, reason="Missing DuckDB")+class TestFindSQLRefs:+ @staticmethod+ def test_find_sql_refs_simple() -> None:+ sql = "SELECT * FROM test_table;"+ assert find_sql_refs(sql) == ["test_table"]++ @staticmethod+ def test_find_sql_refs_multiple() -> None:+ sql = """+ SELECT * FROM table1;+ SELECT * FROM table2;+ """+ assert find_sql_refs(sql) == ["table1", "table2"]++ @staticmethod+ def test_find_sql_refs_with_schema() -> None:+ sql = "SELECT * FROM my_schema.my_table;"+ assert find_sql_refs(sql) == ["my_schema", "my_table"]++ @staticmethod+ def test_find_sql_refs_with_catalog() -> None:+ # Skip the schema if it's coming from a catalog+ # Why? Because it may be called "public" or "main" across all catalogs+ # and they aren't referenced in the code+ sql = "SELECT * FROM my_catalog.my_schema.my_table;"+ assert find_sql_refs(sql) == ["my_catalog", "my_table"]++ @staticmethod+ def test_find_sql_refs_skip_memory_main() -> None:+ # This is the default in-memory catalog and schema+ # and we don't want to include them in the references+ sql = "SELECT * FROM memory.main.my_table;"+ assert find_sql_refs(sql) == ["my_table"]++ @staticmethod+ def test_find_sql_refs_with_join() -> None:+ sql = """+ SELECT * FROM table1+ JOIN table2 ON table1.id = table2.id;+ """+ assert find_sql_refs(sql) == ["table1", "table2"]++ @staticmethod+ def test_find_sql_refs_with_subquery() -> None:+ sql = """+ SELECT * FROM (+ SELECT * FROM inner_table+ ) t;+ """+ assert find_sql_refs(sql) == ["inner_table"]++ @staticmethod+ def test_find_sql_refs_with_cte() -> None:+ sql = """+ WITH cte AS (+ SELECT * FROM source_table+ )+ SELECT * FROM cte;+ """+ assert find_sql_refs(sql) == ["source_table"]++ @staticmethod+ def test_find_sql_refs_with_union() -> None:+ sql = """+ SELECT * FROM table1+ UNION+ SELECT * FROM table2;+ """+ assert find_sql_refs(sql) == ["table1", "table2"]++ @staticmethod+ def test_find_sql_refs_with_quoted_names() -> None:+ sql = """+ SELECT * FROM "My Table"+ JOIN "Weird.Name" ON "My Table".id = "Weird.Name".id;+ """+ assert find_sql_refs(sql) == ["My Table", "Weird.Name"]++ @staticmethod+ @pytest.mark.xfail(reason="Multiple CTEs are not supported")+ def test_find_sql_refs_with_multiple_ctes() -> None:+ sql = """+ WITH+ cte1 AS (SELECT * FROM table1),+ cte2 AS (SELECT * FROM table2),+ cte3 AS (SELECT * FROM cte1 JOIN cte2)+ SELECT * FROM cte3;+ """+ assert find_sql_refs(sql) == ["table1", "table2"]++ @staticmethod+ @pytest.mark.xfail(reason="Nested joins are not supported")+ def test_find_sql_refs_with_nested_joins() -> None:+ sql = """+ SELECT * FROM t1+ JOIN (t2 JOIN t3 ON t2.id = t3.id)+ ON t1.id = t2.id;+ """+ assert find_sql_refs(sql) == ["t1", "t2", "t3"]++ @staticmethod+ def test_find_sql_refs_with_lateral_join() -> None:+ sql = """+ SELECT * FROM employees,+ LATERAL (SELECT * FROM departments WHERE departments.id = employees.dept_id) dept;+ """+ assert find_sql_refs(sql) == ["employees", "departments"]++ @staticmethod+ def test_find_sql_refs_with_schema_switching() -> None:+ sql = """+ SELECT * FROM schema1.table1+ JOIN schema2.table2 ON schema1.table1.id = schema2.table2.id;+ """+ assert find_sql_refs(sql) == ["schema1", "table1", "schema2", "table2"]++ @staticmethod+ def test_find_sql_refs_with_complex_subqueries() -> None:+ sql = """+ SELECT * FROM (+ SELECT * FROM (+ SELECT * FROM deeply.nested.table+ ) t1+ JOIN another_table+ ) t2;+ """+ assert find_sql_refs(sql) == ["deeply", "table", "another_table"]