Skip to content

[SPARK-62087][SQL] Preserve original SQL positions in errors for parameterized queries - #60724

Open
srielau wants to merge 4 commits into
apache:masterfrom
srielau:SPARK-62087
Open

srielau wants to merge 4 commits into
apache:masterfrom
srielau:SPARK-62087

Conversation

@srielau

@srielau srielau commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

What changes were proposed in this pull request?

Parameter substitution rewrites the SQL text before parsing. Error positions for the parsed statement are computed on the substituted text, and the mapping back to the original SQL has gaps. This PR closes them:

  • PositionMapper looks up substitution ranges with binary search instead of a linear scan, and precomputes cumulative offsets.
  • Adds PositionMapper.mapStopToOriginal. An inclusive stop index inside a substituted value maps to the end of the original parameter marker. Previously start and stop both mapped to the start of the marker.
  • Adds line and column mapping helpers, so the line and startPosition of an Origin (and therefore of AnalysisException) are reported in original SQL coordinates.
  • Origin.context uses the stop-aware mapping.
  • SparkParserUtils.positionAndText and SparkParserUtils.position map line and column when a position mapper is present. The stored SQL text and the indexes now refer to the same string.
  • SubstituteParamsParser records the separator space it inserts before a replacement that follows a quote character, so the mapper's offsets match the substituted text.
  • AbstractParser.parse maps the current origin to original-text coordinates when it parses text other than the substituted statement, so nested parses do not apply the outer statement's mapping to unrelated text.
  • ParseErrorListener builds the query context for a syntax error from the offending token mapped to the original SQL. A token inside a substituted value underlines the whole parameter marker. The error also reports the original SQL text as its command, so the == SQL == block shows the original line (review feedback on this PR).
  • SingleStatement.getText and the SQL scripting execution nodes use PositionMapper.originalFragment when a mapper is present. Previously they sliced the original text with substituted indexes.
  • Replaces the position-mapping test helpers in ParametersSuite and ParameterSubstitutionSuite. Those helpers skipped their assertions when no query context was present. The new checks require the context and compare the exact SQL text, range, and fragment.

Why are the changes needed?

When a query contains parameter markers, the parser sees the substituted text. Errors raised after a marker therefore report line, column, and fragment values that depend on the length of the bound values, even when the submitted SQL is the same. Only changing a bound value can move the reported position. The stop-index mapping, the line and column reporting, the syntax-error arrow, and the scripting statement text all have the same root cause: the parser works in substituted coordinates, but the error context is reported against the original SQL.

Does this PR introduce any user-facing change?

Yes. For queries with parameter markers:

  • Error positions (line, column, and query context fragment) for errors that occur after a marker refer to the original SQL text. For the same SQL, changing only a bound value no longer changes the reported position.
  • The fragment reported for an error that spans a marker now ends at the end of the marker, not its start.
  • A syntax error on a token inside a substituted value underlines the whole parameter marker in the original SQL, and the == SQL == block shows the original text.
  • Statement text returned for SQL scripting statements that contain parameter markers is the original statement text.

Queries without parameter markers are not affected.

How was this patch tested?

  • build/sbt "catalyst/testOnly org.apache.spark.sql.catalyst.parser.*": 862 tests passed, 0 failed.
  • build/sbt "sql/testOnly org.apache.spark.sql.ParametersSuite org.apache.spark.sql.errors.QueryParsingErrorsSuite": 212 tests passed, 0 failed. New tests cover:
    • ParametersSuite: a parse error inside a substituted value underlines the marker, and the position is stable across bound values of different lengths.
    • ParameterSubstitutionSuite: stop-index mapping inside a replacement, line and column mapping in multiline Unicode SQL, ParseErrorListener position mapping, quote-adjacent separator spaces, and a direct-parser parse error inside a replacement with and without an outer query context.
    • ParametersSuite: analysis and EXECUTE IMMEDIATE position checks with bound values of different lengths.
  • Scalastyle and scalafmt checks passed (./dev/lint-scala).

The bare parse-error position tests in ParametersSuite (for example SELECT *** ?) were removed. Those inputs produce no SQL query context, so the strict helper cannot assert on them. Parse-error mapping is covered by the ParseErrorListener unit test and the direct-parser test in ParameterSubstitutionSuite. The SPARK-49757 identifier-clause regression test is kept and checks the query context only when one is present.

Not yet run: the full sql and catalyst test suites, and the Connect and Thrift suites.

Was this patch authored or co-authored using generative AI tooling?

Generated-by: Cursor (Auto)

