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.

Guard SQL ref extraction on sqlglot availability (#9656)

Myles Scolnick51b53795a454
diff --git a/marimo/_ast/visitor.py b/marimo/_ast/visitor.py
index cc13455225..6b23ec78af 100644
--- a/marimo/_ast/visitor.py
+++ b/marimo/_ast/visitor.py
@@ -710,6 +710,8 @@ class ScopedVisitor(ast.NodeVisitor):
# so that later statements don't create refs to tables defined in earlier statements
defined_names: set[str] = set()
+ has_sqlglot = DependencyManager.sqlglot.has()
+
for statement_sql in statement_queries:
# Parse the refs and defs of each statement
# Add all tables/dbs created in the query to the defs
@@ -754,14 +756,17 @@ class ScopedVisitor(ast.NodeVisitor):
self._define(None, _catalog, VariableData("catalog"))
defined_names.add(_catalog)
- sql_refs = find_sql_refs_cached(statement_sql)
-
- for ref in sql_refs:
- name = ref.qualified_name
- # Cells that define the same name aren't cycles, so we skip them
- if name in defined_names:
- continue
- self._add_ref(None, name, deleted=False, sql_ref=ref)
+ if has_sqlglot:
+ sql_refs = find_sql_refs_cached(statement_sql)
+
+ for ref in sql_refs:
+ name = ref.qualified_name
+ # Cells that define the same name aren't cycles, so we skip them
+ if name in defined_names:
+ continue
+ self._add_ref(
+ None, name, deleted=False, sql_ref=ref
+ )
# Visit arguments, keyword args, etc.
self.generic_visit(node)
diff --git a/tests/_ast/test_visitor.py b/tests/_ast/test_visitor.py
index f267b06e60..860863c7be 100644
--- a/tests/_ast/test_visitor.py
+++ b/tests/_ast/test_visitor.py
@@ -1369,6 +1369,19 @@ def test_sql_multiple_tables() -> None:
assert v.refs == {"cars", "cars2", "mo"}
[email protected](not HAS_DEPS, reason="Requires duckdb")
+def test_sql_without_sqlglot(monkeypatch: pytest.MonkeyPatch) -> None:
+ # Defs come from duckdb and should still resolve; refs come from sqlglot
+ # and should be skipped instead of raising ModuleNotFoundError.
+ monkeypatch.setattr(DependencyManager.sqlglot, "has", lambda **_: False)
+ code = "mo.sql('CREATE TABLE cars AS SELECT * FROM other_table')"
+ v = visitor.ScopedVisitor()
+ mod = ast.parse(code)
+ v.visit(mod)
+ assert v.defs == {"cars"}
+ assert v.refs == {"mo"}
+
+
@pytest.mark.skipif(not HAS_DEPS, reason="Requires duckdb")
def test_sql_from_another_module() -> None:
code = "df = lib.sql('select * from cars')"