dtenedor opened a new pull request, #60367:
URL: https://github.com/apache/spark/pull/60367

   ### What changes were proposed in this pull request?
   
   This PR adds optional column, field, variable, and named parameter 
references to Spark SQL. The syntax is behind a new conf, 
`spark.sql.optionalReferences.enabled`, which is internal and off by default.
   
   A `?` after an identifier makes that identifier optional. If name resolution 
finds no match for it, the whole reference becomes a static `NULL` of type 
`VOID` instead of raising `UNRESOLVED_COLUMN`, `FIELD_NOT_FOUND`, or 
`UNBOUND_SQL_PARAMETER`. A top-level reference keeps the name of its last 
identifier.
   
   ```sql
   -- t has the columns id INT and addr STRUCT<city: STRING>.
   SELECT id?, name?, addr.state?, ghost?.city FROM t;  -- id, NULL AS name, 
NULL AS state, NULL AS city
   SELECT addr?.state FROM t;                           -- FIELD_NOT_FOUND: `?` 
guards only `addr`
   EXECUTE IMMEDIATE 'SELECT :x?, :y?' USING 1 AS x;    -- 1, NULL
   ```
   
   #### Semantics
   
   - Only not-found errors are suppressed. Ambiguous references, field 
extraction from a value that isn't a struct, and errors about references that 
exist but can't be used (for example `MISSING_AGGREGATION`) are still raised.
   - A reference that resolves without `?` resolves the same way with it. A 
name becomes `NULL` only after every usual step fails to resolve it. These 
steps include lateral column aliases, GROUP BY and ORDER BY aliases, the 
columns below the SELECT list that ORDER BY and HAVING can reference, outer 
references, SQL function parameters, and session and SQL scripting variables.
   - `?` is allowed in queries, the source query of `INSERT ... SELECT`, 
`VALUES`, `CREATE VIEW`, and `CREATE TABLE ... AS SELECT`.
   - `UPDATE`, `DELETE`, and `MERGE` statements (including their common table 
expressions) and the condition of `INSERT ... REPLACE WHERE/ON` raise 
`OPTIONAL_COLUMN_REFERENCE_NOT_SUPPORTED.IN_DML`, so that a missing column 
can't silently change which rows a statement modifies. This also holds for 
statements that are built with the DataFrame API, such as 
`df.writeTo("t").overwrite(expr("deleted_at? IS NULL"))`.
   - Expressions that define table objects (generated columns, `DEFAULT`, and 
`CHECK`) raise `OPTIONAL_COLUMN_REFERENCE_NOT_SUPPORTED.IN_DDL`. Both errors 
use SQLSTATE `0A000`.
   - `:name?` is an optional named parameter marker, and each occurrence is 
independent: in `SELECT :x?, :x`, an unbound `x` still raises 
`UNBOUND_SQL_PARAMETER`.
   - A `?` that could already be parsed as a positional parameter marker still 
is one, for example in `SELECT DISTINCT ?`.
   - `IDENTIFIER(expr)?` is an optional reference to the column that `expr` 
names.
   - Whitespace and comments before `?` are insignificant.
   - An expression that contains a missing reference is named as if `NULL` were 
written in its place, for example `typeof(NULL)`.
   - A missing reference has the type `VOID`. A view in the default schema 
binding mode keeps the types that its columns had when it was created. A view 
over a column that can appear later should therefore cast the reference, for 
example `CAST(deleted_at? AS TIMESTAMP)`, or be created `WITH SCHEMA EVOLUTION`.
   - `?` binds to the identifier before it, so `x?::INT` is `CAST(x? AS INT)`.
   
   #### Implementation
   
   - **Parser.** `SqlBaseParser.g4` has two new rules. `referenceNamePart` is 
an identifier with an optional `?`, for the field of a `dereference`. 
`leadingReferenceNamePart` is the same for a `columnReference`, and it also 
accepts `IDENTIFIER(expr)?`. `namedParameterLiteral` accepts an optional `?`. 
The rules are separate from `primaryExpression` so that the generated method of 
that rule keeps its size: it's 7,851 bytes of bytecode with and without this 
PR, and HotSpot doesn't JIT-compile methods above 8,000 bytes. `AstBuilder` 
records the optional name parts of a multipart name in a tree node tag on 
`UnresolvedAttribute` (and `UnresolvedNamedLambdaVariable`), and it marks 
optional `UnresolvedExtractValue` and `NamedParameter` nodes. Tags avoid 
changing the signatures of these widely used case classes.
   - **Validation.** `OptionalReferenceValidation` checks the conf and the DML 
and DDL restrictions in SQL text. `SubstituteParamsParser` substitutes `NULL` 
for unbound `:name?` markers. It also runs this validation on them, because 
they're substituted before `AstBuilder` sees them. The new analyzer rule 
`CheckOptionalReferencesInDml` rejects optional references in the plans of DML 
statements that weren't parsed from SQL text.
   - **Missing nested fields.** `AttributeSeq.resolve`, `VariableResolution`, 
and the resolution of lambda variables turn a missing optional field into 
`NULL` (`OptionalReferences.extractNestedFields`), but only where the error for 
the same field without `?` is final. A step that only tries to resolve a name, 
such as ORDER BY against the SELECT list, leaves the reference unresolved, like 
a reference without `?`.
   - **Missing names.** A name resolves to `NULL` if its first name part that 
matches nothing is optional (`OptionalReferences.resolvesToNull`).
     - In the fixed-point analyzer, `ResolveOptionalReferences` runs in a new 
batch after "Resolution". It replaces the optional references of the lowest 
operators that are still unresolved with `NULL`, then runs "Resolution" again, 
until nothing changes. It doesn't touch a plan without unresolved optional 
references. It handles the plan of a subquery expression only after the 
operator around it can't be resolved further, because that operator can still 
change what the subquery resolves to, for example by binding parameters or by 
extracting a generator.
     - In the single-pass resolver, `NameScopeStack.resolveMultipartName` 
