You are viewing a plain text version of this content. The canonical link for it is here.
Posted to reviews@spark.apache.org by "cloud-fan (via GitHub)" <gi...@apache.org> on 2024/01/29 15:51:28 UTC

[PR] [SPARK-46849][SQL][FOLLOWUP] Add dedicated class to keep column definition instead of StructField in Create/ReplaceTable command [spark]

cloud-fan opened a new pull request, #44935:
URL: https://github.com/apache/spark/pull/44935

   
   <!--
   Thanks for sending a pull request!  Here are some tips for you:
     1. If this is your first time, please read our contributor guidelines: https://spark.apache.org/contributing.html
     2. Ensure you have added or run the appropriate tests for your PR: https://spark.apache.org/developer-tools.html
     3. If the PR is unfinished, add '[WIP]' in your PR title, e.g., '[WIP][SPARK-XXXX] Your PR title ...'.
     4. Be sure to keep the PR description updated to reflect all changes.
     5. Please write your PR title to summarize what this PR proposes.
     6. If possible, provide a concise example to reproduce the issue for a faster review.
     7. If you want to add a new configuration, please read the guideline first for naming configurations in
        'core/src/main/scala/org/apache/spark/internal/config/ConfigEntry.scala'.
     8. If you want to add or modify an error type or message, please read the guideline first in
        'common/utils/src/main/resources/error/README.md'.
   -->
   
   ### What changes were proposed in this pull request?
   <!--
   Please clarify what changes you are proposing. The purpose of this section is to outline the changes and how this PR fixes the issue. 
   If possible, please consider writing useful notes for better and faster reviews in your PR. See the examples below.
     1. If you refactor some codes with changing classes, showing the class hierarchy will help reviewers.
     2. If you fix some SQL features, you can provide some references of other DBMSes.
     3. If there is design documentation, please add the link.
     4. If there is a discussion in the mailing list, please add the link.
   -->
   This is a follow-up of https://github.com/apache/spark/pull/44876 to refactor the code and make it cleaner. The idea is to add a dedicated class for column definition instead of `StructField` in Create/ReplaceTable command. This is more flexible and cleaner than adding an additional default column expression in `CreateTable` command.
   
   ### Why are the changes needed?
   <!--
   Please clarify why the changes are needed. For instance,
     1. If you propose a new API, clarify the use case for a new API.
     2. If you fix a bug, you can clarify why it is a bug.
   -->
   Code refactor, and makes it easier to fully eliminate the need of a fake analyzer for default value handling in the future.
   
   ### Does this PR introduce _any_ user-facing change?
   <!--
   Note that it means *any* user-facing change including all aspects such as the documentation fix.
   If yes, please clarify the previous behavior and the change this PR proposes - provide the console output, description and/or an example to show the behavior difference if possible.
   If possible, please also clarify if this is a user-facing change compared to the released Spark versions or within the unreleased branches such as master.
   If no, write 'No'.
   -->
   no
   
   ### How was this patch tested?
   <!--
   If tests were added, say they were added here. Please make sure to add some test cases that check the changes thoroughly including negative and positive cases if possible.
   If it was tested in a way different from regular unit tests, please clarify how you tested step by step, ideally copy and paste-able, so that other reviewers can test and check, and descendants can verify in the future.
   If tests were not added, please describe why they were not added and/or why it was difficult to add.
   If benchmark tests were added, please run the benchmarks in GitHub Actions for the consistent environment, and the instructions could accord to: https://spark.apache.org/developer-tools.html#github-workflow-benchmarks.
   -->
   existing tests
   
   ### Was this patch authored or co-authored using generative AI tooling?
   <!--
   If generative AI tooling has been used in the process of authoring this patch, please include the
   phrase: 'Generated-by: ' followed by the name of the tool and its version.
   If no, write 'No'.
   Please refer to the [ASF Generative Tooling Guidance](https://www.apache.org/legal/generative-tooling.html) for details.
   -->
   no


-- 
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] [SPARK-46905][SQL] Add dedicated class to keep column definition instead of StructField in Create/ReplaceTable command [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on PR #44935:
URL: https://github.com/apache/spark/pull/44935#issuecomment-1916197588

   thanks for the review, merging to master!


-- 
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] [SPARK-46905][SQL] Add dedicated class to keep column definition instead of StructField in Create/ReplaceTable command [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan closed pull request #44935: [SPARK-46905][SQL] Add dedicated class to keep column definition instead of StructField in Create/ReplaceTable command
URL: https://github.com/apache/spark/pull/44935


-- 
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] [SPARK-46849][SQL][FOLLOWUP] Add dedicated class to keep column definition instead of StructField in Create/ReplaceTable command [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on code in PR #44935:
URL: https://github.com/apache/spark/pull/44935#discussion_r1469828631


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/parser/AstBuilder.scala:
##########
@@ -3150,61 +3151,44 @@ class AstBuilder extends DataTypeAstBuilder with SQLConfHelper with Logging {
       if (option.NULL != null) {
         if (!nullable) {
           throw QueryParsingErrors.duplicateTableColumnDescriptor(
-            option, colName.getText, "NOT NULL")
+            option, name, "NOT NULL")
         }
         nullable = false
       }
       Option(option.defaultExpression()).foreach { expr =>
+        if (!conf.getConf(SQLConf.ENABLE_DEFAULT_COLUMNS)) {
+          throw QueryParsingErrors.defaultColumnNotEnabledError(ctx)
+        }
         if (defaultExpression.isDefined) {
           throw QueryParsingErrors.duplicateTableColumnDescriptor(
-            option, colName.getText, "DEFAULT")
+            option, name, "DEFAULT")
         }
         defaultExpression = Some(expr)
       }
       Option(option.generationExpression()).foreach { expr =>
         if (generationExpression.isDefined) {
           throw QueryParsingErrors.duplicateTableColumnDescriptor(
-            option, colName.getText, "GENERATED ALWAYS AS")
+            option, name, "GENERATED ALWAYS AS")
         }
         generationExpression = Some(expr)
       }
       Option(option.commentSpec()).foreach { spec =>
         if (commentSpec.isDefined) {
           throw QueryParsingErrors.duplicateTableColumnDescriptor(
-            option, colName.getText, "COMMENT")
+            option, name, "COMMENT")
         }
         commentSpec = Some(spec)
       }
     }
 
