ganeshashree opened a new pull request, #57630:
URL: https://github.com/apache/spark/pull/57630
<!--
Thanks for sending a pull request! Here are some tips for you:
1. If this is your first time, please read our contributor guidelines:
https://spark.apache.org/contributing.html
2. Ensure you have added or run the appropriate tests for your PR:
https://spark.apache.org/developer-tools.html
3. If the PR is unfinished, add '[WIP]' in your PR title, e.g.,
'[WIP][SPARK-XXXX] Your PR title ...'.
4. Be sure to keep the PR description updated to reflect all changes.
5. Please write your PR title to summarize what this PR proposes.
6. If possible, provide a concise example to reproduce the issue for a
faster review.
7. If you want to add a new configuration, please read the guideline first
for naming configurations in
'core/src/main/scala/org/apache/spark/internal/config/ConfigEntry.scala'.
8. If you want to add or modify an error type or message, please read the
guideline first in
'common/utils/src/main/resources/error/README.md'.
-->
### What changes were proposed in this pull request?
<!--
Please clarify what changes you are proposing. The purpose of this section
is to outline the changes and how this PR fixes the issue.
If possible, please consider writing useful notes for better and faster
reviews in your PR. See the examples below.
1. If you refactor some codes with changing classes, showing the class
hierarchy will help reviewers.
2. If you fix some SQL features, you can provide some references of other
DBMSes.
3. If there is design documentation, please add the link.
4. If there is a discussion in the mailing list, please add the link.
-->
This PR adds support for the ANSI SQL `UNNEST` collection derived table in
the FROM clause:
```sql
UNNEST ( expression [ , ... ] ) [ WITH ORDINALITY ] [ table_alias ]
```
UNNEST expands one or more arrays into a relation, producing one row per
element:
- Multiple arrays are expanded in parallel: the number of output rows equals
the length of the longest array, and shorter arrays are padded with NULLs.
- A NULL array is treated as an empty array and contributes no rows (a NULL
element, by contrast, produces a NULL row).
- WITH ORDINALITY appends a trailing 1-based BIGINT position column.
- Correlated arrays are supported via LATERAL (FROM t, LATERAL
UNNEST(t.arr)), reusing the existing lateral-join
machinery, and LEFT JOIN LATERAL UNNEST(...) ON true preserves outer rows
whose array is empty or NULL.
- Only ARRAY arguments are accepted. Each array contributes exactly one
output column holding its element as-is; unlike inline, an array of structs is
not expanded into one column per field.
The semantics follow PostgreSQL and Trino (parallel multi-array expansion
with NULL padding, 1-based WITH ORDINALITY). BigQuery's single-array UNNEST and
0-based WITH OFFSET are intentionally not adopted.
**References:**
- PostgreSQL:
https://www.postgresql.org/docs/17/queries-table-expressions.html
- Trino: https://trino.io/docs/current/sql/select.html
- BigQuery:
https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax
Implementation notes:
- Grammar: UNNEST and ORDINALITY are added as non-reserved keywords (like
PIVOT/UNPIVOT), so existing identifiers named unnest/ordinality keep working. A
dedicated relationPrimary alternative (#unnestTable) and an unnest production
are added to SqlBaseParser.g4, with matching lexer tokens. A table-valued
function named unnest can still be invoked by quoting the name: `unnest`(...).
- A new Unnest generator expression implements the zip-and-pad plus
ordinality semantics. AstBuilder.visitUnnestTable desugars UNNEST into a
Generate over a OneRowRelation, reusing the shared FROM-clause aliasing helper
(mayApplyAliasPlan). UnnestTableContext is whitelisted in the two LATERAL
validation sites so correlated and LEFT JOIN LATERAL forms work.
- Unnest uses interpreted evaluation (CodegenFallback) with a lazy iterator
(one output row built per pull), consistent with other non-CollectionGenerator
generators such as ReplicateRows. A dedicated whole-stage-codegen path is left
as future work (tracked separately) and is documented in the class scaladoc.
Example:
-- multiple arrays, parallel expansion with NULL padding, plus ordinality
SELECT * FROM UNNEST(array(1, 2), array(10, 20, 30)) WITH ORDINALITY AS t(a,
b, ord);
+----+---+---+
| a| b|ord|
+----+---+---+
| 1| 10| 1|
| 2| 20| 2|
|NULL| 30| 3|
+----+---+---+
### Why are the changes needed?
<!--
Please clarify why the changes are needed. For instance,
1. If you propose a new API, clarify the use case for a new API.
2. If you fix a bug, you can clarify why it is a bug.
-->
UNNEST is part of the SQL:2016 standard and is available in PostgreSQL,
Trino/Presto, and BigQuery (and, via FLATTEN, Snowflake). Spark has no
equivalent ANSI syntax today: users must rewrite UNNEST(...) to LATERAL VIEW
EXPLODE or the DataFrame explode API. This is a recurring pain point in
migrations when porting queries from other engines. Array expansion is an
everyday operation, so this closes a genuine standards-compliance gap with
broad reach.
### Does this PR introduce _any_ user-facing change?
<!--
Note that it means *any* user-facing change including all aspects such as
new features, bug fixes, or other behavior changes. Documentation-only updates
are not considered user-facing changes.
If yes, please clarify the previous behavior and the change this PR proposes
- provide the console output, description and/or an example to show the
behavior difference if possible.
If possible, please also clarify if this is a user-facing change compared to
the released Spark versions or within the unreleased branches such as master.
If no, write 'No'.
-->
Yes. UNNEST(...) [WITH ORDINALITY] can now be used in the FROM clause. This
is a new feature, not a change to existing behavior; UNNEST and ORDINALITY
remain valid as regular (non-reserved) identifiers, so existing queries continue
to parse unchanged. New user-facing SQL reference documentation is added
under docs/sql-ref-syntax-qry-select-unnest.md.
### How was this patch tested?
<!--
If tests were added, say they were added here. Please make sure to add some
test cases that check the changes thoroughly including negative and positive
cases if possible.
If it was tested in a way different from regular unit tests, please clarify
how you tested step by step, ideally copy and paste-able, so that other
reviewers can test and check, and descendants can verify in the future.
If tests were not added, please describe why they were not added and/or why
it was difficult to add.
If benchmark tests were added, please run the benchmarks in GitHub Actions
for the consistent environment, and the instructions could accord to:
https://spark.apache.org/developer-tools.html#github-workflow-benchmarks.
-->
Added new tests:
- GeneratorExpressionSuite — unit tests for the Unnest generator: single and
multiple arrays, WITH ORDINALITY, empty/NULL arrays, column naming/nullability,
lazy evaluation (elements read only as rows are pulled), string/EXPLAIN
representation, and type-check errors.
- PlanParserSuite — parser tests: single/multiple arrays, WITH ORDINALITY,
table and column aliases, LATERAL correlation, non-reserved keyword backwards
compatibility (unnest/ordinality as identifiers), and the quoted-name TVF
escape hatch.
- SQLQueryTestSuite golden-file unnest.sql — end-to-end coverage including
parallel padding, NULL vs empty arrays, NULL elements, nested arrays, LEFT JOIN
LATERAL outer-row preservation, arrays of structs, and error cases (non-array
and MAP arguments).
Regression: existing suites that reference unnest/ordinality (e.g.
postgreSQL/with.sql, which uses ordinality as a CTE and table name) pass
without golden-file regeneration, and generators.sql,
generators-resolution-edge-cases.sql, join-lateral.sql, and postgreSQL/join.sql
all pass.
### Was this patch authored or co-authored using generative AI tooling?
<!--
If generative AI tooling has been used in the process of authoring this
patch, please include the
phrase: 'Generated-by: ' followed by the name of the tool and its version.
If no, write 'No'.
Please refer to the [ASF Generative Tooling
Guidance](https://www.apache.org/legal/generative-tooling.html) for details.
-->
Generated-by: Claude Code (Opus 4.8)
--
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]