dtenedor commented on code in PR #60629:
URL: https://github.com/apache/spark/pull/60629#discussion_r4621559243
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/parser/AstBuilder.scala:
##########
@@ -8512,30 +8514,43 @@ class AstBuilder extends DataTypeAstBuilder
withQueryResultClauses(c, PipeOperator(left), forPipeOperators = true)
}.getOrElse(
visitOperatorPipeAggregate(ctx, left)
- ))))))))))))))
+ )))))))))))))))
}
- private def visitOperatorPipeSet(
- ctx: OperatorPipeRightSideContext, left: LogicalPlan): LogicalPlan = {
+ /**
+ * Builds the pipe operator SET or EVAL, named by `clause`. Both replace an
assigned column that
+ * exists in place. EVAL appends a column that does not exist, as EXTEND
would, where SET fails.
+ */
+ private def visitOperatorPipeSetOrEval(
+ ctx: OperatorPipeRightSideContext, left: LogicalPlan, clause: String):
LogicalPlan = {
+ val assignments = ctx.operatorPipeSetAssignmentSeq()
+ withOrigin(assignments) {
+ if (!assignments.DOT.isEmpty) {
+ operationNotAllowed(
+ s"SQL pipe syntax |> $clause operator with multi-part assignment key
" +
+ s"(only single-part keys are allowed)", assignments)
+ }
+ }
val (setIdentifiers: Seq[String], setTargets: Seq[Expression]) =
- visitOperatorPipeSetAssignmentSeq(ctx.operatorPipeSetAssignmentSeq())
+ visitOperatorPipeSetAssignmentSeq(assignments)
+ val appendMissingColumns = clause == PipeOperators.evalClause
var plan = left
setIdentifiers.zip(setTargets).foreach {
case (_, _: Alias) =>
Review Comment:
Nit: I don't think this branch is reachable. `operatorPipeSetAssignmentSeq`
takes a plain `expression`, which can't carry an alias, and the golden output
for `|> eval x = 1 as z` is `PARSE_SYNTAX_ERROR`. So the reworded message is
never shown, for SET or EVAL. Either drop the branch or drop the alias-error
claim from the description.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/unresolved.scala:
##########
@@ -800,6 +808,32 @@ case class UnresolvedStarExceptOrReplace(
filterColumns(expandedCols, exceptPairs)
}
+
+ /**
+ * Expands the star, replacing the columns that match an EXCEPT name and
appending the
+ * replacements of the EXCEPT names that match no column, in EXCEPT list
order.
+ */
+ private def expandStarAppendingMissingReplacements(
+ parameters: ExpandStarParameters): Seq[NamedExpression] = {
+ val replacementList = replacements match {
+ case Some(list) if list.size == excepts.size => list
+ case _ => throw SparkException.internalError(
+ "Appending missing replacements requires one replacement per except")
+ }
+ val expandedAttributes =
AttributeSeq(super.expandStar(parameters).map(_.toAttribute))
+ val (presentExceptsAndReplacements, missingExceptsAndReplacements) =
+ excepts.zip(replacementList).partition { case (exceptParts, _) =>
+ expandedAttributes.resolve(exceptParts, parameters.resolver).isDefined
Review Comment:
`SELECT x, x FROM t |> EVAL x = 1` crashes here instead of failing with
`AMBIGUOUS_REFERENCE`, which the description says a name matching more than one
column should do. Both output columns are the same attribute, so `resolve`
dedupes them (`candidates.distinct` in `resolveCandidates`) and `x` counts as
present. `filterColumns` then matches both columns, and the second match reads
`replacements.get(1)` on a one-element list, throwing
`IndexOutOfBoundsException`. `ResolveReferences.expand` only catches
`AnalysisException`, so this surfaces as an internal error.
This predates the PR (`|> SET x = 1` takes the same path), but EVAL inherits
it. Could you pick one behavior, either `AMBIGUOUS_REFERENCE` or replacing
every match, and add this query as a test?
Related, smaller: `filterColumns` hands out replacements in column order
rather than EXCEPT order, so a node with excepts `[y, x]` over `(x, y)` puts
the replacements in swapped positions. SQL can't reach this, since EVAL builds
one name per node, but looking up each replacement by its except index instead
of a running counter would fix it. A case with two present names out of column
order in `UnresolvedStarExceptOrReplaceSuite` would cover it.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/parser/AstBuilder.scala:
##########
@@ -8512,30 +8514,43 @@ class AstBuilder extends DataTypeAstBuilder
withQueryResultClauses(c, PipeOperator(left), forPipeOperators = true)
}.getOrElse(
visitOperatorPipeAggregate(ctx, left)
- ))))))))))))))
+ )))))))))))))))
}
- private def visitOperatorPipeSet(
- ctx: OperatorPipeRightSideContext, left: LogicalPlan): LogicalPlan = {
+ /**
+ * Builds the pipe operator SET or EVAL, named by `clause`. Both replace an
assigned column that
+ * exists in place. EVAL appends a column that does not exist, as EXTEND
would, where SET fails.
+ */
+ private def visitOperatorPipeSetOrEval(
+ ctx: OperatorPipeRightSideContext, left: LogicalPlan, clause: String):
LogicalPlan = {
+ val assignments = ctx.operatorPipeSetAssignmentSeq()
+ withOrigin(assignments) {
+ if (!assignments.DOT.isEmpty) {
+ operationNotAllowed(
+ s"SQL pipe syntax |> $clause operator with multi-part assignment key
" +
+ s"(only single-part keys are allowed)", assignments)
+ }
+ }
val (setIdentifiers: Seq[String], setTargets: Seq[Expression]) =
- visitOperatorPipeSetAssignmentSeq(ctx.operatorPipeSetAssignmentSeq())
+ visitOperatorPipeSetAssignmentSeq(assignments)
+ val appendMissingColumns = clause == PipeOperators.evalClause
Review Comment:
Nit: this picks the behavior by comparing the display label, so renaming
`evalClause` would silently change semantics. Consider passing
`appendMissingColumns: Boolean` from the call site. That also allows
`Option(ctx.SET).orElse(Option(ctx.EVAL)).map { ... }` above, instead of adding
another level to the `getOrElse` chain.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/parser/AstBuilder.scala:
##########
@@ -8512,30 +8514,43 @@ class AstBuilder extends DataTypeAstBuilder
withQueryResultClauses(c, PipeOperator(left), forPipeOperators = true)
}.getOrElse(
visitOperatorPipeAggregate(ctx, left)
- ))))))))))))))
+ )))))))))))))))
}
- private def visitOperatorPipeSet(
- ctx: OperatorPipeRightSideContext, left: LogicalPlan): LogicalPlan = {
+ /**
+ * Builds the pipe operator SET or EVAL, named by `clause`. Both replace an
assigned column that
+ * exists in place. EVAL appends a column that does not exist, as EXTEND
would, where SET fails.
+ */
+ private def visitOperatorPipeSetOrEval(
+ ctx: OperatorPipeRightSideContext, left: LogicalPlan, clause: String):
LogicalPlan = {
+ val assignments = ctx.operatorPipeSetAssignmentSeq()
+ withOrigin(assignments) {
+ if (!assignments.DOT.isEmpty) {
+ operationNotAllowed(
+ s"SQL pipe syntax |> $clause operator with multi-part assignment key
" +
+ s"(only single-part keys are allowed)", assignments)
+ }
+ }
val (setIdentifiers: Seq[String], setTargets: Seq[Expression]) =
- visitOperatorPipeSetAssignmentSeq(ctx.operatorPipeSetAssignmentSeq())
+ visitOperatorPipeSetAssignmentSeq(assignments)
+ val appendMissingColumns = clause == PipeOperators.evalClause
var plan = left
setIdentifiers.zip(setTargets).foreach {
case (_, _: Alias) =>
operationNotAllowed(
- "SQL pipe syntax |> SET operator with an alias assigned with [AS]
aliasName", ctx)
+ s"SQL pipe syntax |> $clause operator with an alias assigned with
[AS] aliasName", ctx)
case (ident, target) =>
- // Add an UnresolvedStarExceptOrReplace to exclude the SET expression
name from the relation
- // and add the new SET expression to the projection list.
+ // Add an UnresolvedStarExceptOrReplace to exclude the assigned column
from the relation
+ // and add the new expression to the projection list.
// Use a PipeSelect expression to make sure it does not contain any
aggregate functions.
Review Comment:
Nit: there's no `PipeSelect`; this should say `PipeExpression`.
##########
docs/sql-pipe-syntax.md:
##########
@@ -299,6 +303,37 @@ VALUES (0), (1) tab(col)
+---+
```
+#### EVAL
+
+```sql
+|> EVAL <column> = <expression>, ...
+```
+
+Sets columns of the input table to the result of evaluating the provided
expressions. If a column
+appears in the input table, `EVAL` replaces it in place, as `SET` does.
Otherwise, `EVAL` appends it
+after the existing columns, as `EXTEND` does. Each such column reference may
appear in the input
Review Comment:
Nit: "Each such column reference" has nothing to refer to here. Maybe: "A
name that matches more than one column of the input table fails with
`AMBIGUOUS_REFERENCE`."
##########
sql/api/src/main/antlr4/org/apache/spark/sql/catalyst/parser/SqlBaseParser.g4:
##########
@@ -85,7 +85,10 @@ options { tokenVocab = SqlBaseLexer; }
la == DISTRIBUTE || la == SORT || la == LIMIT || la == OFFSET ||
la == AGGREGATE || la == WINDOW || la == LATERAL || la == BIN ||
(la == GAP && _input.LA(3) == FILL && _input.LA(4) == LEFT_PAREN &&
- (_input.LA(5) == PARTITION || _input.LA(5) == ORDER) &&
_input.LA(6) == BY);
+ (_input.LA(5) == PARTITION || _input.LA(5) == ORDER) &&
_input.LA(6) == BY) ||
+ // Requiring an assignment keeps `a | eval`, with a column named
eval, a bitwise OR. DOT
+ // matches a multi-part key, which the parser captures to report a
dedicated error.
+ (la == EVAL && (_input.LA(4) == EQ || _input.LA(4) == DOT));
Review Comment:
This checks the first and third tokens after `|` but not the second, so some
queries that parsed before now fail. In `WHERE (x | eval) = 3`, the tokens
after `|` are `eval`, `)`, `=`, so this returns true. The
`{!isOperatorPipeStart()}?` guard on the bitwise-OR alternative of
`valueExpression` then disables bitwise OR, and the query fails with
`PARSE_SYNTAX_ERROR`. The same happens for `f(x | eval) = 1`, `arr[x | eval] =
1`, `CASE ... THEN x | eval END = 1`, and with `==`. The single-character pipe
is on by default and view text is re-parsed on read, so existing views with
these shapes would break too. That contradicts "Queries that parsed before
parse the same way" in the description.
Columns named after the older pipe keywords already have this problem (`(x |
set) = 1`), but EVAL is new and can avoid it. Suggestion: also require that the
second token after `|` isn't a closing token (`RIGHT_PAREN`, `RIGHT_BRACKET`,
`END`), and add these shapes to the bitwise-OR assertions in the
`PlanParserSuite` test "pipe EVAL after the single-character pipe".
Two smaller points on the same predicate:
- `| EVAL IDENTIFIER('z') = 1` fails after a single `|` but works after
`|>`, because the third token after `|` is `(` rather than `=`.
- The `DOT` branch (multi-part key) has no single-`|` test. `select col from
st | eval col.i1 = 42` should give the same error as the `|>` form.
--
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]