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.

improvement: Add "Hide outputs" to sql cells (#2326)

Myles Scolnickd8abf8edbe2f
diff --git a/frontend/src/core/codemirror/language/__tests__/sql.test.ts b/frontend/src/core/codemirror/language/__tests__/sql.test.ts
index f70578c7aa..846f882c00 100644
--- a/frontend/src/core/codemirror/language/__tests__/sql.test.ts
+++ b/frontend/src/core/codemirror/language/__tests__/sql.test.ts
@@ -89,6 +89,29 @@ describe("SQLLanguageAdapter", () => {
expect(innerCode).toBe("SELECT * FROM {df}");
expect(offset).toBe(22);
});
+
+ it("should handle output flag set to True", () => {
+ const pythonCode = '_df = mo.sql("""SELECT * FROM table""", output=True)';
+ const [innerCode, offset] = adapter.transformIn(pythonCode);
+ expect(innerCode).toBe("SELECT * FROM table");
+ expect(adapter.showOutput).toBe(true);
+ expect(offset).toBe(16);
+ });
+
+ it("should handle output flag set to False", () => {
+ const pythonCode =
+ '_df = mo.sql("""SELECT * FROM table""", output=False)';
+ const [innerCode, offset] = adapter.transformIn(pythonCode);
+ expect(innerCode).toBe("SELECT * FROM table");
+ expect(adapter.showOutput).toBe(false);
+ expect(offset).toBe(16);
+ });
+
+ it("should default to showing output when flag is not specified", () => {
+ const pythonCode = '_df = mo.sql("""SELECT * FROM table""")';
+ adapter.transformIn(pythonCode);
+ expect(adapter.showOutput).toBe(true);
+ });
});
describe("transformOut", () => {
@@ -106,6 +129,38 @@ describe("SQLLanguageAdapter", () => {
`);
expect(offset).toBe(26);
});
+
+ it("should include output flag when set to False", () => {
+ const code = "SELECT * FROM table";
+ adapter.lastQuotePrefix = "f";
+ adapter.dataframeName = "my_df";
+ adapter.showOutput = false;
+ const [wrappedCode, offset] = adapter.transformOut(code);
+ expect(wrappedCode).toMatchInlineSnapshot(`
+ "my_df = mo.sql(
+ f"""
+ SELECT * FROM table
+ """, output=False
+ )"
+ `);
+ expect(offset).toBe(26);
+ });
+
+ it("should not include output flag when set to True", () => {
+ const code = "SELECT * FROM table";
+ adapter.lastQuotePrefix = "f";
+ adapter.dataframeName = "my_df";
+ adapter.showOutput = true;
+ const [wrappedCode, offset] = adapter.transformOut(code);
+ expect(wrappedCode).toMatchInlineSnapshot(`
+ "my_df = mo.sql(
+ f"""
+ SELECT * FROM table
+ """
+ )"
+ `);
+ expect(offset).toBe(26);
+ });
});
describe("isSupported", () => {
@@ -134,5 +189,18 @@ describe("SQLLanguageAdapter", () => {
const pythonCode = [once, once].join("\n");
expect(adapter.isSupported(pythonCode)).toBe(false);
});
+
+ it("should support SQL strings with output flag", () => {
+ expect(
+ adapter.isSupported(
+ 'df = mo.sql("""SELECT * FROM table""", output=True)',
+ ),
+ ).toBe(true);
+ expect(
+ adapter.isSupported(
+ 'df = mo.sql("""SELECT * FROM table""", output=False)',
+ ),
+ ).toBe(true);
+ });
});
});
diff --git a/frontend/src/core/codemirror/language/panel.tsx b/frontend/src/core/codemirror/language/panel.tsx
index 12e6cabab7..6031b18276 100644
--- a/frontend/src/core/codemirror/language/panel.tsx
+++ b/frontend/src/core/codemirror/language/panel.tsx
@@ -11,43 +11,66 @@ export const LanguagePanelComponent: React.FC<{
const languageAdapter = view.state.field(languageAdapterState);
const { spanProps, inputProps } = useAutoGrowInputProps({ minWidth: 50 });
let actions: React.ReactNode = <div />;
+ let showDivider = false;
if (languageAdapter instanceof SQLLanguageAdapter) {
+ showDivider = true;
actions = (
- <div className="flex gap-2 relative">
- Output variable:{" "}
- <input
- {...inputProps}
- defaultValue={languageAdapter.dataframeName}
- onChange={(e) => {
- languageAdapter.dataframeName = e.target.value;
- inputProps.onChange?.(e);
- }}
- onBlur={(e) => {
- // Normalize the name to a valid variable name
- const name = normalizeName(e.target.value, false);
- languageAdapter.dataframeName = name;
- e.target.value = name;
+ <div className="flex flex-1 gap-2 relative items-center justify-between">
+ <label className="flex gap-2 items-center">
+ <span className="select-none">Output variable: </span>
+ <input
+ {...inputProps}
+ defaultValue={languageAdapter.dataframeName}
+ onChange={(e) => {
+ languageAdapter.dataframeName = e.target.value;
+ inputProps.onChange?.(e);
+ }}
+ onBlur={(e) => {
+ // Normalize the name to a valid variable name
+ const name = normalizeName(e.target.value, false);
+ languageAdapter.dataframeName = name;
+ e.target.value = name;
- // Send noop update code event, which will trigger an update to the new output variable name
- view.dispatch({
- changes: {
- from: 0,
- to: view.state.doc.length,
- insert: view.state.doc.toString(),
- },
- });
- }}
- className="min-w-14 w-auto border border-border rounded px-1 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
- />
- <span {...spanProps} />
+ // Send noop update code event, which will trigger an update to the new output variable name
+ view.dispatch({
+ changes: {
+ from: 0,
+ to: view.state.doc.length,
+ insert: view.state.doc.toString(),
+ },
+ });
+ }}
+ className="min-w-14 w-auto border border-border rounded px-1 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
+ />
+ <span {...spanProps} />
+ </label>
+ <label className="flex items-center gap-2">
+ <input
+ type="checkbox"
+ onChange={(e) => {
+ languageAdapter.showOutput = !e.target.checked;
+ // Trigger an update to reflect the change
+ view.dispatch({
+ changes: {
+ from: 0,
+ to: view.state.doc.length,
+ insert: view.state.doc.toString(),
+ },
+ });
+ }}
+ checked={!languageAdapter.showOutput}
+ />
+ <span className="select-none">Hide output</span>
+ </label>
</div>
);
}
return (
- <div className="flex justify-between px-2 pt-2">
+ <div className="flex justify-between items-center gap-4 px-2 pt-2">
{actions}
+ {showDivider && <div className="h-4 border-r border-border" />}
{languageAdapter.type}
</div>
);
diff --git a/frontend/src/core/codemirror/language/sql.ts b/frontend/src/core/codemirror/language/sql.ts
index c851a2548c..206d5887fa 100644
--- a/frontend/src/core/codemirror/language/sql.ts
+++ b/frontend/src/core/codemirror/language/sql.ts
@@ -35,11 +35,11 @@ const pairs = QUOTE_PREFIX_KINDS.flatMap((prefix) =>
const regexes = pairs.map(
([start, end]) =>
- // df = mo.sql( space + start + capture + space + end)
+ // df = mo.sql( space + start + capture + space + end, optional output flag)
[
start,
new RegExp(
- `^(?<dataframe>\\w*)\\s*=\\s*mo\\.sql\\(\\s*${start}(?<sql>.*)${end}\\s*\\)$`,
+ `^(?<dataframe>\\w*)\\s*=\\s*mo\\.sql\\(\\s*${start}(?<sql>.*)${end}\\s*(?:,\\s*output\\s*=\\s*(?<output>True|False))?\\s*\\)$`,
"s",
),
] as const,
@@ -55,6 +55,7 @@ export class SQLLanguageAdapter implements LanguageAdapter {
dataframeName = "_df";
lastQuotePrefix: QuotePrefixKind = "f";
+ showOutput = true;
transformIn(pythonCode: string): [string, number] {
if (!this.isSupported(pythonCode)) {
@@ -66,6 +67,7 @@ export class SQLLanguageAdapter implements LanguageAdapter {
// Handle empty strings
if (pythonCode === "") {
this.lastQuotePrefix = "f";
+ this.showOutput = true;
return ["", 0];
}
@@ -74,11 +76,13 @@ export class SQLLanguageAdapter implements LanguageAdapter {
if (match) {
const dataframe = match.groups?.dataframe || this.dataframeName;
const innerCode = match.groups?.sql || "";
+ const output = match.groups?.output;
const [quotePrefix, quoteType] = splitQuotePrefix(start);
// store the quote prefix for later when we transform out
this.lastQuotePrefix = quotePrefix;
this.dataframeName = dataframe;
+ this.showOutput = output === undefined ? true : output === "True";
const unescapedCode = innerCode.replaceAll(`\\${quoteType}`, quoteType);
const offset = pythonCode.indexOf(innerCode);
@@ -97,7 +101,7 @@ export class SQLLanguageAdapter implements LanguageAdapter {
// Multiline code
const start = `${this.dataframeName} = mo.sql(\n ${prefix}"""\n`;
const escapedCode = code.replaceAll('"""', String.raw`\"""`);
- const end = `\n """\n)`;
+ const end = `\n """${this.showOutput ? "" : ", output=False"}\n)`;
return [start + indentOneTab(escapedCode) + end, start.length + 1];
}
diff --git a/marimo/_sql/sql.py b/marimo/_sql/sql.py
index 303e0bb74e..35b0678c5c 100644
--- a/marimo/_sql/sql.py
+++ b/marimo/_sql/sql.py
@@ -7,11 +7,11 @@ from typing import Any, Literal, Optional, cast
from marimo._dependencies.dependencies import DependencyManager
from marimo._output.rich_help import mddoc
from marimo._plugins.ui._impl import table
-from marimo._runtime import output
from marimo._runtime.context.types import (
ContextNotInitializedError,
get_context,
)
+from marimo._runtime.output import replace
def get_default_result_limit() -> Optional[int]:
@@ -22,6 +22,7 @@ def get_default_result_limit() -> Optional[int]:
@mddoc
def sql(
query: str,
+ output: bool = True,
) -> Any:
"""
Execute a SQL query.
@@ -29,10 +30,11 @@ def sql(
This uses duckdb to execute the query. Any dataframes in the global
namespace can be used inside the query.
- The result of the query is displayed in the UI.
+ The result of the query is displayed in the UI if output is True.
Args:
query: The SQL query to execute.
+ output: Whether to display the result in the UI. Defaults to True.
Returns:
The result of the query.
@@ -101,14 +103,15 @@ def sql(
+ "You can install them with 'pip install pandas polars'"
)
- t = table.table(
- df,
- selection=None,
- page_size=5,
- pagination=True,
- _internal_total_rows=custom_total_count,
- )
- output.replace(t)
+ if output:
+ t = table.table(
+ df,
+ selection=None,
+ page_size=5,
+ pagination=True,
+ _internal_total_rows=custom_total_count,
+ )
+ replace(t)
return df
diff --git a/tests/_sql/test_sql.py b/tests/_sql/test_sql.py
index db78478aa1..e01b2b8e49 100644
--- a/tests/_sql/test_sql.py
+++ b/tests/_sql/test_sql.py
@@ -31,7 +31,7 @@ def test_query_includes_limit():
)
-@patch("marimo._sql.sql.output.replace")
+@patch("marimo._sql.sql.replace")
@pytest.mark.skipif(not HAS_DEPS, reason="polars and duckdb is required")
def test_applies_limit(mock_replace: MagicMock) -> None:
import duckdb
@@ -90,3 +90,36 @@ def test_applies_limit(mock_replace: MagicMock) -> None:
def test_sql_raises_error_without_duckdb():
with pytest.raises(ModuleNotFoundError):
sql("SELECT * FROM t")
+
+
+@patch("marimo._sql.sql.replace")
[email protected](not HAS_DEPS, reason="polars and duckdb is required")
+def test_sql_output_flag(mock_replace: MagicMock) -> None:
+ import duckdb
+ import polars as pl
+
+ from marimo._sql.sql import sql
+
+ # Create a test table
+ duckdb.sql("CREATE TABLE test_table AS SELECT * FROM range(10)")
+
+ # Test when output is None (default, True)
+ result = sql("SELECT * FROM test_table")
+ assert isinstance(result, pl.DataFrame)
+ mock_replace.assert_called_once()
+ mock_replace.reset_mock()
+
+ # Test when output is False
+ result = sql("SELECT * FROM test_table", output=False)
+ assert isinstance(result, pl.DataFrame)
+ mock_replace.assert_not_called()
+ mock_replace.reset_mock()
+
+ # Test when output is True
+ result = sql("SELECT * FROM test_table", output=True)
+ assert isinstance(result, pl.DataFrame)
+ mock_replace.assert_called_once()
+ mock_replace.reset_mock()
+
+ # Clean up
+ duckdb.sql("DROP TABLE test_table")