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.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
feat: Wrap and pass SQL Errors (#6498)
Dylan Madisettie2e1556efb30
diff --git a/frontend/src/components/editor/output/MarimoErrorOutput.tsx b/frontend/src/components/editor/output/MarimoErrorOutput.tsxindex a8a38e2d60..a73059aa14 100644--- a/frontend/src/components/editor/output/MarimoErrorOutput.tsx+++ b/frontend/src/components/editor/output/MarimoErrorOutput.tsx@@ -1,6 +1,10 @@/* Copyright 2024 Marimo. All rights reserved. */-import { NotebookPenIcon, SquareArrowOutUpRightIcon } from "lucide-react";+import {+ InfoIcon,+ NotebookPenIcon,+ SquareArrowOutUpRightIcon,+} from "lucide-react";import { Fragment, type JSX } from "react";import {Accordion,@@ -72,6 +76,8 @@ export const MarimoErrorOutput = ({titleContents = "Ancestor stopped";alertVariant = "default";titleColor = "text-secondary-foreground";+ } else if (errors.some((e) => e.type === "sql-error")) {+ titleContents = "SQL Error in statement";} else {// Check for exception typeconst exceptionError = errors.find((e) => e.type === "exception");@@ -126,6 +132,10 @@ export const MarimoErrorOutput = ({const unknownErrors = errors.filter((e): e is Extract<MarimoError, { type: "unknown" }> => e.type === "unknown",);+ const sqlErrors = errors.filter(+ (e): e is Extract<MarimoError, { type: "sql-error" }> =>+ e.type === "sql-error",+ );const openScratchpad = () => {chromeActions.openApplication("scratchpad");@@ -485,6 +495,55 @@ export const MarimoErrorOutput = ({);}+ if (sqlErrors.length > 0) {+ messages.push(+ <div key="sql-errors">+ {sqlErrors.map((error, idx) => {+ const line =+ error.sql_line != null ? (error?.sql_line | 0) + 1 : null;+ const col = error.sql_col != null ? (error?.sql_col | 0) + 1 : null;+ return (+ <div key={`sql-error-${idx}`} className="space-y-2">+ <p className="text-muted-foreground">{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">+ {error.hint}+ </pre>+ </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>+ )}+ {line !== null && col !== null && (+ <p className="text-xs text-muted-foreground">+ Error at line {line}, column {col}+ </p>+ )}+ </div>+ );+ })}+ {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>,+ );+ }+return messages;};diff --git a/marimo/_ast/sql_utils.py b/marimo/_ast/sql_utils.pyindex 52b06cd981..4b06e6202d 100644--- a/marimo/_ast/sql_utils.py+++ b/marimo/_ast/sql_utils.py@@ -1,11 +1,10 @@# Copyright 2025 Marimo. All rights reserved.-import ast-import re-from typing import Callable, Literal, Optional, TypedDict, Union+from typing import Literal, Optional, Unionfrom marimo import _loggersfrom marimo._dependencies.dependencies import DependencyManager+from marimo._sql.error_utils import log_sql_errorLOGGER = _loggers.marimo_logger()@@ -19,20 +18,6 @@ SQLGLOT_DIALECTS = Literal[]-class SQLErrorMetadata(TypedDict):- """Structured metadata for SQL parsing errors."""-- lint_rule: str- error_type: str- clean_message: str # Just the meaningful error without SQL trace- node_lineno: int- node_col_offset: int- sql_statement: str # Truncated if needed- sql_line: Optional[int] # 0-based line within SQL- sql_col: Optional[int] # 0-based column within SQL- context: str--def classify_sql_statement(sql_statement: str, dialect: Optional[SQLGLOT_DIALECTS] = None) -> Union[SQL_TYPE, Literal["unknown"]]:@@ -75,45 +60,3 @@ def classify_sql_statement(return "DQL"return "unknown"---def log_sql_error(- logger: Callable[..., None],- *,- message: str,- exception: BaseException,- rule_code: str,- node: Optional[ast.expr] = None,- sql_content: str = "",- context: str = "",-) -> None:- """Utility to log SQL-related errors with consistent metadata."""- # Parse SQL position from exception message if available- sql_line = None- sql_col = None-- exception_msg = str(exception)- line_col_match = re.search(r"Line (\d+), Col: (\d+)", exception_msg)- if line_col_match:- sql_line = int(line_col_match.group(1)) - 1 # Convert to 0-based- sql_col = int(line_col_match.group(2)) - 1 # Convert to 0-based-- # Truncate long SQL content- truncated_sql = sql_content- if sql_content and len(sql_content) > 200:- truncated_sql = sql_content[:200] + "..."-- # Create metadata using TypedDict- metadata: SQLErrorMetadata = {- "lint_rule": rule_code,- "error_type": type(exception).__name__,- "clean_message": exception_msg.split("\n", 1)[0],- "node_lineno": node.lineno if node else 0,- "node_col_offset": node.col_offset if node else 0,- "sql_statement": truncated_sql,- "sql_line": sql_line,- "sql_col": sql_col,- "context": context,- }-- logger(message, exception, extra=metadata)diff --git a/marimo/_ast/visitor.py b/marimo/_ast/visitor.pyindex bb2951692c..8fa5bb09d7 100644--- a/marimo/_ast/visitor.py+++ b/marimo/_ast/visitor.py@@ -12,7 +12,6 @@ from uuid import uuid4from marimo import _loggersfrom marimo._ast.errors import ImportStarError-from marimo._ast.sql_utils import log_sql_errorfrom marimo._ast.sql_visitor import (SQLDefs,SQLKind,@@ -23,6 +22,7 @@ from marimo._ast.sql_visitor import ()from marimo._ast.variables import is_localfrom marimo._dependencies.dependencies import DependencyManager+from marimo._sql.error_utils import log_sql_errorfrom marimo._utils.strings import standardize_annotation_quotesLOGGER = _loggers.marimo_logger()diff --git a/marimo/_messaging/errors.py b/marimo/_messaging/errors.pyindex 62e2830eef..f8f44b5fa1 100644--- a/marimo/_messaging/errors.py+++ b/marimo/_messaging/errors.py@@ -113,6 +113,25 @@ class MarimoInternalError(msgspec.Struct, tag="internal"):return self.msg+class MarimoSQLError(msgspec.Struct, tag="sql-error"):+ """+ SQL-specific error with enhanced metadata for debugging.+ """++ msg: str+ sql_statement: str+ hint: Optional[str] = (+ None # Helpful hints like "Did you mean?" or "Candidate bindings"+ )+ sql_line: Optional[int] = None # 0-based line within SQL+ sql_col: Optional[int] = None # 0-based column within SQL+ node_lineno: int = 0+ node_col_offset: int = 0++ def describe(self) -> str:+ return self.msg++def is_unexpected_error(error: Error) -> bool:"""These errors are unexpected, in that they are not intentional.@@ -154,5 +173,6 @@ Error = Union[MarimoInterruptionError,MarimoSyntaxError,MarimoInternalError,+ MarimoSQLError,UnknownError,]diff --git a/marimo/_runtime/runner/cell_runner.py b/marimo/_runtime/runner/cell_runner.pyindex 8c81110786..78e2913c8d 100644--- a/marimo/_runtime/runner/cell_runner.py+++ b/marimo/_runtime/runner/cell_runner.py@@ -38,6 +38,10 @@ from marimo._runtime.executor import (get_executor,)from marimo._runtime.marimo_pdb import MarimoPdb+from marimo._sql.error_utils import (+ create_sql_error_from_exception,+ is_sql_parse_error,+)from marimo._types.ids import CellId_tLOGGER = marimo_logger()@@ -403,6 +407,13 @@ class Runner:exception = outputexcept Exception:pass+ # Handle SQL parsing errors+ elif unwrapped_exception is not None and is_sql_parse_error(+ unwrapped_exception+ ):+ cell = self.graph.cells[cell_id]+ output = create_sql_error_from_exception(unwrapped_exception, cell)+ exception = outputelif isinstance(unwrapped_exception, MarimoStopError):output = unwrapped_exception.outputexception = unwrapped_exceptiondiff --git a/marimo/_runtime/runner/hooks_post_execution.py b/marimo/_runtime/runner/hooks_post_execution.pyindex 6d1396905e..9c31c0f080 100644--- a/marimo/_runtime/runner/hooks_post_execution.py+++ b/marimo/_runtime/runner/hooks_post_execution.py@@ -16,6 +16,7 @@ from marimo._messaging.cell_output import CellChannelfrom marimo._messaging.errors import (MarimoExceptionRaisedError,MarimoInterruptionError,+ MarimoSQLError,MarimoStrictExecutionError,)from marimo._messaging.ops import (@@ -333,6 +334,13 @@ def _broadcast_outputs(clear_console=False,cell_id=cell.cell_id,)+ elif isinstance(run_result.exception, MarimoSQLError):+ LOGGER.debug("Cell %s raised a SQL error", cell.cell_id)+ CellOp.broadcast_error(+ data=[run_result.exception],+ clear_console=True,+ cell_id=cell.cell_id,+ )elif run_result.exception is not None:LOGGER.debug("Cell %s raised %s",diff --git a/marimo/_smoke_tests/sql_error_handling.py b/marimo/_smoke_tests/sql_error_handling.pynew file mode 100644index 0000000000..bc6d3f66e4--- /dev/null+++ b/marimo/_smoke_tests/sql_error_handling.py@@ -0,0 +1,449 @@+# /// script+# requires-python = ">=3.11"+# dependencies = [+# "duckdb",+# "marimo",+# ]+# ///+# Copyright 2025 Marimo. All rights reserved.++import marimo++__generated_with = "0.16.1"+app = marimo.App(width="medium")++with app.setup(hide_code=True):+ import marimo as mo+ import duckdb++[email protected](hide_code=True)+def _():+ mo.md(+ """+ # SQL Error Handling Smoke Test++ This notebook demonstrates marimo's SQL error handling capabilities across different types of SQL errors.+ Each section shows how marimo gracefully handles SQL errors with helpful error messages.+ """+ )+ return++[email protected](hide_code=True)+def _():+ mo.md(+ """+ ## Setup Test Data++ First, let's create some test data to work with.+ """+ )+ return+++def _():+ # Create test data for our error examples+ test_setup = mo.sql(+ f"""+ CREATE OR REPLACE TABLE users (+ id INTEGER,+ name TEXT,+ email TEXT,+ age INTEGER+ )+ """+ )+ return (users,)+++def _(users):+ _df = mo.sql(+ f"""+ INSERT INTO users VALUES+ (1, 'Alice', '[email protected]', 25),+ (2, 'Bob', '[email protected]', 30),+ (3, 'Charlie', '[email protected]', 35)+ """+ )+ return++[email protected](hide_code=True)+def _():+ mo.md(+ """+ ## 1. Table Not Found Errors++ DuckDB provides helpful suggestions when table names don't exist.+ """+ )+ return+++def _(user):+ _df = mo.sql(+ f"""+ -- This will show "Table with name 'user' does not exist! Did you mean 'users'?"+ select * from user+ """+ )+ return+++def _(user_table):+ _df = mo.sql(+ f"""+ -- Another table typo example - completely wrong name+ SELECT * FROM user_table+ """+ )+ return++[email protected](hide_code=True)+def _():+ mo.md(+ """+ ## 2. Column Not Found Errors++ Column reference errors with candidate suggestions.+ """+ )+ return+++def _(users):+ _df = mo.sql(+ f"""+ -- This will show column not found with candidates+ -- Should be 'name' instead of 'user_name'+ SELECT user_name FROM users+ """+ )+ return+++def _(users):+ _df = mo.sql(+ f"""+ -- Another column error+ -- Should be 'name' instead of 'fullname'+ SELECT id, fullname, email FROM users+ """+ )+ return++[email protected](hide_code=True)+def _():+ mo.md(+ """+ ## 3. SQL Syntax Errors++ Various syntax errors with position information.+ """+ )+ return+++def _():+ _df = mo.sql(+ f"""+ -- Missing FROM keyword (FRM instead of FROM)+ SELECT * FRM users+ """+ )+ return+++def _():+ _df = mo.sql(+ f"""+ -- Malformed parentheses+ SELECT ( FROM users+ """+ )+ return+++def _():+ _df = mo.sql(+ f"""+ -- Invalid WHERE clause - missing condition+ SELECT * FROM users WHERE+ """+ )+ return+++def _():+ _df = mo.sql(+ f"""+ -- Multiple FROM clauses - invalid syntax+ SELECT * FROM users FROM users+ """+ )+ return++[email protected](hide_code=True)+def _():+ mo.md(+ """+ ## 4. Data Type Errors++ Type mismatch and conversion errors.+ """+ )+ return+++def _(users):+ _df = mo.sql(+ f"""+ -- Type conversion error - can't divide number by string+ SELECT age / 'invalid_string' FROM users+ """+ )+ return+++def _(users):+ _df = mo.sql(+ f"""+ -- String comparison with number - type mismatch+ SELECT * FROM users WHERE name > 123+ """+ )+ return++[email protected](hide_code=True)+def _():+ mo.md(+ """+ ## 5. Function Errors++ Function call errors and argument mismatches.+ """+ )+ return+++def _(users):+ _df = mo.sql(+ f"""+ -- Invalid function name+ SELECT INVALID_FUNCTION(name) FROM users+ """+ )+ return+++def _(users):+ _df = mo.sql(+ f"""+ -- Wrong number of arguments for SUBSTRING+ -- Missing start position and length parameters+ SELECT SUBSTRING(name) FROM users+ """+ )+ return++[email protected](hide_code=True)+def _():+ mo.md(+ """+ ## 6. Aggregate Function Errors++ GROUP BY and aggregate function errors.+ """+ )+ return+++def _(users):+ _df = mo.sql(+ f"""+ -- Missing GROUP BY for non-aggregated column+ -- 'name' should be in GROUP BY when using COUNT(*)+ SELECT name, COUNT(*) FROM users+ """+ )+ return+++def _(users):+ _df = mo.sql(+ f"""+ -- Invalid HAVING without GROUP BY+ SELECT * FROM users HAVING COUNT(*) > 1+ """+ )+ return++[email protected](hide_code=True)+def _():+ mo.md(+ """+ ## 7. Complex Query Errors++ More complex SQL errors that might occur in real scenarios.+ """+ )+ return+++def _(users):+ _df = mo.sql(+ f"""+ -- Subquery error - invalid_column doesn't exist+ SELECT * FROM users+ WHERE id IN (SELECT invalid_column FROM users)+ """+ )+ return+++def _(nonexistent_table, users):+ _df = mo.sql(+ f"""+ -- JOIN error - nonexistent_table doesn't exist+ SELECT u.name, p.title+ FROM users u+ JOIN nonexistent_table p ON u.id = p.user_id+ """+ )+ return++[email protected](hide_code=True)+def _():+ mo.md(+ """+ ## 8. Very Long SQL Statements++ Testing error handling with long SQL that gets truncated.+ """+ )+ return+++def _(nonexistent_table):+ _df = mo.sql(+ f"""+ -- Very long SELECT with many columns that don't exist+ -- This will show error message truncation+ SELECT {", ".join([f"col_{i}" for i in range(50)])}+ FROM nonexistent_table+ """+ )+ return++[email protected](hide_code=True)+def _():+ mo.md(+ """+ ## 9. SQL with Special Characters++ Testing error handling with special characters and edge cases.+ """+ )+ return+++def _():+ _df = mo.sql(+ f"""+ -- SQL with quotes and special characters in table name+ SELECT * FROM 'table with spaces and quotes'+ """+ )+ return+++def _(用户表):+ _df = mo.sql(+ f"""+ -- SQL with unicode characters in table name+ SELECT * FROM 用户表+ """+ )+ return++[email protected](hide_code=True)+def _():+ mo.md(+ """+ ## 10. Successful Query for Comparison++ Here's a working query to show the contrast with error handling.+ """+ )+ return+++def _(users):+ # This should work perfectly+ successful_query = mo.sql(+ f"""+ SELECT name, age, email+ FROM users+ WHERE age > 25+ ORDER BY age DESC+ """+ )+ return++[email protected](hide_code=True)+def _():+ mo.md(+ """+ ## Summary++ This notebook demonstrates marimo's comprehensive SQL error handling:++ - **Clear Error Messages**: Specific, actionable error descriptions displayed in marimo's error UI+ - **Helpful Suggestions**: DuckDB's friendly error messages with "Did you mean?" suggestions+ - **Position Information**: Line and column details when available+ - **Statement Context**: Shows the problematic SQL statement in the structured error display+ - **Graceful Degradation**: Errors don't crash the notebook, they display as structured errors+ - **Truncation**: Long SQL statements are truncated for readability in error messages++ Each SQL cell above will display a structured error in marimo's error UI, showing how+ different types of SQL errors are handled gracefully with actionable feedback.+ """+ )+ return+++if __name__ == "__main__":+ app.run()diff --git a/marimo/_sql/error_utils.py b/marimo/_sql/error_utils.pynew file mode 100644index 0000000000..0c9510d4c7--- /dev/null+++ b/marimo/_sql/error_utils.py@@ -0,0 +1,263 @@+# Copyright 2025 Marimo. All rights reserved.+import ast+import re+from typing import TYPE_CHECKING, Callable, Optional, TypedDict++from marimo._dependencies.dependencies import DependencyManager++if TYPE_CHECKING:+ from marimo._messaging.errors import MarimoSQLError++from marimo import _loggers++LOGGER = _loggers.marimo_logger()+++class MarimoSQLException(Exception):+ """Exception raised for SQL-related errors in marimo."""++ def __init__(+ self,+ message: str,+ sql_statement: str = "",+ sql_line: Optional[int] = None,+ sql_col: Optional[int] = None,+ hint: Optional[str] = None,+ ):+ super().__init__(message)+ self.sql_statement = sql_statement+ self.sql_line = sql_line+ self.sql_col = sql_col+ self.hint = hint+++class SQLErrorMetadata(TypedDict):+ """Structured metadata for SQL parsing errors."""++ lint_rule: str+ error_type: str+ clean_message: str+ hint: Optional[str]+ node_lineno: int+ node_col_offset: int+ sql_statement: str+ sql_line: Optional[int]+ sql_col: Optional[int]+ context: str+++def is_sql_parse_error(exception: BaseException) -> bool:+ """Check if the exception is a SQL parsing error."""+ # Check for DuckDB exceptions first (most common)+ if DependencyManager.duckdb.has():+ try:+ import duckdb++ # Errors are general enough to capture all meaningful SQL issues.+ # NB. Errors like Binder/CatalogException are under ProgrammingError.+ # The definitions can be found here:+ # https://github.com/duckdb/duckdb-python/blob/0ee500cfa35fc07bf81ed02e8ab6984ea1f665fd/duckdb/__init__.pyi#L82+ if isinstance(+ exception,+ (+ duckdb.ParserException,+ duckdb.ProgrammingError,+ duckdb.IOException,+ duckdb.OperationalError,+ duckdb.IntegrityError,+ duckdb.DataError,+ ),+ ):+ return True+ except ImportError:+ pass++ # Check for SQLGlot exceptions+ if DependencyManager.sqlglot.has():+ try:+ from sqlglot.errors import ParseError++ # Definitions can be found here:+ # https://sqlglot.com/sqlglot/errors.html+ if isinstance(exception, ParseError):+ return True+ except ImportError:+ pass++ return isinstance(exception, MarimoSQLException)+++def extract_sql_position(+ exception_msg: str,+) -> tuple[Optional[int], Optional[int]]:+ """Extract line and column position from SQL exception message."""+ # SqlGlot format: "Line 1, Col: 15"+ line_col_match = re.search(r"Line (\d+), Col: (\d+)", exception_msg)+ if line_col_match:+ return (+ int(line_col_match.group(1)) - 1, # Convert to 0-based+ int(line_col_match.group(2)) - 1,+ )++ # DuckDB format: "LINE 4:" (line only)+ line_only_match = re.search(r"LINE (\d+):", exception_msg)+ if line_only_match:+ return (+ int(line_only_match.group(1)) - 1, # Convert to 0-based+ None, # No column information+ )++ # SQLGlot format variations+ sqlglot_match = re.search(+ r"line (\d+), col (\d+)", exception_msg, re.IGNORECASE+ )+ if sqlglot_match:+ return (+ int(sqlglot_match.group(1)) - 1,+ int(sqlglot_match.group(2)) - 1,+ )++ return None, None+++def create_sql_error_metadata(+ exception: BaseException,+ *,+ rule_code: str,+ node: Optional[ast.expr] = None,+ sql_content: str = "",+ context: str = "",+) -> SQLErrorMetadata:+ """Create structured SQL error metadata from an exception.++ This is the single source of truth for parsing SQL exceptions into metadata.+ """+ exception_msg = str(exception)+ sql_line, sql_col = extract_sql_position(exception_msg)++ # Truncate long SQL content+ truncated_sql = sql_content+ if sql_content and len(sql_content) > 200:+ truncated_sql = sql_content[:200] + "..."++ # Create clean error message (first line only)+ clean_message = exception_msg.split("\n", 1)[0]++ # Extract helpful DuckDB hints separately (including multiline hints)+ hint = None+ lines = exception_msg.split("\n")+ hint_lines = []++ for line in lines[1:]:+ hint_lines.append(line.strip())++ if hint_lines:+ hint = "\n".join(hint_lines)++ return SQLErrorMetadata(+ lint_rule=rule_code,+ error_type=type(exception).__name__,+ clean_message=clean_message,+ hint=hint,+ node_lineno=node.lineno if node else 0,+ node_col_offset=node.col_offset if node else 0,+ sql_statement=truncated_sql,+ sql_line=sql_line,+ sql_col=sql_col,+ context=context,+ )+++def metadata_to_sql_error(metadata: SQLErrorMetadata) -> "MarimoSQLError":+ """Convert SQLErrorMetadata to MarimoSQLError for frontend messaging."""+ from marimo._messaging.errors import MarimoSQLError++ return MarimoSQLError(+ msg=metadata["clean_message"],+ sql_statement=metadata["sql_statement"],+ hint=metadata["hint"],+ sql_line=metadata["sql_line"],+ sql_col=metadata["sql_col"],+ node_lineno=metadata["node_lineno"],+ node_col_offset=metadata["node_col_offset"],+ )+++def log_sql_error(+ logger_func: Callable[..., None],+ *,+ message: str,+ exception: BaseException,+ rule_code: str,+ node: Optional[ast.expr] = None,+ sql_content: str = "",+ context: str = "",+) -> None:+ """Log SQL-related errors with structured metadata."""+ # Use centralized metadata creation+ metadata = create_sql_error_metadata(+ exception,+ rule_code=rule_code,+ node=node,+ sql_content=sql_content,+ context=context,+ )++ # Log clean SQL error without traces+ log_msg = message if message else metadata["clean_message"]+ if metadata["sql_line"] is not None and metadata["sql_col"] is not None:+ log_msg += f" (Line {metadata['sql_line'] + 1}, Col {metadata['sql_col'] + 1})"+ if metadata["sql_statement"]:+ log_msg += f"\nSQL: {metadata['sql_statement']}"++ logger_func(log_msg, extra=metadata)+++def create_sql_error_from_exception(+ exception: BaseException,+ cell: object,+) -> "MarimoSQLError":+ """Create a MarimoSQLError from a SQL parsing exception."""+ # Get SQL statement from cell+ sql_statement = ""+ if hasattr(cell, "sqls") and cell.sqls:+ sql_statement = str(cell.sqls[0])++ # Check if this is a MarimoSQLException with structured hint data+ if isinstance(exception, MarimoSQLException) and exception.hint:+ # Use the structured hint data from the exception+ from marimo._messaging.errors import MarimoSQLError++ return MarimoSQLError(+ msg=str(exception),+ sql_statement=exception.sql_statement,+ hint=exception.hint,+ sql_line=exception.sql_line,+ sql_col=exception.sql_col,+ )++ # Create metadata using centralized function+ metadata = create_sql_error_metadata(+ exception,+ rule_code="runtime",+ node=None,+ sql_content=sql_statement,+ context="cell_execution",+ )++ # Enhance error messages based on exception type+ exception_type = metadata["error_type"]+ clean_message = metadata["clean_message"]+ if exception_type == "ParserException":+ clean_message = f"SQL syntax error: {clean_message}"+ elif "ParseError" in exception_type:+ clean_message = f"SQL parse error: {clean_message}"+ elif "ProgrammingError" in exception_type:+ clean_message = f"SQL programming error: {clean_message}"++ # Update metadata with enhanced message+ enhanced_metadata = metadata.copy()+ enhanced_metadata["clean_message"] = clean_message++ # Convert to MarimoSQLError using converter+ return metadata_to_sql_error(enhanced_metadata)diff --git a/marimo/_sql/sql.py b/marimo/_sql/sql.pyindex b2eeaeb7dd..0026efdccd 100644--- a/marimo/_sql/sql.py+++ b/marimo/_sql/sql.py@@ -11,6 +11,7 @@ from marimo._sql.engines.dbapi import DBAPIConnection, DBAPIEnginefrom marimo._sql.engines.duckdb import DuckDBEnginefrom marimo._sql.engines.sqlalchemy import SQLAlchemyEnginefrom marimo._sql.engines.types import QueryEngine+from marimo._sql.error_utils import MarimoSQLException, is_sql_parse_errorfrom marimo._sql.get_engines import SUPPORTED_ENGINESfrom marimo._sql.utils import (extract_explain_content,@@ -75,7 +76,48 @@ def sql("Unsupported engine. Must be a SQLAlchemy, Ibis, Clickhouse, DuckDB, Redshift or DBAPI 2.0 compatible engine.")- df = sql_engine.execute(query)+ try:+ df = sql_engine.execute(query)+ except Exception as e:+ if is_sql_parse_error(e):+ # Use centralized error processing+ from marimo._sql.error_utils import (+ create_sql_error_metadata,+ )++ metadata = create_sql_error_metadata(+ e,+ rule_code="runtime",+ node=None,+ sql_content=query,+ context="sql_execution",+ )++ # Enhance error messages based on exception type+ exception_type = metadata["error_type"]+ clean_message = metadata["clean_message"]+ if exception_type == "ParserException":+ clean_message = f"SQL syntax error: {clean_message}"+ elif "ParseError" in exception_type:+ clean_message = f"SQL parse error: {clean_message}"+ elif "ProgrammingError" in exception_type:+ clean_message = f"SQL programming error: {clean_message}"++ # Truncate long SQL statements+ truncated_query = (+ query[:200] + "..." if len(query) > 200 else query+ )++ # Raise MarimoSQLException with structured hint data+ raise MarimoSQLException(+ message=clean_message,+ sql_statement=truncated_query,+ sql_line=metadata["sql_line"],+ sql_col=metadata["sql_col"],+ hint=metadata["hint"],+ ) from None+ raise+if df is None:return Nonediff --git a/packages/openapi/api.yaml b/packages/openapi/api.yamlindex d5240531be..d907f430dd 100644--- a/packages/openapi/api.yaml+++ b/packages/openapi/api.yaml@@ -86,15 +86,35 @@ components:title: AiCompletionRequesttype: objectAiConfig:- description: "Configuration options for AI.\n\n **Keys.**\n\n - `rules`:\- \ custom rules to include in all AI completion prompts\n - `max_tokens`:\- \ the maximum number of tokens to use in AI completions\n - `mode`: the\- \ mode to use for AI completions. Can be one of: `\"ask\"` or `\"manual\"\- `\n - `models`: the models to use for AI completions\n - `open_ai`:\- \ the OpenAI config\n - `anthropic`: the Anthropic config\n - `google`:\- \ the Google AI config\n - `bedrock`: the Bedrock config\n - `azure`:\- \ the Azure config\n - `ollama`: the Ollama config\n - `github`: the\- \ GitHub config\n - `open_ai_compatible`: the OpenAI-compatible config"+ description: 'Configuration options for AI.+++ **Keys.**+++ - `rules`: custom rules to include in all AI completion prompts++ - `max_tokens`: the maximum number of tokens to use in AI completions++ - `mode`: the mode to use for AI completions. Can be one of: `"ask"` or `"manual"`++ - `models`: the models to use for AI completions++ - `open_ai`: the OpenAI config++ - `anthropic`: the Anthropic config++ - `google`: the Google AI config++ - `bedrock`: the Bedrock config++ - `azure`: the Azure config++ - `ollama`: the Ollama config++ - `github`: the GitHub config++ - `open_ai_compatible`: the OpenAI-compatible config'properties:anthropic:$ref: '#/components/schemas/AnthropicConfig'@@ -143,12 +163,22 @@ components:title: AiInlineCompletionRequesttype: objectAiModelConfig:- description: "Configuration options for an AI model.\n\n **Keys.**\n\n \- \ - `chat_model`: the model to use for chat completions\n - `edit_model`:\- \ the model to use for edit completions\n - `autocomplete_model`: the model\- \ to use for code completion/autocomplete\n - `displayed_models`: a list\- \ of models to display in the UI\n - `custom_models`: a list of custom\- \ models to use that are not from the default list"+ description: 'Configuration options for an AI model.+++ **Keys.**+++ - `chat_model`: the model to use for chat completions++ - `edit_model`: the model to use for edit completions++ - `autocomplete_model`: the model to use for code completion/autocomplete++ - `displayed_models`: a list of models to display in the UI++ - `custom_models`: a list of custom models to use that are not from the default+ list'properties:autocomplete_model:type: string@@ -191,8 +221,13 @@ components:title: Alerttype: objectAnthropicConfig:- description: "Configuration options for Anthropic.\n\n **Keys.**\n\n -\- \ `api_key`: the Anthropic API key"+ description: 'Configuration options for Anthropic.+++ **Keys.**+++ - `api_key`: the Anthropic API key'properties:api_key:type: string@@ -248,10 +283,19 @@ components:title: BasedpyrightServerConfigtype: objectBedrockConfig:- description: "Configuration options for Bedrock.\n\n **Keys.**\n\n - `profile_name`:\- \ the AWS profile to use\n - `region_name`: the AWS region to use\n \- \ - `aws_access_key_id`: the AWS access key ID\n - `aws_secret_access_key`:\- \ the AWS secret access key"+ description: 'Configuration options for Bedrock.+++ **Keys.**+++ - `profile_name`: the AWS profile to use++ - `region_name`: the AWS region to use++ - `aws_access_key_id`: the AWS access key ID++ - `aws_secret_access_key`: the AWS secret access key'properties:aws_access_key_id:type: string@@ -295,14 +339,14 @@ components:title: CellConfigtype: objectCellOp:- description: "Op to transition a cell.\n\n A CellOp's data has some optional\- \ fields:\n\n output - a CellOutput\n console - a CellOutput\- \ (console msg to append), or a list of\n CellOutputs\n\- \ status - execution status\n stale_inputs - whether the cell\- \ has stale inputs (variables, modules, ...)\n run_id - the run\- \ associated with this cell.\n serialization - the serialization status\- \ of the cell\n\n Omitting a field means that its value should be unchanged!\n\- \n And one required field:\n\n cell_id - the cell id"+ description: "Op to transition a cell.\n\nA CellOp's data has some optional\+ \ fields:\n\noutput - a CellOutput\nconsole - a CellOutput (console\+ \ msg to append), or a list of\n CellOutputs\nstatus \+ \ - execution status\nstale_inputs - whether the cell has stale inputs (variables,\+ \ modules, ...)\nrun_id - the run associated with this cell.\nserialization\+ \ - the serialization status of the cell\n\nOmitting a field means that its\+ \ value should be unchanged!\n\nAnd one required field:\n\ncell_id - the cell\+ \ id"properties:cell_id:type: string@@ -373,6 +417,7 @@ components:- $ref: '#/components/schemas/MarimoInterruptionError'- $ref: '#/components/schemas/MarimoSyntaxError'- $ref: '#/components/schemas/MarimoInternalError'+ - $ref: '#/components/schemas/MarimoSQLError'- $ref: '#/components/schemas/UnknownError'discriminator:mapping:@@ -385,6 +430,7 @@ components:interruption: '#/components/schemas/MarimoInterruptionError'multiple-defs: '#/components/schemas/MultipleDefinitionError'setup-refs: '#/components/schemas/SetupRootError'+ sql-error: '#/components/schemas/MarimoSQLError'strict-exception: '#/components/schemas/MarimoStrictExecutionError'syntax: '#/components/schemas/MarimoSyntaxError'unknown: '#/components/schemas/UnknownError'@@ -597,12 +643,24 @@ components:title: CompletedRuntype: objectCompletionConfig:- description: "Configuration for code completion.\n\n A dict with key/value\- \ pairs configuring code completion in the marimo\n editor.\n\n **Keys.**\n\- \n - `activate_on_typing`: if `False`, completion won't activate\n until\- \ the completion hotkey is entered\n - `copilot`: one of `\"github\"`,\- \ `\"codeium\"`, or `\"custom\"`\n - `codeium_api_key`: the Codeium API\- \ key"+ description: 'Configuration for code completion.+++ A dict with key/value pairs configuring code completion in the marimo++ editor.+++ **Keys.**+++ - `activate_on_typing`: if `False`, completion won''t activate++ until the completion hotkey is entered++ - `copilot`: one of `"github"`, `"codeium"`, or `"custom"`++ - `codeium_api_key`: the Codeium API key'properties:activate_on_typing:type: boolean@@ -975,11 +1033,18 @@ components:title: Datasetstype: objectDatasourcesConfig:- description: "Configuration for datasources panel.\n\n **Keys.**\n\n -\- \ `auto_discover_schemas`: if `True`, include schemas in the datasource\n\- \ - `auto_discover_tables`: if `True`, include tables in the datasource\n\- \ - `auto_discover_columns`: if `True`, include columns & table metadata\- \ in the datasource"+ description: 'Configuration for datasources panel.+++ **Keys.**+++ - `auto_discover_schemas`: if `True`, include schemas in the datasource++ - `auto_discover_tables`: if `True`, include tables in the datasource++ - `auto_discover_columns`: if `True`, include columns & table metadata in+ the datasource'properties:auto_discover_columns:anyOf:@@ -1051,8 +1116,13 @@ components:title: DependencyTreeResponsetype: objectDiagnosticsConfig:- description: "Configuration options for diagnostics.\n\n **Keys.**\n\n \- \ - `enabled`: if `True`, diagnostics will be shown in the editor"+ description: 'Configuration options for diagnostics.+++ **Keys.**+++ - `enabled`: if `True`, diagnostics will be shown in the editor'properties:enabled:type: boolean@@ -1060,16 +1130,31 @@ components:title: DiagnosticsConfigtype: objectDisplayConfig:- description: "Configuration for display.\n\n **Keys.**\n\n - `theme`:\- \ `\"light\"`, `\"dark\"`, or `\"system\"`\n - `code_editor_font_size`:\- \ font size for the code editor\n - `cell_output`: `\"above\"` or `\"below\"\- `\n - `dataframes`: `\"rich\"` or `\"plain\"`\n - `custom_css`: list\- \ of paths to custom CSS files\n - `default_table_page_size`: default number\- \ of rows to display in tables\n - `default_table_max_columns`: default\- \ maximum number of columns to display in tables\n - `reference_highlighting`:\- \ if `True`, highlight reactive variable references\n - `locale`: locale\- \ for date formatting and internationalization (e.g., \"en-US\", \"en-GB\"\- , \"de-DE\")"+ description: 'Configuration for display.+++ **Keys.**+++ - `theme`: `"light"`, `"dark"`, or `"system"`++ - `code_editor_font_size`: font size for the code editor++ - `cell_output`: `"above"` or `"below"`++ - `dataframes`: `"rich"` or `"plain"`++ - `custom_css`: list of paths to custom CSS files++ - `default_table_page_size`: default number of rows to display in tables++ - `default_table_max_columns`: default maximum number of columns to display+ in tables++ - `reference_highlighting`: if `True`, highlight reactive variable references++ - `locale`: locale for date formatting and internationalization (e.g., "en-US",+ "en-GB", "de-DE")'properties:cell_output:enum:@@ -1507,8 +1592,13 @@ components:title: FormatResponsetype: objectFormattingConfig:- description: "Configuration for code formatting.\n\n **Keys.**\n\n - `line_length`:\- \ max line length"+ description: 'Configuration for code formatting.+++ **Keys.**+++ - `line_length`: max line length'properties:line_length:type: integer@@ -1552,8 +1642,15 @@ components:title: FunctionCallResulttype: objectGitHubConfig:- description: "Configuration options for GitHub.\n\n **Keys.**\n\n - `api_key`:\- \ the GitHub API token\n - `base_url`: the base URL for the API"+ description: 'Configuration options for GitHub.+++ **Keys.**+++ - `api_key`: the GitHub API token++ - `base_url`: the base URL for the API'properties:api_key:type: string@@ -1563,8 +1660,13 @@ components:title: GitHubConfigtype: objectGoogleAiConfig:- description: "Configuration options for Google AI.\n\n **Keys.**\n\n -\- \ `api_key`: the Google AI API key"+ description: 'Configuration options for Google AI.+++ **Keys.**+++ - `api_key`: the Google AI API key'properties:api_key:type: string@@ -1828,11 +1930,19 @@ components:title: KernelReadytype: objectKeymapConfig:- description: "Configuration for keymaps.\n\n **Keys.**\n\n - `preset`:\- \ one of `\"default\"` or `\"vim\"`\n - `overrides`: a dict of keymap actions\- \ to their keymap override\n - `vimrc`: path to a vimrc file to load keymaps\- \ from\n - `destructive_delete`: if `True`, allows deleting cells with\- \ content."+ description: 'Configuration for keymaps.+++ **Keys.**+++ - `preset`: one of `"default"` or `"vim"`++ - `overrides`: a dict of keymap actions to their keymap override++ - `vimrc`: path to a vimrc file to load keymaps from++ - `destructive_delete`: if `True`, allows deleting cells with content.'properties:destructive_delete:type: boolean@@ -1877,6 +1987,7 @@ components:- $ref: '#/components/schemas/MarimoInterruptionError'- $ref: '#/components/schemas/MarimoSyntaxError'- $ref: '#/components/schemas/MarimoInternalError'+ - $ref: '#/components/schemas/MarimoSQLError'- $ref: '#/components/schemas/UnknownError'discriminator:mapping:@@ -1889,6 +2000,7 @@ components:interruption: '#/components/schemas/MarimoInterruptionError'multiple-defs: '#/components/schemas/MultipleDefinitionError'setup-refs: '#/components/schemas/SetupRootError'+ sql-error: '#/components/schemas/MarimoSQLError'strict-exception: '#/components/schemas/MarimoStrictExecutionError'syntax: '#/components/schemas/MarimoSyntaxError'unknown: '#/components/schemas/UnknownError'@@ -1965,8 +2077,13 @@ components:title: KnownUnionstype: objectLanguageServersConfig:- description: "Configuration options for language servers.\n\n **Keys.**\n\- \n - `pylsp`: the pylsp config"+ description: 'Configuration options for language servers.+++ **Keys.**+++ - `pylsp`: the pylsp config'properties:basedpyright:$ref: '#/components/schemas/BasedpyrightServerConfig'@@ -2173,6 +2290,43 @@ components:- typetitle: MarimoInterruptionErrortype: object+ MarimoSQLError:+ description: SQL-specific error with enhanced metadata for debugging.+ properties:+ hint:+ anyOf:+ - type: string+ - type: 'null'+ default: null+ msg:+ type: string+ node_col_offset:+ default: 0+ type: integer+ node_lineno:+ default: 0+ type: integer+ sql_col:+ anyOf:+ - type: integer+ - type: 'null'+ default: null+ sql_line:+ anyOf:+ - type: integer+ - type: 'null'+ default: null+ sql_statement:+ type: string+ type:+ enum:+ - sql-error+ required:+ - type+ - msg+ - sql_statement+ title: MarimoSQLError+ type: objectMarimoStrictExecutionError:properties:blamed_cell:@@ -2257,15 +2411,27 @@ components:title: MultipleDefinitionErrortype: objectOpenAiConfig:- description: "Configuration options for OpenAI or OpenAI-compatible services.\n\- \n **Keys.**\n\n - `api_key`: the OpenAI API key\n - `base_url`:\- \ the base URL for the API\n - `ssl_verify` : Boolean argument for httpx\- \ passed to open ai client. httpx defaults to true, but some use cases to\- \ let users override to False in some testing scenarios\n - `ca_bundle_path`:\- \ custom ca bundle to be used for verifying SSL certificates. Used to create\- \ custom SSL context for httpx client\n - `client_pem` : custom path of\- \ a client .pem cert used for verifying identity of client server\n - `extra_headers`:\- \ extra headers to be passed to the OpenAI client"+ description: 'Configuration options for OpenAI or OpenAI-compatible services.+++ **Keys.**+++ - `api_key`: the OpenAI API key++ - `base_url`: the base URL for the API++ - `ssl_verify` : Boolean argument for httpx passed to open ai client. httpx+ defaults to true, but some use cases to let users override to False in some+ testing scenarios++ - `ca_bundle_path`: custom ca bundle to be used for verifying SSL certificates.+ Used to create custom SSL context for httpx client++ - `client_pem` : custom path of a client .pem cert used for verifying identity+ of client server++ - `extra_headers`: extra headers to be passed to the OpenAI client'properties:api_key:type: string@@ -2318,8 +2484,13 @@ components:title: PackageDescriptiontype: objectPackageManagementConfig:- description: "Configuration options for package management.\n\n **Keys.**\n\- \n - `manager`: the package manager to use"+ description: 'Configuration options for package management.+++ **Keys.**+++ - `manager`: the package manager to use'properties:manager:enum:@@ -2620,37 +2791,35 @@ components:title: RunningNotebooksResponsetype: objectRuntimeConfig:- description: "Configuration for runtime.\n\n **Keys.**\n\n - `auto_instantiate`:\- \ if `False`, cells won't automatically\n run on startup. This only\- \ applies when editing a notebook,\n and not when running as an application.\n\- \ The default is `True`.\n - `auto_reload`: if `lazy`, cells importing\- \ modified modules will marked\n as stale; if `autorun`, affected cells\- \ will be automatically run. similar\n to IPython's %autoreload extension\- \ but with more code intelligence.\n - `reactive_tests`: if `True`, marimo\- \ will automatically run pytest on cells containing only test functions and\- \ test classes.\n execution.\n - `on_cell_change`: if `lazy`, cells\- \ will be marked stale when their\n ancestors run but won't autorun;\- \ if `autorun`, cells will automatically\n run when their ancestors run.\n\- \ - `execution_type`: if `relaxed`, marimo will not clone cell declarations;\n\- \ if `strict` marimo will clone cell declarations by default, avoiding\n\- \ hidden potential state build up.\n - `watcher_on_save`: how to handle\- \ file changes when saving. `\"lazy\"` marks\n affected cells as stale,\- \ `\"autorun\"` automatically runs affected cells.\n - `output_max_bytes`:\- \ the maximum size in bytes of cell outputs; larger\n values may affect\- \ frontend performance\n - `std_stream_max_bytes`: the maximum size in\- \ bytes of console outputs;\n larger values may affect frontend performance\n\- \ - `pythonpath`: a list of directories to add to the Python search path.\n\- \ Directories will be added to the head of sys.path. Similar to the\n\- \ `PYTHONPATH` environment variable, the directories will be included\- \ in\n where Python will look for imported modules.\n - `dotenv`:\- \ a list of paths to `.env` files to load.\n If the file does not exist,\- \ it will be silently ignored.\n The default is `[\".env\"]` if a pyproject.toml\- \ is found, otherwise `[]`.\n - `default_sql_output`: the default output\- \ format for SQL queries. Can be one of:\n `\"auto\"`, `\"native\"\- `, `\"polars\"`, `\"lazy-polars\"`, or `\"pandas\"`.\n The default\- \ is `\"auto\"`.\n - `default_auto_download`: an Optional list of export\- \ types to automatically snapshot your notebook as:\n `html`, `markdown`,\- \ `ipynb`.\n The default is None."+ description: "Configuration for runtime.\n\n**Keys.**\n\n- `auto_instantiate`:\+ \ if `False`, cells won't automatically\n run on startup. This only applies\+ \ when editing a notebook,\n and not when running as an application.\n\+ \ The default is `True`.\n- `auto_reload`: if `lazy`, cells importing modified\+ \ modules will marked\n as stale; if `autorun`, affected cells will be automatically\+ \ run. similar\n to IPython's %autoreload extension but with more code intelligence.\n\+ - `reactive_tests`: if `True`, marimo will automatically run pytest on cells\+ \ containing only test functions and test classes.\n execution.\n- `on_cell_change`:\+ \ if `lazy`, cells will be marked stale when their\n ancestors run but won't\+ \ autorun; if `autorun`, cells will automatically\n run when their ancestors\+ \ run.\n- `execution_type`: if `relaxed`, marimo will not clone cell declarations;\n\+ \ if `strict` marimo will clone cell declarations by default, avoiding\n\+ \ hidden potential state build up.\n- `watcher_on_save`: how to handle file\+ \ changes when saving. `\"lazy\"` marks\n affected cells as stale, `\"\+ autorun\"` automatically runs affected cells.\n- `output_max_bytes`: the maximum\+ \ size in bytes of cell outputs; larger\n values may affect frontend performance\n\+ - `std_stream_max_bytes`: the maximum size in bytes of console outputs;\n\+ \ larger values may affect frontend performance\n- `pythonpath`: a list of\+ \ directories to add to the Python search path.\n Directories will be added\+ \ to the head of sys.path. Similar to the\n `PYTHONPATH` environment variable,\+ \ the directories will be included in\n where Python will look for imported\+ \ modules.\n- `dotenv`: a list of paths to `.env` files to load.\n If the\+ \ file does not exist, it will be silently ignored.\n The default is `[\"\+ .env\"]` if a pyproject.toml is found, otherwise `[]`.\n- `default_sql_output`:\+ \ the default output format for SQL queries. Can be one of:\n `\"auto\"\+ `, `\"native\"`, `\"polars\"`, `\"lazy-polars\"`, or `\"pandas\"`.\n The\+ \ default is `\"auto\"`.\n- `default_auto_download`: an Optional list of export\+ \ types to automatically snapshot your notebook as:\n `html`, `markdown`,\+ \ `ipynb`.\n The default is None."properties:auto_instantiate:type: boolean@@ -2761,10 +2930,17 @@ components:title: SaveAppConfigurationRequesttype: objectSaveConfig:- description: "Configuration for saving.\n\n **Keys.**\n\n - `autosave`:\- \ one of `\"off\"` or `\"after_delay\"`\n - `delay`: number of milliseconds\- \ to wait before autosaving\n - `format_on_save`: if `True`, format the\- \ code on save"+ description: 'Configuration for saving.+++ **Keys.**+++ - `autosave`: one of `"off"` or `"after_delay"`++ - `delay`: number of milliseconds to wait before autosaving++ - `format_on_save`: if `True`, format the code on save'properties:autosave:enum:@@ -2931,10 +3107,10 @@ components:title: SendUIElementMessagetype: objectServerConfig:- description: "Configuration for the server.\n\n **Keys.**\n\n - `browser`:\- \ the web browser to use. `\"default\"` or a browser registered\n with\- \ Python's webbrowser module (eg, `\"firefox\"` or `\"chrome\"`)\n - `follow_symlink`:\- \ if true, the server will follow symlinks it finds\n inside its static\+ description: "Configuration for the server.\n\n**Keys.**\n\n- `browser`: the\+ \ web browser to use. `\"default\"` or a browser registered\n with Python's\+ \ webbrowser module (eg, `\"firefox\"` or `\"chrome\"`)\n- `follow_symlink`:\+ \ if true, the server will follow symlinks it finds\n inside its static\\ assets directory."properties:browser:@@ -3029,10 +3205,16 @@ components:title: SetupRootErrortype: objectSharingConfig:- description: "Configuration for sharing features.\n\n **Keys.**\n\n -\- \ `html`: if `False`, HTML sharing options will be hidden from the UI\n \- \ - `wasm`: if `False`, WebAssembly sharing options will be hidden from the\- \ UI"+ description: 'Configuration for sharing features.+++ **Keys.**+++ - `html`: if `False`, HTML sharing options will be hidden from the UI++ - `wasm`: if `False`, WebAssembly sharing options will be hidden from the+ UI'properties:html:type: boolean@@ -3091,8 +3273,13 @@ components:title: Snippetstype: objectSnippetsConfig:- description: "Configuration for snippets.\n\n **Keys.**\n\n - `custom_path`:\- \ the path to the custom snippets directory"+ description: 'Configuration for snippets.+++ **Keys.**+++ - `custom_path`: the path to the custom snippets directory'properties:custom_paths:items:@@ -3342,8 +3529,12 @@ components:title: WorkspaceFilesResponsetype: object_AppConfig:- description: "Program-specific configuration.\n\n Configuration for frontends\- \ or runtimes that is specific to\n a single marimo program."+ description: 'Program-specific configuration.+++ Configuration for frontends or runtimes that is specific to++ a single marimo program.'properties:app_title:anyOf:@@ -3393,7 +3584,7 @@ components:type: objectinfo:title: marimo API- version: 0.15.5+ version: 0.16.1openapi: 3.1.0paths:/@file/{filename_and_length}:diff --git a/packages/openapi/src/api.ts b/packages/openapi/src/api.tsindex 7e8d9a7617..99eb630272 100644--- a/packages/openapi/src/api.ts+++ b/packages/openapi/src/api.ts@@ -2634,20 +2634,20 @@ export interface components {* AiConfig* @description Configuration options for AI.*- * **Keys.**+ * **Keys.***- * - `rules`: custom rules to include in all AI completion prompts- * - `max_tokens`: the maximum number of tokens to use in AI completions- * - `mode`: the mode to use for AI completions. Can be one of: `"ask"` or `"manual"`- * - `models`: the models to use for AI completions- * - `open_ai`: the OpenAI config- * - `anthropic`: the Anthropic config- * - `google`: the Google AI config- * - `bedrock`: the Bedrock config- * - `azure`: the Azure config- * - `ollama`: the Ollama config- * - `github`: the GitHub config- * - `open_ai_compatible`: the OpenAI-compatible config+ * - `rules`: custom rules to include in all AI completion prompts+ * - `max_tokens`: the maximum number of tokens to use in AI completions+ * - `mode`: the mode to use for AI completions. Can be one of: `"ask"` or `"manual"`+ * - `models`: the models to use for AI completions+ * - `open_ai`: the OpenAI config+ * - `anthropic`: the Anthropic config+ * - `google`: the Google AI config+ * - `bedrock`: the Bedrock config+ * - `azure`: the Azure config+ * - `ollama`: the Ollama config+ * - `github`: the GitHub config+ * - `open_ai_compatible`: the OpenAI-compatible config*/AiConfig: {anthropic?: components["schemas"]["AnthropicConfig"];@@ -2678,13 +2678,13 @@ export interface components {* AiModelConfig* @description Configuration options for an AI model.*- * **Keys.**+ * **Keys.***- * - `chat_model`: the model to use for chat completions- * - `edit_model`: the model to use for edit completions- * - `autocomplete_model`: the model to use for code completion/autocomplete- * - `displayed_models`: a list of models to display in the UI- * - `custom_models`: a list of custom models to use that are not from the default list+ * - `chat_model`: the model to use for chat completions+ * - `edit_model`: the model to use for edit completions+ * - `autocomplete_model`: the model to use for code completion/autocomplete+ * - `displayed_models`: a list of models to display in the UI+ * - `custom_models`: a list of custom models to use that are not from the default list*/AiModelConfig: {autocomplete_model?: string;@@ -2706,9 +2706,9 @@ export interface components {* AnthropicConfig* @description Configuration options for Anthropic.*- * **Keys.**+ * **Keys.***- * - `api_key`: the Anthropic API key+ * - `api_key`: the Anthropic API key*/AnthropicConfig: {api_key?: string;@@ -2742,12 +2742,12 @@ export interface components {* BedrockConfig* @description Configuration options for Bedrock.*- * **Keys.**+ * **Keys.***- * - `profile_name`: the AWS profile to use- * - `region_name`: the AWS region to use- * - `aws_access_key_id`: the AWS access key ID- * - `aws_secret_access_key`: the AWS secret access key+ * - `profile_name`: the AWS profile to use+ * - `region_name`: the AWS region to use+ * - `aws_access_key_id`: the AWS access key ID+ * - `aws_secret_access_key`: the AWS secret access key*/BedrockConfig: {aws_access_key_id?: string;@@ -2785,21 +2785,21 @@ export interface components {* CellOp* @description Op to transition a cell.*- * A CellOp's data has some optional fields:+ * A CellOp's data has some optional fields:*- * output - a CellOutput- * console - a CellOutput (console msg to append), or a list of- * CellOutputs- * status - execution status- * stale_inputs - whether the cell has stale inputs (variables, modules, ...)- * run_id - the run associated with this cell.- * serialization - the serialization status of the cell+ * output - a CellOutput+ * console - a CellOutput (console msg to append), or a list of+ * CellOutputs+ * status - execution status+ * stale_inputs - whether the cell has stale inputs (variables, modules, ...)+ * run_id - the run associated with this cell.+ * serialization - the serialization status of the cell*- * Omitting a field means that its value should be unchanged!+ * Omitting a field means that its value should be unchanged!*- * And one required field:+ * And one required field:*- * cell_id - the cell id+ * cell_id - the cell id*/CellOp: {cell_id: string;@@ -2839,6 +2839,7 @@ export interface components {| components["schemas"]["MarimoInterruptionError"]| components["schemas"]["MarimoSyntaxError"]| components["schemas"]["MarimoInternalError"]+ | components["schemas"]["MarimoSQLError"]| components["schemas"]["UnknownError"])[]| Record<string, any>;@@ -2950,15 +2951,15 @@ export interface components {* CompletionConfig* @description Configuration for code completion.*- * A dict with key/value pairs configuring code completion in the marimo- * editor.+ * A dict with key/value pairs configuring code completion in the marimo+ * editor.*- * **Keys.**+ * **Keys.***- * - `activate_on_typing`: if `False`, completion won't activate- * until the completion hotkey is entered- * - `copilot`: one of `"github"`, `"codeium"`, or `"custom"`- * - `codeium_api_key`: the Codeium API key+ * - `activate_on_typing`: if `False`, completion won't activate+ * until the completion hotkey is entered+ * - `copilot`: one of `"github"`, `"codeium"`, or `"custom"`+ * - `codeium_api_key`: the Codeium API key*/CompletionConfig: {activate_on_typing: boolean;@@ -3151,11 +3152,11 @@ export interface components {* DatasourcesConfig* @description Configuration for datasources panel.*- * **Keys.**+ * **Keys.***- * - `auto_discover_schemas`: if `True`, include schemas in the datasource- * - `auto_discover_tables`: if `True`, include tables in the datasource- * - `auto_discover_columns`: if `True`, include columns & table metadata in the datasource+ * - `auto_discover_schemas`: if `True`, include schemas in the datasource+ * - `auto_discover_tables`: if `True`, include tables in the datasource+ * - `auto_discover_columns`: if `True`, include columns & table metadata in the datasource*/DatasourcesConfig: {auto_discover_columns?: boolean | "auto";@@ -3187,9 +3188,9 @@ export interface components {* DiagnosticsConfig* @description Configuration options for diagnostics.*- * **Keys.**+ * **Keys.***- * - `enabled`: if `True`, diagnostics will be shown in the editor+ * - `enabled`: if `True`, diagnostics will be shown in the editor*/DiagnosticsConfig: {enabled?: boolean;@@ -3198,17 +3199,17 @@ export interface components {* DisplayConfig* @description Configuration for display.*- * **Keys.**+ * **Keys.***- * - `theme`: `"light"`, `"dark"`, or `"system"`- * - `code_editor_font_size`: font size for the code editor- * - `cell_output`: `"above"` or `"below"`- * - `dataframes`: `"rich"` or `"plain"`- * - `custom_css`: list of paths to custom CSS files- * - `default_table_page_size`: default number of rows to display in tables- * - `default_table_max_columns`: default maximum number of columns to display in tables- * - `reference_highlighting`: if `True`, highlight reactive variable references- * - `locale`: locale for date formatting and internationalization (e.g., "en-US", "en-GB", "de-DE")+ * - `theme`: `"light"`, `"dark"`, or `"system"`+ * - `code_editor_font_size`: font size for the code editor+ * - `cell_output`: `"above"` or `"below"`+ * - `dataframes`: `"rich"` or `"plain"`+ * - `custom_css`: list of paths to custom CSS files+ * - `default_table_page_size`: default number of rows to display in tables+ * - `default_table_max_columns`: default maximum number of columns to display in tables+ * - `reference_highlighting`: if `True`, highlight reactive variable references+ * - `locale`: locale for date formatting and internationalization (e.g., "en-US", "en-GB", "de-DE")*/DisplayConfig: {/** @enum {unknown} */@@ -3407,9 +3408,9 @@ export interface components {* FormattingConfig* @description Configuration for code formatting.*- * **Keys.**+ * **Keys.***- * - `line_length`: max line length+ * - `line_length`: max line length*/FormattingConfig: {line_length: number;@@ -3436,10 +3437,10 @@ export interface components {* GitHubConfig* @description Configuration options for GitHub.*- * **Keys.**+ * **Keys.***- * - `api_key`: the GitHub API token- * - `base_url`: the base URL for the API+ * - `api_key`: the GitHub API token+ * - `base_url`: the base URL for the API*/GitHubConfig: {api_key?: string;@@ -3449,9 +3450,9 @@ export interface components {* GoogleAiConfig* @description Configuration options for Google AI.*- * **Keys.**+ * **Keys.***- * - `api_key`: the Google AI API key+ * - `api_key`: the Google AI API key*/GoogleAiConfig: {api_key?: string;@@ -3586,12 +3587,12 @@ export interface components {* KeymapConfig* @description Configuration for keymaps.*- * **Keys.**+ * **Keys.***- * - `preset`: one of `"default"` or `"vim"`- * - `overrides`: a dict of keymap actions to their keymap override- * - `vimrc`: path to a vimrc file to load keymaps from- * - `destructive_delete`: if `True`, allows deleting cells with content.+ * - `preset`: one of `"default"` or `"vim"`+ * - `overrides`: a dict of keymap actions to their keymap override+ * - `vimrc`: path to a vimrc file to load keymaps from+ * - `destructive_delete`: if `True`, allows deleting cells with content.*/KeymapConfig: {destructive_delete?: boolean;@@ -3626,6 +3627,7 @@ export interface components {| components["schemas"]["MarimoInterruptionError"]| components["schemas"]["MarimoSyntaxError"]| components["schemas"]["MarimoInternalError"]+ | components["schemas"]["MarimoSQLError"]| components["schemas"]["UnknownError"];operation:| components["schemas"]["CellOp"]@@ -3663,9 +3665,9 @@ export interface components {* LanguageServersConfig* @description Configuration options for language servers.*- * **Keys.**+ * **Keys.***- * - `pylsp`: the pylsp config+ * - `pylsp`: the pylsp config*/LanguageServersConfig: {basedpyright?: components["schemas"]["BasedpyrightServerConfig"];@@ -3764,6 +3766,26 @@ export interface components {/** @enum {unknown} */type: "interruption";};+ /**+ * MarimoSQLError+ * @description SQL-specific error with enhanced metadata for debugging.+ */+ MarimoSQLError: {+ /** @default null */+ hint?: string | null;+ msg: string;+ /** @default 0 */+ node_col_offset?: number;+ /** @default 0 */+ node_lineno?: number;+ /** @default null */+ sql_col?: number | null;+ /** @default null */+ sql_line?: number | null;+ sql_statement: string;+ /** @enum {unknown} */+ type: "sql-error";+ };/** MarimoStrictExecutionError */MarimoStrictExecutionError: {blamed_cell: string | null;@@ -3801,14 +3823,14 @@ export interface components {* OpenAiConfig* @description Configuration options for OpenAI or OpenAI-compatible services.*- * **Keys.**+ * **Keys.***- * - `api_key`: the OpenAI API key- * - `base_url`: the base URL for the API- * - `ssl_verify` : Boolean argument for httpx passed to open ai client. httpx defaults to true, but some use cases to let users override to False in some testing scenarios- * - `ca_bundle_path`: custom ca bundle to be used for verifying SSL certificates. Used to create custom SSL context for httpx client- * - `client_pem` : custom path of a client .pem cert used for verifying identity of client server- * - `extra_headers`: extra headers to be passed to the OpenAI client+ * - `api_key`: the OpenAI API key+ * - `base_url`: the base URL for the API+ * - `ssl_verify` : Boolean argument for httpx passed to open ai client. httpx defaults to true, but some use cases to let users override to False in some testing scenarios+ * - `ca_bundle_path`: custom ca bundle to be used for verifying SSL certificates. Used to create custom SSL context for httpx client+ * - `client_pem` : custom path of a client .pem cert used for verifying identity of client server+ * - `extra_headers`: extra headers to be passed to the OpenAI client*/OpenAiConfig: {api_key?: string;@@ -3846,9 +3868,9 @@ export interface components {* PackageManagementConfig* @description Configuration options for package management.*- * **Keys.**+ * **Keys.***- * - `manager`: the package manager to use+ * - `manager`: the package manager to use*/PackageManagementConfig: {/** @enum {unknown} */@@ -4002,42 +4024,42 @@ export interface components {* RuntimeConfig* @description Configuration for runtime.*- * **Keys.**+ * **Keys.***- * - `auto_instantiate`: if `False`, cells won't automatically- * run on startup. This only applies when editing a notebook,- * and not when running as an application.- * The default is `True`.- * - `auto_reload`: if `lazy`, cells importing modified modules will marked- * as stale; if `autorun`, affected cells will be automatically run. similar- * to IPython's %autoreload extension but with more code intelligence.- * - `reactive_tests`: if `True`, marimo will automatically run pytest on cells containing only test functions and test classes.- * execution.- * - `on_cell_change`: if `lazy`, cells will be marked stale when their- * ancestors run but won't autorun; if `autorun`, cells will automatically- * run when their ancestors run.- * - `execution_type`: if `relaxed`, marimo will not clone cell declarations;- * if `strict` marimo will clone cell declarations by default, avoiding- * hidden potential state build up.- * - `watcher_on_save`: how to handle file changes when saving. `"lazy"` marks- * affected cells as stale, `"autorun"` automatically runs affected cells.- * - `output_max_bytes`: the maximum size in bytes of cell outputs; larger- * values may affect frontend performance- * - `std_stream_max_bytes`: the maximum size in bytes of console outputs;- * larger values may affect frontend performance- * - `pythonpath`: a list of directories to add to the Python search path.- * Directories will be added to the head of sys.path. Similar to the- * `PYTHONPATH` environment variable, the directories will be included in- * where Python will look for imported modules.- * - `dotenv`: a list of paths to `.env` files to load.- * If the file does not exist, it will be silently ignored.- * The default is `[".env"]` if a pyproject.toml is found, otherwise `[]`.- * - `default_sql_output`: the default output format for SQL queries. Can be one of:- * `"auto"`, `"native"`, `"polars"`, `"lazy-polars"`, or `"pandas"`.- * The default is `"auto"`.- * - `default_auto_download`: an Optional list of export types to automatically snapshot your notebook as:- * `html`, `markdown`, `ipynb`.- * The default is None.+ * - `auto_instantiate`: if `False`, cells won't automatically+ * run on startup. This only applies when editing a notebook,+ * and not when running as an application.+ * The default is `True`.+ * - `auto_reload`: if `lazy`, cells importing modified modules will marked+ * as stale; if `autorun`, affected cells will be automatically run. similar+ * to IPython's %autoreload extension but with more code intelligence.+ * - `reactive_tests`: if `True`, marimo will automatically run pytest on cells containing only test functions and test classes.+ * execution.+ * - `on_cell_change`: if `lazy`, cells will be marked stale when their+ * ancestors run but won't autorun; if `autorun`, cells will automatically+ * run when their ancestors run.+ * - `execution_type`: if `relaxed`, marimo will not clone cell declarations;+ * if `strict` marimo will clone cell declarations by default, avoiding+ * hidden potential state build up.+ * - `watcher_on_save`: how to handle file changes when saving. `"lazy"` marks+ * affected cells as stale, `"autorun"` automatically runs affected cells.+ * - `output_max_bytes`: the maximum size in bytes of cell outputs; larger+ * values may affect frontend performance+ * - `std_stream_max_bytes`: the maximum size in bytes of console outputs;+ * larger values may affect frontend performance+ * - `pythonpath`: a list of directories to add to the Python search path.+ * Directories will be added to the head of sys.path. Similar to the+ * `PYTHONPATH` environment variable, the directories will be included in+ * where Python will look for imported modules.+ * - `dotenv`: a list of paths to `.env` files to load.+ * If the file does not exist, it will be silently ignored.+ * The default is `[".env"]` if a pyproject.toml is found, otherwise `[]`.+ * - `default_sql_output`: the default output format for SQL queries. Can be one of:+ * `"auto"`, `"native"`, `"polars"`, `"lazy-polars"`, or `"pandas"`.+ * The default is `"auto"`.+ * - `default_auto_download`: an Optional list of export types to automatically snapshot your notebook as:+ * `html`, `markdown`, `ipynb`.+ * The default is None.*/RuntimeConfig: {auto_instantiate: boolean;@@ -4094,11 +4116,11 @@ export interface components {* SaveConfig* @description Configuration for saving.*- * **Keys.**+ * **Keys.***- * - `autosave`: one of `"off"` or `"after_delay"`- * - `delay`: number of milliseconds to wait before autosaving- * - `format_on_save`: if `True`, format the code on save+ * - `autosave`: one of `"off"` or `"after_delay"`+ * - `delay`: number of milliseconds to wait before autosaving+ * - `format_on_save`: if `True`, format the code on save*/SaveConfig: {/** @enum {unknown} */@@ -4172,12 +4194,12 @@ export interface components {* ServerConfig* @description Configuration for the server.*- * **Keys.**+ * **Keys.***- * - `browser`: the web browser to use. `"default"` or a browser registered- * with Python's webbrowser module (eg, `"firefox"` or `"chrome"`)- * - `follow_symlink`: if true, the server will follow symlinks it finds- * inside its static assets directory.+ * - `browser`: the web browser to use. `"default"` or a browser registered+ * with Python's webbrowser module (eg, `"firefox"` or `"chrome"`)+ * - `follow_symlink`: if true, the server will follow symlinks it finds+ * inside its static assets directory.*/ServerConfig: {browser: "default" | string;@@ -4218,10 +4240,10 @@ export interface components {* SharingConfig* @description Configuration for sharing features.*- * **Keys.**+ * **Keys.***- * - `html`: if `False`, HTML sharing options will be hidden from the UI- * - `wasm`: if `False`, WebAssembly sharing options will be hidden from the UI+ * - `html`: if `False`, HTML sharing options will be hidden from the UI+ * - `wasm`: if `False`, WebAssembly sharing options will be hidden from the UI*/SharingConfig: {html?: boolean;@@ -4252,9 +4274,9 @@ export interface components {* SnippetsConfig* @description Configuration for snippets.*- * **Keys.**+ * **Keys.***- * - `custom_path`: the path to the custom snippets directory+ * - `custom_path`: the path to the custom snippets directory*/SnippetsConfig: {custom_paths?: string[];@@ -4381,8 +4403,8 @@ export interface components {* _AppConfig* @description Program-specific configuration.*- * Configuration for frontends or runtimes that is specific to- * a single marimo program.+ * Configuration for frontends or runtimes that is specific to+ * a single marimo program.*/_AppConfig: {/** @default null */diff --git a/tests/_sql/test_sql_error_handling.py b/tests/_sql/test_sql_error_handling.pynew file mode 100644index 0000000000..24589616cb--- /dev/null+++ b/tests/_sql/test_sql_error_handling.py@@ -0,0 +1,457 @@+# Copyright 2025 Marimo. All rights reserved.++from __future__ import annotations++import pytest++from marimo._dependencies.dependencies import DependencyManager+from marimo._messaging.errors import MarimoSQLError+from marimo._sql.error_utils import (+ MarimoSQLException,+ create_sql_error_from_exception,+ extract_sql_position,+ is_sql_parse_error,+)+from marimo._sql.sql import sql++HAS_DUCKDB = DependencyManager.duckdb.has()+HAS_SQLGLOT = DependencyManager.sqlglot.has()+HAS_PANDAS = DependencyManager.pandas.has()+HAS_POLARS = DependencyManager.polars.has()+++class TestDuckDBRuntimeErrors:+ """Test DuckDB errors that occur during SQL execution."""++ @pytest.mark.skipif(not HAS_DUCKDB, reason="DuckDB not installed")+ def test_table_not_found_error(self):+ """Test error when referencing a non-existent table."""+ with pytest.raises(MarimoSQLException) as exc_info:+ sql("SELECT * FROM nonexistent_table")++ error = exc_info.value+ assert "nonexistent_table" in str(error).lower()+ assert "does not exist" in str(error).lower()+ assert error.sql_statement == "SELECT * FROM nonexistent_table"++ @pytest.mark.skipif(not HAS_DUCKDB, reason="DuckDB not installed")+ def test_column_not_found_error(self):+ """Test error when referencing a non-existent column."""+ # Create a test table first+ sql("CREATE OR REPLACE TABLE test_error_table (id INTEGER, name TEXT)")++ with pytest.raises(MarimoSQLException) as exc_info:+ sql("SELECT invalid_column FROM test_error_table")++ error = exc_info.value+ assert "invalid_column" in str(error)+ assert "test_error_table" in error.sql_statement++ @pytest.mark.skipif(not HAS_DUCKDB, reason="DuckDB not installed")+ def test_syntax_error_missing_from(self):+ """Test syntax error when FROM keyword is misspelled."""+ with pytest.raises(MarimoSQLException) as exc_info:+ sql("SELECT * FRM test_table")++ error = exc_info.value+ assert "syntax error" in str(error).lower()+ assert "SELECT * FRM test_table" in error.sql_statement++ @pytest.mark.skipif(not HAS_DUCKDB, reason="DuckDB not installed")+ def test_syntax_error_malformed_expression(self):+ """Test syntax error with malformed SQL expression."""+ with pytest.raises(MarimoSQLException) as exc_info:+ sql("SELECT ( FROM table")++ error = exc_info.value+ assert (+ "syntax error" in str(error).lower()+ or "parser error" in str(error).lower()+ )++ @pytest.mark.skipif(+ not HAS_DUCKDB or not (HAS_PANDAS or HAS_POLARS),+ reason="DuckDB/Pandas not installed",+ )+ def test_data_type_error(self):+ """Test data type conversion errors."""+ sql("CREATE OR REPLACE TABLE test_type_table (id INTEGER)")+ sql("INSERT INTO test_type_table VALUES (1)")++ with pytest.raises(MarimoSQLException) as exc_info:+ sql("SELECT id / 'invalid_string' FROM test_type_table")++ error = exc_info.value+ # Error message varies by DuckDB version, just ensure we caught it+ assert len(str(error)) > 0++ @pytest.mark.skipif(not HAS_DUCKDB, reason="DuckDB not installed")+ def test_long_sql_statement_truncation(self):+ """Test that long SQL statements are truncated in error messages."""+ long_query = (+ "SELECT "+ + ", ".join([f"col_{i}" for i in range(100)])+ + " FROM nonexistent_table"+ )++ with pytest.raises(MarimoSQLException) as exc_info:+ sql(long_query)++ error = exc_info.value+ # Should be truncated to ~200 chars + "..."+ assert len(error.sql_statement) <= 203+ if len(long_query) > 200:+ assert error.sql_statement.endswith("...")+++class TestSQLGlotParseErrors:+ """Test SQLGlot parsing errors during static analysis."""++ @pytest.mark.skipif(not HAS_SQLGLOT, reason="SQLGlot not installed")+ def test_malformed_case_statement(self):+ """Test ParseError with malformed CASE statement."""+ from sqlglot import parse_one+ from sqlglot.errors import ParseError++ with pytest.raises(ParseError):+ parse_one("SELECT CASE FROM table")++ @pytest.mark.skipif(not HAS_SQLGLOT, reason="SQLGlot not installed")+ def test_incomplete_cte(self):+ """Test ParseError with incomplete CTE."""+ from sqlglot import parse_one+ from sqlglot.errors import ParseError++ with pytest.raises(ParseError):+ parse_one("WITH cte AS (SELECT * FROM x)")++ @pytest.mark.skipif(not HAS_SQLGLOT, reason="SQLGlot not installed")+ def test_function_argument_errors(self):+ """Test ParseError with incorrect function arguments."""+ from sqlglot import parse_one+ from sqlglot.errors import ParseError++ # Too few arguments for IF function+ with pytest.raises(ParseError):+ parse_one("SELECT IF(a > 0)")++ @pytest.mark.skipif(not HAS_SQLGLOT, reason="SQLGlot not installed")+ def test_empty_query_parse(self):+ """Test ParseError with empty query."""+ from sqlglot import parse_one+ from sqlglot.errors import ParseError++ with pytest.raises(ParseError):+ parse_one("")++ @pytest.mark.skipif(not HAS_SQLGLOT, reason="SQLGlot not installed")+ def test_invalid_select_syntax(self):+ """Test ParseError with invalid SELECT syntax."""+ from sqlglot import parse_one+ from sqlglot.errors import ParseError++ with pytest.raises(ParseError):+ parse_one("SELECT * * FROM table")+++class TestErrorUtilityFunctions:+ """Test marimo's SQL error handling utility functions."""++ @pytest.mark.skipif(not HAS_DUCKDB, reason="DuckDB not installed")+ def test_is_sql_parse_error_duckdb(self):+ """Test detection of DuckDB parsing errors."""+ import duckdb++ with pytest.raises(Exception) as exc_info:+ duckdb.sql("SELECT * FROM nonexistent_table")+ assert is_sql_parse_error(exc_info.value) is True++ with pytest.raises(Exception) as exc_info:+ duckdb.sql("SELECT * FRM invalid_syntax")+ assert is_sql_parse_error(exc_info.value) is True++ @pytest.mark.skipif(not HAS_SQLGLOT, reason="SQLGlot not installed")+ def test_is_sql_parse_error_sqlglot(self):+ """Test detection of SQLGlot parsing errors."""+ from sqlglot import parse_one+ from sqlglot.errors import ParseError++ with pytest.raises(ParseError) as exc_info:+ parse_one("SELECT CASE FROM table")+ assert is_sql_parse_error(exc_info.value) is True++ def test_is_sql_parse_error_non_sql_exception(self):+ """Test that non-SQL exceptions are not detected as SQL errors."""+ regular_exception = ValueError("This is not a SQL error")+ assert is_sql_parse_error(regular_exception) is False++ def test_is_sql_parse_error_marimo_sql_exception(self):+ """Test that MarimoSQLException is detected as SQL error."""+ marimo_sql_exception = MarimoSQLException("SQL error message")+ assert is_sql_parse_error(marimo_sql_exception) is True++ @pytest.mark.skipif(not HAS_DUCKDB, reason="DuckDB not installed")+ def test_create_sql_error_from_exception(self):+ """Test conversion of raw exception to MarimoSQLError."""+ import duckdb++ class MockCell:+ def __init__(self, sql_statement: str):+ self.sqls = [sql_statement]++ try:+ duckdb.sql("SELECT * FROM nonexistent_table")+ except Exception as e:+ mock_cell = MockCell("SELECT * FROM nonexistent_table")+ error = create_sql_error_from_exception(e, mock_cell)++ assert isinstance(error, MarimoSQLError)+ assert "nonexistent_table" in error.sql_statement+ assert len(error.msg) > 0+ assert "nonexistent_table" in error.msg+ # Hint field should exist (may be None for this error)+ assert hasattr(error, "hint")++ def test_create_sql_error_long_statement(self):+ """Test SQL statement truncation in error creation."""+ import duckdb++ long_statement = (+ "SELECT "+ + ", ".join([f"col_{i}" for i in range(100)])+ + " FROM test"+ )++ class MockCell:+ def __init__(self, sql_statement: str):+ self.sqls = [sql_statement]++ try:+ duckdb.sql(long_statement)+ except Exception as e:+ mock_cell = MockCell(long_statement)+ error = create_sql_error_from_exception(e, mock_cell)++ # Should be truncated+ assert len(error.sql_statement) <= 203+ if len(long_statement) > 200:+ assert error.sql_statement.endswith("...")+++class TestErrorMessageQuality:+ """Test that error messages are actionable and well-formatted."""++ def test_extract_sql_position_duckdb_format(self):+ """Test position extraction from DuckDB error messages."""+ # DuckDB format: "Line 1, Col: 15"+ duckdb_msg = "Parser Error: syntax error at Line 1, Col: 15"+ line, col = extract_sql_position(duckdb_msg)+ assert line == 0 # 0-based+ assert col == 14 # 0-based++ def test_extract_sql_position_sqlglot_format(self):+ """Test position extraction from SQLGlot error messages."""+ # SQLGlot format variations+ sqlglot_msg = "Parse error at line 2, col 10"+ line, col = extract_sql_position(sqlglot_msg)+ assert line == 1 # 0-based+ assert col == 9 # 0-based++ def test_extract_sql_position_no_position(self):+ """Test position extraction when no position info available."""+ no_position_msg = "Some generic SQL error without position"+ line, col = extract_sql_position(no_position_msg)+ assert line is None+ assert col is None++ @pytest.mark.skipif(not HAS_DUCKDB, reason="DuckDB not installed")+ def test_error_message_enhancement(self):+ """Test that error messages are enhanced with prefixes."""+ import duckdb++ class MockCell:+ sqls = ["SELECT * FRM invalid"]++ try:+ duckdb.sql("SELECT * FRM invalid")+ except Exception as e:+ error = create_sql_error_from_exception(e, MockCell())+ # Should have "SQL syntax error:" prefix for ParserException+ assert error.msg.startswith(+ "SQL syntax error:"+ ) or error.msg.startswith("SQL parse error:")++ def test_error_message_cleaning(self):+ """Test that error messages are cleaned of traces."""++ class MockException(Exception):+ def __str__(self):+ return "SQL error message\nTraceback (most recent call last):\n File..."++ class MockCell:+ sqls = ["SELECT * FROM test"]++ error = create_sql_error_from_exception(MockException(), MockCell())+ # Should only contain the first line, no traceback+ assert "Traceback" not in error.msg+ assert error.msg == "SQL error message"+++class TestIntegrationAndEdgeCases:+ """Test complete error flow and edge cases."""++ @pytest.mark.skipif(not HAS_DUCKDB, reason="DuckDB not installed")+ def test_sql_function_error_flow(self):+ """Test complete error flow through mo.sql() function."""+ with pytest.raises(MarimoSQLException) as exc_info:+ sql("SELECT * FROM definitely_nonexistent_table_12345")++ error = exc_info.value+ assert isinstance(error, MarimoSQLException)+ assert error.sql_statement is not None+ assert len(error.sql_statement) > 0++ def test_empty_sql_statement_error_handling(self):+ """Test error handling with empty SQL statements."""++ class MockCell:+ sqls = []++ mock_exception = Exception("Test error")+ error = create_sql_error_from_exception(mock_exception, MockCell())++ assert error.sql_statement == ""++ def test_cell_without_sqls_attribute(self):+ """Test error handling when cell doesn't have sqls attribute."""++ class MockCellNoSqls:+ pass++ mock_exception = Exception("Test error")+ error = create_sql_error_from_exception(+ mock_exception, MockCellNoSqls()+ )++ assert error.sql_statement == ""++ @pytest.mark.skipif(not HAS_DUCKDB, reason="DuckDB not installed")+ def test_multiple_errors_in_sequence(self):+ """Test handling multiple SQL errors in sequence."""+ # First error+ with pytest.raises(MarimoSQLException):+ sql("SELECT * FROM table1_nonexistent")++ # Second error should still work+ with pytest.raises(MarimoSQLException):+ sql("SELECT * FROM table2_nonexistent")++ def test_error_with_special_characters(self):+ """Test error handling with SQL containing special characters."""+ with pytest.raises(MarimoSQLException):+ sql("SELECT * FROM 'table with spaces and quotes'")++ @pytest.mark.skipif(not HAS_DUCKDB, reason="DuckDB not installed")+ def test_duckdb_hints_preserved(self):+ """Test that DuckDB hints like 'Did you mean?' are preserved in error messages."""+ import duckdb++ # Create a table to generate "Did you mean?" suggestions+ duckdb.sql(+ "CREATE OR REPLACE TABLE test_hints_table (id INT, name TEXT)"+ )++ with pytest.raises(MarimoSQLException) as exc_info:+ sql("SELECT * FROM test_hint") # Missing 's' in table name++ error = exc_info.value+ error_msg = str(error)+ # Check that the main error message is present+ assert "does not exist" in error_msg+ # Check that the hint is properly extracted to the hint field+ assert error.hint is not None+ assert (+ "Did you mean" in error.hint or "candidate" in error.hint.lower()+ )++ @pytest.mark.skipif(not HAS_DUCKDB, reason="DuckDB not installed")+ def test_column_candidates_preserved(self):+ """Test that column candidate hints are preserved in error messages."""+ import duckdb++ # Create a table to generate candidate binding suggestions+ duckdb.sql(+ "CREATE OR REPLACE TABLE test_columns (id INT, user_name TEXT, email TEXT)"+ )++ with pytest.raises(MarimoSQLException) as exc_info:+ sql("SELECT fullname FROM test_columns") # Wrong column name++ error = exc_info.value+ error_msg = str(error)+ # Check that the main error message is present+ assert "not found" in error_msg+ # Check that the hint is properly extracted to the hint field+ assert error.hint is not None+ assert "Candidate" in error.hint or "candidate" in error.hint.lower()++ @pytest.mark.skipif(not HAS_DUCKDB, reason="DuckDB not installed")+ def test_hint_field_in_sql_error_struct(self):+ """Test that MarimoSQLError struct properly includes hint field."""+ import duckdb++ # Create table for hint generation+ duckdb.sql(+ "CREATE OR REPLACE TABLE hint_test_table (id INT, name TEXT)"+ )++ try:+ duckdb.sql("SELECT * FROM hint_test") # Missing letters+ except Exception as e:++ class MockCell:+ sqls = ["SELECT * FROM hint_test"]++ error_struct = create_sql_error_from_exception(e, MockCell())++ # Verify the struct has the hint field and it's populated+ assert hasattr(error_struct, "hint")+ assert error_struct.hint is not None+ assert (+ "Did you mean" in error_struct.hint+ or "candidate" in error_struct.hint.lower()+ )+ # Main message should not contain the hint+ assert error_struct.hint not in error_struct.msg++ @pytest.mark.skipif(not HAS_DUCKDB, reason="DuckDB not installed")+ def test_multiline_hints_preserved(self):+ """Test that multiline hints like function candidates are fully captured."""+ import duckdb++ # Create table for multiline hint generation+ duckdb.sql(+ "CREATE OR REPLACE TABLE hint_multiline_table (id INT, name TEXT)"+ )++ try:+ duckdb.sql(+ "SELECT SUBSTRING(name) FROM hint_multiline_table"+ ) # Wrong args+ except Exception as e:++ class MockCell:+ sqls = ["SELECT SUBSTRING(name) FROM hint_multiline_table"]++ error_struct = create_sql_error_from_exception(e, MockCell())++ # Verify multiline hint is captured completely+ assert hasattr(error_struct, "hint")+ assert error_struct.hint is not None+ assert "Candidate functions:" in error_struct.hint+ assert "substring(VARCHAR, BIGINT, BIGINT)" in error_struct.hint+ assert "substring(VARCHAR, BIGINT)" in error_struct.hint+ # Should be multiline+ assert "\n" in error_struct.hint+ # Main message should be clean+ assert "Candidate functions:" not in error_struct.msg