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.

feat: Render mermaid-based (optimized) query plan for `pl.LazyFrame` (#5247)

Trevor Manze924a6859b89
diff --git a/marimo/_output/formatters/df_formatters.py b/marimo/_output/formatters/df_formatters.py
index bc0dc69e17..16a03c283c 100644
--- a/marimo/_output/formatters/df_formatters.py
+++ b/marimo/_output/formatters/df_formatters.py
@@ -2,6 +2,7 @@
from __future__ import annotations
import os
+import re
import narwhals.stable.v1 as nw
@@ -11,7 +12,7 @@ from marimo._output.formatters.formatter_factory import (
FormatterFactory,
Unregister,
)
-from marimo._output.md import md
+from marimo._plugins.stateless.mermaid import mermaid
from marimo._plugins.ui._impl import tabs
from marimo._plugins.ui._impl.table import get_default_table_page_size, table
from marimo._runtime.patches import patch_polars_write_json
@@ -34,6 +35,43 @@ def include_opinionated() -> bool:
return True
+def polars_dot_to_mermaid(dot: str) -> str:
+ """Converts polars DOT query plan renderings to mermaid.
+
+ Adapted from https://github.com/pola-rs/polars/pull/20607
+ Note: Not comprehensive, only handles components of the dot language used by polars.
+ """
+
+ edge_regex = r"(?P<node1>\w+) -- (?P<node2>\w+)"
+ node_regex = r"(?P<node>\w+)(\s+)?\[label=\"(?P<label>.*)\"]"
+
+ nodes = re.finditer(node_regex, dot)
+ edges = re.finditer(edge_regex, dot)
+
+ mermaid_str = "\n".join(
+ [
+ "graph TD",
+ *[f'\t{n["node"]}["{n["label"]}"]' for n in nodes],
+ *[f"\t{e['node1']} --- {e['node2']}" for e in edges],
+ ]
+ )
+
+ # replace [https://...] with <a> tags to avoid Mermaid interpreting it as markdown
+ mermaid_str = re.sub(
+ r"\[(https?://[^\]]+)\]",
+ lambda m: f"[<a href='{m.group(1)}'>{m.group(1)}</a>]",
+ mermaid_str,
+ )
+
+ # replace escaped newlines
+ mermaid_str = mermaid_str.replace(r"\n", "\n")
+
+ # replace escaped quotes
+ mermaid_str = mermaid_str.replace(r"\"", "#quot;")
+
+ return mermaid_str
+
+
class PolarsFormatter(FormatterFactory):
@staticmethod
def package_name() -> str:
@@ -80,8 +118,14 @@ class PolarsFormatter(FormatterFactory):
) -> tuple[KnownMimeType, str]:
return tabs.tabs(
{
+ # NB(Trevor): Use `optimized=True` to match other methods' defaults (`show_graph`, `collect`).
+ # The _repr_html_ uses `optimized=False`, but "cost" is probably minimal and this is more
+ # accurate/opinionated default.
+ # See: https://github.com/pola-rs/polars/blob/911352/py-polars/polars/lazyframe/frame.py#L773-L790
+ "Query plan": mermaid(
+ polars_dot_to_mermaid(df._ldf.to_dot(optimized=True))
+ ),
"Table": table.lazy(df),
- "Query plan": md(df._repr_html_()),
}
)._mime_()
diff --git a/tests/_output/formatters/test_formatters.py b/tests/_output/formatters/test_formatters.py
index 9efec01c7e..8fc665f457 100644
--- a/tests/_output/formatters/test_formatters.py
+++ b/tests/_output/formatters/test_formatters.py
@@ -10,6 +10,7 @@ import pytest
from marimo._dependencies.dependencies import DependencyManager
from marimo._messaging.mimetypes import KnownMimeType
+from marimo._output.formatters.df_formatters import polars_dot_to_mermaid
from marimo._output.formatters.formatters import register_formatters
from marimo._output.formatting import (
Plain,
@@ -457,3 +458,65 @@ def test_display_protocol_takes_precedence() -> None:
mime, content = formatter(obj)
assert mime == "text/html"
assert content == "<span>foo</span>"
+
+
[email protected](not HAS_DEPS, reason="optional dependencies not installed")
+def test_lazyframe_renders_mermaid_html() -> None:
+ register_formatters()
+
+ import polars as pl
+
+ ldf = pl.DataFrame({"A": [1, 2, 3], "B": ["a", "a", "a"]}).lazy()
+
+ formatter = get_formatter(ldf)
+ assert formatter is not None
+ mimetype, contents = formatter(ldf)
+ assert mimetype == "text/html"
+ assert "<marimo-mermaid" in contents
+
+
[email protected](not HAS_DEPS, reason="optional dependencies not installed")
+def test_polars_dot_to_mermaid() -> None:
+ import polars as pl
+
+ ldf = pl.DataFrame({"A": [1, 2, 3], "B": ["a", "a", "a"]}).lazy()
+
+ result = polars_dot_to_mermaid(ldf._ldf.to_dot(optimized=True))
+ assert result == 'graph TD\n\tp1["TABLE\nπ */2"]'
+
+
[email protected](not HAS_DEPS, reason="optional dependencies not installed")
+def test_polars_dot_to_mermaid_complex() -> None:
+ import polars as pl
+
+ ldf = (
+ pl.DataFrame({"A": [1, 2, 3], "B": ["a", "b", "c"]})
+ .lazy()
+ .filter(pl.col("A") > 1)
+ .select(pl.col("A"), pl.col("B").alias("B_renamed"))
+ .join(pl.DataFrame({"A": [1]}).lazy(), on="A")
+ )
+
+ assert (
+ polars_dot_to_mermaid(ldf._ldf.to_dot(optimized=True))
+ == """graph TD
+\tp4["TABLE\nπ 2/2"]
+\tp3["FILTER BY [(col(#quot;A#quot;)) > (1)]"]
+\tp2["π 2/2"]
+\tp5["TABLE\nπ */1"]
+\tp1["JOIN INNER\nleft: [col(#quot;A#quot;)];\nright: [col(#quot;A#quot;)]"]
+\tp1 --- p2
+\tp2 --- p3
+\tp3 --- p4
+\tp1 --- p5"""
+ )
+
+
+def test_polars_dot_to_mermaid_handles_urls() -> None:
+ assert (
+ polars_dot_to_mermaid("""graph polars_query {
+ p1[label="Check [https://example.com] for more"]
+}""")
+ == """graph TD
+\tp1[\"Check [<a href='https://example.com'>https://example.com</a>] for more\"]"""
+ )