@github-actions github-actions Bot added the SQL label Nov 19, 2026
@shihchengwei-lab

Copy link
Copy Markdown

I tested this query with :a set to abc followed by a newline and def, and :second set to the string not_int:

SELECT :a, CAST(1 AS DECIMAL(:second))

spark.sql underlined the entire original query. I saw the arrow on the wrong line only when I called the parser directly with the position mapping and no query context. It reported line 1, pos 29, exactly where :second starts in the original SQL, but drew the arrow on the expanded SQL:

SELECT 'abc
-----------------------------^^^
def', CAST(1 AS DECIMAL('not_int'))

Could the error underline the full :second marker in the original SQL in both cases?

@srielau

srielau commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the report. This is fixed in 7cbad60.

A parse error on a token inside a substituted value now underlines the whole parameter marker in the original SQL. This holds through spark.sql, and also when the parser is called directly with a position mapper and no query context. For your example the arrow is on line 1 under :second, and the == SQL == block shows the original text.

Tests added:

  • ParametersSuite: a parse error inside a substituted value underlines the marker, and the position stays the same when the bound value changes length.
  • ParameterSubstitutionSuite: the direct-parser path, with and without an outer query context.

@srielau
srielau force-pushed the SPARK-62087 branch 2 times, most recently from f8dcb96 to 0ef4a93 Compare November 27, 2026 23:35

@cloud-fan cloud-fan left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review summary

The position mapping holds up on the paths the new tests cover: stop indexes inside a substituted value now reach the end of the marker, line and column come out in original-SQL coordinates, and a syntax error inside a substituted value underlines the marker. The findings are about two error paths the mapping does not cover yet, and about tests, comments, and two small costs that trail the change.

  • Two error paths still report text or positions from the wrong text: the EXECUTE IMMEDIATE null-query-string error names the bound values instead of the expression as written, and the parameter-substitution parse maps its errors through another statement's mapper when spark.sql runs inside a parameterized CALL.
  • Three behaviors this PR adds have no test: the nested-parse guard in AbstractParser.parse, the original statement text of parameterized SQL scripts, and the EXECUTE IMMEDIATE object type in the token-level syntax-error context.
  • Two costs can go with no change in results: mapping line and column through a mapper that records no substitution, and serializing PositionMapper's derived lookup arrays.
  • Three comments in SparkParserUtils no longer describe what parser origins store or how the position helpers remap their input.

None of these changes a query result; they affect error messages and positions, test coverage, comments, and small parse and serialization costs.

The review also covered the binary-search range lookup and stop-index mapping in PositionMapper, the stop-aware mapping in Origin.context, the original-text command in parse errors, and the separator-space bookkeeping in SubstituteParamsParser, and found nothing to change there.

Cross-cutting observations

  • Three of these findings come from the same change of contract: for a parameterized statement, parser origins now keep the substituted text and indexes into it together with the position mapper, so every reader has to map through the mapper and every parse has to run under its own statement's mapper. The EXECUTE IMMEDIATE null-query message reads the text without mapping, the parameter-substitution parse can run under another statement's mapper, and the withOrigin scaladoc still says the stored text is the original SQL.

    Each can be fixed on its own, since the slice fix, the parse-entry guard, and the comment update touch different code, but they are worth reading together when checking whether any other reader of Origin.sqlText needs the same treatment.

    Related:

    • EXECUTE IMMEDIATE null-query error names bound values instead of the SQL as written
    • Parameter-substitution parse errors are mapped through another statement's mapper
    • withOrigin scaladoc still says origins store the original SQL text

Findings

10 total: 0 P0, 0 P1, 4 P2, 6 P3.

Non-blocking (P2)

  • EXECUTE IMMEDIATE null-query error names bound values instead of the SQL as written — sql/api/src/main/scala/org/apache/spark/sql/catalyst/util/SparkParserUtils.scala:265 — see inline.
  • Parameter-substitution parse errors are mapped through another statement's mapper — sql/api/src/main/scala/org/apache/spark/sql/catalyst/parser/parsers.scala:196 — see inline.
  • The nested-parse guard in AbstractParser.parse has no test — sql/api/src/main/scala/org/apache/spark/sql/catalyst/parser/parsers.scala:73 — see inline.
  • Statement text of parameterized SQL scripts has no test — sql/core/src/main/scala/org/apache/spark/sql/scripting/SqlScriptingExecutionNode.scala:191 — see inline.

