You are viewing a plain text version of this content. The canonical link for it is here.
Posted to reviews@spark.apache.org by "anew (via GitHub)" <gi...@apache.org> on 2026/06/10 00:23:34 UTC

[PR] [CONNECT][SDP][SPARK-56249] Create AUTO CDC syntax for SCD Type 1 in SQL [spark]

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

   ### What changes were proposed in this pull request?
   Add SQL syntax for AUTO CDC (Change Data Capture) with SCD Type 1 semantics. Two forms are supported:
   
   1. CREATE FLOW <name> AS AUTO CDC INTO <target> FROM <source> KEYS (...) SEQUENCE BY <expr>
   2. CREATE [OR REFRESH] STREAMING TABLE <name> FLOW AUTO CDC FROM <source> KEYS (...) SEQUENCE BY <expr>
   
   Optional clauses: APPLY AS DELETE WHEN, COLUMNS, COLUMNS * EXCEPT.
   
   ### Why are the changes needed?
   So farm, there is only a Python API for Auto CDC; this adds a SQL API. 
   
   ### Does this PR introduce _any_ user-facing change?
   Yes, it adds a new SQL syntax
   
   ### How was this patch tested?
   New tests are added: AutoCdcParserSuite
   
   ### Was this patch authored or co-authored using generative AI tooling?
   Generated-by: Opus 4.6
   


-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [CONNECT][SDP][SPARK-56249] Create AUTO CDC syntax for SCD Type 1 in SQL [spark]

Posted by "anew (via GitHub)" <gi...@apache.org>.
anew commented on code in PR #56419:
URL: https://github.com/apache/spark/pull/56419#discussion_r3399418357


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/parser/AstBuilder.scala:
##########
@@ -1362,6 +1362,50 @@ class AstBuilder extends DataTypeAstBuilder
       withSchemaEvolution)
   }
 
+  protected def buildAutoCdcIntoCommand(ctx: AutoCdcCommandContext): AutoCdcIntoCommand =
+    withOrigin(ctx) {
+      val target = visitMultipartIdentifier(ctx.target).asTableIdentifier
+      val (src, keys, delete, seq, specCols, exceptCols) =
+        parseAutoCdcParams(ctx.autoCdcParameters())
+      AutoCdcIntoCommand(target, src, keys, delete, seq, specCols, exceptCols)
+    }
+
+  protected def parseAutoCdcParams(params: AutoCdcParametersContext): (
+      LogicalPlan,
+      Seq[UnresolvedAttribute],
+      Option[Expression],
+      Expression,
+      Seq[UnresolvedAttribute],
+      Seq[UnresolvedAttribute]) =
+    withOrigin(params) {
+      checkDuplicateClauses(params.autoCdcDeleteClause(), "APPLY AS DELETE", params)
+      checkDuplicateClauses(params.autoCdcSequenceByClause(), "SEQUENCE BY", params)
+      checkDuplicateClauses(params.autoCdcColumnsClause(), "COLUMNS", params)
+
+      if (params.autoCdcSequenceByClause().isEmpty) {
+        throw QueryParsingErrors.missingClausesForOperation(

Review Comment:
   yes, good suggestion



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [CONNECT][SDP][SPARK-56249] Create AUTO CDC syntax for SCD Type 1 in SQL [spark]

Posted by "anew (via GitHub)" <gi...@apache.org>.
anew commented on code in PR #56419:
URL: https://github.com/apache/spark/pull/56419#discussion_r3406819962


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/AutoCdcIntoCommand.scala:
##########
@@ -0,0 +1,57 @@
+/*
+ * 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.plans.logical
+
+import org.apache.spark.sql.catalyst.TableIdentifier
+import org.apache.spark.sql.catalyst.analysis.UnresolvedAttribute
+import org.apache.spark.sql.catalyst.expressions.{Attribute, Expression}
+
+/**
+ * Logical plan node for an AUTO CDC INTO command, used by Spark Declarative Pipelines.
+ *
+ * This represents a CDC (Change Data Capture) operation that applies an ordered change event
+ * stream from [[sourceTable]] into [[targetTable]] using SCD Type 1 (upsert) semantics.
+ *
+ * This node serves as a parse-time placeholder for a pipeline CDC definition and cannot be
+ * executed directly. It will be interpreted by the pipeline submodule once execution support
+ * is added (SPARK-57402).
+ *
+ * @param targetTable    The target table to apply changes into.
+ * @param sourceTable    The source relation providing the change events.
+ * @param keys           Column(s) that uniquely identify a row in the target table.
+ * @param deleteCondition An optional expression that marks a source row as a DELETE operation.
+ *                        When absent, all source rows are treated as upserts.
+ * @param sequenceByExpr Expression that orders CDC events to correctly resolve out-of-order
+ *                       arrivals. Must evaluate to a sortable type. Required.
+ * @param specifiedCols  An explicit list of source columns to include in the target table.
+ *                       Mutually exclusive with [[exceptCols]].
+ * @param exceptCols     Source columns to exclude from the target table (i.e., all columns
+ *                       except these). Mutually exclusive with [[specifiedCols]].
+ */
+case class AutoCdcIntoCommand(
+    targetTable: TableIdentifier,
+    sourceTable: LogicalPlan,
+    keys: Seq[UnresolvedAttribute],
+    deleteCondition: Option[Expression],
+    sequenceByExpr: Expression,
+    specifiedCols: Seq[UnresolvedAttribute],
+    exceptCols: Seq[UnresolvedAttribute]
+) extends LeafCommand {

Review Comment:
   Probably true. 



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [CONNECT][SDP][SPARK-56249] Create AUTO CDC syntax for SCD Type 1 in SQL [spark]

Posted by "anew (via GitHub)" <gi...@apache.org>.
anew commented on code in PR #56419:
URL: https://github.com/apache/spark/pull/56419#discussion_r3399857191


##########
sql/core/src/test/scala/org/apache/spark/sql/execution/command/v2/AutoCdcParserSuite.scala:
##########
@@ -0,0 +1,392 @@
+/*
+ * 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.execution.command.v2
+
+import org.apache.spark.sql.catalyst.analysis.{
+  AnalysisTest, UnresolvedAttribute,
+  UnresolvedIdentifier, UnresolvedRelation}
+import org.apache.spark.sql.catalyst.parser.ParseException
+import org.apache.spark.sql.catalyst.plans.logical.{
+  AutoCdcIntoCommand,
+  CreateFlowCommand,
+  CreateStreamingTableAutoCdc
+}
+import org.apache.spark.sql.execution.SparkSqlParser
+
+/**
+ * Parser tests for AUTO CDC syntax.
+ *
+ * Covers two supported forms:
+ *   1. CREATE FLOW <name> [COMMENT ...] AS AUTO CDC INTO <target> ...
+ *   2. CREATE STREAMING TABLE <name> FLOW AUTO CDC ...
+ *
+ * Snapshot CDC, SCD Type 2, IGNORE NULL UPDATES, and APPLY AS TRUNCATE WHEN are not
+ * supported and should fail to parse. The standalone AUTO CDC INTO form (without CREATE FLOW
+ * or CREATE STREAMING TABLE) is also not supported.
+ */
+class AutoCdcParserSuite extends CommandSuiteBase with AnalysisTest {
+  protected lazy val parser = new SparkSqlParser()
+
+  // ---------------------------------------------------------------------------
+  // CREATE FLOW ... AS AUTO CDC INTO
+  // ---------------------------------------------------------------------------
+
+  test("CREATE FLOW AS AUTO CDC INTO - minimal form") {
+    val plan = parser.parsePlan(
+      """CREATE FLOW myflow AS AUTO CDC INTO target
+        |FROM source
+        |KEYS (key1, key2)
+        |SEQUENCE BY timestamp""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateFlowCommand]
+    assert(cmd.name.asInstanceOf[UnresolvedIdentifier].nameParts == Seq("myflow"))
+    assert(cmd.comment.isEmpty)
+
+    val cdc = cmd.flowOperation.asInstanceOf[AutoCdcIntoCommand]
+    assert(cdc.targetTable.table == "target")
+    assert(cdc.sourceTable.isInstanceOf[UnresolvedRelation])
+    assert(cdc.keys.map(_.name) == Seq("key1", "key2"))
+    assert(cdc.deleteCondition.isEmpty)
+    assert(cdc.sequenceByExpr == UnresolvedAttribute("timestamp"))
+    assert(cdc.specifiedCols.isEmpty)
+    assert(cdc.exceptCols.isEmpty)
+  }
+
+  test("CREATE FLOW AS AUTO CDC INTO - with COMMENT") {
+    val plan = parser.parsePlan(
+      """CREATE FLOW myflow COMMENT 'my comment' AS AUTO CDC INTO target
+        |FROM source
+        |KEYS (id)
+        |SEQUENCE BY ts""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateFlowCommand]
+    assert(cmd.comment == Some("my comment"))
+  }
+
+  test("CREATE FLOW AS AUTO CDC INTO - multipart flow name") {
+    val plan = parser.parsePlan(
+      """CREATE FLOW mycat.myschema.myflow AS AUTO CDC INTO target
+        |FROM source
+        |KEYS (id)
+        |SEQUENCE BY ts""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateFlowCommand]
+    assert(cmd.name.asInstanceOf[UnresolvedIdentifier].nameParts ==
+      Seq("mycat", "myschema", "myflow"))
+  }
+
+  test("CREATE FLOW AS AUTO CDC INTO - two-part target table name") {
+    val plan = parser.parsePlan(
+      """CREATE FLOW f AS AUTO CDC INTO myschema.mytable
+        |FROM source
+        |KEYS (k)
+        |SEQUENCE BY ts""".stripMargin)
+
+    val cdc = plan.asInstanceOf[CreateFlowCommand].flowOperation.asInstanceOf[AutoCdcIntoCommand]
+    assert(cdc.targetTable.database == Some("myschema"))
+    assert(cdc.targetTable.table == "mytable")
+  }
+
+  test("CREATE FLOW AS AUTO CDC INTO - APPLY AS DELETE WHEN") {
+    val plan = parser.parsePlan(
+      """CREATE FLOW f AS AUTO CDC INTO target
+        |FROM source
+        |KEYS (id)
+        |APPLY AS DELETE WHEN op = 'DELETE'
+        |SEQUENCE BY ts""".stripMargin)
+
+    val cdc = plan.asInstanceOf[CreateFlowCommand].flowOperation.asInstanceOf[AutoCdcIntoCommand]
+    assert(cdc.deleteCondition.isDefined)
+    assert(cdc.deleteCondition.get.sql.contains("op"))
+  }
+
+  test("CREATE FLOW AS AUTO CDC INTO - COLUMNS include list") {
+    val plan = parser.parsePlan(
+      """CREATE FLOW f AS AUTO CDC INTO target
+        |FROM source
+        |KEYS (id)
+        |SEQUENCE BY ts
+        |COLUMNS id, name, value""".stripMargin)
+
+    val cdc = plan.asInstanceOf[CreateFlowCommand].flowOperation.asInstanceOf[AutoCdcIntoCommand]
+    assert(cdc.specifiedCols.map(_.name) == Seq("id", "name", "value"))
+    assert(cdc.exceptCols.isEmpty)
+  }
+
+  test("CREATE FLOW AS AUTO CDC INTO - COLUMNS * EXCEPT list") {
+    val plan = parser.parsePlan(
+      """CREATE FLOW f AS AUTO CDC INTO target
+        |FROM source
+        |KEYS (id)
+        |SEQUENCE BY ts
+        |COLUMNS * EXCEPT (op, ts)""".stripMargin)
+
+    val cdc = plan.asInstanceOf[CreateFlowCommand].flowOperation.asInstanceOf[AutoCdcIntoCommand]
+    assert(cdc.specifiedCols.isEmpty)
+    assert(cdc.exceptCols.map(_.name) == Seq("op", "ts"))
+  }
+
+  test("CREATE FLOW AS AUTO CDC INTO - all clauses combined") {
+    val plan = parser.parsePlan(
+      """CREATE FLOW f AS AUTO CDC INTO target
+        |FROM source
+        |KEYS (key1, key2)
+        |APPLY AS DELETE WHEN key3 = 3
+        |SEQUENCE BY timestamp
+        |COLUMNS key1, key2, key3, timestamp""".stripMargin)
+
+    val cdc = plan.asInstanceOf[CreateFlowCommand].flowOperation.asInstanceOf[AutoCdcIntoCommand]
+    assert(cdc.keys.map(_.name) == Seq("key1", "key2"))
+    assert(cdc.deleteCondition.isDefined)
+    assert(cdc.sequenceByExpr == UnresolvedAttribute("timestamp"))
+    assert(cdc.specifiedCols.map(_.name) == Seq("key1", "key2", "key3", "timestamp"))
+  }
+
+  // ---------------------------------------------------------------------------
+  // CREATE STREAMING TABLE ... FLOW AUTO CDC
+  // ---------------------------------------------------------------------------
+
+  test("CREATE STREAMING TABLE FLOW AUTO CDC - minimal form") {
+    val plan = parser.parsePlan(
+      """CREATE STREAMING TABLE target
+        |FLOW AUTO CDC
+        |FROM source
+        |KEYS (key1, key2)
+        |SEQUENCE BY timestamp""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateStreamingTableAutoCdc]
+    assert(cmd.name.asInstanceOf[UnresolvedIdentifier].nameParts == Seq("target"))
+    assert(!cmd.ifNotExists)
+    assert(cmd.sourceTable.isInstanceOf[UnresolvedRelation])
+    assert(cmd.keys.map(_.name) == Seq("key1", "key2"))
+    assert(cmd.deleteCondition.isEmpty)
+    assert(cmd.sequenceByExpr == UnresolvedAttribute("timestamp"))
+    assert(cmd.specifiedCols.isEmpty)
+    assert(cmd.exceptCols.isEmpty)
+  }
+
+  test("CREATE STREAMING TABLE IF NOT EXISTS FLOW AUTO CDC") {
+    val plan = parser.parsePlan(
+      """CREATE STREAMING TABLE IF NOT EXISTS target
+        |FLOW AUTO CDC
+        |FROM source
+        |KEYS (id)
+        |SEQUENCE BY ts""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateStreamingTableAutoCdc]
+    assert(cmd.ifNotExists)
+  }
+
+  test("CREATE STREAMING TABLE FLOW AUTO CDC - multipart table name") {
+    val plan = parser.parsePlan(
+      """CREATE STREAMING TABLE myschema.mytable
+        |FLOW AUTO CDC
+        |FROM source
+        |KEYS (id)
+        |SEQUENCE BY ts""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateStreamingTableAutoCdc]
+    assert(cmd.name.asInstanceOf[UnresolvedIdentifier].nameParts == Seq("myschema", "mytable"))
+  }
+
+  test("CREATE STREAMING TABLE FLOW AUTO CDC - APPLY AS DELETE WHEN") {
+    val plan = parser.parsePlan(
+      """CREATE STREAMING TABLE target
+        |FLOW AUTO CDC
+        |FROM source
+        |KEYS (id)
+        |APPLY AS DELETE WHEN op = 'DELETE'
+        |SEQUENCE BY ts""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateStreamingTableAutoCdc]
+    assert(cmd.deleteCondition.isDefined)
+    assert(cmd.deleteCondition.get.sql.contains("op"))
+  }
+
+  test("CREATE STREAMING TABLE FLOW AUTO CDC - COLUMNS include list") {
+    val plan = parser.parsePlan(
+      """CREATE STREAMING TABLE target
+        |FLOW AUTO CDC
+        |FROM source
+        |KEYS (id)
+        |SEQUENCE BY ts
+        |COLUMNS id, name, value""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateStreamingTableAutoCdc]
+    assert(cmd.specifiedCols.map(_.name) == Seq("id", "name", "value"))
+    assert(cmd.exceptCols.isEmpty)
+  }
+
+  test("CREATE STREAMING TABLE FLOW AUTO CDC - COLUMNS * EXCEPT list") {
+    val plan = parser.parsePlan(
+      """CREATE STREAMING TABLE target
+        |FLOW AUTO CDC
+        |FROM source
+        |KEYS (id)
+        |SEQUENCE BY ts
+        |COLUMNS * EXCEPT (op, ts)""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateStreamingTableAutoCdc]
+    assert(cmd.specifiedCols.isEmpty)
+    assert(cmd.exceptCols.map(_.name) == Seq("op", "ts"))
+  }
+
+  test("CREATE STREAMING TABLE FLOW AUTO CDC - all clauses combined") {
+    val plan = parser.parsePlan(
+      """CREATE STREAMING TABLE target
+        |FLOW AUTO CDC
+        |FROM source
+        |KEYS (key1, key2)
+        |APPLY AS DELETE WHEN key3 = 3
+        |SEQUENCE BY timestamp
+        |COLUMNS * EXCEPT (key4)""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateStreamingTableAutoCdc]
+    assert(cmd.keys.map(_.name) == Seq("key1", "key2"))
+    assert(cmd.deleteCondition.isDefined)
+    assert(cmd.sequenceByExpr == UnresolvedAttribute("timestamp"))
+    assert(cmd.exceptCols.map(_.name) == Seq("key4"))
+  }
+
+  // ---------------------------------------------------------------------------
+  // Error cases: missing required clause
+  // ---------------------------------------------------------------------------
+
+  test("CREATE FLOW AS AUTO CDC INTO - SEQUENCE BY is required") {
+    val e = intercept[ParseException] {
+      parser.parsePlan(
+        """CREATE FLOW f AS AUTO CDC INTO target
+          |FROM source
+          |KEYS (id)""".stripMargin)
+    }
+    assert(e.getCondition == "MISSING_CLAUSES_FOR_OPERATION")
+    assert(e.getMessageParameters.get("clauses") == "SEQUENCE BY")
+    assert(e.getMessageParameters.get("operation") == "AUTO CDC INTO")
+  }
+
+  test("CREATE STREAMING TABLE FLOW AUTO CDC - SEQUENCE BY is required") {
+    intercept[ParseException] {
+      parser.parsePlan(
+        """CREATE STREAMING TABLE target
+          |FLOW AUTO CDC
+          |FROM source
+          |KEYS (id)""".stripMargin)
+    }
+  }
+
+  // ---------------------------------------------------------------------------
+  // Error cases: duplicate clauses
+  // ---------------------------------------------------------------------------
+
+  test("duplicate SEQUENCE BY clause") {

Review Comment:
   OK, for those cases, I can just assert PARSE_SYNTAX_ERROR



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [CONNECT][SDP][SPARK-56249] Create AUTO CDC syntax for SCD Type 1 in SQL [spark]

Posted by "anew (via GitHub)" <gi...@apache.org>.
anew commented on code in PR #56419:
URL: https://github.com/apache/spark/pull/56419#discussion_r3399414626


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/v2Commands.scala:
##########
@@ -824,6 +824,47 @@ case class CreateStreamingTable(
     copy(name = newChild)
 }
 
+/**
+ * Command parsed from `CREATE STREAMING TABLE <name> FLOW AUTO CDC ...` SQL syntax.
+ * This command serves as a parse-time placeholder for a pipeline CDC definition and cannot be
+ * executed directly. It is interpreted by the pipeline submodule during a pipeline execution.

Review Comment:
   OK, I thought this would be ok since I will follow up with that in the next PR. 



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [CONNECT][SDP][SPARK-56249] Create AUTO CDC syntax for SCD Type 1 in SQL [spark]

Posted by "anew (via GitHub)" <gi...@apache.org>.
anew commented on code in PR #56419:
URL: https://github.com/apache/spark/pull/56419#discussion_r3406769635


##########
common/utils/src/main/resources/error/error-conditions.json:
##########
@@ -5529,6 +5529,12 @@
     },
     "sqlState" : "0A000"
   },
+  "MISSING_CLAUSES_FOR_OPERATION" : {
+    "message" : [
+      "Missing required clause(s) <clauses> for operation <operation>."
+    ],
+    "sqlState" : "42601"

Review Comment:
   this is now obsolete, with the fixed order it cannot happen any more



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [CONNECT][SDP][SPARK-56249] Create AUTO CDC syntax for SCD Type 1 in SQL [spark]

Posted by "anew (via GitHub)" <gi...@apache.org>.
anew commented on code in PR #56419:
URL: https://github.com/apache/spark/pull/56419#discussion_r3464309574


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/parser/AstBuilder.scala:
##########
@@ -1362,6 +1362,44 @@ class AstBuilder extends DataTypeAstBuilder
       withSchemaEvolution)
   }
 
+  protected def buildAutoCdcIntoCommand(ctx: AutoCdcCommandContext): AutoCdcIntoCommand =
+    withOrigin(ctx) {
+      val target = visitMultipartIdentifier(ctx.target).asTableIdentifier
+      val (src, keys, delete, seq, specCols, exceptCols) =
+        parseAutoCdcParams(ctx.autoCdcParameters())
+      AutoCdcIntoCommand(target, src, keys, delete, seq, specCols, exceptCols)
+    }
+
+  protected def parseAutoCdcParams(params: AutoCdcParametersContext): (
+      LogicalPlan,
+      Seq[UnresolvedAttribute],
+      Option[Expression],
+      Expression,
+      Seq[UnresolvedAttribute],
+      Seq[UnresolvedAttribute]) =
+    withOrigin(params) {
+      val sourceTable = plan(params.source) match {
+        case r: UnresolvedRelation => r.copy(isStreaming = true)
+        case other => other

Review Comment:
   Should I then change the syntax to only accept a tableidentifier?



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [CONNECT][SDP][SPARK-56249] Create AUTO CDC syntax for SCD Type 1 in SQL [spark]

Posted by "AnishMahto (via GitHub)" <gi...@apache.org>.
AnishMahto commented on code in PR #56419:
URL: https://github.com/apache/spark/pull/56419#discussion_r3410612346


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/parser/AstBuilder.scala:
##########
@@ -1362,6 +1362,44 @@ class AstBuilder extends DataTypeAstBuilder
       withSchemaEvolution)
   }
 
+  protected def buildAutoCdcIntoCommand(ctx: AutoCdcCommandContext): AutoCdcIntoCommand =
+    withOrigin(ctx) {
+      val target = visitMultipartIdentifier(ctx.target).asTableIdentifier
+      val (src, keys, delete, seq, specCols, exceptCols) =
+        parseAutoCdcParams(ctx.autoCdcParameters())
+      AutoCdcIntoCommand(target, src, keys, delete, seq, specCols, exceptCols)
+    }
+
+  protected def parseAutoCdcParams(params: AutoCdcParametersContext): (
+      LogicalPlan,
+      Seq[UnresolvedAttribute],
+      Option[Expression],
+      Expression,
+      Seq[UnresolvedAttribute],
+      Seq[UnresolvedAttribute]) =
+    withOrigin(params) {
+      val sourceTable = plan(params.source) match {
+        case r: UnresolvedRelation => r.copy(isStreaming = true)

Review Comment:
   Instead of silently forcing the unresolved relation to be streaming, can we just throw if the user tries specifying a non-streaming relation? The error can guide users to use `STREAM`.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/parser/AstBuilder.scala:
##########
@@ -1362,6 +1362,44 @@ class AstBuilder extends DataTypeAstBuilder
       withSchemaEvolution)
   }
 
+  protected def buildAutoCdcIntoCommand(ctx: AutoCdcCommandContext): AutoCdcIntoCommand =
+    withOrigin(ctx) {
+      val target = visitMultipartIdentifier(ctx.target).asTableIdentifier
+      val (src, keys, delete, seq, specCols, exceptCols) =
+        parseAutoCdcParams(ctx.autoCdcParameters())
+      AutoCdcIntoCommand(target, src, keys, delete, seq, specCols, exceptCols)
+    }
+
+  protected def parseAutoCdcParams(params: AutoCdcParametersContext): (
+      LogicalPlan,
+      Seq[UnresolvedAttribute],
+      Option[Expression],
+      Expression,
+      Seq[UnresolvedAttribute],
+      Seq[UnresolvedAttribute]) =
+    withOrigin(params) {
+      val sourceTable = plan(params.source) match {
+        case r: UnresolvedRelation => r.copy(isStreaming = true)
+        case other => other

Review Comment:
   Eventually in SDP we expect `source` to simply be a string identifier: 
   https://github.com/apache/spark/blob/62e4e166698f95bcbeb16687ceaa61a3a8f14dbc/sql/connect/server/src/main/scala/org/apache/spark/sql/connect/pipelines/PipelinesHandler.scala#L444
   
   https://github.com/apache/spark/blob/62e4e166698f95bcbeb16687ceaa61a3a8f14dbc/sql/connect/common/src/main/protobuf/spark/connect/pipelines.proto#L162



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/parser/AstBuilder.scala:
##########
@@ -1362,6 +1362,44 @@ class AstBuilder extends DataTypeAstBuilder
       withSchemaEvolution)
   }
 
+  protected def buildAutoCdcIntoCommand(ctx: AutoCdcCommandContext): AutoCdcIntoCommand =
+    withOrigin(ctx) {
+      val target = visitMultipartIdentifier(ctx.target).asTableIdentifier
+      val (src, keys, delete, seq, specCols, exceptCols) =
+        parseAutoCdcParams(ctx.autoCdcParameters())
+      AutoCdcIntoCommand(target, src, keys, delete, seq, specCols, exceptCols)
+    }
+
+  protected def parseAutoCdcParams(params: AutoCdcParametersContext): (
+      LogicalPlan,
+      Seq[UnresolvedAttribute],
+      Option[Expression],
+      Expression,
+      Seq[UnresolvedAttribute],
+      Seq[UnresolvedAttribute]) =
+    withOrigin(params) {
+      val sourceTable = plan(params.source) match {
+        case r: UnresolvedRelation => r.copy(isStreaming = true)
+        case other => other

Review Comment:
   Should we invalidate against all other logical plans?
   
   I don't know how this concretely maps against logical plan subclasses, but at the syntax level we should only be allowing source to be a multipart identifier, or STREAM(multipart identifier).
   
   I _think_ both of these will map directly to an `UnresolvedRelation`. And then can we take this a further where `AutoCdcIntoCommand` requires `source` to be a `TableIdentifier`/`Identifier` rather than an arbitrary `LogicalPlan`? Then I guess `AutoCdcIntoCommand` can go back to being a leaf plan type.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/SparkSqlParser.scala:
##########
@@ -1548,22 +1549,43 @@ class SparkSqlAstBuilder extends AstBuilder {
     )
   }
 
-  override def visitCreatePipelineDataset(
-      ctx: CreatePipelineDatasetContext): LogicalPlan = withOrigin(ctx) {
-    val createPipelineDatasetHeaderCtx = ctx.createPipelineDatasetHeader()
-
-    val syntaxTypeErrorStr = if (createPipelineDatasetHeaderCtx.materializedView() != null) {
-      "MATERIALIZED VIEW"
-    } else if (createPipelineDatasetHeaderCtx.streamingTable() != null) {
-      "STREAMING TABLE"
-    } else {
-      // Should never be possible based on grammar definition.
-      throw invalidStatement(ctx.getText, ctx)
-    }
+  override def visitCreateFlowAutoCdc(
+      ctx: CreateFlowAutoCdcContext): LogicalPlan = withOrigin(ctx) {
+    val flowHeaderCtx = ctx.createPipelineFlowHeader()
+    val ident = withIdentClause(flowHeaderCtx.flowName, UnresolvedIdentifier(_))
+    val commentOpt = Option(flowHeaderCtx.commentSpec()).map(visitCommentSpec)
+    val applyChanges = buildAutoCdcIntoCommand(ctx.autoCdcCommand())
+    CreateFlowCommand(
+      name = ident,
+      flowOperation = applyChanges,
+      comment = commentOpt
+    )
+  }
 
-    val ifNotExists = createPipelineDatasetHeaderCtx.EXISTS() != null
-    val provider = Option(ctx.tableProvider).map(_.multipartIdentifier.getText)
-    val (colDefs, colConstraints) = Option(ctx.tableElementList()).map(visitTableElementList)
+  /**
+   * Shared helper for pipeline dataset creation statements (CREATE STREAMING TABLE,
+   * CREATE MATERIALIZED VIEW, CREATE STREAMING TABLE ... FLOW AUTO CDC).
+   *
+   * Validates and extracts column definitions, partitioning, and table spec from the common
+   * grammar elements shared by these statements.
+   *
+   * @return (colDefs, partitioning, spec, ifNotExists, tableIdent)
+   */
+  private def parsePipelineDatasetPrelude(

Review Comment:
   Do we still need this function now that the same `createPipelineDataset` rule is hit for both `AS query` and `FLOW AUTO CDC` sub-rules?



##########
sql/api/src/main/antlr4/org/apache/spark/sql/catalyst/parser/SqlBaseParser.g4:
##########
@@ -750,6 +751,37 @@ dmlStatementNoWith
         notMatchedBySourceClause*                                                  #mergeIntoTable
     ;
 
+autoCdcCommand
+    : AUTO CDC INTO target=multipartIdentifier
+        autoCdcParameters
+    ;
+
+autoCdcBody
+    : AUTO CDC autoCdcParameters
+    ;
+
+autoCdcParameters
+    : FROM source=relationPrimary
+        KEYS LEFT_PAREN keys=multipartIdentifierList RIGHT_PAREN

Review Comment:
   For keys and the column selection clause, we don't actually allow multipart identifiers as part of the AutoCDC API contract.
   
   Should we use `identifier` instead of `multipartIdentifierList` to reflect this? Either way SDP will invalidate multipart identifiers, but I figure we should make it true be construction where possible.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/parser/AstBuilder.scala:
##########
@@ -1362,6 +1362,44 @@ class AstBuilder extends DataTypeAstBuilder
       withSchemaEvolution)
   }
 
+  protected def buildAutoCdcIntoCommand(ctx: AutoCdcCommandContext): AutoCdcIntoCommand =
+    withOrigin(ctx) {
+      val target = visitMultipartIdentifier(ctx.target).asTableIdentifier
+      val (src, keys, delete, seq, specCols, exceptCols) =
+        parseAutoCdcParams(ctx.autoCdcParameters())
+      AutoCdcIntoCommand(target, src, keys, delete, seq, specCols, exceptCols)
+    }
+
+  protected def parseAutoCdcParams(params: AutoCdcParametersContext): (
+      LogicalPlan,
+      Seq[UnresolvedAttribute],
+      Option[Expression],
+      Expression,
+      Seq[UnresolvedAttribute],
+      Seq[UnresolvedAttribute]) =

Review Comment:
   optional: Might be nice to put this in a case class before returning, and then `AutoCdcIntoCommand` can also just hold a reference to said case class. Or maybe even just directly return an `AutoCdcIntoCommand` from this function.
   
   I generally don't like returning a tuple longer than 2-3 elements, its hard to keep track of position <-> semantic value mentally.



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [CONNECT][SDP][SPARK-56249] Create AUTO CDC syntax for SCD Type 1 in SQL [spark]

Posted by "szehon-ho (via GitHub)" <gi...@apache.org>.
szehon-ho commented on PR #56419:
URL: https://github.com/apache/spark/pull/56419#issuecomment-4907637379

   Merged to master, 4.x, thanks!


-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [CONNECT][SDP][SPARK-56249] Create AUTO CDC syntax for SCD Type 1 in SQL [spark]

Posted by "anew (via GitHub)" <gi...@apache.org>.
anew commented on code in PR #56419:
URL: https://github.com/apache/spark/pull/56419#discussion_r3406765888


##########
sql/core/src/test/scala/org/apache/spark/sql/execution/command/v2/AutoCdcParserSuite.scala:
##########
@@ -0,0 +1,494 @@
+/*
+ * 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.execution.command.v2
+
+import org.apache.spark.sql.catalyst.analysis.{
+  AnalysisTest, UnresolvedAttribute,
+  UnresolvedIdentifier, UnresolvedRelation}
+import org.apache.spark.sql.catalyst.parser.ParseException
+import org.apache.spark.sql.catalyst.plans.logical.{
+  AutoCdcIntoCommand,
+  CreateFlowCommand,
+  CreateStreamingTableAutoCdc
+}
+import org.apache.spark.sql.execution.SparkSqlParser
+
+/**
+ * Parser tests for AUTO CDC syntax.
+ *
+ * Covers two supported forms:
+ *   1. CREATE FLOW <name> [COMMENT ...] AS AUTO CDC INTO <target> ...
+ *   2. CREATE STREAMING TABLE <name> FLOW AUTO CDC ...
+ *
+ * Snapshot CDC, SCD Type 2, IGNORE NULL UPDATES, and APPLY AS TRUNCATE WHEN are not
+ * supported and should fail to parse. The standalone AUTO CDC INTO form (without CREATE FLOW
+ * or CREATE STREAMING TABLE) is also not supported.
+ */
+class AutoCdcParserSuite extends CommandSuiteBase with AnalysisTest {
+  protected lazy val parser = new SparkSqlParser()
+
+  // ---------------------------------------------------------------------------
+  // CREATE FLOW ... AS AUTO CDC INTO
+  // ---------------------------------------------------------------------------
+
+  test("CREATE FLOW AS AUTO CDC INTO - minimal form") {
+    val plan = parser.parsePlan(
+      """CREATE FLOW myflow AS AUTO CDC INTO target
+        |FROM source
+        |KEYS (key1, key2)
+        |SEQUENCE BY timestamp""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateFlowCommand]
+    assert(cmd.name.asInstanceOf[UnresolvedIdentifier].nameParts == Seq("myflow"))
+    assert(cmd.comment.isEmpty)
+
+    val cdc = cmd.flowOperation.asInstanceOf[AutoCdcIntoCommand]
+    assert(cdc.targetTable.table == "target")
+    assert(cdc.sourceTable.isInstanceOf[UnresolvedRelation])
+    assert(cdc.sourceTable.asInstanceOf[UnresolvedRelation].isStreaming)
+    assert(cdc.keys.map(_.name) == Seq("key1", "key2"))
+    assert(cdc.deleteCondition.isEmpty)
+    assert(cdc.sequenceByExpr == UnresolvedAttribute("timestamp"))
+    assert(cdc.specifiedCols.isEmpty)
+    assert(cdc.exceptCols.isEmpty)
+  }
+
+  test("CREATE FLOW AS AUTO CDC INTO - with COMMENT") {
+    val plan = parser.parsePlan(
+      """CREATE FLOW myflow COMMENT 'my comment' AS AUTO CDC INTO target
+        |FROM source
+        |KEYS (id)
+        |SEQUENCE BY ts""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateFlowCommand]
+    assert(cmd.comment == Some("my comment"))
+  }
+
+  test("CREATE FLOW AS AUTO CDC INTO - multipart flow name") {
+    val plan = parser.parsePlan(
+      """CREATE FLOW mycat.myschema.myflow AS AUTO CDC INTO target
+        |FROM source
+        |KEYS (id)
+        |SEQUENCE BY ts""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateFlowCommand]
+    assert(cmd.name.asInstanceOf[UnresolvedIdentifier].nameParts ==
+      Seq("mycat", "myschema", "myflow"))
+  }
+
+  test("CREATE FLOW AS AUTO CDC INTO - two-part target table name") {
+    val plan = parser.parsePlan(
+      """CREATE FLOW f AS AUTO CDC INTO myschema.mytable
+        |FROM source
+        |KEYS (k)
+        |SEQUENCE BY ts""".stripMargin)
+
+    val cdc = plan.asInstanceOf[CreateFlowCommand].flowOperation.asInstanceOf[AutoCdcIntoCommand]
+    assert(cdc.targetTable.database == Some("myschema"))
+    assert(cdc.targetTable.table == "mytable")
+  }
+
+  test("CREATE FLOW AS AUTO CDC INTO - APPLY AS DELETE WHEN") {
+    val plan = parser.parsePlan(
+      """CREATE FLOW f AS AUTO CDC INTO target
+        |FROM source
+        |KEYS (id)
+        |APPLY AS DELETE WHEN op = 'DELETE'
+        |SEQUENCE BY ts""".stripMargin)
+
+    val cdc = plan.asInstanceOf[CreateFlowCommand].flowOperation.asInstanceOf[AutoCdcIntoCommand]
+    assert(cdc.deleteCondition.isDefined)
+    assert(cdc.deleteCondition.get.sql.contains("op"))
+  }
+
+  test("CREATE FLOW AS AUTO CDC INTO - COLUMNS include list") {
+    val plan = parser.parsePlan(
+      """CREATE FLOW f AS AUTO CDC INTO target
+        |FROM source
+        |KEYS (id)
+        |SEQUENCE BY ts
+        |COLUMNS id, name, value""".stripMargin)
+
+    val cdc = plan.asInstanceOf[CreateFlowCommand].flowOperation.asInstanceOf[AutoCdcIntoCommand]
+    assert(cdc.specifiedCols.map(_.name) == Seq("id", "name", "value"))
+    assert(cdc.exceptCols.isEmpty)
+  }
+
+  test("CREATE FLOW AS AUTO CDC INTO - COLUMNS * EXCEPT list") {
+    val plan = parser.parsePlan(
+      """CREATE FLOW f AS AUTO CDC INTO target
+        |FROM source
+        |KEYS (id)
+        |SEQUENCE BY ts
+        |COLUMNS * EXCEPT (op, ts)""".stripMargin)
+
+    val cdc = plan.asInstanceOf[CreateFlowCommand].flowOperation.asInstanceOf[AutoCdcIntoCommand]
+    assert(cdc.specifiedCols.isEmpty)
+    assert(cdc.exceptCols.map(_.name) == Seq("op", "ts"))
+  }
+
+  test("CREATE FLOW AS AUTO CDC INTO - all clauses combined") {
+    val plan = parser.parsePlan(
+      """CREATE FLOW f AS AUTO CDC INTO target
+        |FROM source
+        |KEYS (key1, key2)
+        |APPLY AS DELETE WHEN key3 = 3
+        |SEQUENCE BY timestamp
+        |COLUMNS key1, key2, key3, timestamp""".stripMargin)
+
+    val cdc = plan.asInstanceOf[CreateFlowCommand].flowOperation.asInstanceOf[AutoCdcIntoCommand]
+    assert(cdc.keys.map(_.name) == Seq("key1", "key2"))
+    assert(cdc.deleteCondition.isDefined)
+    assert(cdc.sequenceByExpr == UnresolvedAttribute("timestamp"))
+    assert(cdc.specifiedCols.map(_.name) == Seq("key1", "key2", "key3", "timestamp"))
+  }
+
+  // ---------------------------------------------------------------------------
+  // CREATE STREAMING TABLE ... FLOW AUTO CDC
+  // ---------------------------------------------------------------------------
+
+  test("CREATE STREAMING TABLE FLOW AUTO CDC - minimal form") {
+    val plan = parser.parsePlan(
+      """CREATE STREAMING TABLE target
+        |FLOW AUTO CDC
+        |FROM source
+        |KEYS (key1, key2)
+        |SEQUENCE BY timestamp""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateStreamingTableAutoCdc]
+    assert(cmd.name.asInstanceOf[UnresolvedIdentifier].nameParts == Seq("target"))
+    assert(!cmd.ifNotExists)
+    assert(cmd.sourceTable.isInstanceOf[UnresolvedRelation])
+    assert(cmd.sourceTable.asInstanceOf[UnresolvedRelation].isStreaming)
+    assert(cmd.keys.map(_.name) == Seq("key1", "key2"))
+    assert(cmd.deleteCondition.isEmpty)
+    assert(cmd.sequenceByExpr == UnresolvedAttribute("timestamp"))
+    assert(cmd.specifiedCols.isEmpty)
+    assert(cmd.exceptCols.isEmpty)
+  }
+
+  test("CREATE STREAMING TABLE IF NOT EXISTS FLOW AUTO CDC") {
+    val plan = parser.parsePlan(
+      """CREATE STREAMING TABLE IF NOT EXISTS target
+        |FLOW AUTO CDC
+        |FROM source
+        |KEYS (id)
+        |SEQUENCE BY ts""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateStreamingTableAutoCdc]
+    assert(cmd.ifNotExists)
+  }
+
+  test("CREATE STREAMING TABLE FLOW AUTO CDC - multipart table name") {
+    val plan = parser.parsePlan(
+      """CREATE STREAMING TABLE myschema.mytable
+        |FLOW AUTO CDC
+        |FROM source
+        |KEYS (id)
+        |SEQUENCE BY ts""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateStreamingTableAutoCdc]
+    assert(cmd.name.asInstanceOf[UnresolvedIdentifier].nameParts == Seq("myschema", "mytable"))
+  }
+
+  test("CREATE STREAMING TABLE FLOW AUTO CDC - APPLY AS DELETE WHEN") {
+    val plan = parser.parsePlan(
+      """CREATE STREAMING TABLE target
+        |FLOW AUTO CDC
+        |FROM source
+        |KEYS (id)
+        |APPLY AS DELETE WHEN op = 'DELETE'
+        |SEQUENCE BY ts""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateStreamingTableAutoCdc]
+    assert(cmd.deleteCondition.isDefined)
+    assert(cmd.deleteCondition.get.sql.contains("op"))
+  }
+
+  test("CREATE STREAMING TABLE FLOW AUTO CDC - COLUMNS include list") {
+    val plan = parser.parsePlan(
+      """CREATE STREAMING TABLE target
+        |FLOW AUTO CDC
+        |FROM source
+        |KEYS (id)
+        |SEQUENCE BY ts
+        |COLUMNS id, name, value""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateStreamingTableAutoCdc]
+    assert(cmd.specifiedCols.map(_.name) == Seq("id", "name", "value"))
+    assert(cmd.exceptCols.isEmpty)
+  }
+
+  test("CREATE STREAMING TABLE FLOW AUTO CDC - COLUMNS * EXCEPT list") {
+    val plan = parser.parsePlan(
+      """CREATE STREAMING TABLE target
+        |FLOW AUTO CDC
+        |FROM source
+        |KEYS (id)
+        |SEQUENCE BY ts
+        |COLUMNS * EXCEPT (op, ts)""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateStreamingTableAutoCdc]
+    assert(cmd.specifiedCols.isEmpty)
+    assert(cmd.exceptCols.map(_.name) == Seq("op", "ts"))
+  }
+
+  test("CREATE STREAMING TABLE FLOW AUTO CDC - all clauses combined") {
+    val plan = parser.parsePlan(
+      """CREATE STREAMING TABLE target
+        |FLOW AUTO CDC
+        |FROM source
+        |KEYS (key1, key2)
+        |APPLY AS DELETE WHEN key3 = 3
+        |SEQUENCE BY timestamp
+        |COLUMNS * EXCEPT (key4)""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateStreamingTableAutoCdc]
+    assert(cmd.keys.map(_.name) == Seq("key1", "key2"))
+    assert(cmd.deleteCondition.isDefined)
+    assert(cmd.sequenceByExpr == UnresolvedAttribute("timestamp"))
+    assert(cmd.exceptCols.map(_.name) == Seq("key4"))
+  }
+
+  // ---------------------------------------------------------------------------
+  // Error cases: missing required clause
+  // ---------------------------------------------------------------------------
+
+  test("CREATE FLOW AS AUTO CDC INTO - SEQUENCE BY is required") {
+    val e = intercept[ParseException] {
+      parser.parsePlan(
+        """CREATE FLOW f AS AUTO CDC INTO target
+          |FROM source
+          |KEYS (id)""".stripMargin)
+    }
+    assert(e.getCondition == "AUTOCDC_MISSING_SEQUENCE_BY")
+  }
+
+  test("CREATE STREAMING TABLE FLOW AUTO CDC - SEQUENCE BY is required") {
+    val e = intercept[ParseException] {
+      parser.parsePlan(
+        """CREATE STREAMING TABLE target
+          |FLOW AUTO CDC
+          |FROM source
+          |KEYS (id)""".stripMargin)
+    }
+    assert(e.getCondition == "AUTOCDC_MISSING_SEQUENCE_BY")
+  }
+
+  // ---------------------------------------------------------------------------
+  // Error cases: duplicate clauses
+  // ---------------------------------------------------------------------------
+
+  test("duplicate SEQUENCE BY clause") {
+    val e = intercept[ParseException] {
+      parser.parsePlan(
+        """CREATE FLOW f AS AUTO CDC INTO target
+          |FROM source
+          |KEYS (id)
+          |SEQUENCE BY ts1
+          |SEQUENCE BY ts2""".stripMargin)
+    }
+    assert(e.getCondition == "DUPLICATE_CLAUSES")
+  }
+
+  test("duplicate APPLY AS DELETE clause") {
+    val e = intercept[ParseException] {
+      parser.parsePlan(
+        """CREATE FLOW f AS AUTO CDC INTO target
+          |FROM source
+          |KEYS (id)
+          |APPLY AS DELETE WHEN a = 1
+          |APPLY AS DELETE WHEN b = 2
+          |SEQUENCE BY ts""".stripMargin)
+    }
+    assert(e.getCondition == "DUPLICATE_CLAUSES")

Review Comment:
   good point but with the latest change this cannot happen no more. 



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [CONNECT][SDP][SPARK-56249] Create AUTO CDC syntax for SCD Type 1 in SQL [spark]

Posted by "szehon-ho (via GitHub)" <gi...@apache.org>.
szehon-ho commented on code in PR #56419:
URL: https://github.com/apache/spark/pull/56419#discussion_r3494526634


##########
sql/api/src/main/antlr4/org/apache/spark/sql/catalyst/parser/SqlBaseParser.g4:
##########
@@ -750,6 +751,41 @@ dmlStatementNoWith
         notMatchedBySourceClause*                                                  #mergeIntoTable
     ;
 
+autoCdcCommand
+    : AUTO CDC INTO target=multipartIdentifier
+        autoCdcParameters
+    ;
+
+autoCdcBody
+    : AUTO CDC autoCdcParameters
+    ;
+
+autoCdcParameters
+    : FROM source=autoCdcSource
+        KEYS LEFT_PAREN keys=identifierSeq RIGHT_PAREN
+        autoCdcDeleteClause?
+        autoCdcSequenceByClause
+        autoCdcColumnsClause?
+    ;
+
+autoCdcSource
+    : STREAM LEFT_PAREN multipartIdentifier RIGHT_PAREN
+    ;
+
+autoCdcDeleteClause
+    : APPLY AS DELETE WHEN deleteCondition=booleanExpression
+    ;
+
+autoCdcSequenceByClause
+    : SEQUENCE BY sequence=expression
+    ;
+
+autoCdcColumnsClause
+    : COLUMNS (
+        columns=identifierSeq |

Review Comment:
   For consideration: the include-list has no parentheses while the `* EXCEPT` branch requires them, so the two forms are asymmetric and diverge from the established AUTO CDC / APPLY CHANGES syntax which parenthesizes both:
   
   ```sql
   -- this PR accepts (bare list):
   COLUMNS id, name, value
   -- but the conventional form is:
   COLUMNS (id, name, value)
   ```
   
   As written, a user typing `COLUMNS (id, name, value)` gets a parse error. Would it be cleaner to wrap the include list in `LEFT_PAREN ... RIGHT_PAREN` too, to match `* EXCEPT (...)` and the existing syntax?



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/parser/AstBuilder.scala:
##########
@@ -1362,6 +1362,58 @@ class AstBuilder extends DataTypeAstBuilder
       withSchemaEvolution)
   }
 
+  protected def buildAutoCdcIntoCommand(ctx: AutoCdcCommandContext): AutoCdcIntoCommand =
+    withOrigin(ctx) {
+      val target = visitMultipartIdentifier(ctx.target).asTableIdentifier

Review Comment:
   For consideration: `asTableIdentifier` on a `Seq[String]` only accepts 1- or 2-part names and otherwise throws `IDENTIFIER_TOO_MANY_NAME_PARTS`. So while the source supports 3 parts (`FROM STREAM(mycat.myschema.source)`, which is tested), a catalog-qualified target fails:
   
   ```sql
   -- works:
   CREATE FLOW f AS AUTO CDC INTO target FROM STREAM(mycat.myschema.source) KEYS (id) SEQUENCE BY ts;
   -- fails with IDENTIFIER_TOO_MANY_NAME_PARTS:
   CREATE FLOW f AS AUTO CDC INTO mycat.myschema.target FROM STREAM(source) KEYS (id) SEQUENCE BY ts;
   ```
   
   This is also inconsistent with the `CREATE STREAMING TABLE mycat.myschema.target FLOW AUTO CDC ...` form, which accepts the 3-part name (it uses `UnresolvedIdentifier`). Could we model the target as a multi-part identifier here too (or at least raise a clean 'not supported' error and add a 3-part-target test)?



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [CONNECT][SDP][SPARK-56249] Create AUTO CDC syntax for SCD Type 1 in SQL [spark]

Posted by "anew (via GitHub)" <gi...@apache.org>.
anew commented on code in PR #56419:
URL: https://github.com/apache/spark/pull/56419#discussion_r3399425866


##########
sql/core/src/test/scala/org/apache/spark/sql/execution/command/v2/AutoCdcParserSuite.scala:
##########
@@ -0,0 +1,392 @@
+/*
+ * 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.execution.command.v2
+
+import org.apache.spark.sql.catalyst.analysis.{
+  AnalysisTest, UnresolvedAttribute,
+  UnresolvedIdentifier, UnresolvedRelation}
+import org.apache.spark.sql.catalyst.parser.ParseException
+import org.apache.spark.sql.catalyst.plans.logical.{
+  AutoCdcIntoCommand,
+  CreateFlowCommand,
+  CreateStreamingTableAutoCdc
+}
+import org.apache.spark.sql.execution.SparkSqlParser
+
+/**
+ * Parser tests for AUTO CDC syntax.
+ *
+ * Covers two supported forms:
+ *   1. CREATE FLOW <name> [COMMENT ...] AS AUTO CDC INTO <target> ...
+ *   2. CREATE STREAMING TABLE <name> FLOW AUTO CDC ...
+ *
+ * Snapshot CDC, SCD Type 2, IGNORE NULL UPDATES, and APPLY AS TRUNCATE WHEN are not
+ * supported and should fail to parse. The standalone AUTO CDC INTO form (without CREATE FLOW
+ * or CREATE STREAMING TABLE) is also not supported.
+ */
+class AutoCdcParserSuite extends CommandSuiteBase with AnalysisTest {
+  protected lazy val parser = new SparkSqlParser()
+
+  // ---------------------------------------------------------------------------
+  // CREATE FLOW ... AS AUTO CDC INTO
+  // ---------------------------------------------------------------------------
+
+  test("CREATE FLOW AS AUTO CDC INTO - minimal form") {
+    val plan = parser.parsePlan(
+      """CREATE FLOW myflow AS AUTO CDC INTO target
+        |FROM source
+        |KEYS (key1, key2)
+        |SEQUENCE BY timestamp""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateFlowCommand]
+    assert(cmd.name.asInstanceOf[UnresolvedIdentifier].nameParts == Seq("myflow"))
+    assert(cmd.comment.isEmpty)
+
+    val cdc = cmd.flowOperation.asInstanceOf[AutoCdcIntoCommand]
+    assert(cdc.targetTable.table == "target")
+    assert(cdc.sourceTable.isInstanceOf[UnresolvedRelation])
+    assert(cdc.keys.map(_.name) == Seq("key1", "key2"))
+    assert(cdc.deleteCondition.isEmpty)
+    assert(cdc.sequenceByExpr == UnresolvedAttribute("timestamp"))
+    assert(cdc.specifiedCols.isEmpty)
+    assert(cdc.exceptCols.isEmpty)
+  }
+
+  test("CREATE FLOW AS AUTO CDC INTO - with COMMENT") {
+    val plan = parser.parsePlan(
+      """CREATE FLOW myflow COMMENT 'my comment' AS AUTO CDC INTO target
+        |FROM source
+        |KEYS (id)
+        |SEQUENCE BY ts""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateFlowCommand]
+    assert(cmd.comment == Some("my comment"))
+  }
+
+  test("CREATE FLOW AS AUTO CDC INTO - multipart flow name") {
+    val plan = parser.parsePlan(
+      """CREATE FLOW mycat.myschema.myflow AS AUTO CDC INTO target
+        |FROM source
+        |KEYS (id)
+        |SEQUENCE BY ts""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateFlowCommand]
+    assert(cmd.name.asInstanceOf[UnresolvedIdentifier].nameParts ==
+      Seq("mycat", "myschema", "myflow"))
+  }
+
+  test("CREATE FLOW AS AUTO CDC INTO - two-part target table name") {
+    val plan = parser.parsePlan(
+      """CREATE FLOW f AS AUTO CDC INTO myschema.mytable
+        |FROM source
+        |KEYS (k)
+        |SEQUENCE BY ts""".stripMargin)
+
+    val cdc = plan.asInstanceOf[CreateFlowCommand].flowOperation.asInstanceOf[AutoCdcIntoCommand]
+    assert(cdc.targetTable.database == Some("myschema"))
+    assert(cdc.targetTable.table == "mytable")
+  }
+
+  test("CREATE FLOW AS AUTO CDC INTO - APPLY AS DELETE WHEN") {
+    val plan = parser.parsePlan(
+      """CREATE FLOW f AS AUTO CDC INTO target
+        |FROM source
+        |KEYS (id)
+        |APPLY AS DELETE WHEN op = 'DELETE'
+        |SEQUENCE BY ts""".stripMargin)
+
+    val cdc = plan.asInstanceOf[CreateFlowCommand].flowOperation.asInstanceOf[AutoCdcIntoCommand]
+    assert(cdc.deleteCondition.isDefined)
+    assert(cdc.deleteCondition.get.sql.contains("op"))
+  }
+
+  test("CREATE FLOW AS AUTO CDC INTO - COLUMNS include list") {
+    val plan = parser.parsePlan(
+      """CREATE FLOW f AS AUTO CDC INTO target
+        |FROM source
+        |KEYS (id)
+        |SEQUENCE BY ts
+        |COLUMNS id, name, value""".stripMargin)
+
+    val cdc = plan.asInstanceOf[CreateFlowCommand].flowOperation.asInstanceOf[AutoCdcIntoCommand]
+    assert(cdc.specifiedCols.map(_.name) == Seq("id", "name", "value"))
+    assert(cdc.exceptCols.isEmpty)
+  }
+
+  test("CREATE FLOW AS AUTO CDC INTO - COLUMNS * EXCEPT list") {
+    val plan = parser.parsePlan(
+      """CREATE FLOW f AS AUTO CDC INTO target
+        |FROM source
+        |KEYS (id)
+        |SEQUENCE BY ts
+        |COLUMNS * EXCEPT (op, ts)""".stripMargin)
+
+    val cdc = plan.asInstanceOf[CreateFlowCommand].flowOperation.asInstanceOf[AutoCdcIntoCommand]
+    assert(cdc.specifiedCols.isEmpty)
+    assert(cdc.exceptCols.map(_.name) == Seq("op", "ts"))
+  }
+
+  test("CREATE FLOW AS AUTO CDC INTO - all clauses combined") {
+    val plan = parser.parsePlan(
+      """CREATE FLOW f AS AUTO CDC INTO target
+        |FROM source
+        |KEYS (key1, key2)
+        |APPLY AS DELETE WHEN key3 = 3
+        |SEQUENCE BY timestamp
+        |COLUMNS key1, key2, key3, timestamp""".stripMargin)
+
+    val cdc = plan.asInstanceOf[CreateFlowCommand].flowOperation.asInstanceOf[AutoCdcIntoCommand]
+    assert(cdc.keys.map(_.name) == Seq("key1", "key2"))
+    assert(cdc.deleteCondition.isDefined)
+    assert(cdc.sequenceByExpr == UnresolvedAttribute("timestamp"))
+    assert(cdc.specifiedCols.map(_.name) == Seq("key1", "key2", "key3", "timestamp"))
+  }
+
+  // ---------------------------------------------------------------------------
+  // CREATE STREAMING TABLE ... FLOW AUTO CDC
+  // ---------------------------------------------------------------------------
+
+  test("CREATE STREAMING TABLE FLOW AUTO CDC - minimal form") {
+    val plan = parser.parsePlan(
+      """CREATE STREAMING TABLE target
+        |FLOW AUTO CDC
+        |FROM source
+        |KEYS (key1, key2)
+        |SEQUENCE BY timestamp""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateStreamingTableAutoCdc]
+    assert(cmd.name.asInstanceOf[UnresolvedIdentifier].nameParts == Seq("target"))
+    assert(!cmd.ifNotExists)
+    assert(cmd.sourceTable.isInstanceOf[UnresolvedRelation])
+    assert(cmd.keys.map(_.name) == Seq("key1", "key2"))
+    assert(cmd.deleteCondition.isEmpty)
+    assert(cmd.sequenceByExpr == UnresolvedAttribute("timestamp"))
+    assert(cmd.specifiedCols.isEmpty)
+    assert(cmd.exceptCols.isEmpty)
+  }
+
+  test("CREATE STREAMING TABLE IF NOT EXISTS FLOW AUTO CDC") {
+    val plan = parser.parsePlan(
+      """CREATE STREAMING TABLE IF NOT EXISTS target
+        |FLOW AUTO CDC
+        |FROM source
+        |KEYS (id)
+        |SEQUENCE BY ts""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateStreamingTableAutoCdc]
+    assert(cmd.ifNotExists)
+  }
+
+  test("CREATE STREAMING TABLE FLOW AUTO CDC - multipart table name") {
+    val plan = parser.parsePlan(
+      """CREATE STREAMING TABLE myschema.mytable
+        |FLOW AUTO CDC
+        |FROM source
+        |KEYS (id)
+        |SEQUENCE BY ts""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateStreamingTableAutoCdc]
+    assert(cmd.name.asInstanceOf[UnresolvedIdentifier].nameParts == Seq("myschema", "mytable"))
+  }
+
+  test("CREATE STREAMING TABLE FLOW AUTO CDC - APPLY AS DELETE WHEN") {
+    val plan = parser.parsePlan(
+      """CREATE STREAMING TABLE target
+        |FLOW AUTO CDC
+        |FROM source
+        |KEYS (id)
+        |APPLY AS DELETE WHEN op = 'DELETE'
+        |SEQUENCE BY ts""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateStreamingTableAutoCdc]
+    assert(cmd.deleteCondition.isDefined)
+    assert(cmd.deleteCondition.get.sql.contains("op"))
+  }
+
+  test("CREATE STREAMING TABLE FLOW AUTO CDC - COLUMNS include list") {
+    val plan = parser.parsePlan(
+      """CREATE STREAMING TABLE target
+        |FLOW AUTO CDC
+        |FROM source
+        |KEYS (id)
+        |SEQUENCE BY ts
+        |COLUMNS id, name, value""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateStreamingTableAutoCdc]
+    assert(cmd.specifiedCols.map(_.name) == Seq("id", "name", "value"))
+    assert(cmd.exceptCols.isEmpty)
+  }
+
+  test("CREATE STREAMING TABLE FLOW AUTO CDC - COLUMNS * EXCEPT list") {
+    val plan = parser.parsePlan(
+      """CREATE STREAMING TABLE target
+        |FLOW AUTO CDC
+        |FROM source
+        |KEYS (id)
+        |SEQUENCE BY ts
+        |COLUMNS * EXCEPT (op, ts)""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateStreamingTableAutoCdc]
+    assert(cmd.specifiedCols.isEmpty)
+    assert(cmd.exceptCols.map(_.name) == Seq("op", "ts"))
+  }
+
+  test("CREATE STREAMING TABLE FLOW AUTO CDC - all clauses combined") {

Review Comment:
   ok



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [CONNECT][SDP][SPARK-56249] Create AUTO CDC syntax for SCD Type 1 in SQL [spark]

Posted by "anew (via GitHub)" <gi...@apache.org>.
anew commented on code in PR #56419:
URL: https://github.com/apache/spark/pull/56419#discussion_r3482437642


##########
common/utils/src/main/resources/error/error-conditions.json:
##########
@@ -5529,6 +5529,12 @@
     },
     "sqlState" : "0A000"
   },
+  "MISSING_CLAUSES_FOR_OPERATION" : {

Review Comment:
   I will send a separate PR for this



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [CONNECT][SDP][SPARK-56249] Create AUTO CDC syntax for SCD Type 1 in SQL [spark]

Posted by "AnishMahto (via GitHub)" <gi...@apache.org>.
AnishMahto commented on code in PR #56419:
URL: https://github.com/apache/spark/pull/56419#discussion_r3406660538


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/AutoCdcIntoCommand.scala:
##########
@@ -0,0 +1,57 @@
+/*
+ * 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.plans.logical
+
+import org.apache.spark.sql.catalyst.TableIdentifier
+import org.apache.spark.sql.catalyst.analysis.UnresolvedAttribute
+import org.apache.spark.sql.catalyst.expressions.{Attribute, Expression}
+
+/**
+ * Logical plan node for an AUTO CDC INTO command, used by Spark Declarative Pipelines.
+ *
+ * This represents a CDC (Change Data Capture) operation that applies an ordered change event
+ * stream from [[sourceTable]] into [[targetTable]] using SCD Type 1 (upsert) semantics.
+ *
+ * This node serves as a parse-time placeholder for a pipeline CDC definition and cannot be
+ * executed directly. It will be interpreted by the pipeline submodule once execution support
+ * is added (SPARK-57402).
+ *
+ * @param targetTable    The target table to apply changes into.
+ * @param sourceTable    The source relation providing the change events.
+ * @param keys           Column(s) that uniquely identify a row in the target table.
+ * @param deleteCondition An optional expression that marks a source row as a DELETE operation.
+ *                        When absent, all source rows are treated as upserts.
+ * @param sequenceByExpr Expression that orders CDC events to correctly resolve out-of-order
+ *                       arrivals. Must evaluate to a sortable type. Required.
+ * @param specifiedCols  An explicit list of source columns to include in the target table.
+ *                       Mutually exclusive with [[exceptCols]].
+ * @param exceptCols     Source columns to exclude from the target table (i.e., all columns
+ *                       except these). Mutually exclusive with [[specifiedCols]].
+ */
+case class AutoCdcIntoCommand(
+    targetTable: TableIdentifier,
+    sourceTable: LogicalPlan,
+    keys: Seq[UnresolvedAttribute],
+    deleteCondition: Option[Expression],
+    sequenceByExpr: Expression,
+    specifiedCols: Seq[UnresolvedAttribute],
+    exceptCols: Seq[UnresolvedAttribute]
+) extends LeafCommand {

Review Comment:
   I forget, does `LeafCommand` imply the command has no child logical plans? Any chance we should be using `UnaryCommand` given the `sourceTable` child?



##########
common/utils/src/main/resources/error/error-conditions.json:
##########
@@ -5529,6 +5529,12 @@
     },
     "sqlState" : "0A000"
   },
+  "MISSING_CLAUSES_FOR_OPERATION" : {
+    "message" : [
+      "Missing required clause(s) <clauses> for operation <operation>."
+    ],
+    "sqlState" : "42601"

Review Comment:
   To me this sounds like a semantic error not a syntactical error, maybe use 42613 or something else?



##########
sql/api/src/main/antlr4/org/apache/spark/sql/catalyst/parser/SqlBaseParser.g4:
##########
@@ -417,7 +417,11 @@ statement
     | createPipelineDatasetHeader (LEFT_PAREN tableElementList? RIGHT_PAREN)? tableProvider?
         createTableClauses
         (AS query)?                                                    #createPipelineDataset
+    | createPipelineDatasetHeader (LEFT_PAREN tableElementList? RIGHT_PAREN)? tableProvider?
+        createTableClauses
+        FLOW autoCdcBody                                               #createStreamingTableAutoCdc

Review Comment:
   Did we consider collapsing `createStreamingTableAutoCdc` with `createPipelineDataset` using `|` for the query clause?
   
   I.e is there a good reason for duplicating the shared `createPipelineDatasetHeader (LEFT_PAREN tableElementList? RIGHT_PAREN)? tableProvider?
           createTableClauses`. 



##########
sql/core/src/test/scala/org/apache/spark/sql/execution/command/v2/AutoCdcParserSuite.scala:
##########
@@ -0,0 +1,494 @@
+/*
+ * 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.execution.command.v2
+
+import org.apache.spark.sql.catalyst.analysis.{
+  AnalysisTest, UnresolvedAttribute,
+  UnresolvedIdentifier, UnresolvedRelation}
+import org.apache.spark.sql.catalyst.parser.ParseException
+import org.apache.spark.sql.catalyst.plans.logical.{
+  AutoCdcIntoCommand,
+  CreateFlowCommand,
+  CreateStreamingTableAutoCdc
+}
+import org.apache.spark.sql.execution.SparkSqlParser
+
+/**
+ * Parser tests for AUTO CDC syntax.
+ *
+ * Covers two supported forms:
+ *   1. CREATE FLOW <name> [COMMENT ...] AS AUTO CDC INTO <target> ...
+ *   2. CREATE STREAMING TABLE <name> FLOW AUTO CDC ...
+ *
+ * Snapshot CDC, SCD Type 2, IGNORE NULL UPDATES, and APPLY AS TRUNCATE WHEN are not
+ * supported and should fail to parse. The standalone AUTO CDC INTO form (without CREATE FLOW
+ * or CREATE STREAMING TABLE) is also not supported.
+ */
+class AutoCdcParserSuite extends CommandSuiteBase with AnalysisTest {
+  protected lazy val parser = new SparkSqlParser()
+
+  // ---------------------------------------------------------------------------
+  // CREATE FLOW ... AS AUTO CDC INTO
+  // ---------------------------------------------------------------------------
+
+  test("CREATE FLOW AS AUTO CDC INTO - minimal form") {
+    val plan = parser.parsePlan(
+      """CREATE FLOW myflow AS AUTO CDC INTO target
+        |FROM source
+        |KEYS (key1, key2)
+        |SEQUENCE BY timestamp""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateFlowCommand]
+    assert(cmd.name.asInstanceOf[UnresolvedIdentifier].nameParts == Seq("myflow"))
+    assert(cmd.comment.isEmpty)
+
+    val cdc = cmd.flowOperation.asInstanceOf[AutoCdcIntoCommand]
+    assert(cdc.targetTable.table == "target")
+    assert(cdc.sourceTable.isInstanceOf[UnresolvedRelation])
+    assert(cdc.sourceTable.asInstanceOf[UnresolvedRelation].isStreaming)
+    assert(cdc.keys.map(_.name) == Seq("key1", "key2"))
+    assert(cdc.deleteCondition.isEmpty)
+    assert(cdc.sequenceByExpr == UnresolvedAttribute("timestamp"))
+    assert(cdc.specifiedCols.isEmpty)
+    assert(cdc.exceptCols.isEmpty)
+  }
+
+  test("CREATE FLOW AS AUTO CDC INTO - with COMMENT") {
+    val plan = parser.parsePlan(
+      """CREATE FLOW myflow COMMENT 'my comment' AS AUTO CDC INTO target
+        |FROM source
+        |KEYS (id)
+        |SEQUENCE BY ts""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateFlowCommand]
+    assert(cmd.comment == Some("my comment"))
+  }
+
+  test("CREATE FLOW AS AUTO CDC INTO - multipart flow name") {
+    val plan = parser.parsePlan(
+      """CREATE FLOW mycat.myschema.myflow AS AUTO CDC INTO target
+        |FROM source
+        |KEYS (id)
+        |SEQUENCE BY ts""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateFlowCommand]
+    assert(cmd.name.asInstanceOf[UnresolvedIdentifier].nameParts ==
+      Seq("mycat", "myschema", "myflow"))
+  }
+
+  test("CREATE FLOW AS AUTO CDC INTO - two-part target table name") {
+    val plan = parser.parsePlan(
+      """CREATE FLOW f AS AUTO CDC INTO myschema.mytable
+        |FROM source
+        |KEYS (k)
+        |SEQUENCE BY ts""".stripMargin)
+
+    val cdc = plan.asInstanceOf[CreateFlowCommand].flowOperation.asInstanceOf[AutoCdcIntoCommand]
+    assert(cdc.targetTable.database == Some("myschema"))
+    assert(cdc.targetTable.table == "mytable")
+  }
+
+  test("CREATE FLOW AS AUTO CDC INTO - APPLY AS DELETE WHEN") {
+    val plan = parser.parsePlan(
+      """CREATE FLOW f AS AUTO CDC INTO target
+        |FROM source
+        |KEYS (id)
+        |APPLY AS DELETE WHEN op = 'DELETE'
+        |SEQUENCE BY ts""".stripMargin)
+
+    val cdc = plan.asInstanceOf[CreateFlowCommand].flowOperation.asInstanceOf[AutoCdcIntoCommand]
+    assert(cdc.deleteCondition.isDefined)
+    assert(cdc.deleteCondition.get.sql.contains("op"))
+  }
+
+  test("CREATE FLOW AS AUTO CDC INTO - COLUMNS include list") {
+    val plan = parser.parsePlan(
+      """CREATE FLOW f AS AUTO CDC INTO target
+        |FROM source
+        |KEYS (id)
+        |SEQUENCE BY ts
+        |COLUMNS id, name, value""".stripMargin)
+
+    val cdc = plan.asInstanceOf[CreateFlowCommand].flowOperation.asInstanceOf[AutoCdcIntoCommand]
+    assert(cdc.specifiedCols.map(_.name) == Seq("id", "name", "value"))
+    assert(cdc.exceptCols.isEmpty)
+  }
+
+  test("CREATE FLOW AS AUTO CDC INTO - COLUMNS * EXCEPT list") {
+    val plan = parser.parsePlan(
+      """CREATE FLOW f AS AUTO CDC INTO target
+        |FROM source
+        |KEYS (id)
+        |SEQUENCE BY ts
+        |COLUMNS * EXCEPT (op, ts)""".stripMargin)
+
+    val cdc = plan.asInstanceOf[CreateFlowCommand].flowOperation.asInstanceOf[AutoCdcIntoCommand]
+    assert(cdc.specifiedCols.isEmpty)
+    assert(cdc.exceptCols.map(_.name) == Seq("op", "ts"))
+  }
+
+  test("CREATE FLOW AS AUTO CDC INTO - all clauses combined") {
+    val plan = parser.parsePlan(
+      """CREATE FLOW f AS AUTO CDC INTO target
+        |FROM source
+        |KEYS (key1, key2)
+        |APPLY AS DELETE WHEN key3 = 3
+        |SEQUENCE BY timestamp
+        |COLUMNS key1, key2, key3, timestamp""".stripMargin)
+
+    val cdc = plan.asInstanceOf[CreateFlowCommand].flowOperation.asInstanceOf[AutoCdcIntoCommand]
+    assert(cdc.keys.map(_.name) == Seq("key1", "key2"))
+    assert(cdc.deleteCondition.isDefined)
+    assert(cdc.sequenceByExpr == UnresolvedAttribute("timestamp"))
+    assert(cdc.specifiedCols.map(_.name) == Seq("key1", "key2", "key3", "timestamp"))
+  }
+
+  // ---------------------------------------------------------------------------
+  // CREATE STREAMING TABLE ... FLOW AUTO CDC
+  // ---------------------------------------------------------------------------
+
+  test("CREATE STREAMING TABLE FLOW AUTO CDC - minimal form") {
+    val plan = parser.parsePlan(
+      """CREATE STREAMING TABLE target
+        |FLOW AUTO CDC
+        |FROM source
+        |KEYS (key1, key2)
+        |SEQUENCE BY timestamp""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateStreamingTableAutoCdc]
+    assert(cmd.name.asInstanceOf[UnresolvedIdentifier].nameParts == Seq("target"))
+    assert(!cmd.ifNotExists)
+    assert(cmd.sourceTable.isInstanceOf[UnresolvedRelation])
+    assert(cmd.sourceTable.asInstanceOf[UnresolvedRelation].isStreaming)
+    assert(cmd.keys.map(_.name) == Seq("key1", "key2"))
+    assert(cmd.deleteCondition.isEmpty)
+    assert(cmd.sequenceByExpr == UnresolvedAttribute("timestamp"))
+    assert(cmd.specifiedCols.isEmpty)
+    assert(cmd.exceptCols.isEmpty)
+  }
+
+  test("CREATE STREAMING TABLE IF NOT EXISTS FLOW AUTO CDC") {
+    val plan = parser.parsePlan(
+      """CREATE STREAMING TABLE IF NOT EXISTS target
+        |FLOW AUTO CDC
+        |FROM source
+        |KEYS (id)
+        |SEQUENCE BY ts""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateStreamingTableAutoCdc]
+    assert(cmd.ifNotExists)
+  }
+
+  test("CREATE STREAMING TABLE FLOW AUTO CDC - multipart table name") {
+    val plan = parser.parsePlan(
+      """CREATE STREAMING TABLE myschema.mytable
+        |FLOW AUTO CDC
+        |FROM source
+        |KEYS (id)
+        |SEQUENCE BY ts""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateStreamingTableAutoCdc]
+    assert(cmd.name.asInstanceOf[UnresolvedIdentifier].nameParts == Seq("myschema", "mytable"))
+  }
+
+  test("CREATE STREAMING TABLE FLOW AUTO CDC - APPLY AS DELETE WHEN") {
+    val plan = parser.parsePlan(
+      """CREATE STREAMING TABLE target
+        |FLOW AUTO CDC
+        |FROM source
+        |KEYS (id)
+        |APPLY AS DELETE WHEN op = 'DELETE'
+        |SEQUENCE BY ts""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateStreamingTableAutoCdc]
+    assert(cmd.deleteCondition.isDefined)
+    assert(cmd.deleteCondition.get.sql.contains("op"))
+  }
+
+  test("CREATE STREAMING TABLE FLOW AUTO CDC - COLUMNS include list") {
+    val plan = parser.parsePlan(
+      """CREATE STREAMING TABLE target
+        |FLOW AUTO CDC
+        |FROM source
+        |KEYS (id)
+        |SEQUENCE BY ts
+        |COLUMNS id, name, value""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateStreamingTableAutoCdc]
+    assert(cmd.specifiedCols.map(_.name) == Seq("id", "name", "value"))
+    assert(cmd.exceptCols.isEmpty)
+  }
+
+  test("CREATE STREAMING TABLE FLOW AUTO CDC - COLUMNS * EXCEPT list") {
+    val plan = parser.parsePlan(
+      """CREATE STREAMING TABLE target
+        |FLOW AUTO CDC
+        |FROM source
+        |KEYS (id)
+        |SEQUENCE BY ts
+        |COLUMNS * EXCEPT (op, ts)""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateStreamingTableAutoCdc]
+    assert(cmd.specifiedCols.isEmpty)
+    assert(cmd.exceptCols.map(_.name) == Seq("op", "ts"))
+  }
+
+  test("CREATE STREAMING TABLE FLOW AUTO CDC - all clauses combined") {
+    val plan = parser.parsePlan(
+      """CREATE STREAMING TABLE target
+        |FLOW AUTO CDC
+        |FROM source
+        |KEYS (key1, key2)
+        |APPLY AS DELETE WHEN key3 = 3
+        |SEQUENCE BY timestamp
+        |COLUMNS * EXCEPT (key4)""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateStreamingTableAutoCdc]
+    assert(cmd.keys.map(_.name) == Seq("key1", "key2"))
+    assert(cmd.deleteCondition.isDefined)
+    assert(cmd.sequenceByExpr == UnresolvedAttribute("timestamp"))
+    assert(cmd.exceptCols.map(_.name) == Seq("key4"))
+  }
+
+  // ---------------------------------------------------------------------------
+  // Error cases: missing required clause
+  // ---------------------------------------------------------------------------
+
+  test("CREATE FLOW AS AUTO CDC INTO - SEQUENCE BY is required") {
+    val e = intercept[ParseException] {
+      parser.parsePlan(
+        """CREATE FLOW f AS AUTO CDC INTO target
+          |FROM source
+          |KEYS (id)""".stripMargin)
+    }
+    assert(e.getCondition == "AUTOCDC_MISSING_SEQUENCE_BY")
+  }
+
+  test("CREATE STREAMING TABLE FLOW AUTO CDC - SEQUENCE BY is required") {
+    val e = intercept[ParseException] {
+      parser.parsePlan(
+        """CREATE STREAMING TABLE target
+          |FLOW AUTO CDC
+          |FROM source
+          |KEYS (id)""".stripMargin)
+    }
+    assert(e.getCondition == "AUTOCDC_MISSING_SEQUENCE_BY")
+  }
+
+  // ---------------------------------------------------------------------------
+  // Error cases: duplicate clauses
+  // ---------------------------------------------------------------------------
+
+  test("duplicate SEQUENCE BY clause") {
+    val e = intercept[ParseException] {
+      parser.parsePlan(
+        """CREATE FLOW f AS AUTO CDC INTO target
+          |FROM source
+          |KEYS (id)
+          |SEQUENCE BY ts1
+          |SEQUENCE BY ts2""".stripMargin)
+    }
+    assert(e.getCondition == "DUPLICATE_CLAUSES")
+  }
+
+  test("duplicate APPLY AS DELETE clause") {
+    val e = intercept[ParseException] {
+      parser.parsePlan(
+        """CREATE FLOW f AS AUTO CDC INTO target
+          |FROM source
+          |KEYS (id)
+          |APPLY AS DELETE WHEN a = 1
+          |APPLY AS DELETE WHEN b = 2
+          |SEQUENCE BY ts""".stripMargin)
+    }
+    assert(e.getCondition == "DUPLICATE_CLAUSES")
+  }
+
+  test("duplicate COLUMNS clause") {
+    val e = intercept[ParseException] {
+      parser.parsePlan(
+        """CREATE FLOW f AS AUTO CDC INTO target
+          |FROM source
+          |KEYS (id)
+          |SEQUENCE BY ts
+          |COLUMNS a, b
+          |COLUMNS c, d""".stripMargin)
+    }
+    assert(e.getCondition == "DUPLICATE_CLAUSES")
+  }
+
+  test("both COLUMNS include list and COLUMNS * EXCEPT is an error") {
+    val e = intercept[ParseException] {
+      parser.parsePlan(
+        """CREATE FLOW f AS AUTO CDC INTO target
+          |FROM source
+          |KEYS (id)
+          |SEQUENCE BY ts
+          |COLUMNS a, b
+          |COLUMNS * EXCEPT (c)""".stripMargin)
+    }
+    assert(e.getCondition == "AUTOCDC_BOTH_COLUMN_LIST_AND_EXCEPT_COLUMN_LIST")
+  }
+
+  // ---------------------------------------------------------------------------
+  // Error cases: standalone form not supported
+  // ---------------------------------------------------------------------------
+
+  test("standalone AUTO CDC INTO is not supported") {
+    val e = intercept[ParseException] {
+      parser.parsePlan(
+        """AUTO CDC INTO target
+          |FROM source
+          |KEYS (id)
+          |SEQUENCE BY ts""".stripMargin)
+    }
+    assert(e.getCondition == "PARSE_SYNTAX_ERROR")
+  }
+
+  // ---------------------------------------------------------------------------
+  // Error cases: unsupported dataset types and table features
+  // ---------------------------------------------------------------------------
+
+  test("AUTO CDC is not supported for MATERIALIZED VIEW") {
+    val e = intercept[ParseException] {
+      parser.parsePlan(
+        """CREATE MATERIALIZED VIEW target
+          |FLOW AUTO CDC
+          |FROM source
+          |KEYS (id)
+          |SEQUENCE BY ts""".stripMargin)
+    }
+    assert(e.getMessage.contains("AUTO CDC is only supported for STREAMING TABLE"))

Review Comment:
   nit: here and other tests, use `checkError` and assert on expected error conditions/message parameters.



##########
common/utils/src/main/resources/error/error-conditions.json:
##########
@@ -5529,6 +5529,12 @@
     },
     "sqlState" : "0A000"
   },
+  "MISSING_CLAUSES_FOR_OPERATION" : {

Review Comment:
   Is this actually used anywhere?



##########
sql/api/src/main/antlr4/org/apache/spark/sql/catalyst/parser/SqlBaseParser.g4:
##########
@@ -750,6 +754,38 @@ dmlStatementNoWith
         notMatchedBySourceClause*                                                  #mergeIntoTable
     ;
 
+autoCdcCommand
+    : AUTO CDC INTO target=multipartIdentifier
+        autoCdcParameters
+    ;
+
+autoCdcBody
+    : AUTO CDC autoCdcParameters
+    ;
+
+autoCdcParameters
+    : FROM source=relationPrimary
+        KEYS LEFT_PAREN keys=multipartIdentifierList RIGHT_PAREN
+        (autoCdcDeleteClause
+        | autoCdcSequenceByClause
+        | autoCdcColumnsClause
+        )*

Review Comment:
   Is `*` the right expression to use here? Implies there can be multiple sequence clauses for example, and pushes validation down to AST logic rather than being invalidated at a syntactical level.



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [CONNECT][SDP][SPARK-56249] Create AUTO CDC syntax for SCD Type 1 in SQL [spark]

Posted by "anew (via GitHub)" <gi...@apache.org>.
anew commented on code in PR #56419:
URL: https://github.com/apache/spark/pull/56419#discussion_r3399422169


##########
sql/api/src/main/antlr4/org/apache/spark/sql/catalyst/parser/SqlBaseLexer.g4:
##########
@@ -139,8 +139,10 @@ AND: 'AND';
 ANTI: 'ANTI';
 ANY: 'ANY';
 ANY_VALUE: 'ANY_VALUE';
+APPLY: 'APPLY';
 APPROX: 'APPROX';
 ARCHIVE: 'ARCHIVE';
+AUTO: 'AUTO';

Review Comment:
   good catch will do. (it is amazing how many mistakes Claude makes when sorting :)



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [CONNECT][SDP][SPARK-56249] Create AUTO CDC syntax for SCD Type 1 in SQL [spark]

Posted by "szehon-ho (via GitHub)" <gi...@apache.org>.
szehon-ho commented on PR #56419:
URL: https://github.com/apache/spark/pull/56419#issuecomment-4896094015

   ci failed but looks unrelated, retiggering


-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [CONNECT][SDP][SPARK-56249] Create AUTO CDC syntax for SCD Type 1 in SQL [spark]

Posted by "anew (via GitHub)" <gi...@apache.org>.
anew commented on code in PR #56419:
URL: https://github.com/apache/spark/pull/56419#discussion_r3399828130


##########
sql/core/src/test/scala/org/apache/spark/sql/execution/command/v2/AutoCdcParserSuite.scala:
##########
@@ -0,0 +1,392 @@
+/*
+ * 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.execution.command.v2
+
+import org.apache.spark.sql.catalyst.analysis.{
+  AnalysisTest, UnresolvedAttribute,
+  UnresolvedIdentifier, UnresolvedRelation}
+import org.apache.spark.sql.catalyst.parser.ParseException
+import org.apache.spark.sql.catalyst.plans.logical.{
+  AutoCdcIntoCommand,
+  CreateFlowCommand,
+  CreateStreamingTableAutoCdc
+}
+import org.apache.spark.sql.execution.SparkSqlParser
+
+/**
+ * Parser tests for AUTO CDC syntax.
+ *
+ * Covers two supported forms:
+ *   1. CREATE FLOW <name> [COMMENT ...] AS AUTO CDC INTO <target> ...
+ *   2. CREATE STREAMING TABLE <name> FLOW AUTO CDC ...
+ *
+ * Snapshot CDC, SCD Type 2, IGNORE NULL UPDATES, and APPLY AS TRUNCATE WHEN are not
+ * supported and should fail to parse. The standalone AUTO CDC INTO form (without CREATE FLOW
+ * or CREATE STREAMING TABLE) is also not supported.
+ */
+class AutoCdcParserSuite extends CommandSuiteBase with AnalysisTest {
+  protected lazy val parser = new SparkSqlParser()
+
+  // ---------------------------------------------------------------------------
+  // CREATE FLOW ... AS AUTO CDC INTO
+  // ---------------------------------------------------------------------------
+
+  test("CREATE FLOW AS AUTO CDC INTO - minimal form") {
+    val plan = parser.parsePlan(
+      """CREATE FLOW myflow AS AUTO CDC INTO target
+        |FROM source
+        |KEYS (key1, key2)
+        |SEQUENCE BY timestamp""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateFlowCommand]
+    assert(cmd.name.asInstanceOf[UnresolvedIdentifier].nameParts == Seq("myflow"))
+    assert(cmd.comment.isEmpty)
+
+    val cdc = cmd.flowOperation.asInstanceOf[AutoCdcIntoCommand]
+    assert(cdc.targetTable.table == "target")
+    assert(cdc.sourceTable.isInstanceOf[UnresolvedRelation])
+    assert(cdc.keys.map(_.name) == Seq("key1", "key2"))
+    assert(cdc.deleteCondition.isEmpty)
+    assert(cdc.sequenceByExpr == UnresolvedAttribute("timestamp"))
+    assert(cdc.specifiedCols.isEmpty)
+    assert(cdc.exceptCols.isEmpty)
+  }
+
+  test("CREATE FLOW AS AUTO CDC INTO - with COMMENT") {
+    val plan = parser.parsePlan(
+      """CREATE FLOW myflow COMMENT 'my comment' AS AUTO CDC INTO target
+        |FROM source
+        |KEYS (id)
+        |SEQUENCE BY ts""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateFlowCommand]
+    assert(cmd.comment == Some("my comment"))
+  }
+
+  test("CREATE FLOW AS AUTO CDC INTO - multipart flow name") {
+    val plan = parser.parsePlan(
+      """CREATE FLOW mycat.myschema.myflow AS AUTO CDC INTO target
+        |FROM source
+        |KEYS (id)
+        |SEQUENCE BY ts""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateFlowCommand]
+    assert(cmd.name.asInstanceOf[UnresolvedIdentifier].nameParts ==
+      Seq("mycat", "myschema", "myflow"))
+  }
+
+  test("CREATE FLOW AS AUTO CDC INTO - two-part target table name") {
+    val plan = parser.parsePlan(
+      """CREATE FLOW f AS AUTO CDC INTO myschema.mytable
+        |FROM source
+        |KEYS (k)
+        |SEQUENCE BY ts""".stripMargin)
+
+    val cdc = plan.asInstanceOf[CreateFlowCommand].flowOperation.asInstanceOf[AutoCdcIntoCommand]
+    assert(cdc.targetTable.database == Some("myschema"))
+    assert(cdc.targetTable.table == "mytable")
+  }
+
+  test("CREATE FLOW AS AUTO CDC INTO - APPLY AS DELETE WHEN") {
+    val plan = parser.parsePlan(
+      """CREATE FLOW f AS AUTO CDC INTO target
+        |FROM source
+        |KEYS (id)
+        |APPLY AS DELETE WHEN op = 'DELETE'
+        |SEQUENCE BY ts""".stripMargin)
+
+    val cdc = plan.asInstanceOf[CreateFlowCommand].flowOperation.asInstanceOf[AutoCdcIntoCommand]
+    assert(cdc.deleteCondition.isDefined)
+    assert(cdc.deleteCondition.get.sql.contains("op"))
+  }
+
+  test("CREATE FLOW AS AUTO CDC INTO - COLUMNS include list") {
+    val plan = parser.parsePlan(
+      """CREATE FLOW f AS AUTO CDC INTO target
+        |FROM source
+        |KEYS (id)
+        |SEQUENCE BY ts
+        |COLUMNS id, name, value""".stripMargin)
+
+    val cdc = plan.asInstanceOf[CreateFlowCommand].flowOperation.asInstanceOf[AutoCdcIntoCommand]
+    assert(cdc.specifiedCols.map(_.name) == Seq("id", "name", "value"))
+    assert(cdc.exceptCols.isEmpty)
+  }
+
+  test("CREATE FLOW AS AUTO CDC INTO - COLUMNS * EXCEPT list") {
+    val plan = parser.parsePlan(
+      """CREATE FLOW f AS AUTO CDC INTO target
+        |FROM source
+        |KEYS (id)
+        |SEQUENCE BY ts
+        |COLUMNS * EXCEPT (op, ts)""".stripMargin)
+
+    val cdc = plan.asInstanceOf[CreateFlowCommand].flowOperation.asInstanceOf[AutoCdcIntoCommand]
+    assert(cdc.specifiedCols.isEmpty)
+    assert(cdc.exceptCols.map(_.name) == Seq("op", "ts"))
+  }
+
+  test("CREATE FLOW AS AUTO CDC INTO - all clauses combined") {
+    val plan = parser.parsePlan(
+      """CREATE FLOW f AS AUTO CDC INTO target
+        |FROM source
+        |KEYS (key1, key2)
+        |APPLY AS DELETE WHEN key3 = 3
+        |SEQUENCE BY timestamp
+        |COLUMNS key1, key2, key3, timestamp""".stripMargin)
+
+    val cdc = plan.asInstanceOf[CreateFlowCommand].flowOperation.asInstanceOf[AutoCdcIntoCommand]
+    assert(cdc.keys.map(_.name) == Seq("key1", "key2"))
+    assert(cdc.deleteCondition.isDefined)
+    assert(cdc.sequenceByExpr == UnresolvedAttribute("timestamp"))
+    assert(cdc.specifiedCols.map(_.name) == Seq("key1", "key2", "key3", "timestamp"))
+  }
+
+  // ---------------------------------------------------------------------------
+  // CREATE STREAMING TABLE ... FLOW AUTO CDC
+  // ---------------------------------------------------------------------------
+
+  test("CREATE STREAMING TABLE FLOW AUTO CDC - minimal form") {
+    val plan = parser.parsePlan(
+      """CREATE STREAMING TABLE target
+        |FLOW AUTO CDC
+        |FROM source
+        |KEYS (key1, key2)
+        |SEQUENCE BY timestamp""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateStreamingTableAutoCdc]
+    assert(cmd.name.asInstanceOf[UnresolvedIdentifier].nameParts == Seq("target"))
+    assert(!cmd.ifNotExists)
+    assert(cmd.sourceTable.isInstanceOf[UnresolvedRelation])
+    assert(cmd.keys.map(_.name) == Seq("key1", "key2"))
+    assert(cmd.deleteCondition.isEmpty)
+    assert(cmd.sequenceByExpr == UnresolvedAttribute("timestamp"))
+    assert(cmd.specifiedCols.isEmpty)
+    assert(cmd.exceptCols.isEmpty)
+  }
+
+  test("CREATE STREAMING TABLE IF NOT EXISTS FLOW AUTO CDC") {
+    val plan = parser.parsePlan(
+      """CREATE STREAMING TABLE IF NOT EXISTS target
+        |FLOW AUTO CDC
+        |FROM source
+        |KEYS (id)
+        |SEQUENCE BY ts""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateStreamingTableAutoCdc]
+    assert(cmd.ifNotExists)
+  }
+
+  test("CREATE STREAMING TABLE FLOW AUTO CDC - multipart table name") {
+    val plan = parser.parsePlan(
+      """CREATE STREAMING TABLE myschema.mytable
+        |FLOW AUTO CDC
+        |FROM source
+        |KEYS (id)
+        |SEQUENCE BY ts""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateStreamingTableAutoCdc]
+    assert(cmd.name.asInstanceOf[UnresolvedIdentifier].nameParts == Seq("myschema", "mytable"))
+  }
+
+  test("CREATE STREAMING TABLE FLOW AUTO CDC - APPLY AS DELETE WHEN") {
+    val plan = parser.parsePlan(
+      """CREATE STREAMING TABLE target
+        |FLOW AUTO CDC
+        |FROM source
+        |KEYS (id)
+        |APPLY AS DELETE WHEN op = 'DELETE'
+        |SEQUENCE BY ts""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateStreamingTableAutoCdc]
+    assert(cmd.deleteCondition.isDefined)
+    assert(cmd.deleteCondition.get.sql.contains("op"))
+  }
+
+  test("CREATE STREAMING TABLE FLOW AUTO CDC - COLUMNS include list") {
+    val plan = parser.parsePlan(
+      """CREATE STREAMING TABLE target
+        |FLOW AUTO CDC
+        |FROM source
+        |KEYS (id)
+        |SEQUENCE BY ts
+        |COLUMNS id, name, value""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateStreamingTableAutoCdc]
+    assert(cmd.specifiedCols.map(_.name) == Seq("id", "name", "value"))
+    assert(cmd.exceptCols.isEmpty)
+  }
+
+  test("CREATE STREAMING TABLE FLOW AUTO CDC - COLUMNS * EXCEPT list") {
+    val plan = parser.parsePlan(
+      """CREATE STREAMING TABLE target
+        |FLOW AUTO CDC
+        |FROM source
+        |KEYS (id)
+        |SEQUENCE BY ts
+        |COLUMNS * EXCEPT (op, ts)""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateStreamingTableAutoCdc]
+    assert(cmd.specifiedCols.isEmpty)
+    assert(cmd.exceptCols.map(_.name) == Seq("op", "ts"))
+  }
+
+  test("CREATE STREAMING TABLE FLOW AUTO CDC - all clauses combined") {
+    val plan = parser.parsePlan(
+      """CREATE STREAMING TABLE target
+        |FLOW AUTO CDC
+        |FROM source
+        |KEYS (key1, key2)
+        |APPLY AS DELETE WHEN key3 = 3
+        |SEQUENCE BY timestamp
+        |COLUMNS * EXCEPT (key4)""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateStreamingTableAutoCdc]
+    assert(cmd.keys.map(_.name) == Seq("key1", "key2"))
+    assert(cmd.deleteCondition.isDefined)
+    assert(cmd.sequenceByExpr == UnresolvedAttribute("timestamp"))
+    assert(cmd.exceptCols.map(_.name) == Seq("key4"))
+  }
+
+  // ---------------------------------------------------------------------------
+  // Error cases: missing required clause
+  // ---------------------------------------------------------------------------
+
+  test("CREATE FLOW AS AUTO CDC INTO - SEQUENCE BY is required") {
+    val e = intercept[ParseException] {
+      parser.parsePlan(
+        """CREATE FLOW f AS AUTO CDC INTO target
+          |FROM source
+          |KEYS (id)""".stripMargin)
+    }
+    assert(e.getCondition == "MISSING_CLAUSES_FOR_OPERATION")
+    assert(e.getMessageParameters.get("clauses") == "SEQUENCE BY")
+    assert(e.getMessageParameters.get("operation") == "AUTO CDC INTO")
+  }
+
+  test("CREATE STREAMING TABLE FLOW AUTO CDC - SEQUENCE BY is required") {
+    intercept[ParseException] {
+      parser.parsePlan(
+        """CREATE STREAMING TABLE target
+          |FLOW AUTO CDC
+          |FROM source
+          |KEYS (id)""".stripMargin)
+    }
+  }
+
+  // ---------------------------------------------------------------------------
+  // Error cases: duplicate clauses
+  // ---------------------------------------------------------------------------
+
+  test("duplicate SEQUENCE BY clause") {

Review Comment:
   Added for the errors where we explicitly throw an exception. 
   For the cases that the parser already catches, it's hard to predict what the error code would be. 



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [CONNECT][SDP][SPARK-56249] Create AUTO CDC syntax for SCD Type 1 in SQL [spark]

Posted by "szehon-ho (via GitHub)" <gi...@apache.org>.
szehon-ho commented on code in PR #56419:
URL: https://github.com/apache/spark/pull/56419#discussion_r3456141102


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/SparkSqlParser.scala:
##########
@@ -1548,22 +1549,43 @@ class SparkSqlAstBuilder extends AstBuilder {
     )
   }
 
-  override def visitCreatePipelineDataset(
-      ctx: CreatePipelineDatasetContext): LogicalPlan = withOrigin(ctx) {
-    val createPipelineDatasetHeaderCtx = ctx.createPipelineDatasetHeader()
-
-    val syntaxTypeErrorStr = if (createPipelineDatasetHeaderCtx.materializedView() != null) {
-      "MATERIALIZED VIEW"
-    } else if (createPipelineDatasetHeaderCtx.streamingTable() != null) {
-      "STREAMING TABLE"
-    } else {
-      // Should never be possible based on grammar definition.
-      throw invalidStatement(ctx.getText, ctx)
-    }
+  override def visitCreateFlowAutoCdc(
+      ctx: CreateFlowAutoCdcContext): LogicalPlan = withOrigin(ctx) {
+    val flowHeaderCtx = ctx.createPipelineFlowHeader()
+    val ident = withIdentClause(flowHeaderCtx.flowName, UnresolvedIdentifier(_))
+    val commentOpt = Option(flowHeaderCtx.commentSpec()).map(visitCommentSpec)
+    val applyChanges = buildAutoCdcIntoCommand(ctx.autoCdcCommand())
+    CreateFlowCommand(
+      name = ident,
+      flowOperation = applyChanges,
+      comment = commentOpt
+    )
+  }
 
-    val ifNotExists = createPipelineDatasetHeaderCtx.EXISTS() != null
-    val provider = Option(ctx.tableProvider).map(_.multipartIdentifier.getText)
-    val (colDefs, colConstraints) = Option(ctx.tableElementList()).map(visitTableElementList)
+  /**
+   * Shared helper for pipeline dataset creation statements (CREATE STREAMING TABLE,
+   * CREATE MATERIALIZED VIEW, CREATE STREAMING TABLE ... FLOW AUTO CDC).
+   *
+   * Validates and extracts column definitions, partitioning, and table spec from the common
+   * grammar elements shared by these statements.
+   *
+   * @return (colDefs, partitioning, spec, ifNotExists, tableIdent)
+   */
+  private def parsePipelineDatasetPrelude(

Review Comment:
   +1 -- after the grammar merge removed `visitCreateStreamingTableAutoCdc`, this helper has a single caller (`visitCreatePipelineDataset`), and all of its params are just forwarded from that one `ctx`. The dedup rationale is gone, so I'd inline it back to avoid the extra 6-param/5-tuple indirection.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/parser/AstBuilder.scala:
##########
@@ -1362,6 +1362,44 @@ class AstBuilder extends DataTypeAstBuilder
       withSchemaEvolution)
   }
 
+  protected def buildAutoCdcIntoCommand(ctx: AutoCdcCommandContext): AutoCdcIntoCommand =
+    withOrigin(ctx) {
+      val target = visitMultipartIdentifier(ctx.target).asTableIdentifier
+      val (src, keys, delete, seq, specCols, exceptCols) =
+        parseAutoCdcParams(ctx.autoCdcParameters())
+      AutoCdcIntoCommand(target, src, keys, delete, seq, specCols, exceptCols)
+    }
+
+  protected def parseAutoCdcParams(params: AutoCdcParametersContext): (
+      LogicalPlan,
+      Seq[UnresolvedAttribute],
+      Option[Expression],
+      Expression,
+      Seq[UnresolvedAttribute],
+      Seq[UnresolvedAttribute]) =
+    withOrigin(params) {
+      val sourceTable = plan(params.source) match {
+        case r: UnresolvedRelation => r.copy(isStreaming = true)

Review Comment:
   +1. Silently coercing to `isStreaming = true` (and the `case other => other` passthrough) hides cases the contract does not actually allow. I'd throw a clear error for a non-streaming/non-identifier source and point users at `STREAM(...)`, matching the Connect/Python path which models the source as a streaming relation.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/parser/AstBuilder.scala:
##########
@@ -1362,6 +1362,44 @@ class AstBuilder extends DataTypeAstBuilder
       withSchemaEvolution)
   }
 
+  protected def buildAutoCdcIntoCommand(ctx: AutoCdcCommandContext): AutoCdcIntoCommand =
+    withOrigin(ctx) {
+      val target = visitMultipartIdentifier(ctx.target).asTableIdentifier
+      val (src, keys, delete, seq, specCols, exceptCols) =
+        parseAutoCdcParams(ctx.autoCdcParameters())
+      AutoCdcIntoCommand(target, src, keys, delete, seq, specCols, exceptCols)
+    }
+
+  protected def parseAutoCdcParams(params: AutoCdcParametersContext): (
+      LogicalPlan,
+      Seq[UnresolvedAttribute],
+      Option[Expression],
+      Expression,
+      Seq[UnresolvedAttribute],
+      Seq[UnresolvedAttribute]) =
+    withOrigin(params) {
+      val sourceTable = plan(params.source) match {
+        case r: UnresolvedRelation => r.copy(isStreaming = true)
+        case other => other

Review Comment:
   Agree. Since `source=relationPrimary`, `case other => other` currently accepts subqueries, inline `VALUES`, TVFs, etc. as the source child and passes them through unmarked. Given SDP expects `source` to be a plain identifier (`optional string source`), I'd restrict this to a (optionally `STREAM`-wrapped) table identifier and reject the rest. That also lets `AutoCdcIntoCommand` carry a `TableIdentifier` and go back to a leaf, as you noted.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/parser/AstBuilder.scala:
##########
@@ -1362,6 +1362,44 @@ class AstBuilder extends DataTypeAstBuilder
       withSchemaEvolution)
   }
 
+  protected def buildAutoCdcIntoCommand(ctx: AutoCdcCommandContext): AutoCdcIntoCommand =
+    withOrigin(ctx) {
+      val target = visitMultipartIdentifier(ctx.target).asTableIdentifier
+      val (src, keys, delete, seq, specCols, exceptCols) =
+        parseAutoCdcParams(ctx.autoCdcParameters())
+      AutoCdcIntoCommand(target, src, keys, delete, seq, specCols, exceptCols)
+    }
+
+  protected def parseAutoCdcParams(params: AutoCdcParametersContext): (
+      LogicalPlan,
+      Seq[UnresolvedAttribute],
+      Option[Expression],
+      Expression,
+      Seq[UnresolvedAttribute],
+      Seq[UnresolvedAttribute]) =

Review Comment:
   +1, same reaction. A 6-element tuple destructured at two call sites is easy to misorder; a small `AutoCdcParams` case class (or returning `AutoCdcIntoCommand` directly) would be clearer.



##########
sql/api/src/main/antlr4/org/apache/spark/sql/catalyst/parser/SqlBaseParser.g4:
##########
@@ -750,6 +751,37 @@ dmlStatementNoWith
         notMatchedBySourceClause*                                                  #mergeIntoTable
     ;
 
+autoCdcCommand
+    : AUTO CDC INTO target=multipartIdentifier
+        autoCdcParameters
+    ;
+
+autoCdcBody
+    : AUTO CDC autoCdcParameters
+    ;
+
+autoCdcParameters
+    : FROM source=relationPrimary
+        KEYS LEFT_PAREN keys=multipartIdentifierList RIGHT_PAREN

Review Comment:
   +1 -- keys and the COLUMNS list only allow simple column identifiers per the contract, so `multipartIdentifierList` lets e.g. `KEYS (a.b.c)` parse and pushes the check downstream. Using `identifierSeq`/`identifierList` makes it correct by construction.



##########
common/utils/src/main/resources/error/error-conditions.json:
##########
@@ -5529,6 +5529,12 @@
     },
     "sqlState" : "0A000"
   },
+  "MISSING_CLAUSES_FOR_OPERATION" : {

Review Comment:
   Confirmed it should stay, though not for AUTO CDC: on current master `QueryParsingErrors.missingClausesForOperation` is referenced by the METRIC VIEW path (`SparkSqlParser`), but `MISSING_CLAUSES_FOR_OPERATION` is not actually defined in `error-conditions.json` on master -- so this entry is what backs that error. Probably cleaner to land it as its own small fix since it is orthogonal to AUTO CDC.



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [CONNECT][SDP][SPARK-56249] Create AUTO CDC syntax for SCD Type 1 in SQL [spark]

Posted by "anew (via GitHub)" <gi...@apache.org>.
anew commented on code in PR #56419:
URL: https://github.com/apache/spark/pull/56419#discussion_r3483392075


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/parser/AstBuilder.scala:
##########
@@ -1362,6 +1362,44 @@ class AstBuilder extends DataTypeAstBuilder
       withSchemaEvolution)
   }
 
+  protected def buildAutoCdcIntoCommand(ctx: AutoCdcCommandContext): AutoCdcIntoCommand =
+    withOrigin(ctx) {
+      val target = visitMultipartIdentifier(ctx.target).asTableIdentifier
+      val (src, keys, delete, seq, specCols, exceptCols) =
+        parseAutoCdcParams(ctx.autoCdcParameters())
+      AutoCdcIntoCommand(target, src, keys, delete, seq, specCols, exceptCols)
+    }
+
+  protected def parseAutoCdcParams(params: AutoCdcParametersContext): (
+      LogicalPlan,
+      Seq[UnresolvedAttribute],
+      Option[Expression],
+      Expression,
+      Seq[UnresolvedAttribute],
+      Seq[UnresolvedAttribute]) =
+    withOrigin(params) {
+      val sourceTable = plan(params.source) match {
+        case r: UnresolvedRelation => r.copy(isStreaming = true)

Review Comment:
   changed this to always require STREAM()



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [CONNECT][SDP][SPARK-56249] Create AUTO CDC syntax for SCD Type 1 in SQL [spark]

Posted by "jose-torres (via GitHub)" <gi...@apache.org>.
jose-torres commented on code in PR #56419:
URL: https://github.com/apache/spark/pull/56419#discussion_r3405444686


##########
sql/core/src/test/scala/org/apache/spark/sql/execution/command/v2/AutoCdcParserSuite.scala:
##########
@@ -0,0 +1,494 @@
+/*
+ * 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.execution.command.v2
+
+import org.apache.spark.sql.catalyst.analysis.{
+  AnalysisTest, UnresolvedAttribute,
+  UnresolvedIdentifier, UnresolvedRelation}
+import org.apache.spark.sql.catalyst.parser.ParseException
+import org.apache.spark.sql.catalyst.plans.logical.{
+  AutoCdcIntoCommand,
+  CreateFlowCommand,
+  CreateStreamingTableAutoCdc
+}
+import org.apache.spark.sql.execution.SparkSqlParser
+
+/**
+ * Parser tests for AUTO CDC syntax.
+ *
+ * Covers two supported forms:
+ *   1. CREATE FLOW <name> [COMMENT ...] AS AUTO CDC INTO <target> ...
+ *   2. CREATE STREAMING TABLE <name> FLOW AUTO CDC ...
+ *
+ * Snapshot CDC, SCD Type 2, IGNORE NULL UPDATES, and APPLY AS TRUNCATE WHEN are not
+ * supported and should fail to parse. The standalone AUTO CDC INTO form (without CREATE FLOW
+ * or CREATE STREAMING TABLE) is also not supported.
+ */
+class AutoCdcParserSuite extends CommandSuiteBase with AnalysisTest {
+  protected lazy val parser = new SparkSqlParser()
+
+  // ---------------------------------------------------------------------------
+  // CREATE FLOW ... AS AUTO CDC INTO
+  // ---------------------------------------------------------------------------
+
+  test("CREATE FLOW AS AUTO CDC INTO - minimal form") {
+    val plan = parser.parsePlan(
+      """CREATE FLOW myflow AS AUTO CDC INTO target
+        |FROM source
+        |KEYS (key1, key2)
+        |SEQUENCE BY timestamp""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateFlowCommand]
+    assert(cmd.name.asInstanceOf[UnresolvedIdentifier].nameParts == Seq("myflow"))
+    assert(cmd.comment.isEmpty)
+
+    val cdc = cmd.flowOperation.asInstanceOf[AutoCdcIntoCommand]
+    assert(cdc.targetTable.table == "target")
+    assert(cdc.sourceTable.isInstanceOf[UnresolvedRelation])
+    assert(cdc.sourceTable.asInstanceOf[UnresolvedRelation].isStreaming)
+    assert(cdc.keys.map(_.name) == Seq("key1", "key2"))
+    assert(cdc.deleteCondition.isEmpty)
+    assert(cdc.sequenceByExpr == UnresolvedAttribute("timestamp"))
+    assert(cdc.specifiedCols.isEmpty)
+    assert(cdc.exceptCols.isEmpty)
+  }
+
+  test("CREATE FLOW AS AUTO CDC INTO - with COMMENT") {
+    val plan = parser.parsePlan(
+      """CREATE FLOW myflow COMMENT 'my comment' AS AUTO CDC INTO target
+        |FROM source
+        |KEYS (id)
+        |SEQUENCE BY ts""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateFlowCommand]
+    assert(cmd.comment == Some("my comment"))
+  }
+
+  test("CREATE FLOW AS AUTO CDC INTO - multipart flow name") {
+    val plan = parser.parsePlan(
+      """CREATE FLOW mycat.myschema.myflow AS AUTO CDC INTO target
+        |FROM source
+        |KEYS (id)
+        |SEQUENCE BY ts""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateFlowCommand]
+    assert(cmd.name.asInstanceOf[UnresolvedIdentifier].nameParts ==
+      Seq("mycat", "myschema", "myflow"))
+  }
+
+  test("CREATE FLOW AS AUTO CDC INTO - two-part target table name") {
+    val plan = parser.parsePlan(
+      """CREATE FLOW f AS AUTO CDC INTO myschema.mytable
+        |FROM source
+        |KEYS (k)
+        |SEQUENCE BY ts""".stripMargin)
+
+    val cdc = plan.asInstanceOf[CreateFlowCommand].flowOperation.asInstanceOf[AutoCdcIntoCommand]
+    assert(cdc.targetTable.database == Some("myschema"))
+    assert(cdc.targetTable.table == "mytable")
+  }
+
+  test("CREATE FLOW AS AUTO CDC INTO - APPLY AS DELETE WHEN") {
+    val plan = parser.parsePlan(
+      """CREATE FLOW f AS AUTO CDC INTO target
+        |FROM source
+        |KEYS (id)
+        |APPLY AS DELETE WHEN op = 'DELETE'
+        |SEQUENCE BY ts""".stripMargin)
+
+    val cdc = plan.asInstanceOf[CreateFlowCommand].flowOperation.asInstanceOf[AutoCdcIntoCommand]
+    assert(cdc.deleteCondition.isDefined)
+    assert(cdc.deleteCondition.get.sql.contains("op"))
+  }
+
+  test("CREATE FLOW AS AUTO CDC INTO - COLUMNS include list") {
+    val plan = parser.parsePlan(
+      """CREATE FLOW f AS AUTO CDC INTO target
+        |FROM source
+        |KEYS (id)
+        |SEQUENCE BY ts
+        |COLUMNS id, name, value""".stripMargin)
+
+    val cdc = plan.asInstanceOf[CreateFlowCommand].flowOperation.asInstanceOf[AutoCdcIntoCommand]
+    assert(cdc.specifiedCols.map(_.name) == Seq("id", "name", "value"))
+    assert(cdc.exceptCols.isEmpty)
+  }
+
+  test("CREATE FLOW AS AUTO CDC INTO - COLUMNS * EXCEPT list") {
+    val plan = parser.parsePlan(
+      """CREATE FLOW f AS AUTO CDC INTO target
+        |FROM source
+        |KEYS (id)
+        |SEQUENCE BY ts
+        |COLUMNS * EXCEPT (op, ts)""".stripMargin)
+
+    val cdc = plan.asInstanceOf[CreateFlowCommand].flowOperation.asInstanceOf[AutoCdcIntoCommand]
+    assert(cdc.specifiedCols.isEmpty)
+    assert(cdc.exceptCols.map(_.name) == Seq("op", "ts"))
+  }
+
+  test("CREATE FLOW AS AUTO CDC INTO - all clauses combined") {
+    val plan = parser.parsePlan(
+      """CREATE FLOW f AS AUTO CDC INTO target
+        |FROM source
+        |KEYS (key1, key2)
+        |APPLY AS DELETE WHEN key3 = 3
+        |SEQUENCE BY timestamp
+        |COLUMNS key1, key2, key3, timestamp""".stripMargin)
+
+    val cdc = plan.asInstanceOf[CreateFlowCommand].flowOperation.asInstanceOf[AutoCdcIntoCommand]
+    assert(cdc.keys.map(_.name) == Seq("key1", "key2"))
+    assert(cdc.deleteCondition.isDefined)
+    assert(cdc.sequenceByExpr == UnresolvedAttribute("timestamp"))
+    assert(cdc.specifiedCols.map(_.name) == Seq("key1", "key2", "key3", "timestamp"))
+  }
+
+  // ---------------------------------------------------------------------------
+  // CREATE STREAMING TABLE ... FLOW AUTO CDC
+  // ---------------------------------------------------------------------------
+
+  test("CREATE STREAMING TABLE FLOW AUTO CDC - minimal form") {
+    val plan = parser.parsePlan(
+      """CREATE STREAMING TABLE target
+        |FLOW AUTO CDC
+        |FROM source
+        |KEYS (key1, key2)
+        |SEQUENCE BY timestamp""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateStreamingTableAutoCdc]
+    assert(cmd.name.asInstanceOf[UnresolvedIdentifier].nameParts == Seq("target"))
+    assert(!cmd.ifNotExists)
+    assert(cmd.sourceTable.isInstanceOf[UnresolvedRelation])
+    assert(cmd.sourceTable.asInstanceOf[UnresolvedRelation].isStreaming)
+    assert(cmd.keys.map(_.name) == Seq("key1", "key2"))
+    assert(cmd.deleteCondition.isEmpty)
+    assert(cmd.sequenceByExpr == UnresolvedAttribute("timestamp"))
+    assert(cmd.specifiedCols.isEmpty)
+    assert(cmd.exceptCols.isEmpty)
+  }
+
+  test("CREATE STREAMING TABLE IF NOT EXISTS FLOW AUTO CDC") {
+    val plan = parser.parsePlan(
+      """CREATE STREAMING TABLE IF NOT EXISTS target
+        |FLOW AUTO CDC
+        |FROM source
+        |KEYS (id)
+        |SEQUENCE BY ts""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateStreamingTableAutoCdc]
+    assert(cmd.ifNotExists)
+  }
+
+  test("CREATE STREAMING TABLE FLOW AUTO CDC - multipart table name") {
+    val plan = parser.parsePlan(
+      """CREATE STREAMING TABLE myschema.mytable
+        |FLOW AUTO CDC
+        |FROM source
+        |KEYS (id)
+        |SEQUENCE BY ts""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateStreamingTableAutoCdc]
+    assert(cmd.name.asInstanceOf[UnresolvedIdentifier].nameParts == Seq("myschema", "mytable"))
+  }
+
+  test("CREATE STREAMING TABLE FLOW AUTO CDC - APPLY AS DELETE WHEN") {
+    val plan = parser.parsePlan(
+      """CREATE STREAMING TABLE target
+        |FLOW AUTO CDC
+        |FROM source
+        |KEYS (id)
+        |APPLY AS DELETE WHEN op = 'DELETE'
+        |SEQUENCE BY ts""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateStreamingTableAutoCdc]
+    assert(cmd.deleteCondition.isDefined)
+    assert(cmd.deleteCondition.get.sql.contains("op"))
+  }
+
+  test("CREATE STREAMING TABLE FLOW AUTO CDC - COLUMNS include list") {
+    val plan = parser.parsePlan(
+      """CREATE STREAMING TABLE target
+        |FLOW AUTO CDC
+        |FROM source
+        |KEYS (id)
+        |SEQUENCE BY ts
+        |COLUMNS id, name, value""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateStreamingTableAutoCdc]
+    assert(cmd.specifiedCols.map(_.name) == Seq("id", "name", "value"))
+    assert(cmd.exceptCols.isEmpty)
+  }
+
+  test("CREATE STREAMING TABLE FLOW AUTO CDC - COLUMNS * EXCEPT list") {
+    val plan = parser.parsePlan(
+      """CREATE STREAMING TABLE target
+        |FLOW AUTO CDC
+        |FROM source
+        |KEYS (id)
+        |SEQUENCE BY ts
+        |COLUMNS * EXCEPT (op, ts)""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateStreamingTableAutoCdc]
+    assert(cmd.specifiedCols.isEmpty)
+    assert(cmd.exceptCols.map(_.name) == Seq("op", "ts"))
+  }
+
+  test("CREATE STREAMING TABLE FLOW AUTO CDC - all clauses combined") {
+    val plan = parser.parsePlan(
+      """CREATE STREAMING TABLE target
+        |FLOW AUTO CDC
+        |FROM source
+        |KEYS (key1, key2)
+        |APPLY AS DELETE WHEN key3 = 3
+        |SEQUENCE BY timestamp
+        |COLUMNS * EXCEPT (key4)""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateStreamingTableAutoCdc]
+    assert(cmd.keys.map(_.name) == Seq("key1", "key2"))
+    assert(cmd.deleteCondition.isDefined)
+    assert(cmd.sequenceByExpr == UnresolvedAttribute("timestamp"))
+    assert(cmd.exceptCols.map(_.name) == Seq("key4"))
+  }
+
+  // ---------------------------------------------------------------------------
+  // Error cases: missing required clause
+  // ---------------------------------------------------------------------------
+
+  test("CREATE FLOW AS AUTO CDC INTO - SEQUENCE BY is required") {
+    val e = intercept[ParseException] {
+      parser.parsePlan(
+        """CREATE FLOW f AS AUTO CDC INTO target
+          |FROM source
+          |KEYS (id)""".stripMargin)
+    }
+    assert(e.getCondition == "AUTOCDC_MISSING_SEQUENCE_BY")
+  }
+
+  test("CREATE STREAMING TABLE FLOW AUTO CDC - SEQUENCE BY is required") {
+    val e = intercept[ParseException] {
+      parser.parsePlan(
+        """CREATE STREAMING TABLE target
+          |FLOW AUTO CDC
+          |FROM source
+          |KEYS (id)""".stripMargin)
+    }
+    assert(e.getCondition == "AUTOCDC_MISSING_SEQUENCE_BY")
+  }
+
+  // ---------------------------------------------------------------------------
+  // Error cases: duplicate clauses
+  // ---------------------------------------------------------------------------
+
+  test("duplicate SEQUENCE BY clause") {
+    val e = intercept[ParseException] {
+      parser.parsePlan(
+        """CREATE FLOW f AS AUTO CDC INTO target
+          |FROM source
+          |KEYS (id)
+          |SEQUENCE BY ts1
+          |SEQUENCE BY ts2""".stripMargin)
+    }
+    assert(e.getCondition == "DUPLICATE_CLAUSES")
+  }
+
+  test("duplicate APPLY AS DELETE clause") {
+    val e = intercept[ParseException] {
+      parser.parsePlan(
+        """CREATE FLOW f AS AUTO CDC INTO target
+          |FROM source
+          |KEYS (id)
+          |APPLY AS DELETE WHEN a = 1
+          |APPLY AS DELETE WHEN b = 2
+          |SEQUENCE BY ts""".stripMargin)
+    }
+    assert(e.getCondition == "DUPLICATE_CLAUSES")

Review Comment:
   nit: Worth checking the specific clause being duplicated, it would be easy to end up with a bug pointing to the wrong one if we add more clauses in the future



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [CONNECT][SDP][SPARK-56249] Create AUTO CDC syntax for SCD Type 1 in SQL [spark]

Posted by "anew (via GitHub)" <gi...@apache.org>.
anew commented on code in PR #56419:
URL: https://github.com/apache/spark/pull/56419#discussion_r3399411652


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/parser/AstBuilder.scala:
##########
@@ -1362,6 +1362,50 @@ class AstBuilder extends DataTypeAstBuilder
       withSchemaEvolution)
   }
 
+  protected def buildAutoCdcIntoCommand(ctx: AutoCdcCommandContext): AutoCdcIntoCommand =
+    withOrigin(ctx) {
+      val target = visitMultipartIdentifier(ctx.target).asTableIdentifier
+      val (src, keys, delete, seq, specCols, exceptCols) =
+        parseAutoCdcParams(ctx.autoCdcParameters())
+      AutoCdcIntoCommand(target, src, keys, delete, seq, specCols, exceptCols)
+    }
+
+  protected def parseAutoCdcParams(params: AutoCdcParametersContext): (
+      LogicalPlan,
+      Seq[UnresolvedAttribute],
+      Option[Expression],
+      Expression,
+      Seq[UnresolvedAttribute],
+      Seq[UnresolvedAttribute]) =
+    withOrigin(params) {
+      checkDuplicateClauses(params.autoCdcDeleteClause(), "APPLY AS DELETE", params)
+      checkDuplicateClauses(params.autoCdcSequenceByClause(), "SEQUENCE BY", params)
+      checkDuplicateClauses(params.autoCdcColumnsClause(), "COLUMNS", params)
+
+      if (params.autoCdcSequenceByClause().isEmpty) {
+        throw QueryParsingErrors.missingClausesForOperation(
+          params, "SEQUENCE BY", "AUTO CDC INTO")
+      }
+
+      val sourceTable = plan(params.source.relationPrimary)

Review Comment:
   We only want the source itself. Let me fix this



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [CONNECT][SDP][SPARK-56249] Create AUTO CDC syntax for SCD Type 1 in SQL [spark]

Posted by "szehon-ho (via GitHub)" <gi...@apache.org>.
szehon-ho commented on code in PR #56419:
URL: https://github.com/apache/spark/pull/56419#discussion_r3398976554


##########
sql/core/src/test/scala/org/apache/spark/sql/execution/command/v2/AutoCdcParserSuite.scala:
##########
@@ -0,0 +1,392 @@
+/*
+ * 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.execution.command.v2
+
+import org.apache.spark.sql.catalyst.analysis.{
+  AnalysisTest, UnresolvedAttribute,
+  UnresolvedIdentifier, UnresolvedRelation}
+import org.apache.spark.sql.catalyst.parser.ParseException
+import org.apache.spark.sql.catalyst.plans.logical.{
+  AutoCdcIntoCommand,
+  CreateFlowCommand,
+  CreateStreamingTableAutoCdc
+}
+import org.apache.spark.sql.execution.SparkSqlParser
+
+/**
+ * Parser tests for AUTO CDC syntax.
+ *
+ * Covers two supported forms:
+ *   1. CREATE FLOW <name> [COMMENT ...] AS AUTO CDC INTO <target> ...
+ *   2. CREATE STREAMING TABLE <name> FLOW AUTO CDC ...
+ *
+ * Snapshot CDC, SCD Type 2, IGNORE NULL UPDATES, and APPLY AS TRUNCATE WHEN are not
+ * supported and should fail to parse. The standalone AUTO CDC INTO form (without CREATE FLOW
+ * or CREATE STREAMING TABLE) is also not supported.
+ */
+class AutoCdcParserSuite extends CommandSuiteBase with AnalysisTest {
+  protected lazy val parser = new SparkSqlParser()
+
+  // ---------------------------------------------------------------------------
+  // CREATE FLOW ... AS AUTO CDC INTO
+  // ---------------------------------------------------------------------------
+
+  test("CREATE FLOW AS AUTO CDC INTO - minimal form") {
+    val plan = parser.parsePlan(
+      """CREATE FLOW myflow AS AUTO CDC INTO target
+        |FROM source
+        |KEYS (key1, key2)
+        |SEQUENCE BY timestamp""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateFlowCommand]
+    assert(cmd.name.asInstanceOf[UnresolvedIdentifier].nameParts == Seq("myflow"))
+    assert(cmd.comment.isEmpty)
+
+    val cdc = cmd.flowOperation.asInstanceOf[AutoCdcIntoCommand]
+    assert(cdc.targetTable.table == "target")
+    assert(cdc.sourceTable.isInstanceOf[UnresolvedRelation])
+    assert(cdc.keys.map(_.name) == Seq("key1", "key2"))
+    assert(cdc.deleteCondition.isEmpty)
+    assert(cdc.sequenceByExpr == UnresolvedAttribute("timestamp"))
+    assert(cdc.specifiedCols.isEmpty)
+    assert(cdc.exceptCols.isEmpty)
+  }
+
+  test("CREATE FLOW AS AUTO CDC INTO - with COMMENT") {
+    val plan = parser.parsePlan(
+      """CREATE FLOW myflow COMMENT 'my comment' AS AUTO CDC INTO target
+        |FROM source
+        |KEYS (id)
+        |SEQUENCE BY ts""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateFlowCommand]
+    assert(cmd.comment == Some("my comment"))
+  }
+
+  test("CREATE FLOW AS AUTO CDC INTO - multipart flow name") {
+    val plan = parser.parsePlan(
+      """CREATE FLOW mycat.myschema.myflow AS AUTO CDC INTO target
+        |FROM source
+        |KEYS (id)
+        |SEQUENCE BY ts""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateFlowCommand]
+    assert(cmd.name.asInstanceOf[UnresolvedIdentifier].nameParts ==
+      Seq("mycat", "myschema", "myflow"))
+  }
+
+  test("CREATE FLOW AS AUTO CDC INTO - two-part target table name") {
+    val plan = parser.parsePlan(
+      """CREATE FLOW f AS AUTO CDC INTO myschema.mytable
+        |FROM source
+        |KEYS (k)
+        |SEQUENCE BY ts""".stripMargin)
+
+    val cdc = plan.asInstanceOf[CreateFlowCommand].flowOperation.asInstanceOf[AutoCdcIntoCommand]
+    assert(cdc.targetTable.database == Some("myschema"))
+    assert(cdc.targetTable.table == "mytable")
+  }
+
+  test("CREATE FLOW AS AUTO CDC INTO - APPLY AS DELETE WHEN") {
+    val plan = parser.parsePlan(
+      """CREATE FLOW f AS AUTO CDC INTO target
+        |FROM source
+        |KEYS (id)
+        |APPLY AS DELETE WHEN op = 'DELETE'
+        |SEQUENCE BY ts""".stripMargin)
+
+    val cdc = plan.asInstanceOf[CreateFlowCommand].flowOperation.asInstanceOf[AutoCdcIntoCommand]
+    assert(cdc.deleteCondition.isDefined)
+    assert(cdc.deleteCondition.get.sql.contains("op"))
+  }
+
+  test("CREATE FLOW AS AUTO CDC INTO - COLUMNS include list") {
+    val plan = parser.parsePlan(
+      """CREATE FLOW f AS AUTO CDC INTO target
+        |FROM source
+        |KEYS (id)
+        |SEQUENCE BY ts
+        |COLUMNS id, name, value""".stripMargin)
+
+    val cdc = plan.asInstanceOf[CreateFlowCommand].flowOperation.asInstanceOf[AutoCdcIntoCommand]
+    assert(cdc.specifiedCols.map(_.name) == Seq("id", "name", "value"))
+    assert(cdc.exceptCols.isEmpty)
+  }
+
+  test("CREATE FLOW AS AUTO CDC INTO - COLUMNS * EXCEPT list") {
+    val plan = parser.parsePlan(
+      """CREATE FLOW f AS AUTO CDC INTO target
+        |FROM source
+        |KEYS (id)
+        |SEQUENCE BY ts
+        |COLUMNS * EXCEPT (op, ts)""".stripMargin)
+
+    val cdc = plan.asInstanceOf[CreateFlowCommand].flowOperation.asInstanceOf[AutoCdcIntoCommand]
+    assert(cdc.specifiedCols.isEmpty)
+    assert(cdc.exceptCols.map(_.name) == Seq("op", "ts"))
+  }
+
+  test("CREATE FLOW AS AUTO CDC INTO - all clauses combined") {
+    val plan = parser.parsePlan(
+      """CREATE FLOW f AS AUTO CDC INTO target
+        |FROM source
+        |KEYS (key1, key2)
+        |APPLY AS DELETE WHEN key3 = 3
+        |SEQUENCE BY timestamp
+        |COLUMNS key1, key2, key3, timestamp""".stripMargin)
+
+    val cdc = plan.asInstanceOf[CreateFlowCommand].flowOperation.asInstanceOf[AutoCdcIntoCommand]
+    assert(cdc.keys.map(_.name) == Seq("key1", "key2"))
+    assert(cdc.deleteCondition.isDefined)
+    assert(cdc.sequenceByExpr == UnresolvedAttribute("timestamp"))
+    assert(cdc.specifiedCols.map(_.name) == Seq("key1", "key2", "key3", "timestamp"))
+  }
+
+  // ---------------------------------------------------------------------------
+  // CREATE STREAMING TABLE ... FLOW AUTO CDC
+  // ---------------------------------------------------------------------------
+
+  test("CREATE STREAMING TABLE FLOW AUTO CDC - minimal form") {
+    val plan = parser.parsePlan(
+      """CREATE STREAMING TABLE target
+        |FLOW AUTO CDC
+        |FROM source
+        |KEYS (key1, key2)
+        |SEQUENCE BY timestamp""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateStreamingTableAutoCdc]
+    assert(cmd.name.asInstanceOf[UnresolvedIdentifier].nameParts == Seq("target"))
+    assert(!cmd.ifNotExists)
+    assert(cmd.sourceTable.isInstanceOf[UnresolvedRelation])
+    assert(cmd.keys.map(_.name) == Seq("key1", "key2"))
+    assert(cmd.deleteCondition.isEmpty)
+    assert(cmd.sequenceByExpr == UnresolvedAttribute("timestamp"))
+    assert(cmd.specifiedCols.isEmpty)
+    assert(cmd.exceptCols.isEmpty)
+  }
+
+  test("CREATE STREAMING TABLE IF NOT EXISTS FLOW AUTO CDC") {
+    val plan = parser.parsePlan(
+      """CREATE STREAMING TABLE IF NOT EXISTS target
+        |FLOW AUTO CDC
+        |FROM source
+        |KEYS (id)
+        |SEQUENCE BY ts""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateStreamingTableAutoCdc]
+    assert(cmd.ifNotExists)
+  }
+
+  test("CREATE STREAMING TABLE FLOW AUTO CDC - multipart table name") {
+    val plan = parser.parsePlan(
+      """CREATE STREAMING TABLE myschema.mytable
+        |FLOW AUTO CDC
+        |FROM source
+        |KEYS (id)
+        |SEQUENCE BY ts""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateStreamingTableAutoCdc]
+    assert(cmd.name.asInstanceOf[UnresolvedIdentifier].nameParts == Seq("myschema", "mytable"))
+  }
+
+  test("CREATE STREAMING TABLE FLOW AUTO CDC - APPLY AS DELETE WHEN") {
+    val plan = parser.parsePlan(
+      """CREATE STREAMING TABLE target
+        |FLOW AUTO CDC
+        |FROM source
+        |KEYS (id)
+        |APPLY AS DELETE WHEN op = 'DELETE'
+        |SEQUENCE BY ts""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateStreamingTableAutoCdc]
+    assert(cmd.deleteCondition.isDefined)
+    assert(cmd.deleteCondition.get.sql.contains("op"))
+  }
+
+  test("CREATE STREAMING TABLE FLOW AUTO CDC - COLUMNS include list") {
+    val plan = parser.parsePlan(
+      """CREATE STREAMING TABLE target
+        |FLOW AUTO CDC
+        |FROM source
+        |KEYS (id)
+        |SEQUENCE BY ts
+        |COLUMNS id, name, value""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateStreamingTableAutoCdc]
+    assert(cmd.specifiedCols.map(_.name) == Seq("id", "name", "value"))
+    assert(cmd.exceptCols.isEmpty)
+  }
+
+  test("CREATE STREAMING TABLE FLOW AUTO CDC - COLUMNS * EXCEPT list") {
+    val plan = parser.parsePlan(
+      """CREATE STREAMING TABLE target
+        |FLOW AUTO CDC
+        |FROM source
+        |KEYS (id)
+        |SEQUENCE BY ts
+        |COLUMNS * EXCEPT (op, ts)""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateStreamingTableAutoCdc]
+    assert(cmd.specifiedCols.isEmpty)
+    assert(cmd.exceptCols.map(_.name) == Seq("op", "ts"))
+  }
+
+  test("CREATE STREAMING TABLE FLOW AUTO CDC - all clauses combined") {
+    val plan = parser.parsePlan(
+      """CREATE STREAMING TABLE target
+        |FLOW AUTO CDC
+        |FROM source
+        |KEYS (key1, key2)
+        |APPLY AS DELETE WHEN key3 = 3
+        |SEQUENCE BY timestamp
+        |COLUMNS * EXCEPT (key4)""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateStreamingTableAutoCdc]
+    assert(cmd.keys.map(_.name) == Seq("key1", "key2"))
+    assert(cmd.deleteCondition.isDefined)
+    assert(cmd.sequenceByExpr == UnresolvedAttribute("timestamp"))
+    assert(cmd.exceptCols.map(_.name) == Seq("key4"))
+  }
+
+  // ---------------------------------------------------------------------------
+  // Error cases: missing required clause
+  // ---------------------------------------------------------------------------
+
+  test("CREATE FLOW AS AUTO CDC INTO - SEQUENCE BY is required") {
+    val e = intercept[ParseException] {
+      parser.parsePlan(
+        """CREATE FLOW f AS AUTO CDC INTO target
+          |FROM source
+          |KEYS (id)""".stripMargin)
+    }
+    assert(e.getCondition == "MISSING_CLAUSES_FOR_OPERATION")
+    assert(e.getMessageParameters.get("clauses") == "SEQUENCE BY")
+    assert(e.getMessageParameters.get("operation") == "AUTO CDC INTO")
+  }
+
+  test("CREATE STREAMING TABLE FLOW AUTO CDC - SEQUENCE BY is required") {
+    intercept[ParseException] {
+      parser.parsePlan(
+        """CREATE STREAMING TABLE target
+          |FLOW AUTO CDC
+          |FROM source
+          |KEYS (id)""".stripMargin)
+    }
+  }
+
+  // ---------------------------------------------------------------------------
+  // Error cases: duplicate clauses
+  // ---------------------------------------------------------------------------
+
+  test("duplicate SEQUENCE BY clause") {

Review Comment:
   These `intercept[ParseException]` cases (duplicate `SEQUENCE BY`/`APPLY AS DELETE`/`COLUMNS`, "standalone", `APPLY AS TRUNCATE`, etc.) don't assert the cause. E.g. the TRUNCATE case fails only because `TRUNCATE` isn't in the grammar, not because of a deliberate rejection — so it'd still "pass" if the parser broke for an unrelated reason. Suggest asserting `getCondition` (e.g. `DUPLICATE_CLAUSES` for the duplicate cases), like the missing-`SEQUENCE BY` test above already does.



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [CONNECT][SDP][SPARK-56249] Create AUTO CDC syntax for SCD Type 1 in SQL [spark]

Posted by "anew (via GitHub)" <gi...@apache.org>.
anew commented on code in PR #56419:
URL: https://github.com/apache/spark/pull/56419#discussion_r3399428217


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/SparkSqlParser.scala:
##########
@@ -1516,6 +1516,98 @@ class SparkSqlAstBuilder extends AstBuilder {
     )
   }
 
+  override def visitCreateFlowAutoCdc(
+      ctx: CreateFlowAutoCdcContext): LogicalPlan = withOrigin(ctx) {
+    val flowHeaderCtx = ctx.createPipelineFlowHeader()
+    val ident = withIdentClause(flowHeaderCtx.flowName, UnresolvedIdentifier(_))
+    val commentOpt = Option(flowHeaderCtx.commentSpec()).map(visitCommentSpec)
+    val applyChanges = buildAutoCdcIntoCommand(ctx.autoCdcCommand())
+    CreateFlowCommand(
+      name = ident,
+      flowOperation = applyChanges,
+      comment = commentOpt
+    )
+  }
+
+  override def visitCreateStreamingTableAutoCdc(
+      ctx: CreateStreamingTableAutoCdcContext): LogicalPlan = withOrigin(ctx) {
+    val headerCtx = ctx.createPipelineDatasetHeader()
+
+    if (headerCtx.materializedView() != null) {
+      throw operationNotAllowed(
+        "AUTO CDC is only supported for STREAMING TABLE, not MATERIALIZED VIEW.", ctx)
+    }
+
+    val ifNotExists = headerCtx.EXISTS() != null
+    val provider = Option(ctx.tableProvider).map(_.multipartIdentifier.getText)
+    val (colDefs, colConstraints) = Option(ctx.tableElementList()).map(visitTableElementList)

Review Comment:
   good point



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [CONNECT][SDP][SPARK-56249] Create AUTO CDC syntax for SCD Type 1 in SQL [spark]

Posted by "anew (via GitHub)" <gi...@apache.org>.
anew commented on code in PR #56419:
URL: https://github.com/apache/spark/pull/56419#discussion_r3406816343


##########
common/utils/src/main/resources/error/error-conditions.json:
##########
@@ -5529,6 +5529,12 @@
     },
     "sqlState" : "0A000"
   },
+  "MISSING_CLAUSES_FOR_OPERATION" : {

Review Comment:
   interestingly this is used by the parser for METRIC VIEWS now, so I can't remove it. 



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [CONNECT][SDP][SPARK-56249] Create AUTO CDC syntax for SCD Type 1 in SQL [spark]

Posted by "anew (via GitHub)" <gi...@apache.org>.
anew commented on code in PR #56419:
URL: https://github.com/apache/spark/pull/56419#discussion_r3400079307


##########
sql/core/src/test/scala/org/apache/spark/sql/execution/command/v2/AutoCdcParserSuite.scala:
##########
@@ -0,0 +1,392 @@
+/*
+ * 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.execution.command.v2
+
+import org.apache.spark.sql.catalyst.analysis.{
+  AnalysisTest, UnresolvedAttribute,
+  UnresolvedIdentifier, UnresolvedRelation}
+import org.apache.spark.sql.catalyst.parser.ParseException
+import org.apache.spark.sql.catalyst.plans.logical.{
+  AutoCdcIntoCommand,
+  CreateFlowCommand,
+  CreateStreamingTableAutoCdc
+}
+import org.apache.spark.sql.execution.SparkSqlParser
+
+/**
+ * Parser tests for AUTO CDC syntax.
+ *
+ * Covers two supported forms:
+ *   1. CREATE FLOW <name> [COMMENT ...] AS AUTO CDC INTO <target> ...
+ *   2. CREATE STREAMING TABLE <name> FLOW AUTO CDC ...
+ *
+ * Snapshot CDC, SCD Type 2, IGNORE NULL UPDATES, and APPLY AS TRUNCATE WHEN are not
+ * supported and should fail to parse. The standalone AUTO CDC INTO form (without CREATE FLOW
+ * or CREATE STREAMING TABLE) is also not supported.
+ */
+class AutoCdcParserSuite extends CommandSuiteBase with AnalysisTest {
+  protected lazy val parser = new SparkSqlParser()
+
+  // ---------------------------------------------------------------------------
+  // CREATE FLOW ... AS AUTO CDC INTO
+  // ---------------------------------------------------------------------------
+
+  test("CREATE FLOW AS AUTO CDC INTO - minimal form") {
+    val plan = parser.parsePlan(
+      """CREATE FLOW myflow AS AUTO CDC INTO target
+        |FROM source
+        |KEYS (key1, key2)
+        |SEQUENCE BY timestamp""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateFlowCommand]
+    assert(cmd.name.asInstanceOf[UnresolvedIdentifier].nameParts == Seq("myflow"))
+    assert(cmd.comment.isEmpty)
+
+    val cdc = cmd.flowOperation.asInstanceOf[AutoCdcIntoCommand]
+    assert(cdc.targetTable.table == "target")
+    assert(cdc.sourceTable.isInstanceOf[UnresolvedRelation])
+    assert(cdc.keys.map(_.name) == Seq("key1", "key2"))
+    assert(cdc.deleteCondition.isEmpty)
+    assert(cdc.sequenceByExpr == UnresolvedAttribute("timestamp"))
+    assert(cdc.specifiedCols.isEmpty)
+    assert(cdc.exceptCols.isEmpty)
+  }
+
+  test("CREATE FLOW AS AUTO CDC INTO - with COMMENT") {
+    val plan = parser.parsePlan(
+      """CREATE FLOW myflow COMMENT 'my comment' AS AUTO CDC INTO target
+        |FROM source
+        |KEYS (id)
+        |SEQUENCE BY ts""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateFlowCommand]
+    assert(cmd.comment == Some("my comment"))
+  }
+
+  test("CREATE FLOW AS AUTO CDC INTO - multipart flow name") {
+    val plan = parser.parsePlan(
+      """CREATE FLOW mycat.myschema.myflow AS AUTO CDC INTO target
+        |FROM source
+        |KEYS (id)
+        |SEQUENCE BY ts""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateFlowCommand]
+    assert(cmd.name.asInstanceOf[UnresolvedIdentifier].nameParts ==
+      Seq("mycat", "myschema", "myflow"))
+  }
+
+  test("CREATE FLOW AS AUTO CDC INTO - two-part target table name") {
+    val plan = parser.parsePlan(
+      """CREATE FLOW f AS AUTO CDC INTO myschema.mytable
+        |FROM source
+        |KEYS (k)
+        |SEQUENCE BY ts""".stripMargin)
+
+    val cdc = plan.asInstanceOf[CreateFlowCommand].flowOperation.asInstanceOf[AutoCdcIntoCommand]
+    assert(cdc.targetTable.database == Some("myschema"))
+    assert(cdc.targetTable.table == "mytable")
+  }
+
+  test("CREATE FLOW AS AUTO CDC INTO - APPLY AS DELETE WHEN") {
+    val plan = parser.parsePlan(
+      """CREATE FLOW f AS AUTO CDC INTO target
+        |FROM source
+        |KEYS (id)
+        |APPLY AS DELETE WHEN op = 'DELETE'
+        |SEQUENCE BY ts""".stripMargin)
+
+    val cdc = plan.asInstanceOf[CreateFlowCommand].flowOperation.asInstanceOf[AutoCdcIntoCommand]
+    assert(cdc.deleteCondition.isDefined)
+    assert(cdc.deleteCondition.get.sql.contains("op"))
+  }
+
+  test("CREATE FLOW AS AUTO CDC INTO - COLUMNS include list") {
+    val plan = parser.parsePlan(
+      """CREATE FLOW f AS AUTO CDC INTO target
+        |FROM source
+        |KEYS (id)
+        |SEQUENCE BY ts
+        |COLUMNS id, name, value""".stripMargin)
+
+    val cdc = plan.asInstanceOf[CreateFlowCommand].flowOperation.asInstanceOf[AutoCdcIntoCommand]
+    assert(cdc.specifiedCols.map(_.name) == Seq("id", "name", "value"))
+    assert(cdc.exceptCols.isEmpty)
+  }
+
+  test("CREATE FLOW AS AUTO CDC INTO - COLUMNS * EXCEPT list") {
+    val plan = parser.parsePlan(
+      """CREATE FLOW f AS AUTO CDC INTO target
+        |FROM source
+        |KEYS (id)
+        |SEQUENCE BY ts
+        |COLUMNS * EXCEPT (op, ts)""".stripMargin)
+
+    val cdc = plan.asInstanceOf[CreateFlowCommand].flowOperation.asInstanceOf[AutoCdcIntoCommand]
+    assert(cdc.specifiedCols.isEmpty)
+    assert(cdc.exceptCols.map(_.name) == Seq("op", "ts"))
+  }
+
+  test("CREATE FLOW AS AUTO CDC INTO - all clauses combined") {
+    val plan = parser.parsePlan(
+      """CREATE FLOW f AS AUTO CDC INTO target
+        |FROM source
+        |KEYS (key1, key2)
+        |APPLY AS DELETE WHEN key3 = 3
+        |SEQUENCE BY timestamp
+        |COLUMNS key1, key2, key3, timestamp""".stripMargin)
+
+    val cdc = plan.asInstanceOf[CreateFlowCommand].flowOperation.asInstanceOf[AutoCdcIntoCommand]
+    assert(cdc.keys.map(_.name) == Seq("key1", "key2"))
+    assert(cdc.deleteCondition.isDefined)
+    assert(cdc.sequenceByExpr == UnresolvedAttribute("timestamp"))
+    assert(cdc.specifiedCols.map(_.name) == Seq("key1", "key2", "key3", "timestamp"))
+  }
+
+  // ---------------------------------------------------------------------------
+  // CREATE STREAMING TABLE ... FLOW AUTO CDC
+  // ---------------------------------------------------------------------------
+
+  test("CREATE STREAMING TABLE FLOW AUTO CDC - minimal form") {
+    val plan = parser.parsePlan(
+      """CREATE STREAMING TABLE target
+        |FLOW AUTO CDC
+        |FROM source
+        |KEYS (key1, key2)
+        |SEQUENCE BY timestamp""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateStreamingTableAutoCdc]
+    assert(cmd.name.asInstanceOf[UnresolvedIdentifier].nameParts == Seq("target"))
+    assert(!cmd.ifNotExists)
+    assert(cmd.sourceTable.isInstanceOf[UnresolvedRelation])
+    assert(cmd.keys.map(_.name) == Seq("key1", "key2"))
+    assert(cmd.deleteCondition.isEmpty)
+    assert(cmd.sequenceByExpr == UnresolvedAttribute("timestamp"))
+    assert(cmd.specifiedCols.isEmpty)
+    assert(cmd.exceptCols.isEmpty)
+  }
+
+  test("CREATE STREAMING TABLE IF NOT EXISTS FLOW AUTO CDC") {
+    val plan = parser.parsePlan(
+      """CREATE STREAMING TABLE IF NOT EXISTS target
+        |FLOW AUTO CDC
+        |FROM source
+        |KEYS (id)
+        |SEQUENCE BY ts""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateStreamingTableAutoCdc]
+    assert(cmd.ifNotExists)
+  }
+
+  test("CREATE STREAMING TABLE FLOW AUTO CDC - multipart table name") {
+    val plan = parser.parsePlan(
+      """CREATE STREAMING TABLE myschema.mytable
+        |FLOW AUTO CDC
+        |FROM source
+        |KEYS (id)
+        |SEQUENCE BY ts""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateStreamingTableAutoCdc]
+    assert(cmd.name.asInstanceOf[UnresolvedIdentifier].nameParts == Seq("myschema", "mytable"))
+  }
+
+  test("CREATE STREAMING TABLE FLOW AUTO CDC - APPLY AS DELETE WHEN") {
+    val plan = parser.parsePlan(
+      """CREATE STREAMING TABLE target
+        |FLOW AUTO CDC
+        |FROM source
+        |KEYS (id)
+        |APPLY AS DELETE WHEN op = 'DELETE'
+        |SEQUENCE BY ts""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateStreamingTableAutoCdc]
+    assert(cmd.deleteCondition.isDefined)
+    assert(cmd.deleteCondition.get.sql.contains("op"))
+  }
+
+  test("CREATE STREAMING TABLE FLOW AUTO CDC - COLUMNS include list") {
+    val plan = parser.parsePlan(
+      """CREATE STREAMING TABLE target
+        |FLOW AUTO CDC
+        |FROM source
+        |KEYS (id)
+        |SEQUENCE BY ts
+        |COLUMNS id, name, value""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateStreamingTableAutoCdc]
+    assert(cmd.specifiedCols.map(_.name) == Seq("id", "name", "value"))
+    assert(cmd.exceptCols.isEmpty)
+  }
+
+  test("CREATE STREAMING TABLE FLOW AUTO CDC - COLUMNS * EXCEPT list") {
+    val plan = parser.parsePlan(
+      """CREATE STREAMING TABLE target
+        |FLOW AUTO CDC
+        |FROM source
+        |KEYS (id)
+        |SEQUENCE BY ts
+        |COLUMNS * EXCEPT (op, ts)""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateStreamingTableAutoCdc]
+    assert(cmd.specifiedCols.isEmpty)
+    assert(cmd.exceptCols.map(_.name) == Seq("op", "ts"))
+  }
+
+  test("CREATE STREAMING TABLE FLOW AUTO CDC - all clauses combined") {
+    val plan = parser.parsePlan(
+      """CREATE STREAMING TABLE target
+        |FLOW AUTO CDC
+        |FROM source
+        |KEYS (key1, key2)
+        |APPLY AS DELETE WHEN key3 = 3
+        |SEQUENCE BY timestamp
+        |COLUMNS * EXCEPT (key4)""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateStreamingTableAutoCdc]
+    assert(cmd.keys.map(_.name) == Seq("key1", "key2"))
+    assert(cmd.deleteCondition.isDefined)
+    assert(cmd.sequenceByExpr == UnresolvedAttribute("timestamp"))
+    assert(cmd.exceptCols.map(_.name) == Seq("key4"))
+  }
+
+  // ---------------------------------------------------------------------------
+  // Error cases: missing required clause
+  // ---------------------------------------------------------------------------
+
+  test("CREATE FLOW AS AUTO CDC INTO - SEQUENCE BY is required") {
+    val e = intercept[ParseException] {
+      parser.parsePlan(
+        """CREATE FLOW f AS AUTO CDC INTO target
+          |FROM source
+          |KEYS (id)""".stripMargin)
+    }
+    assert(e.getCondition == "MISSING_CLAUSES_FOR_OPERATION")
+    assert(e.getMessageParameters.get("clauses") == "SEQUENCE BY")
+    assert(e.getMessageParameters.get("operation") == "AUTO CDC INTO")
+  }
+
+  test("CREATE STREAMING TABLE FLOW AUTO CDC - SEQUENCE BY is required") {
+    intercept[ParseException] {
+      parser.parsePlan(
+        """CREATE STREAMING TABLE target
+          |FLOW AUTO CDC
+          |FROM source
+          |KEYS (id)""".stripMargin)
+    }
+  }
+
+  // ---------------------------------------------------------------------------
+  // Error cases: duplicate clauses
+  // ---------------------------------------------------------------------------
+
+  test("duplicate SEQUENCE BY clause") {

Review Comment:
   I added all assertions, but note that now we check syntax errors for syntaxes that do not exist yet :) 



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [CONNECT][SDP][SPARK-56249] Create AUTO CDC syntax for SCD Type 1 in SQL [spark]

Posted by "szehon-ho (via GitHub)" <gi...@apache.org>.
szehon-ho commented on code in PR #56419:
URL: https://github.com/apache/spark/pull/56419#discussion_r3398976541


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/v2Commands.scala:
##########
@@ -824,6 +824,47 @@ case class CreateStreamingTable(
     copy(name = newChild)
 }
 
+/**
+ * Command parsed from `CREATE STREAMING TABLE <name> FLOW AUTO CDC ...` SQL syntax.
+ * This command serves as a parse-time placeholder for a pipeline CDC definition and cannot be
+ * executed directly. It is interpreted by the pipeline submodule during a pipeline execution.

Review Comment:
   This says the node "is interpreted by the pipeline submodule during a pipeline execution," but there's currently no handler: `SqlGraphRegistrationContext.processSqlQuery` has no case for `CreateStreamingTableAutoCdc` (it hits the `unsupportedLogicalPlan` branch), and `CreateFlowHandler` only accepts `InsertIntoStatement`. So this SQL parses but always fails at registration today. Please soften to something like "will be interpreted once execution support is added" (and link the follow-up), or add the handling. Same wording applies to `AutoCdcIntoCommand`.



##########
sql/api/src/main/antlr4/org/apache/spark/sql/catalyst/parser/SqlBaseLexer.g4:
##########
@@ -139,8 +139,10 @@ AND: 'AND';
 ANTI: 'ANTI';
 ANY: 'ANY';
 ANY_VALUE: 'ANY_VALUE';
+APPLY: 'APPLY';
 APPROX: 'APPROX';
 ARCHIVE: 'ARCHIVE';
+AUTO: 'AUTO';

Review Comment:
   `AUTO` is out of alphabetical order here (between `ARCHIVE` and `ARRAY`); it should sit after `AUTHORIZATION`. Same issue for `SEQUENCE` (between `SCHEMA` and `SCHEMAS`), and in `nonReserved` / the `sql-ref-ansi-compliance.md` table (where `AUTO` is listed before `ATOMIC`). The generated `.sql.out` golden files are already correctly sorted — just the hand-maintained lists are off. Minor, but worth fixing since you already have an ordering-fix commit.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/parser/AstBuilder.scala:
##########
@@ -1362,6 +1362,50 @@ class AstBuilder extends DataTypeAstBuilder
       withSchemaEvolution)
   }
 
+  protected def buildAutoCdcIntoCommand(ctx: AutoCdcCommandContext): AutoCdcIntoCommand =
+    withOrigin(ctx) {
+      val target = visitMultipartIdentifier(ctx.target).asTableIdentifier
+      val (src, keys, delete, seq, specCols, exceptCols) =
+        parseAutoCdcParams(ctx.autoCdcParameters())
+      AutoCdcIntoCommand(target, src, keys, delete, seq, specCols, exceptCols)
+    }
+
+  protected def parseAutoCdcParams(params: AutoCdcParametersContext): (
+      LogicalPlan,
+      Seq[UnresolvedAttribute],
+      Option[Expression],
+      Expression,
+      Seq[UnresolvedAttribute],
+      Seq[UnresolvedAttribute]) =
+    withOrigin(params) {
+      checkDuplicateClauses(params.autoCdcDeleteClause(), "APPLY AS DELETE", params)
+      checkDuplicateClauses(params.autoCdcSequenceByClause(), "SEQUENCE BY", params)
+      checkDuplicateClauses(params.autoCdcColumnsClause(), "COLUMNS", params)
+
+      if (params.autoCdcSequenceByClause().isEmpty) {
+        throw QueryParsingErrors.missingClausesForOperation(

Review Comment:
   The Connect path reports specific conditions for the same mistakes — `AUTOCDC_MISSING_SEQUENCE_BY`, `AUTOCDC_MISSING_SOURCE`, `AUTOCDC_BOTH_COLUMN_LIST_AND_EXCEPT_COLUMN_LIST`, `AUTOCDC_NON_COLUMN_IDENTIFIER` (see `PipelinesHandler.buildAutoCdcFlow`). Here a missing `SEQUENCE BY` raises `MISSING_CLAUSES_FOR_OPERATION` instead, so the same error surfaces a different condition depending on whether the user came via SQL or Python. Could we reuse the `AUTOCDC_*` conditions (at minimum for missing sequence-by) for consistency across front-ends?



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/parser/AstBuilder.scala:
##########
@@ -1362,6 +1362,50 @@ class AstBuilder extends DataTypeAstBuilder
       withSchemaEvolution)
   }
 
+  protected def buildAutoCdcIntoCommand(ctx: AutoCdcCommandContext): AutoCdcIntoCommand =
+    withOrigin(ctx) {
+      val target = visitMultipartIdentifier(ctx.target).asTableIdentifier
+      val (src, keys, delete, seq, specCols, exceptCols) =
+        parseAutoCdcParams(ctx.autoCdcParameters())
+      AutoCdcIntoCommand(target, src, keys, delete, seq, specCols, exceptCols)
+    }
+
+  protected def parseAutoCdcParams(params: AutoCdcParametersContext): (
+      LogicalPlan,
+      Seq[UnresolvedAttribute],
+      Option[Expression],
+      Expression,
+      Seq[UnresolvedAttribute],
+      Seq[UnresolvedAttribute]) =
+    withOrigin(params) {
+      checkDuplicateClauses(params.autoCdcDeleteClause(), "APPLY AS DELETE", params)
+      checkDuplicateClauses(params.autoCdcSequenceByClause(), "SEQUENCE BY", params)
+      checkDuplicateClauses(params.autoCdcColumnsClause(), "COLUMNS", params)
+
+      if (params.autoCdcSequenceByClause().isEmpty) {
+        throw QueryParsingErrors.missingClausesForOperation(
+          params, "SEQUENCE BY", "AUTO CDC INTO")
+      }
+
+      val sourceTable = plan(params.source.relationPrimary)

Review Comment:
   `plan(params.source.relationPrimary)` only consumes the `relationPrimary` of `source=relation`. Since `relation : LATERAL? relationPrimary relationExtension*`, any join/pivot/unpivot/`LATERAL` on the source is parsed and then silently discarded. For example, both of these parse fine but use only `source`:
   
   ```sql
   -- JOIN dropped; only `source` is read
   CREATE FLOW f AS AUTO CDC INTO target
   FROM source JOIN dim ON source.id = dim.id
   KEYS (id) SEQUENCE BY ts
   
   -- PIVOT dropped; only `source` is read
   CREATE FLOW f AS AUTO CDC INTO target
   FROM source PIVOT (sum(amt) FOR region IN ('US','EU'))
   KEYS (id) SEQUENCE BY ts
   ```
   
   Either restrict the grammar to `source=relationPrimary` so the extra syntax is a parse error, or build from the full `relation`. Also note the Connect path models the source as a streaming relation (`UnresolvedRelation(isStreaming = true)`); here it's a plain relation with no streaming marker, so resolution semantics will diverge from the Python/Connect path.



##########
sql/core/src/test/scala/org/apache/spark/sql/execution/command/v2/AutoCdcParserSuite.scala:
##########
@@ -0,0 +1,392 @@
+/*
+ * 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.execution.command.v2
+
+import org.apache.spark.sql.catalyst.analysis.{
+  AnalysisTest, UnresolvedAttribute,
+  UnresolvedIdentifier, UnresolvedRelation}
+import org.apache.spark.sql.catalyst.parser.ParseException
+import org.apache.spark.sql.catalyst.plans.logical.{
+  AutoCdcIntoCommand,
+  CreateFlowCommand,
+  CreateStreamingTableAutoCdc
+}
+import org.apache.spark.sql.execution.SparkSqlParser
+
+/**
+ * Parser tests for AUTO CDC syntax.
+ *
+ * Covers two supported forms:
+ *   1. CREATE FLOW <name> [COMMENT ...] AS AUTO CDC INTO <target> ...
+ *   2. CREATE STREAMING TABLE <name> FLOW AUTO CDC ...
+ *
+ * Snapshot CDC, SCD Type 2, IGNORE NULL UPDATES, and APPLY AS TRUNCATE WHEN are not
+ * supported and should fail to parse. The standalone AUTO CDC INTO form (without CREATE FLOW
+ * or CREATE STREAMING TABLE) is also not supported.
+ */
+class AutoCdcParserSuite extends CommandSuiteBase with AnalysisTest {
+  protected lazy val parser = new SparkSqlParser()
+
+  // ---------------------------------------------------------------------------
+  // CREATE FLOW ... AS AUTO CDC INTO
+  // ---------------------------------------------------------------------------
+
+  test("CREATE FLOW AS AUTO CDC INTO - minimal form") {
+    val plan = parser.parsePlan(
+      """CREATE FLOW myflow AS AUTO CDC INTO target
+        |FROM source
+        |KEYS (key1, key2)
+        |SEQUENCE BY timestamp""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateFlowCommand]
+    assert(cmd.name.asInstanceOf[UnresolvedIdentifier].nameParts == Seq("myflow"))
+    assert(cmd.comment.isEmpty)
+
+    val cdc = cmd.flowOperation.asInstanceOf[AutoCdcIntoCommand]
+    assert(cdc.targetTable.table == "target")
+    assert(cdc.sourceTable.isInstanceOf[UnresolvedRelation])
+    assert(cdc.keys.map(_.name) == Seq("key1", "key2"))
+    assert(cdc.deleteCondition.isEmpty)
+    assert(cdc.sequenceByExpr == UnresolvedAttribute("timestamp"))
+    assert(cdc.specifiedCols.isEmpty)
+    assert(cdc.exceptCols.isEmpty)
+  }
+
+  test("CREATE FLOW AS AUTO CDC INTO - with COMMENT") {
+    val plan = parser.parsePlan(
+      """CREATE FLOW myflow COMMENT 'my comment' AS AUTO CDC INTO target
+        |FROM source
+        |KEYS (id)
+        |SEQUENCE BY ts""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateFlowCommand]
+    assert(cmd.comment == Some("my comment"))
+  }
+
+  test("CREATE FLOW AS AUTO CDC INTO - multipart flow name") {
+    val plan = parser.parsePlan(
+      """CREATE FLOW mycat.myschema.myflow AS AUTO CDC INTO target
+        |FROM source
+        |KEYS (id)
+        |SEQUENCE BY ts""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateFlowCommand]
+    assert(cmd.name.asInstanceOf[UnresolvedIdentifier].nameParts ==
+      Seq("mycat", "myschema", "myflow"))
+  }
+
+  test("CREATE FLOW AS AUTO CDC INTO - two-part target table name") {
+    val plan = parser.parsePlan(
+      """CREATE FLOW f AS AUTO CDC INTO myschema.mytable
+        |FROM source
+        |KEYS (k)
+        |SEQUENCE BY ts""".stripMargin)
+
+    val cdc = plan.asInstanceOf[CreateFlowCommand].flowOperation.asInstanceOf[AutoCdcIntoCommand]
+    assert(cdc.targetTable.database == Some("myschema"))
+    assert(cdc.targetTable.table == "mytable")
+  }
+
+  test("CREATE FLOW AS AUTO CDC INTO - APPLY AS DELETE WHEN") {
+    val plan = parser.parsePlan(
+      """CREATE FLOW f AS AUTO CDC INTO target
+        |FROM source
+        |KEYS (id)
+        |APPLY AS DELETE WHEN op = 'DELETE'
+        |SEQUENCE BY ts""".stripMargin)
+
+    val cdc = plan.asInstanceOf[CreateFlowCommand].flowOperation.asInstanceOf[AutoCdcIntoCommand]
+    assert(cdc.deleteCondition.isDefined)
+    assert(cdc.deleteCondition.get.sql.contains("op"))
+  }
+
+  test("CREATE FLOW AS AUTO CDC INTO - COLUMNS include list") {
+    val plan = parser.parsePlan(
+      """CREATE FLOW f AS AUTO CDC INTO target
+        |FROM source
+        |KEYS (id)
+        |SEQUENCE BY ts
+        |COLUMNS id, name, value""".stripMargin)
+
+    val cdc = plan.asInstanceOf[CreateFlowCommand].flowOperation.asInstanceOf[AutoCdcIntoCommand]
+    assert(cdc.specifiedCols.map(_.name) == Seq("id", "name", "value"))
+    assert(cdc.exceptCols.isEmpty)
+  }
+
+  test("CREATE FLOW AS AUTO CDC INTO - COLUMNS * EXCEPT list") {
+    val plan = parser.parsePlan(
+      """CREATE FLOW f AS AUTO CDC INTO target
+        |FROM source
+        |KEYS (id)
+        |SEQUENCE BY ts
+        |COLUMNS * EXCEPT (op, ts)""".stripMargin)
+
+    val cdc = plan.asInstanceOf[CreateFlowCommand].flowOperation.asInstanceOf[AutoCdcIntoCommand]
+    assert(cdc.specifiedCols.isEmpty)
+    assert(cdc.exceptCols.map(_.name) == Seq("op", "ts"))
+  }
+
+  test("CREATE FLOW AS AUTO CDC INTO - all clauses combined") {
+    val plan = parser.parsePlan(
+      """CREATE FLOW f AS AUTO CDC INTO target
+        |FROM source
+        |KEYS (key1, key2)
+        |APPLY AS DELETE WHEN key3 = 3
+        |SEQUENCE BY timestamp
+        |COLUMNS key1, key2, key3, timestamp""".stripMargin)
+
+    val cdc = plan.asInstanceOf[CreateFlowCommand].flowOperation.asInstanceOf[AutoCdcIntoCommand]
+    assert(cdc.keys.map(_.name) == Seq("key1", "key2"))
+    assert(cdc.deleteCondition.isDefined)
+    assert(cdc.sequenceByExpr == UnresolvedAttribute("timestamp"))
+    assert(cdc.specifiedCols.map(_.name) == Seq("key1", "key2", "key3", "timestamp"))
+  }
+
+  // ---------------------------------------------------------------------------
+  // CREATE STREAMING TABLE ... FLOW AUTO CDC
+  // ---------------------------------------------------------------------------
+
+  test("CREATE STREAMING TABLE FLOW AUTO CDC - minimal form") {
+    val plan = parser.parsePlan(
+      """CREATE STREAMING TABLE target
+        |FLOW AUTO CDC
+        |FROM source
+        |KEYS (key1, key2)
+        |SEQUENCE BY timestamp""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateStreamingTableAutoCdc]
+    assert(cmd.name.asInstanceOf[UnresolvedIdentifier].nameParts == Seq("target"))
+    assert(!cmd.ifNotExists)
+    assert(cmd.sourceTable.isInstanceOf[UnresolvedRelation])
+    assert(cmd.keys.map(_.name) == Seq("key1", "key2"))
+    assert(cmd.deleteCondition.isEmpty)
+    assert(cmd.sequenceByExpr == UnresolvedAttribute("timestamp"))
+    assert(cmd.specifiedCols.isEmpty)
+    assert(cmd.exceptCols.isEmpty)
+  }
+
+  test("CREATE STREAMING TABLE IF NOT EXISTS FLOW AUTO CDC") {
+    val plan = parser.parsePlan(
+      """CREATE STREAMING TABLE IF NOT EXISTS target
+        |FLOW AUTO CDC
+        |FROM source
+        |KEYS (id)
+        |SEQUENCE BY ts""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateStreamingTableAutoCdc]
+    assert(cmd.ifNotExists)
+  }
+
+  test("CREATE STREAMING TABLE FLOW AUTO CDC - multipart table name") {
+    val plan = parser.parsePlan(
+      """CREATE STREAMING TABLE myschema.mytable
+        |FLOW AUTO CDC
+        |FROM source
+        |KEYS (id)
+        |SEQUENCE BY ts""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateStreamingTableAutoCdc]
+    assert(cmd.name.asInstanceOf[UnresolvedIdentifier].nameParts == Seq("myschema", "mytable"))
+  }
+
+  test("CREATE STREAMING TABLE FLOW AUTO CDC - APPLY AS DELETE WHEN") {
+    val plan = parser.parsePlan(
+      """CREATE STREAMING TABLE target
+        |FLOW AUTO CDC
+        |FROM source
+        |KEYS (id)
+        |APPLY AS DELETE WHEN op = 'DELETE'
+        |SEQUENCE BY ts""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateStreamingTableAutoCdc]
+    assert(cmd.deleteCondition.isDefined)
+    assert(cmd.deleteCondition.get.sql.contains("op"))
+  }
+
+  test("CREATE STREAMING TABLE FLOW AUTO CDC - COLUMNS include list") {
+    val plan = parser.parsePlan(
+      """CREATE STREAMING TABLE target
+        |FLOW AUTO CDC
+        |FROM source
+        |KEYS (id)
+        |SEQUENCE BY ts
+        |COLUMNS id, name, value""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateStreamingTableAutoCdc]
+    assert(cmd.specifiedCols.map(_.name) == Seq("id", "name", "value"))
+    assert(cmd.exceptCols.isEmpty)
+  }
+
+  test("CREATE STREAMING TABLE FLOW AUTO CDC - COLUMNS * EXCEPT list") {
+    val plan = parser.parsePlan(
+      """CREATE STREAMING TABLE target
+        |FLOW AUTO CDC
+        |FROM source
+        |KEYS (id)
+        |SEQUENCE BY ts
+        |COLUMNS * EXCEPT (op, ts)""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateStreamingTableAutoCdc]
+    assert(cmd.specifiedCols.isEmpty)
+    assert(cmd.exceptCols.map(_.name) == Seq("op", "ts"))
+  }
+
+  test("CREATE STREAMING TABLE FLOW AUTO CDC - all clauses combined") {

Review Comment:
   `visitCreateStreamingTableAutoCdc` rejects MATERIALIZED VIEW, bucketing, options, serde, location, and column constraints via `operationNotAllowed`, but none of those branches are covered here. Please add at least the MV-rejection case (and ideally column-constraints), since they're easy to regress silently.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/SparkSqlParser.scala:
##########
@@ -1516,6 +1516,98 @@ class SparkSqlAstBuilder extends AstBuilder {
     )
   }
 
+  override def visitCreateFlowAutoCdc(
+      ctx: CreateFlowAutoCdcContext): LogicalPlan = withOrigin(ctx) {
+    val flowHeaderCtx = ctx.createPipelineFlowHeader()
+    val ident = withIdentClause(flowHeaderCtx.flowName, UnresolvedIdentifier(_))
+    val commentOpt = Option(flowHeaderCtx.commentSpec()).map(visitCommentSpec)
+    val applyChanges = buildAutoCdcIntoCommand(ctx.autoCdcCommand())
+    CreateFlowCommand(
+      name = ident,
+      flowOperation = applyChanges,
+      comment = commentOpt
+    )
+  }
+
+  override def visitCreateStreamingTableAutoCdc(
+      ctx: CreateStreamingTableAutoCdcContext): LogicalPlan = withOrigin(ctx) {
+    val headerCtx = ctx.createPipelineDatasetHeader()
+
+    if (headerCtx.materializedView() != null) {
+      throw operationNotAllowed(
+        "AUTO CDC is only supported for STREAMING TABLE, not MATERIALIZED VIEW.", ctx)
+    }
+
+    val ifNotExists = headerCtx.EXISTS() != null
+    val provider = Option(ctx.tableProvider).map(_.multipartIdentifier.getText)
+    val (colDefs, colConstraints) = Option(ctx.tableElementList()).map(visitTableElementList)

Review Comment:
   This whole prelude — the `colConstraints` check, the `visitCreateTableClauses` destructure, the `partitioning` computation, the `bucketSpec`/`options`/`serde`/`location` guards, and the `TableSpec(...)` block — is duplicated almost verbatim from `visitCreatePipelineDataset` below. Suggest extracting a shared private helper (e.g. returning `(colDefs, partitioning, spec, ifNotExists, tableIdent)`) and calling it from both, so they can't drift.
   
   Note the copy also quietly shortened the error messages (e.g. dropping the "Please remove any CHECK, UNIQUE, PK, and FK constraints..." guidance, and collapsing the `STORED AS` vs Hive-SerDe distinction). Factoring out the helper would keep these consistent with the existing `CREATE STREAMING TABLE` messages.



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [CONNECT][SDP][SPARK-56249] Create AUTO CDC syntax for SCD Type 1 in SQL [spark]

Posted by "anew (via GitHub)" <gi...@apache.org>.
anew commented on code in PR #56419:
URL: https://github.com/apache/spark/pull/56419#discussion_r3484609531


##########
common/utils/src/main/resources/error/error-conditions.json:
##########
@@ -5529,6 +5529,12 @@
     },
     "sqlState" : "0A000"
   },
+  "MISSING_CLAUSES_FOR_OPERATION" : {

Review Comment:
   Addressed in this PR: https://github.com/apache/spark/pull/56827



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [CONNECT][SDP][SPARK-56249] Create AUTO CDC syntax for SCD Type 1 in SQL [spark]

Posted by "szehon-ho (via GitHub)" <gi...@apache.org>.
szehon-ho closed pull request #56419: [CONNECT][SDP][SPARK-56249] Create AUTO CDC syntax for SCD Type 1 in SQL
URL: https://github.com/apache/spark/pull/56419


-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [CONNECT][SDP][SPARK-56249] Create AUTO CDC syntax for SCD Type 1 in SQL [spark]

Posted by "szehon-ho (via GitHub)" <gi...@apache.org>.
szehon-ho commented on code in PR #56419:
URL: https://github.com/apache/spark/pull/56419#discussion_r3509168244


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/SparkSqlParser.scala:
##########
@@ -1646,6 +1659,10 @@ class SparkSqlAstBuilder extends AstBuilder {
     )
 
     if (createPipelineDatasetHeaderCtx.materializedView() != null) {
+      if (ctx.autoCdcBody() != null) {
+        throw operationNotAllowed(

Review Comment:
   Should this new user-facing message go through a proper named error condition instead of `operationNotAllowed` (which maps to `_LEGACY_ERROR_TEMP_0035`)? We're generally trying to move away from `_LEGACY_ERROR_TEMP_*` for new errors. That said, it's consistent with the neighboring pipeline-dataset guards below, so I'm fine leaving it if you'd rather keep them uniform for now -- just raising the question.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/parser/AstBuilder.scala:
##########
@@ -7710,3 +7762,14 @@ class AstBuilder extends DataTypeAstBuilder
     }
   }
 }
+
+/**
+ * Parameters parsed from an AUTO CDC clause.
+ */
+case class AutoCdcParams(
+    source: LogicalPlan,

Review Comment:
   `resolveAutoCdcSource` always returns an `UnresolvedRelation` (and the tests assert that), so could `AutoCdcParams.source` be typed as `UnresolvedRelation` to document that invariant? (The `source` on `AutoCdcIntoCommand` / `CreateStreamingTableAutoCdc` needs to stay `LogicalPlan` since it's a resolvable plan child, but this transient parser carrier isn't a child.) Or is the wider `LogicalPlan` type intentional to leave room for other source shapes later?



##########
sql/core/src/test/scala/org/apache/spark/sql/execution/command/v2/AutoCdcParserSuite.scala:
##########
@@ -0,0 +1,659 @@
+/*
+ * 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.execution.command.v2
+
+import org.apache.spark.sql.catalyst.analysis.{
+  AnalysisTest, UnresolvedAttribute, UnresolvedIdentifier, UnresolvedRelation}
+import org.apache.spark.sql.catalyst.parser.ParseException
+import org.apache.spark.sql.catalyst.plans.logical.{
+  AutoCdcIntoCommand,
+  CreateFlowCommand,
+  CreateStreamingTableAutoCdc
+}
+import org.apache.spark.sql.execution.SparkSqlParser
+
+/**
+ * Parser tests for AUTO CDC syntax.
+ *
+ * Covers two supported forms:
+ *   1. CREATE FLOW <name> [COMMENT ...] AS AUTO CDC INTO <target> ...
+ *   2. CREATE STREAMING TABLE <name> FLOW AUTO CDC ...
+ *
+ * Snapshot CDC, SCD Type 2, IGNORE NULL UPDATES, and APPLY AS TRUNCATE WHEN are not
+ * supported and should fail to parse. The standalone AUTO CDC INTO form (without CREATE FLOW
+ * or CREATE STREAMING TABLE) is also not supported.
+ */
+class AutoCdcParserSuite extends CommandSuiteBase with AnalysisTest {
+  protected lazy val parser = new SparkSqlParser()
+
+  // ---------------------------------------------------------------------------
+  // CREATE FLOW ... AS AUTO CDC INTO
+  // ---------------------------------------------------------------------------
+
+  test("CREATE FLOW AS AUTO CDC INTO - minimal form") {
+    val plan = parser.parsePlan(
+      """CREATE FLOW myflow AS AUTO CDC INTO target
+        |FROM STREAM(source)
+        |KEYS (key1, key2)
+        |SEQUENCE BY timestamp""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateFlowCommand]
+    assert(cmd.name.asInstanceOf[UnresolvedIdentifier].nameParts == Seq("myflow"))
+    assert(cmd.comment.isEmpty)
+
+    val cdc = cmd.flowOperation.asInstanceOf[AutoCdcIntoCommand]
+    assert(cdc.targetTable.asInstanceOf[UnresolvedIdentifier].nameParts == Seq("target"))
+    val source = cdc.source.asInstanceOf[UnresolvedRelation]
+    assert(source.multipartIdentifier == Seq("source"))
+    assert(source.isStreaming)
+    assert(cdc.keys.map(_.name) == Seq("key1", "key2"))
+    assert(cdc.deleteCondition.isEmpty)
+    assert(cdc.sequenceByExpr == UnresolvedAttribute("timestamp"))
+    assert(cdc.includeColumns.isEmpty)
+    assert(cdc.excludeColumns.isEmpty)
+  }
+
+  test("CREATE FLOW AS AUTO CDC INTO - multipart source name") {
+    val plan = parser.parsePlan(
+      """CREATE FLOW myflow AS AUTO CDC INTO target
+        |FROM STREAM(mycat.myschema.source)
+        |KEYS (id)
+        |SEQUENCE BY ts""".stripMargin)
+
+    val cdc = plan.asInstanceOf[CreateFlowCommand].flowOperation.asInstanceOf[AutoCdcIntoCommand]
+    val source = cdc.source.asInstanceOf[UnresolvedRelation]
+    assert(source.multipartIdentifier == Seq("mycat", "myschema", "source"))
+    assert(source.isStreaming)
+  }
+
+  test("CREATE FLOW AS AUTO CDC INTO - with COMMENT") {
+    val plan = parser.parsePlan(
+      """CREATE FLOW myflow COMMENT 'my comment' AS AUTO CDC INTO target
+        |FROM STREAM(source)
+        |KEYS (id)
+        |SEQUENCE BY ts""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateFlowCommand]
+    assert(cmd.comment == Some("my comment"))
+  }
+
+  test("CREATE FLOW AS AUTO CDC INTO - multipart flow name") {
+    val plan = parser.parsePlan(
+      """CREATE FLOW mycat.myschema.myflow AS AUTO CDC INTO target
+        |FROM STREAM(source)
+        |KEYS (id)
+        |SEQUENCE BY ts""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateFlowCommand]
+    assert(cmd.name.asInstanceOf[UnresolvedIdentifier].nameParts ==
+      Seq("mycat", "myschema", "myflow"))
+  }
+
+  test("CREATE FLOW AS AUTO CDC INTO - two-part target table name") {
+    val plan = parser.parsePlan(
+      """CREATE FLOW f AS AUTO CDC INTO myschema.mytable
+        |FROM STREAM(source)
+        |KEYS (k)
+        |SEQUENCE BY ts""".stripMargin)
+
+    val cdc = plan.asInstanceOf[CreateFlowCommand].flowOperation.asInstanceOf[AutoCdcIntoCommand]
+    assert(cdc.targetTable.asInstanceOf[UnresolvedIdentifier].nameParts ==
+      Seq("myschema", "mytable"))
+  }
+
+  test("CREATE FLOW AS AUTO CDC INTO - three-part target table name") {
+    val plan = parser.parsePlan(
+      """CREATE FLOW f AS AUTO CDC INTO mycat.myschema.mytable
+        |FROM STREAM(source)
+        |KEYS (k)
+        |SEQUENCE BY ts""".stripMargin)
+
+    val cdc = plan.asInstanceOf[CreateFlowCommand].flowOperation.asInstanceOf[AutoCdcIntoCommand]
+    assert(cdc.targetTable.asInstanceOf[UnresolvedIdentifier].nameParts ==
+      Seq("mycat", "myschema", "mytable"))
+  }
+
+  test("CREATE FLOW AS AUTO CDC INTO - APPLY AS DELETE WHEN") {
+    val plan = parser.parsePlan(
+      """CREATE FLOW f AS AUTO CDC INTO target
+        |FROM STREAM(source)
+        |KEYS (id)
+        |APPLY AS DELETE WHEN op = 'DELETE'
+        |SEQUENCE BY ts""".stripMargin)
+
+    val cdc = plan.asInstanceOf[CreateFlowCommand].flowOperation.asInstanceOf[AutoCdcIntoCommand]
+    assert(cdc.deleteCondition.isDefined)
+    assert(cdc.deleteCondition.get.sql.contains("op"))
+  }
+
+  test("CREATE FLOW AS AUTO CDC INTO - COLUMNS include list") {
+    val plan = parser.parsePlan(
+      """CREATE FLOW f AS AUTO CDC INTO target
+        |FROM STREAM(source)
+        |KEYS (id)
+        |SEQUENCE BY ts
+        |COLUMNS (id, name, value)""".stripMargin)
+
+    val cdc = plan.asInstanceOf[CreateFlowCommand].flowOperation.asInstanceOf[AutoCdcIntoCommand]
+    assert(cdc.includeColumns.get.map(_.name) == Seq("id", "name", "value"))
+    assert(cdc.excludeColumns.isEmpty)
+  }
+
+  test("CREATE FLOW AS AUTO CDC INTO - COLUMNS * EXCEPT list") {
+    val plan = parser.parsePlan(
+      """CREATE FLOW f AS AUTO CDC INTO target
+        |FROM STREAM(source)
+        |KEYS (id)
+        |SEQUENCE BY ts
+        |COLUMNS * EXCEPT (op, ts)""".stripMargin)
+
+    val cdc = plan.asInstanceOf[CreateFlowCommand].flowOperation.asInstanceOf[AutoCdcIntoCommand]
+    assert(cdc.includeColumns.isEmpty)
+    assert(cdc.excludeColumns.get.map(_.name) == Seq("op", "ts"))
+  }
+
+  test("CREATE FLOW AS AUTO CDC INTO - all clauses combined") {
+    val plan = parser.parsePlan(
+      """CREATE FLOW f AS AUTO CDC INTO target
+        |FROM STREAM(source)
+        |KEYS (key1, key2)
+        |APPLY AS DELETE WHEN key3 = 3
+        |SEQUENCE BY timestamp
+        |COLUMNS (key1, key2, key3, timestamp)""".stripMargin)
+
+    val cdc = plan.asInstanceOf[CreateFlowCommand].flowOperation.asInstanceOf[AutoCdcIntoCommand]
+    assert(cdc.keys.map(_.name) == Seq("key1", "key2"))
+    assert(cdc.deleteCondition.isDefined)
+    assert(cdc.sequenceByExpr == UnresolvedAttribute("timestamp"))
+    assert(cdc.includeColumns.get.map(_.name) == Seq("key1", "key2", "key3", "timestamp"))
+  }
+
+  // ---------------------------------------------------------------------------
+  // CREATE STREAMING TABLE ... FLOW AUTO CDC
+  // ---------------------------------------------------------------------------
+
+  test("CREATE STREAMING TABLE FLOW AUTO CDC - minimal form") {
+    val plan = parser.parsePlan(
+      """CREATE STREAMING TABLE target
+        |FLOW AUTO CDC
+        |FROM STREAM(source)
+        |KEYS (key1, key2)
+        |SEQUENCE BY timestamp""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateStreamingTableAutoCdc]
+    assert(cmd.name.asInstanceOf[UnresolvedIdentifier].nameParts == Seq("target"))
+    assert(!cmd.ifNotExists)
+    val source = cmd.source.asInstanceOf[UnresolvedRelation]
+    assert(source.multipartIdentifier == Seq("source"))
+    assert(source.isStreaming)
+    assert(cmd.keys.map(_.name) == Seq("key1", "key2"))
+    assert(cmd.deleteCondition.isEmpty)
+    assert(cmd.sequenceByExpr == UnresolvedAttribute("timestamp"))
+    assert(cmd.includeColumns.isEmpty)
+    assert(cmd.excludeColumns.isEmpty)
+  }
+
+  test("CREATE STREAMING TABLE FLOW AUTO CDC - multipart source name") {
+    val plan = parser.parsePlan(
+      """CREATE STREAMING TABLE target
+        |FLOW AUTO CDC
+        |FROM STREAM(mycat.myschema.source)
+        |KEYS (id)
+        |SEQUENCE BY ts""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateStreamingTableAutoCdc]
+    val source = cmd.source.asInstanceOf[UnresolvedRelation]
+    assert(source.multipartIdentifier == Seq("mycat", "myschema", "source"))
+    assert(source.isStreaming)
+  }
+
+  test("CREATE STREAMING TABLE IF NOT EXISTS FLOW AUTO CDC") {
+    val plan = parser.parsePlan(
+      """CREATE STREAMING TABLE IF NOT EXISTS target
+        |FLOW AUTO CDC
+        |FROM STREAM(source)
+        |KEYS (id)
+        |SEQUENCE BY ts""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateStreamingTableAutoCdc]
+    assert(cmd.ifNotExists)
+  }
+
+  test("CREATE STREAMING TABLE FLOW AUTO CDC - multipart table name") {
+    val plan = parser.parsePlan(
+      """CREATE STREAMING TABLE myschema.mytable
+        |FLOW AUTO CDC
+        |FROM STREAM(source)
+        |KEYS (id)
+        |SEQUENCE BY ts""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateStreamingTableAutoCdc]
+    assert(cmd.name.asInstanceOf[UnresolvedIdentifier].nameParts == Seq("myschema", "mytable"))
+  }
+
+  test("CREATE STREAMING TABLE FLOW AUTO CDC - APPLY AS DELETE WHEN") {
+    val plan = parser.parsePlan(
+      """CREATE STREAMING TABLE target
+        |FLOW AUTO CDC
+        |FROM STREAM(source)
+        |KEYS (id)
+        |APPLY AS DELETE WHEN op = 'DELETE'
+        |SEQUENCE BY ts""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateStreamingTableAutoCdc]
+    assert(cmd.deleteCondition.isDefined)
+    assert(cmd.deleteCondition.get.sql.contains("op"))
+  }
+
+  test("CREATE STREAMING TABLE FLOW AUTO CDC - COLUMNS include list") {
+    val plan = parser.parsePlan(
+      """CREATE STREAMING TABLE target
+        |FLOW AUTO CDC
+        |FROM STREAM(source)
+        |KEYS (id)
+        |SEQUENCE BY ts
+        |COLUMNS (id, name, value)""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateStreamingTableAutoCdc]
+    assert(cmd.includeColumns.get.map(_.name) == Seq("id", "name", "value"))
+    assert(cmd.excludeColumns.isEmpty)
+  }
+
+  test("CREATE STREAMING TABLE FLOW AUTO CDC - COLUMNS * EXCEPT list") {
+    val plan = parser.parsePlan(
+      """CREATE STREAMING TABLE target
+        |FLOW AUTO CDC
+        |FROM STREAM(source)
+        |KEYS (id)
+        |SEQUENCE BY ts
+        |COLUMNS * EXCEPT (op, ts)""".stripMargin)
+
+    val cmd = plan.asInstanceOf[CreateStreamingTableAutoCdc]
+    assert(cmd.includeColumns.isEmpty)
+    assert(cmd.excludeColumns.get.map(_.name) == Seq("op", "ts"))
+  }
+
+  test("CREATE STREAMING TABLE FLOW AUTO CDC - all clauses combined") {

Review Comment:
   Nice coverage of the AUTO CDC clauses here. `CreateStreamingTableAutoCdc` also carries `partitioning`, `tableSpec`, and `columns`, but I don't see a positive test exercising `PARTITIONED BY` / `COMMENT` / `TBLPROPERTIES` flowing through on the AUTO CDC streaming-table form. Could we add one so those pass-through fields don't regress silently?



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org