spark-test commented on code in PR #60353:
URL: https://github.com/apache/spark/pull/60353#discussion_r4557248379


##########
sql/api/src/main/antlr4/org/apache/spark/sql/catalyst/parser/SqlBaseParser.g4:
##########
@@ -1309,6 +1309,40 @@ binByClause
       RIGHT_PAREN (AS? tblAlias=errorCapturingIdentifier)?
     ;
 
+gapFillClause
+    : GAP FILL LEFT_PAREN
+        (PARTITION BY partitionCol+=multipartIdentifier
+          (COMMA partitionCol+=multipartIdentifier)*)?
+        ORDER BY timeCol=multipartIdentifier
+        BIN WIDTH binWidth=expression
+        (ALIGN TO origin=expression
+          | FROM rangeStart=expression TO rangeEnd=expression

Review Comment:
   **Blocking (P1):** This alternative changes how Spark's first parsing stage 
predicts unit-to-unit interval literals in statements that do not use GAP FILL. 
That stage runs in SLL mode, which predicts with context-free follow sets. On 
the base branch TO follows a value expression only in `changesClause`, where 
SYSTEM_TIME or TIMESTAMP must come next, so for `INTERVAL '1 2' DAY TO HOUR` 
the multi-unit reading dies at HOUR. Here, HOUR (a non-reserved word) can start 
the range end, so when the literal is followed by `)` and the rest of the 
statement could also follow a relation, both alternatives of the `interval` 
rule stay viable and SLL picks the first one, 
`errorCapturingMultiUnitsInterval`, which then fails at TO.
   
   What happens next depends on the keyword mode:
   
   - With `spark.sql.ansi.enforceReservedKeywords=true` (ANSI is on by 
default), the failure is a NoViableAlt. 
`SparkParserErrorStrategy.reportNoViableAlternative` hands it to 
`ParseErrorListener`, which throws before `executeWithTwoStageStrategy` can 
retry in LL. In a repro with parsers generated from both grammars, `SELECT * 
FROM t WHERE d IN (SELECT INTERVAL '1 2' DAY TO HOUR)`, `SELECT (SELECT 
INTERVAL '2-1' YEAR TO MONTH)`, `SELECT * FROM (SELECT INTERVAL '10:20' MINUTE 
TO SECOND) s` and derived tables under INSERT, CTAS and CREATE VIEW parse on 
the base branch but fail at head with PARSE_SYNTAX_ERROR at 'TO', while an 
LL-only parse of each succeeds.
   - In the default keyword mode the failure is a token mismatch, so the 
statement is re-parsed in LL with an unchanged tree. In the same repro, 31 
statements from `extract.sql` and `interval.sql`, such as `SELECT extract(YEAR 
FROM INTERVAL '2-1' YEAR TO MONTH)`, now take that path, and a 1000-column 
GROUP BY ending in that call went from about 4.8 ms to 52.7 ms per warm parse.
   
   Adding `AND e > 1` after the IN subquery makes the head parser succeed in 
SLL again, so the trigger is what may follow the literal, not the literal 
alone. `spark.sql.gapFillRelationOperator.enabled` gates only the analyzer 
rule, so no setting avoids this.
   
   **Recommended change:** List errorCapturingUnitToUnitInterval before 
errorCapturingMultiUnitsInterval in the `interval` rule of the SQL grammar, 
keeping the GAP FILL range syntax as the PR declares it, and add parser tests 
that pin how statements with unit-to-unit interval literals parse in both 
keyword modes.
   
   **Why this works:** ANTLR resolves an SLL conflict by choosing the 
lowest-numbered conflicting alternative. With the unit-to-unit form listed 
first, the conflict the new GAP FILL range creates resolves to the reading full 
LL context selects for every statement outside a GAP FILL range. SLL then 
succeeds there as it does on the base branch, so no SLL failure is left to 
surface as a syntax error. Inside a GAP FILL range start, where the multi-units 
reading can be the valid one, an SLL misprediction fails where the range syntax 
requires TO, a token mismatch that falls back to LL, which picks the 
full-context reading.
   
   **Scope:** Reorder one alternative in the SQL grammar's interval rule, and 
add parser tests for the interval-literal shapes the new GAP FILL range 
disturbed.
   
   **Compatibility:** The GAP FILL syntax the PR declares, including `FROM 
startExpr TO endExpr`, and the parse trees and error messages of every 
statement that does not use GAP FILL.
   
   **Risks:** Every statement with an interval literal now predicts through the 
reordered decision. The corpus run shows no outcome, tree or error-message 
change against the base branch, but shapes outside the corpus rest on the same 
reasoning rather than on a test. A GAP FILL range start that ends in an 
interval literal followed by TO and a column named like a unit, such as `FROM s 
- INTERVAL '1' YEAR TO month`, now mispredicts in SLL and takes the LL retry. 
It still parses to the same tree, and reverting the reorder undoes this.
   
   **Constraints:** Keep the GAP FILL range syntax as the PR declares it. Do 
not change the two-stage error strategy or remove the parse error listener from 
the SLL stage.
   
   **Exclusions:**
   - Changing Spark's two-stage strategy so that an SLL-stage syntax error also 
falls back to LL is a separate, repository-wide change that this fix does not 
need.
   
   **Success:** With ANSI mode and spark.sql.ansi.enforceReservedKeywords on, 
`SELECT * FROM t WHERE d IN (SELECT INTERVAL '1 2' DAY TO HOUR)`, `SELECT 
(SELECT INTERVAL '2-1' YEAR TO MONTH)` and `SELECT * FROM (SELECT INTERVAL 
'10:20' MINUTE TO SECOND) s` parse to the same plans as on the base branch. In 
both keyword modes, statements such as `SELECT extract(YEAR FROM INTERVAL '2-1' 
YEAR TO MONTH)` and `SELECT signum(INTERVAL '0-0' YEAR TO MONTH)` parse in the 
first (SLL) stage without the LL retry, as on the base branch. GAP FILL 
clauses, including a range whose start ends in an interval literal, parse to 
the same plan nodes as before the change.
   
   **Verification:**
   - **Regression:** With ANSI mode and reserved-keyword enforcement on, parse 
scalar, IN and EXISTS subqueries and derived tables, including derived tables 
under INSERT, CREATE TABLE AS SELECT and CREATE VIEW, whose select list ends in 
a YEAR TO MONTH, DAY TO HOUR or MINUTE TO SECOND interval literal directly 
before the closing parenthesis, with nothing but the end of the statement or an 
alias after that parenthesis, and assert that each produces the base-branch 
plan instead of PARSE_SYNTAX_ERROR.
   - **Regression:** In both keyword modes, parse statements that end by 
closing a unit-to-unit interval literal with a parenthesis, such as extract and 
signum arguments, parenthesized expressions, IN lists and VALUES rows, using 
only the first stage (SLL prediction with the bail strategy), and assert that 
it succeeds without the LL retry.
   - **Compatibility:** Interval literals outside a GAP FILL range, including 
the error-capturing forms that the interval tests exercise, keep their 
base-branch parse trees and error messages in both keyword modes.
   - **Behavior:** In both keyword modes, a GAP FILL range whose start ends in 
an interval literal followed by TO and a column named like a unit parses as a 
multi-unit interval start and a column end.



##########
sql/api/src/main/antlr4/org/apache/spark/sql/catalyst/parser/SqlBaseParser.g4:
##########
@@ -2395,6 +2430,7 @@ operatorPipeRightSide
     | pivotClause unpivotClause?
     | unpivotClause pivotClause?
     | binByClause
+    | gapFillClause

Review Comment:
   **Non-blocking (P2):** `isOperatorPipeStart()` (lines 74-87) decides whether 
a single `|` starts a pipe step by checking the next token against the first 
token of each `operatorPipeRightSide` alternative, including BIN for BIN BY, 
but it has no entry for GAP. 
`spark.sql.parser.singleCharacterPipeOperator.enabled` (public, default true) 
documents `|` as an alternative to `|>`, yet in a repro with the generated head 
parser `FROM t | GAP FILL (ORDER BY ts BIN WIDTH INTERVAL '5' MINUTE)` and 
`TABLE t | GAP FILL (...)` fail with PARSE_SYNTAX_ERROR at '|' in both keyword 
modes, while `FROM t |> GAP FILL (...)` and `FROM t | BIN BY (...)` parse. 
Users who write the `|` spelling get a syntax error instead of 
UNSUPPORTED_FEATURE.GAP_FILL today and will keep getting it after the operator 
works, and only the `|>` form is tested.
   
   A bare `la == GAP` would make `SELECT 1 | gap FROM t`, which parses today as 
bitwise OR with a column named gap, fail the way `SELECT 1 | bin FROM t` 
already does. In the same repro, accepting GAP only when `_input.LA(3) == FILL 
&& _input.LA(4) == LEFT_PAREN` makes the `|` forms parse and keeps `SELECT 1 | 
gap FROM t` and `SELECT a | gap fill FROM t` parsing as bitwise OR.
   
   **Verification:**
   - **Behavior:** With the single-character pipe operator enabled, `| GAP FILL 
(...)` after a FROM or TABLE query, on its own and followed by another pipe 
step, parses to the same plan as the `|>` spelling.
   - **Regression:** With the single-character pipe operator enabled, bitwise 
OR with a column named gap, with and without a following alias named fill, 
keeps parsing as bitwise OR.
   - **Compatibility:** With the single-character pipe operator disabled, `| 
GAP FILL (...)` is still rejected and `|` remains bitwise OR.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ResolveGapFill.scala:
##########
@@ -0,0 +1,40 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.catalyst.analysis
+
+import org.apache.spark.sql.catalyst.plans.logical.{LogicalPlan, 
UnresolvedGapFill}
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.catalyst.trees.TreePattern.UNRESOLVED_GAP_FILL
+import org.apache.spark.sql.errors.QueryCompilationErrors
+import org.apache.spark.sql.internal.SQLConf
+
+/**
+ * Rejects [[UnresolvedGapFill]] until the operator is implemented.
+ *
+ * When `spark.sql.gapFillRelationOperator.enabled` is off, it fails without 
waiting for the
+ * child, so a missing table also gets this error. When it is on, it waits for 
the child to
+ * resolve, so an error in the child (such as a missing table) is still 
reported first.

Review Comment:
   **Nit (P3):** The guard on line 37 only waits for `g.childrenResolved`, and 
the rule throws in the Resolution batch, which runs before CheckAnalysis. So, 
by the review's reading of the code, with the gate on an error that 
CheckAnalysis raises on a child that is already resolved comes after the GAP 
FILL error: in `SELECT * FROM (SELECT * FROM metrics WHERE 1) GAP FILL (ORDER 
BY ts BIN WIDTH INTERVAL '5' MINUTE)`, `Filter(Literal(1))` counts as resolved 
and DATATYPE_MISMATCH.FILTER_NOT_BOOLEAN is raised only by CheckAnalysis, so 
the user would see UNSUPPORTED_FEATURE.GAP_FILL instead. Errors that leave the 
child unresolved, such as a missing table or column, do come first. Consider 
limiting this sentence to those errors, as commit bec270d511e did for the 
gate-off sentence, and saying that errors CheckAnalysis raises on a resolved 
child come after.
   
   **Verification:**
   - **Inspection:** The rule's documentation of the enabled gate limits 
child-first reporting to errors that leave the child unresolved and does not 
claim that every error in the child is reported first.



##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/parser/PlanParserSuite.scala:
##########
@@ -3560,6 +3560,272 @@ class PlanParserSuite extends AnalysisTest {
         |)""".stripMargin)).size == 1)
   }
 
+  test("GAP FILL: clause parses into the expected UnresolvedGapFill") {
+    // Minimal clause without PARTITION BY, optional clauses or a table alias.
+    val minimal = singleGapFill(parsePlan(
+      """SELECT * FROM metrics GAP FILL (
+        |  ORDER BY ts
+        |  BIN WIDTH INTERVAL '5' MINUTE
+        |)""".stripMargin))
+    assert(minimal.partitionColumns.isEmpty)
+    assert(minimal.timeColumn == UnresolvedAttribute(Seq("ts")))
+    assert(minimal.binWidthExpr == parseExpression("INTERVAL '5' MINUTE"))
+    assert(minimal.originExpr.isEmpty)
+    assert(minimal.rangeStartExpr.isEmpty && minimal.rangeEndExpr.isEmpty)
+    assert(minimal.fillColumns.isEmpty)
+    assert(minimal.maxGapExpr.isEmpty)
+    assert(minimal.binStart.isEmpty && minimal.isGenerated.isEmpty)
+
+    // Qualified columns and several PARTITION BY columns.
+    val partitioned = singleGapFill(parsePlan(
+      """SELECT * FROM t1 GAP FILL (
+        |  PARTITION BY t1.region, t1.device_id
+        |  ORDER BY t1.ts
+        |  BIN WIDTH INTERVAL '5' MINUTE
+        |)""".stripMargin))
+    assert(partitioned.partitionColumns == Seq(
+      UnresolvedAttribute(Seq("t1", "region")),
+      UnresolvedAttribute(Seq("t1", "device_id"))))
+    assert(partitioned.timeColumn == UnresolvedAttribute(Seq("t1", "ts")))
+  }
+
+  test("GAP FILL: every clause and fill method parses") {
+    val maximal = singleGapFill(parsePlan(
+      """SELECT * FROM metrics GAP FILL (
+        |  PARTITION BY device_id
+        |  ORDER BY ts
+        |  BIN WIDTH INTERVAL '5' MINUTE
+        |  ALIGN TO TIMESTAMP '2024-01-01 00:02:00'
+        |  FROM TIMESTAMP '2024-01-01 00:00:00' TO TIMESTAMP '2024-01-02 
00:00:00'
+        |  FILL (a LINEAR, b FFILL, c FORWARD FILL, d BFILL, e BACKWARD FILL,
+        |    f CONSTANT 'unknown', g NULL)
+        |  MAX GAP INTERVAL '40' MINUTE
+        |  BIN_START AS bin_begin
+        |  IS_GENERATED AS gen
+        |)""".stripMargin))
+    assert(maximal.partitionColumns == 
Seq(UnresolvedAttribute(Seq("device_id"))))
+    assert(maximal.originExpr.contains(parseExpression("TIMESTAMP '2024-01-01 
00:02:00'")))
+    assert(maximal.rangeStartExpr.contains(parseExpression("TIMESTAMP 
'2024-01-01 00:00:00'")))
+    assert(maximal.rangeEndExpr.contains(parseExpression("TIMESTAMP 
'2024-01-02 00:00:00'")))
+    def fill(name: String, method: GapFillMethod): GapFillColumn =
+      GapFillColumn(UnresolvedAttribute(Seq(name)), method)
+    assert(maximal.fillColumns == Seq(
+      fill("a", GapFillMethod.Linear),
+      fill("b", GapFillMethod.ForwardFill),
+      fill("c", GapFillMethod.ForwardFill),
+      fill("d", GapFillMethod.BackwardFill),
+      fill("e", GapFillMethod.BackwardFill),
+      fill("f", GapFillMethod.Constant(parseExpression("'unknown'"))),
+      fill("g", GapFillMethod.Null)))
+    assert(maximal.maxGapExpr.contains(parseExpression("INTERVAL '40' 
MINUTE")))
+    assert(maximal.binStart.contains(GapFillOutputColumn(Some("bin_begin"))))
+    assert(maximal.isGenerated.contains(GapFillOutputColumn(Some("gen"))))
+  }
+
+  test("GAP FILL: optional clauses can come in any order, with default column 
names") {
+    val inOrder = singleGapFill(parsePlan(
+      """SELECT * FROM t GAP FILL (
+        |  ORDER BY ts BIN WIDTH INTERVAL '5' MINUTE
+        |  ALIGN TO TIMESTAMP '2024-01-01 00:02:00'
+        |  FROM TIMESTAMP '2024-01-01 00:00:00' TO TIMESTAMP '2024-01-02 
00:00:00'
+        |  FILL (a FFILL)
+        |  MAX GAP INTERVAL '40' MINUTE
+        |  BIN_START
+        |  IS_GENERATED
+        |)""".stripMargin))
+    val shuffled = singleGapFill(parsePlan(
+      """SELECT * FROM t GAP FILL (
+        |  ORDER BY ts BIN WIDTH INTERVAL '5' MINUTE
+        |  IS_GENERATED
+        |  MAX GAP INTERVAL '40' MINUTE
+        |  FROM TIMESTAMP '2024-01-01 00:00:00' TO TIMESTAMP '2024-01-02 
00:00:00'
+        |  BIN_START
+        |  FILL (a FFILL)
+        |  ALIGN TO TIMESTAMP '2024-01-01 00:02:00'
+        |)""".stripMargin))
+    assert(inOrder == shuffled)
+    // Without AS, no name is stored, which requests the default name.
+    assert(inOrder.binStart.contains(GapFillOutputColumn(None)))
+    assert(inOrder.isGenerated.contains(GapFillOutputColumn(None)))
+  }
+
+  test("GAP FILL: a repeated clause raises DUPLICATE_CLAUSES") {
+    Seq(
+      "ALIGN TO TIMESTAMP '2024-01-01 00:02:00'" -> "ALIGN TO",
+      "FROM TIMESTAMP '2024-01-01 00:00:00' TO TIMESTAMP '2024-01-02 
00:00:00'" -> "FROM",
+      "FILL (a FFILL)" -> "FILL",
+      "MAX GAP INTERVAL '40' MINUTE" -> "MAX GAP",
+      "BIN_START" -> "BIN_START",
+      "IS_GENERATED" -> "IS_GENERATED").foreach { case (clause, clauseName) =>
+      val sql = s"""SELECT * FROM t GAP FILL (
+         |  ORDER BY ts BIN WIDTH INTERVAL '5' MINUTE
+         |  $clause
+         |  $clause
+         |)""".stripMargin
+      val start = sql.indexOf("GAP")
+      checkError(
+        exception = parseException(sql),
+        condition = "DUPLICATE_CLAUSES",
+        parameters = Map("clauseName" -> clauseName),
+        context = ExpectedContext(
+          fragment = sql.substring(start),
+          start = start,
+          stop = sql.length - 1))
+    }
+  }
+
+  test("GAP FILL: several repeated clauses report the first one in a fixed 
order") {
+    // The order is ALIGN TO, FROM, FILL, MAX GAP, BIN_START, IS_GENERATED, 
wherever the repeats
+    // are in the query.
+    val e = parseException("SELECT * FROM t GAP FILL (ORDER BY ts BIN WIDTH 
INTERVAL '5' MINUTE " +
+      "IS_GENERATED IS_GENERATED ALIGN TO x ALIGN TO y)")
+    assert(e.getCondition == "DUPLICATE_CLAUSES")
+    assert(e.getMessageParameters.get("clauseName") == "ALIGN TO")
+  }
+
+  test("GAP FILL: a syntax error is reported before a repeated clause") {
+    val base = "SELECT * FROM t GAP FILL (ORDER BY ts BIN WIDTH INTERVAL '5' 
MINUTE " +
+      "MAX GAP a MAX GAP b"
+    checkError(
+      exception = parseException(s"$base) AS g (c)"),
+      condition = "PARSE_SYNTAX_ERROR",
+      parameters = Map("error" -> "'('", "hint" -> ""))
+    checkError(
+      exception = parseException(s"$base BOGUS)"),
+      condition = "PARSE_SYNTAX_ERROR",
+      parameters = Map("error" -> "'BOGUS'", "hint" -> ": extra input 
'BOGUS'"))
+  }
+
+  test("GAP FILL: column references carry their own position") {
+    // An error about a GAP FILL column, such as UNRESOLVED_COLUMN, points at 
that column.
+    val sql = "SELECT * FROM t GAP FILL (PARTITION BY p ORDER BY ts " +
+      "BIN WIDTH INTERVAL '5' MINUTE FILL (a FFILL))"
+    val gapFill = singleGapFill(parsePlan(sql))
+    
assert(gapFill.partitionColumns.head.origin.startIndex.contains(sql.indexOf(" p 
") + 1))
+    assert(gapFill.timeColumn.origin.startIndex.contains(sql.indexOf(" ts ") + 
1))
+    
assert(gapFill.fillColumns.head.column.origin.startIndex.contains(sql.indexOf("(a
 ") + 1))
+  }
+
+  test("GAP FILL: table alias with or without AS, and no column aliases") {
+    Seq(") AS g", ") g").foreach { tail =>
+      val parsed = parsePlan(
+        s"""SELECT * FROM metrics GAP FILL (
+           |  ORDER BY ts
+           |  BIN WIDTH INTERVAL '5' MINUTE
+           |$tail""".stripMargin)
+      val aliases = parsed.collect { case s: SubqueryAlias if s.alias == "g" 
=> s }
+      assert(aliases.size == 1, s"alias tail '$tail' did not produce a 
SubqueryAlias")
+      assert(aliases.head.child.isInstanceOf[UnresolvedGapFill])
+    }
+
+    checkError(
+      exception = parseException(
+        """SELECT * FROM metrics GAP FILL (
+          |  ORDER BY ts
+          |  BIN WIDTH INTERVAL '5' MINUTE
+          |) AS g (a, b)""".stripMargin),
+      condition = "PARSE_SYNTAX_ERROR",
+      parameters = Map("error" -> "'('", "hint" -> ""))
+  }
+
+  test("GAP FILL: a join keyword after the clause starts a join, not a table 
alias") {
+    val gapFill = "metrics GAP FILL (ORDER BY ts BIN WIDTH INTERVAL '5' 
MINUTE)"
+    Seq(
+      "LEFT JOIN t ON metrics.k = t.k" -> LeftOuter,
+      "RIGHT JOIN t ON metrics.k = t.k" -> RightOuter,
+      "FULL JOIN t ON metrics.k = t.k" -> FullOuter,
+      "INNER JOIN t ON metrics.k = t.k" -> Inner,
+      "LEFT SEMI JOIN t ON metrics.k = t.k" -> LeftSemi,
+      "LEFT ANTI JOIN t ON metrics.k = t.k" -> LeftAnti,
+      "CROSS JOIN t" -> Cross,
+      "NATURAL JOIN t" -> NaturalJoin(Inner)).foreach { case (join, joinType) 
=>
+      val joins = parsePlan(s"SELECT * FROM $gapFill $join").collect { case j: 
Join => j }
+      assert(joins.map(_.joinType) == Seq(joinType), join)
+      assert(joins.head.left.isInstanceOf[UnresolvedGapFill], join)
+    }
+  }
+
+  test("GAP FILL: works as a SQL pipe operator") {
+    val clause =
+      """GAP FILL (
+        |  PARTITION BY device_id
+        |  ORDER BY ts
+        |  BIN WIDTH INTERVAL '5' MINUTE
+        |  FILL (a FFILL)
+        |)""".stripMargin
+    val direct = singleGapFill(parsePlan(s"SELECT * FROM metrics $clause"))
+    val piped = singleGapFill(parsePlan(s"FROM metrics\n|> $clause"))
+    assert(piped.copy(child = direct.child) == direct)
+    assert(piped.child.collectFirst { case r: UnresolvedRelation => 
r.multipartIdentifier }
+      .contains(Seq("metrics")))
+
+    // A later pipe operator applies to the GAP FILL output.
+    val chained = parsePlan(s"FROM metrics\n|> $clause\n|> WHERE a > 0")
+    val filter = chained.collectFirst { case f: Filter => f }
+    assert(filter.exists(f => gapFillNodes(f).size == 1))
+  }
+
+  test("GAP FILL: malformed clauses raise PARSE_SYNTAX_ERROR") {
+    Seq(
+      "SELECT * FROM t GAP FILL (BIN WIDTH INTERVAL '5' MINUTE)" -> ("'BIN'", 
""),
+      "SELECT * FROM t GAP FILL (ORDER BY ts)" -> ("')'", ""),
+      "SELECT * FROM t GAP FILL (ORDER BY ts BIN WIDTH INTERVAL '5' MINUTE 
FILL ())" -> ("')'", ""),
+      "SELECT * FROM t GAP FILL (ORDER BY ts BIN WIDTH INTERVAL '5' MINUTE 
FILL (a))" ->
+        ("')'", ""),
+      "SELECT * FROM t GAP FILL (ORDER BY ts BIN WIDTH INTERVAL '5' MINUTE " +
+        "MAX INTERVAL '40' MINUTE)" -> ("'INTERVAL'", ": missing 'GAP'"),
+      "SELECT * FROM t GAP FILL (ORDER BY ts PARTITION BY id BIN WIDTH 
INTERVAL '5' MINUTE)" ->
+        ("'PARTITION'", "")
+    ).foreach { case (query, (error, hint)) =>
+      checkError(
+        exception = parseException(query),
+        condition = "PARSE_SYNTAX_ERROR",
+        parameters = Map("error" -> error, "hint" -> hint))
+    }
+  }
+
+  test("GAP FILL: FILL columns and CONSTANT values are visible to plan 
walkers") {
+    // Analyzer rules find expressions through `expressions` and 
`transformExpressions`, so the
+    // FILL columns and the CONSTANT value must be reachable there.
+    val gapFill = singleGapFill(parsePlan(
+      """SELECT * FROM t GAP FILL (
+        |  ORDER BY ts BIN WIDTH INTERVAL '5' MINUTE
+        |  FILL (a CONSTANT upper('x'), b LINEAR)
+        |)""".stripMargin))
+    val reachable = gapFill.expressions.flatMap(_.collect { case e => e })
+    assert(reachable.contains(UnresolvedAttribute(Seq("a"))))
+    assert(reachable.contains(UnresolvedAttribute(Seq("b"))))
+    assert(reachable.exists(_.isInstanceOf[UnresolvedFunction]))
+
+    val renamed = gapFill.transformExpressions {
+      case UnresolvedAttribute(Seq("a")) => UnresolvedAttribute(Seq("renamed"))
+    }.asInstanceOf[UnresolvedGapFill]
+    assert(renamed.fillColumns.head.column == 
UnresolvedAttribute(Seq("renamed")))

Review Comment:
   **Nit (P3):** This assertion checks only the renamed column of the CONSTANT 
entry. By the review's reading, `upper('x')` and `b` come back unchanged, and 
`mapChildren` returns the node itself when no child changes, so neither the 
CONSTANT-value rebuild (`GapFillMethod.Constant(newChildren(1))`) nor the 
non-CONSTANT branch of `GapFillColumn.withNewChildrenInternal` is observed: 
keeping the old CONSTANT value, or returning `this` for a LINEAR entry, would 
still pass. Rewriting `b` and an expression inside the CONSTANT value in the 
same `transformExpressions` call, and asserting that the rebuilt entries keep 
their fill methods, would pin both branches before the resolution PRs rely on 
them.
   
   **Verification:**
   - **Regression:** Rewriting the column of a non-CONSTANT FILL entry and an 
expression inside a CONSTANT value through transformExpressions yields FILL 
entries with the rewritten children and the original fill methods.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala:
##########
@@ -6428,6 +6428,16 @@ object SQLConf {
       .booleanConf
       .createWithDefault(false)
 
+  val GAP_FILL_ENABLED =
+    buildConf("spark.sql.gapFillRelationOperator.enabled")
+      .doc("Enable the GAP FILL relation operator, which adds a row at each 
bin start of a " +

Review Comment:
   **Nit (P3):** This tells readers that the flag enables an operator that adds 
rows, but in this PR both values reject every GAP FILL query: with the flag on, 
`ResolveGapFill` only waits for the child to resolve before throwing 
UNSUPPORTED_FEATURE.GAP_FILL. Flags for unfinished features in this file say 
so, for example 'This feature is currently under development.' at lines 479 and 
497, and BIN BY's similar doc is accurate because BIN BY already resolves when 
its gate is on. Consider saying that the operator is under development, that 
GAP FILL queries are rejected whatever the value, and that when the flag is 
true the rejection waits until the input relation resolves, so errors that 
leave it unresolved, such as a missing table, are reported first.
   
   **Verification:**
   - **Inspection:** The GAP FILL gate's doc describes both values as rejecting 
GAP FILL queries, describes the enabled value only as reporting errors that 
leave the input unresolved first, and does not claim that rows are added.



##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/analysis/ResolveGapFillSuite.scala:
##########
@@ -0,0 +1,82 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.catalyst.analysis
+
+import org.apache.spark.sql.AnalysisException
+import org.apache.spark.sql.catalyst.dsl.expressions._
+import org.apache.spark.sql.catalyst.expressions.Literal
+import org.apache.spark.sql.catalyst.plans.logical.{LocalRelation, 
LogicalPlan, UnresolvedGapFill}
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.types.DayTimeIntervalType
+
+class ResolveGapFillSuite extends AnalysisTest {
+
+  private def unresolved(child: LogicalPlan): UnresolvedGapFill =
+    UnresolvedGapFill(
+      partitionColumns = Nil,
+      timeColumn = $"ts",
+      binWidthExpr = Literal(5L * 60L * 1000000L, DayTimeIntervalType()),
+      originExpr = None,
+      rangeStartExpr = None,
+      rangeEndExpr = None,
+      fillColumns = Nil,
+      maxGapExpr = None,
+      binStart = None,
+      isGenerated = None,
+      child = child)
+
+  private val resolvedInput = LocalRelation($"ts".timestampNTZ)
+  private val missingTable = UnresolvedRelation(Seq("missing"))
+
+  private def expectNotSupported(plan: LogicalPlan): Unit =
+    checkError(
+      exception = intercept[AnalysisException](ResolveGapFill.apply(plan)),
+      condition = "UNSUPPORTED_FEATURE.GAP_FILL",
+      sqlState = "0A000",
+      parameters = Map.empty[String, String])
+
+  test("GAP FILL is rejected as not yet supported once its child is resolved") 
{
+    withSQLConf(SQLConf.GAP_FILL_ENABLED.key -> "true") {
+      val waiting = unresolved(missingTable)
+      // A missing table must still win, so the node is left alone until its 
child resolves.
+      assert(ResolveGapFill.apply(waiting) == waiting)
+      expectNotSupported(unresolved(resolvedInput))
+    }
+  }
+
+  test("GAP FILL is rejected at once when the operator is disabled") {
+    // The gate does not wait for the child, so a missing table also gets this 
error.
+    withSQLConf(SQLConf.GAP_FILL_ENABLED.key -> "false") {
+      expectNotSupported(unresolved(missingTable))
+      expectNotSupported(unresolved(resolvedInput))
+    }
+  }
+
+  test("GAP FILL errors through the full analyzer") {
+    withSQLConf(SQLConf.GAP_FILL_ENABLED.key -> "true") {
+      assertAnalysisErrorCondition(
+        unresolved(resolvedInput), "UNSUPPORTED_FEATURE.GAP_FILL", Map.empty)

Review Comment:
   **Nit (P3):** This full-analyzer gate-on case uses `resolvedInput`, a 
LocalRelation that is resolved before analysis starts, so the rule rejects it 
on its first application wherever it runs, and the other gate-on case uses a 
table that never resolves. The transition the gate exists for, waiting while 
the analyzer resolves a real relation and then rejecting it, has no assertion, 
and `GapFillSuite`'s temp-view query runs with the gate off. One gate-on query 
over a temp view or catalog table through the full analyzer, for example in 
`GapFillSuite` under `withSQLConf(SQLConf.GAP_FILL_ENABLED.key -> "true")`, 
would pin it.
   
   **Verification:**
   - **Behavior:** With the gate on, a GAP FILL query over a relation that the 
analyzer resolves, such as a temp view or catalog table, fails with 
UNSUPPORTED_FEATURE.GAP_FILL.



-- 
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