Nit (P3)

  • Line and column are mapped for every origin even when no value was substituted — sql/api/src/main/scala/org/apache/spark/sql/catalyst/util/SparkParserUtils.scala:269 — see inline.

  • The position helpers' docs omit that they remap through the current mapper — sql/api/src/main/scala/org/apache/spark/sql/catalyst/util/SparkParserUtils.scala:204 — see inline.

  • positionAndText comment says the mapper is used only later, in Origin.context — sql/api/src/main/scala/org/apache/spark/sql/catalyst/util/SparkParserUtils.scala:263 — see inline.

  • PositionMapper serializes its derived lookup arrays — sql/api/src/main/scala/org/apache/spark/sql/catalyst/parser/PositionMapper.scala:81 — see inline.

  • The EXECUTE IMMEDIATE object type in the token-level context has no test — sql/api/src/main/scala/org/apache/spark/sql/catalyst/parser/parsers.scala:241 — see inline.

  • withOrigin scaladoc still says origins store the original SQL text — sql/api/src/main/scala/org/apache/spark/sql/catalyst/util/SparkParserUtils.scala:265
    The withOrigin scaladoc in SparkParserUtils.scala (lines 217-219) still says it will "automatically adjust the positions and SQL text to refer to the original SQL". Since the change to positionAndText (SparkParserUtils.scala:265), the origin stores the substituted text with indexes into it, and only line and column are mapped when the origin is created. A caller that trusts the doc and reads origin.sqlText or origin.sqlTextSlice gets the substituted text, which is how ResolveExecuteImmediate.extractOriginalText ends up reporting bound values. The scaladoc should say that indexes and text stay in the parsed text, that the mapper is kept so readers can map them, and that line and column are reported in the original SQL.

    See Shared repair plan 3 in the review body.

Shared repair plans

Shared repair plan 1

Covered findings:

  • EXECUTE IMMEDIATE null-query error names bound values instead of the SQL as written — sql/api/src/main/scala/org/apache/spark/sql/catalyst/util/SparkParserUtils.scala:265
  • Statement text of parameterized SQL scripts has no test — sql/core/src/main/scala/org/apache/spark/sql/scripting/SqlScriptingExecutionNode.scala:191

Recommended change: Make Origin.sqlTextSlice return positionMapper.originalFragment(startIndex, stopIndex) when the origin carries a position mapper, and the code-point slice of sqlText otherwise, and update its scaladoc to say it returns the SQL text as written for the origin's range. Then make SingleStatement.getText and SingleStatementExec.getText read origin.sqlTextSlice again instead of their own mapper branch, and leave ResolveExecuteImmediate.extractOriginalText unchanged. Add parameter tests for EXECUTE IMMEDIATE's null query string with a substituted marker, and a SQL scripting test that runs a parameterized script whose IF condition is not boolean.

Why this works: Every consumer reads the slice through one method that knows whether the origin's indexes refer to substituted text, so no consumer can slice the substituted text by mistake. originalFragment maps the start with mapToOriginal and the inclusive stop with mapStopToOriginal, so a range that starts or ends inside a substituted value covers the whole marker as written.

Risks: Code outside the repository that reads Origin.sqlTextSlice on an origin with a position mapper would get the SQL as written instead of the substituted text. Origin is an internal catalyst class, and no consumer in the repository wants the substituted slice.

Constraints: Origins without a position mapper must keep returning the code-point slice of sqlText, including after a supplementary character.

Exclusions:

  • Readers of origin.sqlText itself, the constraint-characteristic and parameter-marker ParseException commands, stay as they are, because AbstractParser's parse already rewrites those commands to the original SQL.

Verification:

  • Regression: spark.sql("EXECUTE IMMEDIATE IF(:flag, CAST(NULL AS STRING), 'SELECT 1')", Map("flag" -> true)) fails with NULL_QUERY_STRING_EXECUTE_IMMEDIATE whose varName is IF(:flag, CAST(NULL AS STRING), 'SELECT 1') as the user wrote it, quoted as an identifier, not the substituted IF(true, CAST(NULL AS STRING), 'SELECT 1') that the current head reports.
  • Compatibility: With SQL scripting enabled, spark.sql("BEGIN IF :p THEN SELECT 1; END IF; END", Map("p" -> 1)) fails with INVALID_BOOLEAN_STATEMENT whose invalidStatement parameter is :P, the marker as written in the uppercase form the error uses for statements, not the bound value 1.
  • Compatibility: An origin without a position mapper still returns the code-point slice of its own SQL text, including for a range after a supplementary character.

Shared repair plan 2

Covered findings:

  • Parameter-substitution parse errors are mapped through another statement's mapper — sql/api/src/main/scala/org/apache/spark/sql/catalyst/parser/parsers.scala:196
  • The nested-parse guard in AbstractParser.parse has no test — sql/api/src/main/scala/org/apache/spark/sql/catalyst/parser/parsers.scala:73