returns `NULL` when no source resolves the name.
   - **Single-pass resolver coverage.** `ResolverGuard` sends two cases to the 
fixed-point analyzer: optional named parameter markers, because the single-pass 
resolver doesn't resolve named parameters, and optional fields of expressions 
other than names (`arr[0].f?`), because the two analyzers would produce 
different plans for them in ORDER BY.
   - **Confs.**
     - `spark.sql.optionalReferences.enabled` (internal, default `false`) 
enables the syntax. While it's off, `?` remains a syntax error. A view captures 
the conf, so a view that was created while it was on can still be queried by a 
session that doesn't set it.
     - 
`spark.sql.analyzer.singlePassResolver.enableOptionalReferenceResolution` 
(internal, default `true`) lets `ResolverGuard` admit plans with optional 
references to the single-pass resolver.
   
   ### Why are the changes needed?
   
   The main use case is a query or a view that keeps working while its source 
tables evolve. `CREATE VIEW v AS SELECT id, CAST(deleted_at? AS TIMESTAMP) AS 
deleted_at FROM t` is valid whether or not `t` has the column `deleted_at`, and 
its schema is the same either way. Today this takes either a catalog lookup 
before the query is built or one query variant per schema.
   
   ### Does this PR introduce _any_ user-facing change?
   
   No. The syntax is only accepted while `spark.sql.optionalReferences.enabled` 
is `true`, and the conf is internal and `false` by default. While it's off, 
statements that were valid before parse to the same plans, and a `?` after an 
identifier is still `PARSE_SYNTAX_ERROR`.
   
   For statements that were already invalid, details of the error can differ. 
For example, the message can lose its `: extra input '?'` hint, and `SELECT 
:name ?` raises `PARSE_SYNTAX_ERROR` instead of 
`UNEXPECTED_USE_OF_PARAMETER_MARKER` or `INVALID_QUERY_MIXED_QUERY_PARAMETERS`.
   
   ### How was this patch tested?
   
   - New golden file `optional-references.sql`, with results and analyzer 
results. It has positive and negative cases for:
     - missing and existing columns, and qualified, nested, and three-part 
names with every placement of `?`;
     - the errors that are still raised: ambiguity, invalid field extraction, 
`MISSING_AGGREGATION`, and not-found errors for identifiers without `?`;
     - expressions, predicates, GROUP BY, HAVING, QUALIFY, and ORDER BY 
(including SELECT-list aliases and names that resolve differently in the SELECT 
list and below it), window functions, GROUP BY ALL, joins, common table 
expressions, set operations, lateral column aliases, session and SQL scripting 
variables, correlated, nested, and lateral subqueries, lambda functions, field 
extraction from other expressions, the IDENTIFIER clause, SQL user-defined 
functions, and SQL pipe syntax;
     - casts with `::`, optional named parameter markers (bound, unbound, mixed 
with unmarked occurrences, and mixed with positional markers), and unchanged 
positional markers;
     - temporary and persistent views, including `WITH SCHEMA EVOLUTION`, the 
default schema binding mode, a source table that gains or loses a column, and a 
session that doesn't set the conf;
     - `INSERT ... SELECT`, `VALUES`, and CTAS;
     - the `IN_DML` and `IN_DDL` errors, including common table expressions 
before DML statements and named parameter markers with and without parameter 
values;
     - syntax errors, and the disabled conf.
   - New streaming golden file `streaming/optional-references.sql`, with 
optional references in a flow over a streaming source.
   - New `OptionalReferencesParserSuite` with parser and parameter substitution 
tests.
   - New tests in existing suites:
     - `ResolverGuardSuite`: the single-pass conf and the two cases that fall 
back to the fixed-point analyzer.
     - `ParametersSuite`: optional named parameter markers with 
`spark.sql(sqlText, args)`, in and outside of subqueries, both with and without 
`spark.sql.legacy.parameterSubstitution.constantsOnly`.
     - `DataFrameSuite`: `selectExpr`, `expr`, and `filter` with optional 
references.
     - `DataFrameWriterV2Suite` and `MergeIntoDataFrameSuite`: the `IN_DML` 
error for `overwrite(condition)` and `mergeInto`.
   - The golden files run with both analyzers on every query that the 
single-pass resolver supports, and the two plans are compared.
   - Manual checks:
     - Parsed about 180 statements that have `?` in different positions on 
master and on this branch with the conf off and on. Every statement that is 
valid on master parses to the same plan in all three runs.
     - Measured the bytecode size of `SqlBaseParser.primaryExpression` with 
`javap` on master and on this branch.
   - Ran these existing suites:
     - All suites of the `catalyst` module.
     - `SQLQueryTestSuite` and `StreamingSQLQueryTestSuite` (all golden files), 
and `ThriftServerQueryTestSuite` (the new golden file).
     - `sql/core`: all suites in `org.apache.spark.sql.analysis.resolver`, 
`ParametersSuite`, `ExecuteImmediateEndToEndSuite`, `LateralColumnAliasSuite`, 
`SubquerySuite`, `SQLViewSuite`, `DataFrameSuite`, `DataFrameWriterV2Suite`, 
the SQL scripting suites, and the DELETE, UPDATE, and MERGE suites in 
`org.apache.spark.sql.connector`.
     - `SparkThrowableSuite` and `SparkConfigBindingPolicySuite`.
   
   ### Was this patch authored or co-authored using generative AI tooling?
   
   Generated-by: Isaac (Claude Code, Fable 5.2)
   
   This pull request and its description were written by Isaac.
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to