-    val builder = new MetadataBuilder
-    // Add comment to metadata
-    commentSpec.map(visitCommentSpec).foreach {
-      builder.putString("comment", _)
-    }
-    // Add the 'DEFAULT expression' clause in the column definition, if any, to the column metadata.
-    defaultExpression.map(visitDefaultExpression).foreach { field =>
-      if (conf.getConf(SQLConf.ENABLE_DEFAULT_COLUMNS)) {
-        // Add default to metadata
-        builder.putString(ResolveDefaultColumns.CURRENT_DEFAULT_COLUMN_METADATA_KEY, field)
-        builder.putString(ResolveDefaultColumns.EXISTS_DEFAULT_COLUMN_METADATA_KEY, field)

Review Comment:
   The code is moved to `ColumnDefinition#toV1Column`. We only need to encode the default value in `StructField` when running with v1 command.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/parser/AstBuilder.scala:
##########
@@ -3150,61 +3151,44 @@ class AstBuilder extends DataTypeAstBuilder with SQLConfHelper with Logging {
       if (option.NULL != null) {
         if (!nullable) {
           throw QueryParsingErrors.duplicateTableColumnDescriptor(
-            option, colName.getText, "NOT NULL")
+            option, name, "NOT NULL")
         }
         nullable = false
       }
       Option(option.defaultExpression()).foreach { expr =>
+        if (!conf.getConf(SQLConf.ENABLE_DEFAULT_COLUMNS)) {
+          throw QueryParsingErrors.defaultColumnNotEnabledError(ctx)
+        }
         if (defaultExpression.isDefined) {
           throw QueryParsingErrors.duplicateTableColumnDescriptor(
-            option, colName.getText, "DEFAULT")
+            option, name, "DEFAULT")
         }
         defaultExpression = Some(expr)
       }
       Option(option.generationExpression()).foreach { expr =>
         if (generationExpression.isDefined) {
           throw QueryParsingErrors.duplicateTableColumnDescriptor(
-            option, colName.getText, "GENERATED ALWAYS AS")
+            option, name, "GENERATED ALWAYS AS")
         }
         generationExpression = Some(expr)
       }
       Option(option.commentSpec()).foreach { spec =>
         if (commentSpec.isDefined) {
           throw QueryParsingErrors.duplicateTableColumnDescriptor(
-            option, colName.getText, "COMMENT")
+            option, name, "COMMENT")
         }
         commentSpec = Some(spec)
       }
     }
 
-    val builder = new MetadataBuilder
-    // Add comment to metadata
-    commentSpec.map(visitCommentSpec).foreach {
-      builder.putString("comment", _)
-    }
-    // Add the 'DEFAULT expression' clause in the column definition, if any, to the column metadata.
-    defaultExpression.map(visitDefaultExpression).foreach { field =>
-      if (conf.getConf(SQLConf.ENABLE_DEFAULT_COLUMNS)) {
-        // Add default to metadata
-        builder.putString(ResolveDefaultColumns.CURRENT_DEFAULT_COLUMN_METADATA_KEY, field)
-        builder.putString(ResolveDefaultColumns.EXISTS_DEFAULT_COLUMN_METADATA_KEY, field)
-      } else {
-        throw QueryParsingErrors.defaultColumnNotEnabledError(ctx)
-      }
-    }
-    // Add the 'GENERATED ALWAYS AS expression' clause in the column definition, if any, to the
-    // column metadata.
-    generationExpression.map(visitGenerationExpression).foreach { field =>
-      builder.putString(GeneratedColumn.GENERATION_EXPRESSION_METADATA_KEY, field)

Review Comment:
   ditto



-- 
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] [SPARK-46905][SQL] Add dedicated class to keep column definition instead of StructField in Create/ReplaceTable command [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on code in PR #44935:
URL: https://github.com/apache/spark/pull/44935#discussion_r1470433840


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/ColumnDefinition.scala:
##########
@@ -0,0 +1,124 @@
+/*
+ * 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.expressions.{Expression, Literal, UnaryExpression, Unevaluable}
+import org.apache.spark.sql.catalyst.parser.ParserInterface
+import org.apache.spark.sql.catalyst.util.GeneratedColumn
+import org.apache.spark.sql.catalyst.util.ResolveDefaultColumnsUtils.{CURRENT_DEFAULT_COLUMN_METADATA_KEY, EXISTS_DEFAULT_COLUMN_METADATA_KEY}
+import org.apache.spark.sql.connector.catalog.{Column => V2Column, ColumnDefaultValue}
+import org.apache.spark.sql.connector.expressions.LiteralValue
+import org.apache.spark.sql.errors.QueryCompilationErrors
+import org.apache.spark.sql.internal.connector.ColumnImpl
+import org.apache.spark.sql.types.{DataType, Metadata, MetadataBuilder, StructField}
+
+/**
+ * Column definition for tables. This is an expression so that analyzer can resolve the default
+ * value expression in DDL commands automatically.
+ */
+case class ColumnDefinition(
+    name: String,
+    dataType: DataType,
+    nullable: Boolean = true,
+    comment: Option[String] = None,
+    defaultValue: Option[DefaultValueExpression] = None,
+    generationExpression: Option[String] = None,
+    metadata: Metadata = Metadata.empty) extends Expression with Unevaluable {
+  override def children: Seq[Expression] = defaultValue.toSeq
+
+  override protected def withNewChildrenInternal(
+      newChildren: IndexedSeq[Expression]): Expression = {
+    copy(defaultValue = newChildren.headOption.map(_.asInstanceOf[DefaultValueExpression]))
+  }
+
+  def toV2Column(statement: String): V2Column = {
+    ColumnImpl(
+      name,
+      dataType,
+      nullable,
+      comment.orNull,
+      defaultValue.map(_.toV2(statement, name)).orNull,
+      generationExpression.orNull,
+      if (metadata == Metadata.empty) null else metadata.json)
+  }
+
+  def toV1Column: StructField = {
+    val metadataBuilder = new MetadataBuilder().withMetadata(metadata)
+    comment.foreach { c =>
+      metadataBuilder.putString("comment", c)
+    }
+    defaultValue.foreach { default =>
+      // For v1 CREATE TABLE command, we will resolve and execute the default value expression later
+      // in the rule `DataSourceAnalysis`. We just need to put the default value SQL string here.

Review Comment:
   Actually I can't recall it now... The existing code did not have comments: https://github.com/apache/spark/pull/44935/files#diff-26fe6b511f4b8aedf5bdffae0d7c03aba69463c09fa4f881d77520125796e0faL3188



-- 
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] [SPARK-46905][SQL] Add dedicated class to keep column definition instead of StructField in Create/ReplaceTable command [spark]

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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/ColumnDefinition.scala:
##########
@@ -0,0 +1,124 @@
+/*
+ * 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.expressions.{Expression, Literal, UnaryExpression, Unevaluable}
+import org.apache.spark.sql.catalyst.parser.ParserInterface
+import org.apache.spark.sql.catalyst.util.GeneratedColumn
+import org.apache.spark.sql.catalyst.util.ResolveDefaultColumnsUtils.{CURRENT_DEFAULT_COLUMN_METADATA_KEY, EXISTS_DEFAULT_COLUMN_METADATA_KEY}
+import org.apache.spark.sql.connector.catalog.{Column => V2Column, ColumnDefaultValue}
+import org.apache.spark.sql.connector.expressions.LiteralValue
+import org.apache.spark.sql.errors.QueryCompilationErrors
+import org.apache.spark.sql.internal.connector.ColumnImpl
+import org.apache.spark.sql.types.{DataType, Metadata, MetadataBuilder, StructField}
+
+/**
+ * Column definition for tables. This is an expression so that analyzer can resolve the default
+ * value expression in DDL commands automatically.
+ */
+case class ColumnDefinition(
+    name: String,
+    dataType: DataType,
+    nullable: Boolean = true,
+    comment: Option[String] = None,
+    defaultValue: Option[DefaultValueExpression] = None,
+    generationExpression: Option[String] = None,
+    metadata: Metadata = Metadata.empty) extends Expression with Unevaluable {
+  override def children: Seq[Expression] = defaultValue.toSeq
+
+  override protected def withNewChildrenInternal(
+      newChildren: IndexedSeq[Expression]): Expression = {
+    copy(defaultValue = newChildren.headOption.map(_.asInstanceOf[DefaultValueExpression]))
+  }
+
+  def toV2Column(statement: String): V2Column = {
+    ColumnImpl(
+      name,
+      dataType,
+      nullable,
+      comment.orNull,
+      defaultValue.map(_.toV2(statement, name)).orNull,
+      generationExpression.orNull,
+      if (metadata == Metadata.empty) null else metadata.json)
+  }
+
+  def toV1Column: StructField = {
+    val metadataBuilder = new MetadataBuilder().withMetadata(metadata)
+    comment.foreach { c =>
+      metadataBuilder.putString("comment", c)
+    }
+    defaultValue.foreach { default =>
+      // For v1 CREATE TABLE command, we will resolve and execute the default value expression later
+      // in the rule `DataSourceAnalysis`. We just need to put the default value SQL string here.

Review Comment:
   Oh this is just moving the code from its previous location :) nevermind then.



-- 
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] [SPARK-46905][SQL] Add dedicated class to keep column definition instead of StructField in Create/ReplaceTable command [spark]

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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/ColumnDefinition.scala:
##########
@@ -0,0 +1,124 @@
+/*
+ * 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.expressions.{Expression, Literal, UnaryExpression, Unevaluable}
+import org.apache.spark.sql.catalyst.parser.ParserInterface
+import org.apache.spark.sql.catalyst.util.GeneratedColumn
+import org.apache.spark.sql.catalyst.util.ResolveDefaultColumnsUtils.{CURRENT_DEFAULT_COLUMN_METADATA_KEY, EXISTS_DEFAULT_COLUMN_METADATA_KEY}
+import org.apache.spark.sql.connector.catalog.{Column => V2Column, ColumnDefaultValue}
+import org.apache.spark.sql.connector.expressions.LiteralValue
+import org.apache.spark.sql.errors.QueryCompilationErrors
+import org.apache.spark.sql.internal.connector.ColumnImpl
+import org.apache.spark.sql.types.{DataType, Metadata, MetadataBuilder, StructField}
+
+/**
+ * Column definition for tables. This is an expression so that analyzer can resolve the default
+ * value expression in DDL commands automatically.
+ */
+case class ColumnDefinition(
+    name: String,
+    dataType: DataType,
+    nullable: Boolean = true,
+    comment: Option[String] = None,
+    defaultValue: Option[DefaultValueExpression] = None,

Review Comment:
   👍 missed that, looks like we are OK then.



-- 
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] [SPARK-46849][SQL][FOLLOWUP] Add dedicated class to keep column definition instead of StructField in Create/ReplaceTable command [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on PR #44935:
URL: https://github.com/apache/spark/pull/44935#issuecomment-1915064190

   cc @dtenedor @dongjoon-hyun 


-- 
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] [SPARK-46905][SQL] Add dedicated class to keep column definition instead of StructField in Create/ReplaceTable command [spark]

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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/ColumnDefinition.scala:
##########
@@ -0,0 +1,124 @@
+/*
+ * 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.expressions.{Expression, Literal, UnaryExpression, Unevaluable}
+import org.apache.spark.sql.catalyst.parser.ParserInterface
+import org.apache.spark.sql.catalyst.util.GeneratedColumn
+import org.apache.spark.sql.catalyst.util.ResolveDefaultColumnsUtils.{CURRENT_DEFAULT_COLUMN_METADATA_KEY, EXISTS_DEFAULT_COLUMN_METADATA_KEY}
+import org.apache.spark.sql.connector.catalog.{Column => V2Column, ColumnDefaultValue}
+import org.apache.spark.sql.connector.expressions.LiteralValue
+import org.apache.spark.sql.errors.QueryCompilationErrors
+import org.apache.spark.sql.internal.connector.ColumnImpl
+import org.apache.spark.sql.types.{DataType, Metadata, MetadataBuilder, StructField}
+
+/**
+ * Column definition for tables. This is an expression so that analyzer can resolve the default
+ * value expression in DDL commands automatically.
+ */
+case class ColumnDefinition(
+    name: String,
+    dataType: DataType,
+    nullable: Boolean = true,
+    comment: Option[String] = None,
+    defaultValue: Option[DefaultValueExpression] = None,
+    generationExpression: Option[String] = None,
+    metadata: Metadata = Metadata.empty) extends Expression with Unevaluable {
+  override def children: Seq[Expression] = defaultValue.toSeq
+
+  override protected def withNewChildrenInternal(
+      newChildren: IndexedSeq[Expression]): Expression = {
+    copy(defaultValue = newChildren.headOption.map(_.asInstanceOf[DefaultValueExpression]))
+  }
+
+  def toV2Column(statement: String): V2Column = {
+    ColumnImpl(
+      name,
+      dataType,
+      nullable,
+      comment.orNull,
+      defaultValue.map(_.toV2(statement, name)).orNull,
+      generationExpression.orNull,
+      if (metadata == Metadata.empty) null else metadata.json)
+  }
+
+  def toV1Column: StructField = {
+    val metadataBuilder = new MetadataBuilder().withMetadata(metadata)
+    comment.foreach { c =>
+      metadataBuilder.putString("comment", c)
+    }
+    defaultValue.foreach { default =>
+      // For v1 CREATE TABLE command, we will resolve and execute the default value expression later
+      // in the rule `DataSourceAnalysis`. We just need to put the default value SQL string here.

Review Comment:
   please briefly mention why we need to set both the "current default value" and "existence default value" column metadata here?



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/ResolveDefaultColumnsUtil.scala:
##########
@@ -445,6 +444,54 @@ object ResolveDefaultColumns extends QueryErrorsBase with ResolveDefaultColumnsU
   def hasExistenceDefaultValues(schema: StructType): Boolean =
     existenceDefaultValues(schema).exists(_ != null)
 
+
+  def checkColumnDefaultValues(plan: LogicalPlan): Unit = {
+    plan match {
+      // Do not check anything if the children are not resolved yet.
+      case _ if !plan.childrenResolved =>
+
+      case cmd: V2CreateTablePlan if cmd.columns.exists(_.defaultValue.isDefined) =>
+        val statement = cmd match {
+          case _: CreateTable => "CREATE TABLE"
+          case _: ReplaceTable => "REPLACE TABLE"
+          case other =>
+            val cmd = other.getClass.getSimpleName
+            throw SparkException.internalError(
+              s"Command $cmd should not have column default value expression.")
+        }
+        cmd.columns.foreach { col =>
+          col.defaultValue.foreach { default =>
+            validateDefaultValueExpr(default, statement, col.name, col.dataType)
+          }
+        }
+
+      case _ =>
+    }
+  }
+
+  private def validateDefaultValueExpr(
+      default: DefaultValueExpression,
+      statement: String,
+      colName: String,
+      targetType: DataType): Unit = {
+    if (default.containsPattern(PLAN_EXPRESSION)) {
+      throw QueryCompilationErrors.defaultValuesMayNotContainSubQueryExpressions(
+        statement, colName, default.originalSQL)
+    } else if (default.resolved) {
+      if (!Cast.canUpCast(default.child.dataType, targetType)) {
+        throw QueryCompilationErrors.defaultValuesDataTypeError(
+          statement, colName, default.originalSQL, targetType, default.child.dataType)
+      }
+      // Check passes. We do not check foldable here, as the plan is not optimized yet.
+    } else if (default.references.nonEmpty) {
+      // Ideally we should let the rest of `CheckAnalysis` to report errors about why the default

Review Comment:
   ```suggestion
         // Ideally we should let the rest of `CheckAnalysis` report errors about why the default
   ```



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/ColumnDefinition.scala:
##########
@@ -0,0 +1,124 @@
+/*
+ * 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.expressions.{Expression, Literal, UnaryExpression, Unevaluable}
+import org.apache.spark.sql.catalyst.parser.ParserInterface
+import org.apache.spark.sql.catalyst.util.GeneratedColumn
+import org.apache.spark.sql.catalyst.util.ResolveDefaultColumnsUtils.{CURRENT_DEFAULT_COLUMN_METADATA_KEY, EXISTS_DEFAULT_COLUMN_METADATA_KEY}
+import org.apache.spark.sql.connector.catalog.{Column => V2Column, ColumnDefaultValue}
+import org.apache.spark.sql.connector.expressions.LiteralValue
+import org.apache.spark.sql.errors.QueryCompilationErrors
+import org.apache.spark.sql.internal.connector.ColumnImpl
+import org.apache.spark.sql.types.{DataType, Metadata, MetadataBuilder, StructField}
+
+/**
+ * Column definition for tables. This is an expression so that analyzer can resolve the default
+ * value expression in DDL commands automatically.
+ */
+case class ColumnDefinition(
+    name: String,
+    dataType: DataType,
+    nullable: Boolean = true,
+    comment: Option[String] = None,
+    defaultValue: Option[DefaultValueExpression] = None,

Review Comment:
   Just a note that I've found when working with this code that the `Option` might confuse some of our Catalyst code that looks for expressions within operators. I think our `mapExpressions` [1] knows how to recurse into the `Option`, but our `resolved` method uses `QueryPlan.expressions`, which does not [2].
   
   It might simplify our work here to just skip the `Option` and make the field a normal `Expression` that defaults to literal NULL. We could have a separate boolean field like `hasExplicitDefault` to differentiate between when the `CREATE TABLE` command included an explicit `DEFAULT NULL` or not. Up to you.
   
   [1] https://github.com/apache/spark/blob/c468c3d5c685c5a5ecd7caf01f3004addce1f3b6/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/QueryPlan.scala#L203
   
   [2] 
   https://github.com/apache/spark/blob/c468c3d5c685c5a5ecd7caf01f3004addce1f3b6/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/QueryPlan.scala#L266



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/ResolveDefaultColumnsUtil.scala:
##########
@@ -445,6 +444,54 @@ object ResolveDefaultColumns extends QueryErrorsBase with ResolveDefaultColumnsU
   def hasExistenceDefaultValues(schema: StructType): Boolean =
     existenceDefaultValues(schema).exists(_ != null)
 
+
+  def checkColumnDefaultValues(plan: LogicalPlan): Unit = {
+    plan match {
+      // Do not check anything if the children are not resolved yet.
+      case _ if !plan.childrenResolved =>
+
+      case cmd: V2CreateTablePlan if cmd.columns.exists(_.defaultValue.isDefined) =>
+        val statement = cmd match {
+          case _: CreateTable => "CREATE TABLE"
+          case _: ReplaceTable => "REPLACE TABLE"
+          case other =>
+            val cmd = other.getClass.getSimpleName
+            throw SparkException.internalError(
+              s"Command $cmd should not have column default value expression.")
+        }
+        cmd.columns.foreach { col =>
+          col.defaultValue.foreach { default =>
+            validateDefaultValueExpr(default, statement, col.name, col.dataType)
+          }
+        }
+
+      case _ =>
+    }
+  }
+
+  private def validateDefaultValueExpr(
+      default: DefaultValueExpression,
+      statement: String,
+      colName: String,
+      targetType: DataType): Unit = {
+    if (default.containsPattern(PLAN_EXPRESSION)) {
+      throw QueryCompilationErrors.defaultValuesMayNotContainSubQueryExpressions(
+        statement, colName, default.originalSQL)
+    } else if (default.resolved) {
+      if (!Cast.canUpCast(default.child.dataType, targetType)) {
+        throw QueryCompilationErrors.defaultValuesDataTypeError(
+          statement, colName, default.originalSQL, targetType, default.child.dataType)
+      }
+      // Check passes. We do not check foldable here, as the plan is not optimized yet.

Review Comment:
   ```suggestion
         // Our analysis check passes here. We do not further inspect whether the
         // expression is `foldable` here, as the plan is not optimized yet.
   ```



##########
common/utils/src/main/resources/error/error-classes.json:
##########
@@ -1766,6 +1766,11 @@
           "which requires <expectedType> type, but the statement provided a value of incompatible <actualType> type."
         ]
       },
+      "NOT_CONSTANT" : {
+        "message" : [
+          "which is not a constant."

Review Comment:
   ```suggestion
             "which is not a constant expression whose equivalent value is known at query planning time; please update your command to change the column default value to satisfy this constraint and then retry the command again."
   ```



-- 
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] [SPARK-46905][SQL] Add dedicated class to keep column definition instead of StructField in Create/ReplaceTable command [spark]

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


##########
common/utils/src/main/resources/error/error-classes.json:
##########
@@ -1766,6 +1766,11 @@
           "which requires <expectedType> type, but the statement provided a value of incompatible <actualType> type."
         ]
       },
+      "NOT_CONSTANT" : {
+        "message" : [
+          "which is not a constant expression whose equivalent value is known at query planning time; please update your command to change the column default value to satisfy this constraint and then retry the command again."

Review Comment:
   A bit earful?



-- 
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] [SPARK-46905][SQL] Add dedicated class to keep column definition instead of StructField in Create/ReplaceTable command [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on code in PR #44935:
URL: https://github.com/apache/spark/pull/44935#discussion_r1470435740


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/ColumnDefinition.scala:
##########
@@ -0,0 +1,124 @@
+/*
+ * 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.expressions.{Expression, Literal, UnaryExpression, Unevaluable}
+import org.apache.spark.sql.catalyst.parser.ParserInterface
+import org.apache.spark.sql.catalyst.util.GeneratedColumn
+import org.apache.spark.sql.catalyst.util.ResolveDefaultColumnsUtils.{CURRENT_DEFAULT_COLUMN_METADATA_KEY, EXISTS_DEFAULT_COLUMN_METADATA_KEY}
+import org.apache.spark.sql.connector.catalog.{Column => V2Column, ColumnDefaultValue}
+import org.apache.spark.sql.connector.expressions.LiteralValue
+import org.apache.spark.sql.errors.QueryCompilationErrors
+import org.apache.spark.sql.internal.connector.ColumnImpl
+import org.apache.spark.sql.types.{DataType, Metadata, MetadataBuilder, StructField}
+
+/**
+ * Column definition for tables. This is an expression so that analyzer can resolve the default
+ * value expression in DDL commands automatically.
+ */
+case class ColumnDefinition(
+    name: String,
+    dataType: DataType,
+    nullable: Boolean = true,
+    comment: Option[String] = None,
+    defaultValue: Option[DefaultValueExpression] = None,

Review Comment:
   `QueryPlan.expressions` does support `Option[Expression]`: https://github.com/apache/spark/blob/c468c3d5c685c5a5ecd7caf01f3004addce1f3b6/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/QueryPlan.scala#L276



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