Recommended change: Move the origin handling at the top of AbstractParser.parse into a helper on the AbstractParser companion object that takes the text about to be parsed and, when CurrentOrigin carries a mapper whose substituted text is a different string, runs the body under the current origin mapped to original coordinates (start through mapToOriginal, stop through mapStopToOriginal, sqlText set to the mapper's original text) with the mapper dropped, and otherwise runs it unchanged. Call it from AbstractParser.parse as today and around the body of SubstituteParamsParser.substitute after its quick check for '?' and ':'. Add parser tests: a substitution parse that fails while the current origin carries another statement's mapper, and a parameterized statement whose IDENTIFIER string fails to parse after a value of a different length than its marker.

Why this works: Every parse that installs ParseErrorListener then runs under an origin whose mapper, if any, belongs to the text being parsed, so the listener, the position helpers, and positionAndText map only coordinates of that text, and an outer statement's origin is reported, as for any nested parse, as its enclosing node in the outer statement's original SQL.

Risks: A substitution-stage error raised under another parameterized statement's origin now reports that origin's enclosing node in the outer statement's original SQL, which is what the base branch and nested parses report, instead of the fragment the current head computes from the inner token's indexes.

Constraints: The main parse of a parameterized statement, whose text is the mapper's substituted text, must keep running under the statement's own mapper so its errors keep the token-level context on the marker.

Verification:

  • Regression: While the current origin carries the position mapper of CALL cat.p(:a) with :a bound to 12345, substituting parameters into SELECT :x FRM t fails with a parse error at line 1, position 14, the position of t in SELECT :x FRM t, and with no query context whose fragment is :a; the current head reports position 11 and the fragment :a of the CALL statement.
  • Compatibility: A parameterized statement in which an earlier value has a different length than its marker and an IDENTIFIER clause's bound string fails to parse reports a query context in the original SQL that contains the IDENTIFIER clause as written, never text chosen by the identifier string's own token indexes.

Shared repair plan 3

Covered findings:

  • The position helpers' docs omit that they remap through the current mapper — sql/api/src/main/scala/org/apache/spark/sql/catalyst/util/SparkParserUtils.scala:204
  • positionAndText comment says the mapper is used only later, in Origin.context — sql/api/src/main/scala/org/apache/spark/sql/catalyst/util/SparkParserUtils.scala:263
  • withOrigin scaladoc still says origins store the original SQL text — sql/api/src/main/scala/org/apache/spark/sql/catalyst/util/SparkParserUtils.scala:265

Verification:

  • Inspection: The comments of SparkParserUtils.withOrigin, positionAndText, position(token), and position(line, startPosition) describe origins as keeping indexes and text in the parsed text and line and column in the original SQL, describe the position helpers as reading their input in the current mapper's substituted text, and none of them says the mapper is used only by Origin.context or that the stored SQL text is the original SQL.

…meterized queries

Parameter substitution rewrites SQL before parsing, so error line, column,
and fragments could track substituted text and shift when only a bound value
changed. Map stop indexes, line/column, and quote-adjacent separators back to
the original SQL. A syntax error on a token inside a substituted value
underlines the whole parameter marker, and the reported SQL text is the
original statement.
…s with substituted values

Only map a parse error token back to the original SQL when a parameter value
was actually substituted. Statements parsed as written (legacy constants-only
mode, or a parameter context without markers) keep their whole-statement query
context. Update the SPARK-58794 expectations to the parameter marker range.
…ppers, add tests

- Origin.sqlTextSlice returns the SQL as written when the origin carries a
  position mapper, so every reader of the slice (EXECUTE IMMEDIATE null query
  string, SQL scripting statement text) reports the original text. The
  scripting getText methods read it again.
- Run a parse under an origin whose mapper belongs to the parsed text
  (AbstractParser.withOriginOfText). The parameter substitution parse uses it
  too, so a spark.sql call made while a parameterized statement is processed no
  longer maps its errors through that statement's mapper.
- Skip the line and column mapping when the mapper recorded no substitution.
- Keep PositionMapper's derived lookup arrays out of the serialized form.
- Document that origins keep indexes and text in the parsed text, and that the
  position helpers read their input in the mapper's substituted text.
- Add tests for the nested parse guard, the foreign mapper substitution parse,
  sqlTextSlice, mapper serialization, the EXECUTE IMMEDIATE null query string,
  the EXECUTE IMMEDIATE USING object type, and a parameterized IF condition.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants