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.

strips explain, better error output for sql error (#6518)

Shahmir Varqhadbf3528fc075
diff --git a/frontend/src/components/editor/Cell.tsx b/frontend/src/components/editor/Cell.tsx
index 27b1ee579f..1c22f8c577 100644
--- a/frontend/src/components/editor/Cell.tsx
+++ b/frontend/src/components/editor/Cell.tsx
@@ -451,6 +451,7 @@ const EditableCellComponent = ({
});
const canCollapse = canCollapseOutline(cellRuntime.outline);
const hasOutput = !isOutputEmpty(cellRuntime.output);
+ const isStaleCell = outputIsStale(cellRuntime, cellData.edited);
const hasConsoleOutput = cellRuntime.consoleOutputs.length > 0;
const cellOutput = userConfig.display.cell_output;
@@ -511,7 +512,7 @@ const EditableCellComponent = ({
className="output-area"
cellId={cellId}
output={cellRuntime.output}
- stale={outputIsStale(cellRuntime, cellData.edited)}
+ stale={isStaleCell}
loading={outputIsLoading(cellRuntime.status)}
/>
{isMarkdownCodeHidden &&
@@ -654,7 +655,10 @@ const EditableCellComponent = ({
)}
</div>
</div>
- <SqlValidationErrorBanner cellId={cellId} />
+ <SqlValidationErrorBanner
+ cellId={cellId}
+ hide={cellRuntime.errored && !isStaleCell}
+ />
{cellOutput === "below" && outputArea}
{cellRuntime.serialization && (
<div className="py-1 px-2 flex items-center justify-end gap-2 last:rounded-b">
diff --git a/frontend/src/components/editor/errors/sql-validation-errors.tsx b/frontend/src/components/editor/errors/sql-validation-errors.tsx
index 835be89321..d9e89e8fc0 100644
--- a/frontend/src/components/editor/errors/sql-validation-errors.tsx
+++ b/frontend/src/components/editor/errors/sql-validation-errors.tsx
@@ -4,27 +4,33 @@ import { AlertCircleIcon } from "lucide-react";
import type { CellId } from "@/core/cells/ids";
import { useSqlValidationErrorsForCell } from "@/core/codemirror/language/languages/sql/validation-errors";
-export const SqlValidationErrorBanner = ({ cellId }: { cellId: CellId }) => {
+export const SqlValidationErrorBanner = ({
+ cellId,
+ hide,
+}: {
+ cellId: CellId;
+ hide: boolean;
+}) => {
const error = useSqlValidationErrorsForCell(cellId);
- if (!error) {
+ if (!error || hide) {
return;
}
return (
- <div className="p-3 text-sm flex flex-col text-muted-foreground gap-1.5 bg-destructive/5">
+ <div className="p-3 text-sm flex flex-col text-muted-foreground gap-1.5 bg-destructive/4">
<div className="flex items-start gap-1.5">
<AlertCircleIcon size={13} className="mt-[3px] text-destructive" />
<p>
<span className="font-bold text-destructive">{error.errorType}:</span>{" "}
- {error.errorMessage}
+ <span className="whitespace-pre-wrap">{error.errorMessage}</span>
</p>
</div>
{error.codeblock && (
<pre
lang="sql"
- className="text-xs bg-muted rounded p-2 pb-0 mx-3 overflow-x-auto font-mono whitespace-pre-wrap"
+ className="text-xs bg-muted/80 rounded p-2 pb-0 mx-3 font-medium whitespace-pre-wrap"
>
{error.codeblock}
</pre>
diff --git a/frontend/src/components/editor/output/MarimoErrorOutput.tsx b/frontend/src/components/editor/output/MarimoErrorOutput.tsx
index 5891b14994..f460b4cb90 100644
--- a/frontend/src/components/editor/output/MarimoErrorOutput.tsx
+++ b/frontend/src/components/editor/output/MarimoErrorOutput.tsx
@@ -77,7 +77,7 @@ export const MarimoErrorOutput = ({
alertVariant = "default";
titleColor = "text-secondary-foreground";
} else if (errors.some((e) => e.type === "sql-error")) {
- titleContents = "SQL Error in statement";
+ titleContents = "SQL error";
} else {
// Check for exception type
const exceptionError = errors.find((e) => e.type === "exception");
@@ -504,22 +504,26 @@ export const MarimoErrorOutput = ({
const col =
error.sql_col == null ? null : Math.trunc(error?.sql_col) + 1;
return (
- <div key={`sql-error-${idx}`} className="space-y-2">
- <p className="text-muted-foreground">{error.msg}</p>
+ <div key={`sql-error-${idx}`} className="space-y-2 mt-2">
+ <p className="text-muted-foreground font-medium">{error.msg}</p>
{error.hint && (
<div className="flex items-start gap-2">
- <InfoIcon className="h-4 w-4 text-muted-foreground mt-0.5 flex-shrink-0" />
- <pre className="whitespace-pre-wrap text-sm text-muted-foreground">
+ <InfoIcon
+ size={11}
+ className="text-muted-foreground mt-1 flex-shrink-0"
+ />
+ <p className="whitespace-pre-wrap text-sm text-muted-foreground">
{error.hint}
- </pre>
+ </p>
</div>
)}
{error.sql_statement && (
- <div className="bg-muted/50 p-2 rounded text-xs font-mono">
- <pre className="whitespace-pre-wrap">
- {error.sql_statement}
- </pre>
- </div>
+ <pre
+ lang="sql"
+ className="text-xs bg-muted/80 rounded whitespace-pre-wrap p-3.5"
+ >
+ {error.sql_statement.trim()}
+ </pre>
)}
{line !== null && col !== null && (
<p className="text-xs text-muted-foreground">
@@ -530,17 +534,6 @@ export const MarimoErrorOutput = ({
);
})}
{cellId && <AutoFixButton errors={sqlErrors} cellId={cellId} />}
- <Tip title="How to fix SQL errors">
- <p className="pb-2">
- SQL parsing errors often occur due to invalid syntax, missing
- keywords, or unsupported SQL features.
- </p>
- <p className="py-2">
- Check your SQL syntax and ensure you're using supported SQL
- dialect features. The error location can help you identify the
- problematic part of your query.
- </p>
- </Tip>
</div>,
);
}
diff --git a/marimo/_smoke_tests/sql_error_handling.py b/marimo/_smoke_tests/sql_error_handling.py
index bc6d3f66e4..07ac10f8e2 100644
--- a/marimo/_smoke_tests/sql_error_handling.py
+++ b/marimo/_smoke_tests/sql_error_handling.py
@@ -396,12 +396,34 @@ def _(用户表):
)
return
[email protected](hide_code=True)
+def _():
+ mo.md(
+ r"""
+ ## 11. Multiple Statements
+
+ Test sql cells with multiple queries
+ """
+ )
+ return
+
+
+def _(users):
+ _df = mo.sql(
+ f"""
+ SELECT * FROM users;
+ SELECT names FROM users
+ """
+ )
+ return
+
@app.cell(hide_code=True)
def _():
mo.md(
"""
- ## 10. Successful Query for Comparison
+ ## 12. Successful Query for Comparison
Here's a working query to show the contrast with error handling.
"""
diff --git a/marimo/_sql/engines/types.py b/marimo/_sql/engines/types.py
index 7097a3f416..a0eb89b9a8 100644
--- a/marimo/_sql/engines/types.py
+++ b/marimo/_sql/engines/types.py
@@ -13,7 +13,11 @@ from marimo._runtime.context.types import (
get_context,
runtime_context_installed,
)
-from marimo._sql.utils import is_query_empty, wrap_query_with_explain
+from marimo._sql.utils import (
+ is_query_empty,
+ strip_explain_from_error_message,
+ wrap_query_with_explain,
+)
from marimo._types.ids import VariableName
NO_SCHEMA_NAME = ""
@@ -143,7 +147,7 @@ class QueryEngine(BaseEngine[CONN], ABC):
except Exception as e:
if is_query_empty(query):
return None, None
- return None, str(e)
+ return None, strip_explain_from_error_message(str(e))
class SQLConnection(EngineCatalog[CONN], QueryEngine[CONN]):
diff --git a/marimo/_sql/utils.py b/marimo/_sql/utils.py
index c19c1e8dfc..ce3aa7dab1 100644
--- a/marimo/_sql/utils.py
+++ b/marimo/_sql/utils.py
@@ -262,3 +262,43 @@ def extract_explain_content(df: Any) -> str:
except Exception as e:
LOGGER.debug("Failed to extract explain content: %s", e)
return repr(df)
+
+
+def strip_explain_from_error_message(error_message: str) -> str:
+ """Strip EXPLAIN from an error message. Also adjusts the caret position
+
+ Example:
+ ```
+ LINE 1: EXPLAIN SELECT * FROM t
+ ^
+ ```
+ becomes
+ ```
+ LINE 1: SELECT * FROM t
+ ^
+ ```
+ """
+ # Find the first occurrence of "EXPLAIN " and replace it
+ explain_pos = error_message.find("EXPLAIN ")
+ if explain_pos == -1:
+ return error_message
+
+ explain_length = len("EXPLAIN ")
+
+ # Replace the first "EXPLAIN " with empty string
+ result = (
+ error_message[:explain_pos]
+ + error_message[explain_pos + explain_length :]
+ )
+
+ # Find the next newline and strip the same amount from the next line
+ next_newline = result.find("\n", explain_pos)
+ if next_newline != -1 and next_newline + explain_length < len(result):
+ # Remove the same length from the beginning of the next line
+ # This is the caret position
+ result = (
+ result[: next_newline + 1]
+ + result[next_newline + 1 + explain_length :]
+ )
+
+ return result
diff --git a/tests/_sql/test_sql.py b/tests/_sql/test_sql.py
index 3726358569..83b7a24a57 100644
--- a/tests/_sql/test_sql.py
+++ b/tests/_sql/test_sql.py
@@ -17,6 +17,7 @@ from marimo._sql.utils import (
extract_explain_content,
is_explain_query,
is_query_empty,
+ strip_explain_from_error_message,
wrap_query_with_explain,
)
@@ -568,3 +569,59 @@ logical_plan
# Invalid SQL
assert is_query_empty("NOT A VALID SQL QUERY") is False
assert is_query_empty("SELECT * FROM t WHERE x = '") is False
+
+ def test_strip_explain_from_error_message(self):
+ """Test strip_explain_from_error_message function."""
+ # Basic case - simple EXPLAIN removal
+ assert (
+ strip_explain_from_error_message("EXPLAIN SELECT * FROM t")
+ == "SELECT * FROM t"
+ )
+
+ # Case insensitive - should not match lowercase
+ assert (
+ strip_explain_from_error_message("explain SELECT * FROM t")
+ == "explain SELECT * FROM t"
+ )
+
+ # Error message with caret position adjustment
+ error_message = """
+LINE 1: EXPLAIN SELECT * FROM pokemons
+ ^
+"""
+ assert (
+ strip_explain_from_error_message(error_message)
+ == """
+LINE 1: SELECT * FROM pokemons
+ ^
+"""
+ )
+
+ # No EXPLAIN - should return unchanged
+ assert (
+ strip_explain_from_error_message("SELECT * FROM t")
+ == "SELECT * FROM t"
+ )
+
+ # Empty string
+ assert strip_explain_from_error_message("") == ""
+
+ # Multiple EXPLAIN occurrences - should only remove first
+ assert (
+ strip_explain_from_error_message("EXPLAIN EXPLAIN SELECT * FROM t")
+ == "EXPLAIN SELECT * FROM t"
+ )
+
+ # EXPLAIN at end of line with no next line
+ assert strip_explain_from_error_message("Error: EXPLAIN ") == "Error: "
+
+ # EXPLAIN with multiline error and caret
+ multiline_error = """Syntax error at line 1:
+EXPLAIN SELECT * FROM users WHERE
+ ^
+Expected 'FROM' keyword"""
+ expected = """Syntax error at line 1:
+SELECT * FROM users WHERE
+ ^
+Expected 'FROM' keyword"""
+ assert strip_explain_from_error_message(multiline_error) == expected