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.

fix: SQL cases for referencing catalog and schema in CREATE table statements (#2827)

Myles Scolnick4a482a3831ba
diff --git a/marimo/_ast/sql_visitor.py b/marimo/_ast/sql_visitor.py
index b9dc01958e..f870d5d962 100644
--- a/marimo/_ast/sql_visitor.py
+++ b/marimo/_ast/sql_visitor.py
@@ -3,7 +3,7 @@ from __future__ import annotations
import ast
import re
-from dataclasses import dataclass
+from dataclasses import dataclass, field
from typing import Any, List, Optional
from marimo import _loggers
@@ -122,18 +122,25 @@ class TokenExtractor:
@dataclass
class SQLDefs:
- tables: list[str]
- views: list[str]
- schemas: list[str]
+ tables: list[str] = field(default_factory=list)
+ views: list[str] = field(default_factory=list)
+ schemas: list[str] = field(default_factory=list)
+ catalogs: list[str] = field(default_factory=list)
+
+ # The schemas referenced in the CREATE SQL statement
+ reffed_schemas: list[str] = field(default_factory=list)
+ # The catalogs referenced in the CREATE SQL statement
+ reffed_catalogs: list[str] = field(default_factory=list)
def find_sql_defs(sql_statement: str) -> SQLDefs:
"""
- Find the tables, views, and schemas created/attached in a SQL statement.
+ Find the tables, views, schemas, and catalogs 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.
+ names created, views created, schemas created, and catalogs attached in the
+ statement.
Args:
sql_statement: The SQL statement to parse.
@@ -142,7 +149,7 @@ def find_sql_defs(sql_statement: str) -> SQLDefs:
SQLDefs
"""
if not DependencyManager.duckdb.has():
- return SQLDefs([], [], [])
+ return SQLDefs()
import duckdb
@@ -153,6 +160,10 @@ def find_sql_defs(sql_statement: str) -> SQLDefs:
created_tables: list[str] = []
created_views: list[str] = []
created_schemas: list[str] = []
+ created_catalogs: list[str] = []
+
+ reffed_schemas: list[str] = []
+ reffed_catalogs: list[str] = []
i = 0
# See
@@ -167,7 +178,7 @@ def find_sql_defs(sql_statement: str) -> SQLDefs:
# for ATTACH syntax
while i < len(tokens):
if token_extractor.is_keyword(i, "create"):
- # CREATE TABLE and CREATE VIEW have the same syntax
+ # CREATE TABLE, CREATE VIEW, CREATE SCHEMA have the same syntax
i += 1
if i < len(tokens) and token_extractor.is_keyword(i, "or"):
i += 2 # Skip 'OR REPLACE'
@@ -176,50 +187,112 @@ def find_sql_defs(sql_statement: str) -> SQLDefs:
or token_extractor.is_keyword(i, "temp")
):
i += 1 # Skip 'TEMPORARY' or 'TEMP'
+
+ is_table = False
+ is_view = False
+ is_schema = False
+
if i < len(tokens) and (
(is_table := token_extractor.is_keyword(i, "table"))
- or token_extractor.is_keyword(i, "view")
+ or (is_view := token_extractor.is_keyword(i, "view"))
+ or (is_schema := token_extractor.is_keyword(i, "schema"))
):
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)
- )
+ # Get table name parts, this could be:
+ # - catalog.schema.table
+ # - catalog.table (this is shorthand for catalog.main.table)
+ # - table
+
+ parts: List[str] = []
+ while i < len(tokens):
+ part = token_extractor.strip_quotes(
+ token_extractor.token_str(i)
+ )
+ parts.append(part)
+ # next token is a dot, so we continue getting parts
+ if (
+ i + 1 < len(tokens)
+ and token_extractor.token_str(i + 1) == "."
+ ):
+ i += 2
+ continue
+ break
+
+ # Assert parts is either 1, 2, or 3
+ if len(parts) not in (1, 2, 3):
+ LOGGER.warning(
+ "Unexpected number of parts in CREATE TABLE: %s",
+ parts,
+ )
+
if is_table:
- created_tables.append(table_name)
- else:
- created_views.append(table_name)
+ # only add the table name
+ created_tables.append(parts[-1])
+ # add the catalog and schema if exist
+ if len(parts) == 3:
+ reffed_catalogs.append(parts[0])
+ reffed_schemas.append(parts[1])
+ if len(parts) == 2:
+ reffed_catalogs.append(parts[0])
+ elif is_view:
+ # only add the table name
+ created_views.append(parts[-1])
+ # add the catalog and schema if exist
+ if len(parts) == 3:
+ reffed_catalogs.append(parts[0])
+ reffed_schemas.append(parts[1])
+ if len(parts) == 2:
+ reffed_catalogs.append(parts[0])
+ elif is_schema:
+ # only add the schema name
+ created_schemas.append(parts[-1])
+ # add the catalog if exist
+ if len(parts) == 2:
+ reffed_catalogs.append(parts[0])
elif token_extractor.is_keyword(i, "attach"):
- schema_name = None
+ catalog_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(
+ catalog_name = token_extractor.strip_quotes(
token_extractor.token_str(i)
)
- if "." in schema_name:
+ if "." in catalog_name:
# strip the extension from the name
- schema_name = schema_name.split(".")[0]
+ catalog_name = catalog_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(
+ catalog_name = token_extractor.strip_quotes(
token_extractor.token_str(i)
)
- if schema_name is not None:
- created_schemas.append(schema_name)
+ if catalog_name is not None:
+ created_catalogs.append(catalog_name)
i += 1
+ # Remove 'memory' from catalogs, as this is the default and doesn't have a def
+ if "memory" in reffed_catalogs:
+ reffed_catalogs.remove("memory")
+ # Remove 'main' from schemas, as this is the default and doesn't have a def
+ if "main" in reffed_schemas:
+ reffed_schemas.remove("main")
+
return SQLDefs(
- tables=created_tables, views=created_views, schemas=created_schemas
+ tables=created_tables,
+ views=created_views,
+ schemas=created_schemas,
+ catalogs=created_catalogs,
+ reffed_schemas=reffed_schemas,
+ reffed_catalogs=reffed_catalogs,
)
@@ -288,42 +361,41 @@ def find_sql_refs(
if token_extractor.token_str(i) == "(":
continue
+ # Get table name parts, this could be:
+ # - catalog.schema.table
+ # - catalog.table (this is shorthand for catalog.main.table)
+ # - table
+
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",
- ")",
+ parts.append(part)
+ # next token is a dot, so we continue getting parts
+ if (
+ i + 1 < len(tokens)
+ and token_extractor.token_str(i + 1) == "."
):
- 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
+ i += 2
+ continue
+ break
if len(parts) == 3:
+ # If its the default in-memory catalog,
+ # only add the table name
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)
+ # If its the default in-memory catalog, only add the table
+ if parts[0] == "memory":
+ refs.append(parts[1])
+ else:
+ # It's a catalog and table, add both
+ 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:
@@ -337,5 +409,10 @@ def find_sql_refs(
i -= 1 # Compensate for outer loop increment
i += 1
+ # Re-use find_sql_defs to find referenced schemas and catalogs during creation.
+ defs = find_sql_defs(sql_statement)
+ refs.extend(defs.reffed_schemas)
+ refs.extend(defs.reffed_catalogs)
+
# Remove duplicates while preserving order
return list(dict.fromkeys(refs))
diff --git a/marimo/_ast/visitor.py b/marimo/_ast/visitor.py
index ea9949f1da..c2c11206d6 100644
--- a/marimo/_ast/visitor.py
+++ b/marimo/_ast/visitor.py
@@ -44,9 +44,16 @@ class ImportData:
@dataclass
class VariableData:
- # "table", "view", and "schema" are SQL variables, not Python.
+ # "table", "view", "schema", and "catalog" are SQL variables, not Python.
kind: Literal[
- "function", "class", "import", "variable", "table", "view", "schema"
+ "function",
+ "class",
+ "import",
+ "variable",
+ "table",
+ "view",
+ "schema",
+ "catalog",
] = "variable"
# If kind == function or class, it may be dependent on externally defined
@@ -72,6 +79,7 @@ class VariableData:
self.kind == "table"
or self.kind == "schema"
or self.kind == "view"
+ or self.kind == "catalog"
)
else "python"
)
@@ -519,6 +527,8 @@ class ScopedVisitor(ast.NodeVisitor):
self._define(None, _view, VariableData("view"))
for _schema in sql_defs.schemas:
self._define(None, _schema, VariableData("schema"))
+ for _catalog in sql_defs.catalogs:
+ self._define(None, _catalog, VariableData("catalog"))
# Visit arguments, keyword args, etc.
self.generic_visit(node)
diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.py
index e79b400a4c..a9dca7ca76 100644
--- a/marimo/_runtime/runtime.py
+++ b/marimo/_runtime/runtime.py
@@ -770,14 +770,14 @@ class Kernel:
duckdb.execute(f"DROP VIEW IF EXISTS memory.main.{name}")
except Exception as e:
LOGGER.warning("Failed to drop view %s: %s", name, str(e))
- elif variable.kind == "schema" and DependencyManager.duckdb.has():
+ elif variable.kind == "catalog" and DependencyManager.duckdb.has():
import duckdb
try:
duckdb.execute(f"DETACH DATABASE IF EXISTS {name}")
except Exception as e:
LOGGER.warning(
- "Failed to detach schema %s: %s", name, str(e)
+ "Failed to detach catalog %s: %s", name, str(e)
)
else:
if name in self.globals:
diff --git a/marimo/_smoke_tests/sql/local_db_deps.py b/marimo/_smoke_tests/sql/local_db_deps.py
new file mode 100644
index 0000000000..4fad5fba35
--- /dev/null
+++ b/marimo/_smoke_tests/sql/local_db_deps.py
@@ -0,0 +1,44 @@
+import marimo
+
+__generated_with = "0.9.16"
+app = marimo.App(width="medium")
+
+
+def __():
+ import marimo as mo
+ return (mo,)
+
+
+def __(mo):
+ _df = mo.sql(
+ f"""
+ ATTACH 'my_db.db' as my_db;
+ """
+ )
+ return (my_db,)
+
+
+def __(mo):
+ _df = mo.sql(
+ f"""
+ CREATE OR REPLACE TABLE my_db.my_table as (SELECT 42);
+ """
+ )
+ return
+
+
+def __(mo, my_db, my_table):
+ _df = mo.sql(
+ f"""
+ SELECT * FROM my_db.main.my_table LIMIT 100
+ """
+ )
+ return
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/tests/_ast/test_sql_visitor.py b/tests/_ast/test_sql_visitor.py
index 212b6958eb..3ab2c766b1 100644
--- a/tests/_ast/test_sql_visitor.py
+++ b/tests/_ast/test_sql_visitor.py
@@ -97,16 +97,12 @@ class TestFindSQLDefs:
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"],
- [],
- [],
+ tables=["test_table"],
)
sql = "CREATE VIEW test_view (id INT, name VARCHAR(255));"
assert find_sql_defs(sql) == SQLDefs(
- [],
- ["test_view"],
- [],
+ views=["test_view"],
)
@staticmethod
@@ -116,12 +112,10 @@ class TestFindSQLDefs:
CREATE TABLE table2 (name VARCHAR(255));
"""
assert find_sql_defs(sql) == SQLDefs(
- [
+ tables=[
"table1",
"table2",
],
- [],
- [],
)
sql = """
@@ -129,12 +123,10 @@ class TestFindSQLDefs:
CREATE VIEW table2 (name VARCHAR(255));
"""
assert find_sql_defs(sql) == SQLDefs(
- [],
- [
+ views=[
"table1",
"table2",
],
- [],
)
@staticmethod
@@ -149,12 +141,10 @@ class TestFindSQLDefs:
CREATE TABLE table2 (name VARCHAR(255));
"""
assert find_sql_defs(sql) == SQLDefs(
- [
+ tables=[
"table1",
"table2",
],
- [],
- [],
)
sql = """
@@ -167,60 +157,46 @@ class TestFindSQLDefs:
CREATE VIEW table2 (name VARCHAR(255));
"""
assert find_sql_defs(sql) == SQLDefs(
- [],
- [
+ views=[
"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"],
- [],
- [],
+ tables=["test_table"],
)
sql = "CREATE OR REPLACE VIEW test_view (id INT);"
assert find_sql_defs(sql) == SQLDefs(
- [],
- ["test_view"],
- [],
+ views=["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"],
- [],
- [],
+ tables=["temp_table"],
)
sql = "CREATE TEMPORARY VIEW temp_table (id INT);"
assert find_sql_defs(sql) == SQLDefs(
- [],
- ["temp_table"],
- [],
+ views=["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"],
- [],
- [],
+ tables=["new_table"],
)
sql = "CREATE VIEW IF NOT EXISTS new_table (id INT);"
assert find_sql_defs(sql) == SQLDefs(
- [],
- ["new_table"],
- [],
+ views=["new_table"],
)
@staticmethod
@@ -231,13 +207,11 @@ class TestFindSQLDefs:
CREATE TABLE table3 (date DATE);
""" # noqa: E501
assert find_sql_defs(sql) == SQLDefs(
- [
+ tables=[
"table1",
"table2",
"table3",
],
- [],
- [],
)
sql = """
@@ -246,34 +220,28 @@ class TestFindSQLDefs:
CREATE VIEW table3 (date DATE);
""" # noqa: E501
assert find_sql_defs(sql) == SQLDefs(
- [],
- [
+ views=[
"table1",
"table2",
"table3",
],
- [],
)
@staticmethod
def test_find_sql_defs_no_create() -> None:
sql = "SELECT * FROM existing_table;"
- assert find_sql_defs(sql) == SQLDefs([], [], [])
+ 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"],
- [],
- [],
+ tables=["Test_Table"],
)
sql = "create VIEW Test_Table (id INT);"
assert find_sql_defs(sql) == SQLDefs(
- [],
- ["Test_Table"],
- [],
+ views=["Test_Table"],
)
@staticmethod
@@ -288,11 +256,7 @@ class TestFindSQLDefs:
def test_find_sql_defs_empty_input(
query: str,
) -> None:
- assert find_sql_defs(query) == SQLDefs(
- [],
- [],
- [],
- )
+ assert find_sql_defs(query) == SQLDefs()
@staticmethod
@pytest.mark.parametrize(
@@ -339,9 +303,7 @@ class TestFindSQLDefs:
query: str,
) -> None:
assert find_sql_defs(query) == SQLDefs(
- ["my_table"],
- [],
- [],
+ tables=["my_table"],
)
@staticmethod
@@ -368,7 +330,7 @@ class TestFindSQLDefs:
CREATE TABLE e'escaped\ntable' (id INT);
"""
assert find_sql_defs(sql) == SQLDefs(
- [
+ tables=[
"my--table",
"my_table_with_select",
"my/*weird*/table",
@@ -376,44 +338,120 @@ class TestFindSQLDefs:
"single-quotes",
r"escaped\ntable",
],
- [],
- [],
)
@staticmethod
def test_find_created_database() -> None:
sql = "ATTACH 'Chinook.sqlite';"
assert find_sql_defs(sql) == SQLDefs(
- [],
- [],
- ["Chinook"],
+ catalogs=["Chinook"],
)
sql = "ATTACH 'Chinook.sqlite' AS my_db;"
assert find_sql_defs(sql) == SQLDefs(
- [],
- [],
- ["my_db"],
+ catalogs=["my_db"],
)
sql = "ATTACH DATABASE 'Chinook.sqlite';"
assert find_sql_defs(sql) == SQLDefs(
- [],
- [],
- ["Chinook"],
+ catalogs=["Chinook"],
)
sql = "ATTACH DATABASE IF NOT EXISTS 'Chinook.sqlite';"
assert find_sql_defs(sql) == SQLDefs(
- [],
- [],
- ["Chinook"],
+ catalogs=["Chinook"],
)
sql = "ATTACH DATABASE IF NOT EXISTS 'Chinook.sqlite' AS my_db;"
assert find_sql_defs(sql) == SQLDefs(
- [],
- [],
- ["my_db"],
+ catalogs=["my_db"],
+ )
+
+ @staticmethod
+ def test_find_sql_defs_with_catalog() -> None:
+ sql = """
+ CREATE TABLE my_catalog.my_table (id INT);
+ """
+ assert find_sql_defs(sql) == SQLDefs(
+ tables=["my_table"],
+ reffed_catalogs=["my_catalog"],
+ )
+
+ @staticmethod
+ def test_find_sql_defs_create_or_replace_with_catalog() -> None:
+ sql = """
+ CREATE OR REPLACE TABLE my_db.my_table as (SELECT 42);
+ """
+ assert find_sql_defs(sql) == SQLDefs(
+ tables=["my_table"],
+ reffed_catalogs=["my_db"],
+ )
+
+ @staticmethod
+ def test_find_sql_defs_with_catalog_and_schema() -> None:
+ sql = """
+ CREATE TABLE my_catalog.my_schema.my_table (id INT);
+ """
+ assert find_sql_defs(sql) == SQLDefs(
+ tables=["my_table"],
+ reffed_catalogs=["my_catalog"],
+ reffed_schemas=["my_schema"],
+ )
+
+ @staticmethod
+ def test_find_sql_defs_with_catalog_and_main() -> None:
+ sql = """
+ CREATE TABLE my_catalog.main.my_table (id INT);
+ """
+ assert find_sql_defs(sql) == SQLDefs(
+ tables=["my_table"],
+ reffed_catalogs=["my_catalog"],
+ reffed_schemas=[], # main not included, since that is the default
+ )
+
+ @staticmethod
+ def test_find_sql_defs_create_schema() -> None:
+ sql = """
+ CREATE SCHEMA my_catalog.my_schema;
+ """
+ assert find_sql_defs(sql) == SQLDefs(
+ schemas=["my_schema"],
+ reffed_catalogs=["my_catalog"],
+ )
+
+ @staticmethod
+ def test_find_sql_defs_with_in_memory_catalog_and_schema() -> None:
+ sql = """
+ CREATE TABLE memory.main.my_table (id INT);
+ """
+ assert find_sql_defs(sql) == SQLDefs(
+ tables=["my_table"],
+ )
+
+ @staticmethod
+ def test_find_sql_defs_with_in_memory_catalog() -> None:
+ sql = """
+ CREATE TABLE memory.my_table (id INT);
+ """
+ assert find_sql_defs(sql) == SQLDefs(
+ tables=["my_table"],
+ )
+
+ @staticmethod
+ def test_find_sql_defs_with_temp_table() -> None:
+ sql = """
+ CREATE TEMP TABLE my_temp_table (id INT);
+ """
+ assert find_sql_defs(sql) == SQLDefs(
+ tables=["my_temp_table"],
+ )
+
+ @staticmethod
+ def test_find_sql_defs_with_if_not_exists() -> None:
+ sql = """
+ CREATE TABLE IF NOT EXISTS my_table (id INT);
+ """
+ assert find_sql_defs(sql) == SQLDefs(
+ tables=["my_table"],
)
@@ -421,7 +459,7 @@ class TestFindSQLDefs:
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([], [], [])
+ assert find_sql_defs("CREATE TABLE test (id INT);") == SQLDefs()
@pytest.mark.skipif(not HAS_DUCKDB, reason="Missing DuckDB")