dtenedor commented on code in PR #39942:
URL: https://github.com/apache/spark/pull/39942#discussion_r1106172353


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/types/StructType.scala:
##########
@@ -394,6 +395,31 @@ case class StructType(fields: Array[StructField]) extends 
DataType with Seq[Stru
 
   protected[sql] def toAttributes: Seq[AttributeReference] = map(field => 
field.toAttribute)
 
+  private[sql] def toColumns: Array[Column] = fields.map { f =>
+    val defaultValue = f.getCurrentDefaultValue().map { sql =>
+      val existDefaultOpt = f.getExistenceDefaultValue()
+      assert(existDefaultOpt.isDefined, "current and exist default must be 
both set or neither")

Review Comment:
   Technically, the existence default value can be set but the current default 
value can be absent if we do `create table t (col int default 42) using 
parquet` and then `alter table t alter column col drop default`. Maybe reword 
this message to "if the current default value is set, the existence default 
value must also be set"?



##########
sql/catalyst/src/main/java/org/apache/spark/sql/connector/catalog/ColumnDefaultValue.java:
##########
@@ -0,0 +1,61 @@
+/*
+ * 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.connector.catalog;
+
+import java.util.Objects;
+import javax.annotation.Nonnull;
+
+import org.apache.spark.sql.connector.expressions.Literal;
+
+public class ColumnDefaultValue {

Review Comment:
   Could we add a class comment to describe what this is used for, the 
corresponding SQL syntax, etc.?



##########
sql/catalyst/src/test/scala/org/apache/spark/sql/types/StructTypeSuite.scala:
##########
@@ -471,34 +471,22 @@ class StructTypeSuite extends SparkFunSuite with 
SQLHelper {
     assert(source1.existenceDefaultValues(1) == UTF8String.fromString("abc"))
     assert(source1.existenceDefaultValues(2) == null)
 
-    // Positive test: StructType.defaultValues works because the existence 
default value parses and
-    // resolves successfully, then evaluates to a non-literal expression: this 
is constant-folded at

Review Comment:
   do we still test this constant-folding somewhere?



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/DescribeTableExec.scala:
##########
@@ -37,6 +38,7 @@ case class DescribeTableExec(
     addPartitioning(rows)
 
     if (isExtended) {
+      addColumnDefaultValue(rows)

Review Comment:
   does this add the column default information earlier in the result than 
before? that might be OK...



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/types/StructType.scala:
##########
@@ -394,6 +395,31 @@ case class StructType(fields: Array[StructField]) extends 
DataType with Seq[Stru
 
   protected[sql] def toAttributes: Seq[AttributeReference] = map(field => 
field.toAttribute)
 
+  private[sql] def toColumns: Array[Column] = fields.map { f =>
+    val defaultValue = f.getCurrentDefaultValue().map { sql =>
+      val existDefaultOpt = f.getExistenceDefaultValue()
+      assert(existDefaultOpt.isDefined, "current and exist default must be 
both set or neither")
+      val e = 
CatalystSqlParser.parseExpression(f.getExistenceDefaultValue().get)

Review Comment:
   ```suggestion
         val e = CatalystSqlParser.parseExpression(existDefaultOpt.get)
   ```



##########
sql/core/src/main/scala/org/apache/spark/sql/catalyst/analysis/ResolveSessionCatalog.scala:
##########
@@ -50,17 +50,26 @@ class ResolveSessionCatalog(val catalogManager: 
CatalogManager)
   import org.apache.spark.sql.execution.datasources.v2.DataSourceV2Implicits._
 
   override def apply(plan: LogicalPlan): LogicalPlan = plan.resolveOperatorsUp 
{
-    case AddColumns(ResolvedV1TableIdentifier(ident), cols) =>
-      cols.foreach { c =>
+    case a @ AddColumns(ResolvedV1TableIdentifier(ident), colsToAdd) if 
a.resolved =>
+      colsToAdd.foreach { c =>
         if (c.name.length > 1) {
           throw QueryCompilationErrors.operationOnlySupportedWithV2TableError(
             Seq(ident.catalog.get, ident.database.get, ident.table),
             "ADD COLUMN with qualified column")
         }
-        if (!c.nullable) {
+        if (!c.column.nullable) {
           throw 
QueryCompilationErrors.addColumnWithV1TableCannotSpecifyNotNullError
         }
       }
+      // Check default values before converting to v1 command.
+      DefaultColumnUtil.checkDefaultValuesInPlan(a, isForV1 = true)
+      val cols = if (colsToAdd.exists(_.column.defaultValue.isDefined)) {
+        // Do a constant-folding, as we need to store the expression SQL 
string which should be in

Review Comment:
   we should probably put this into a util method in 
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/ResolveDefaultColumnsUtil.scala
 for better clarity of the code



##########
sql/core/src/test/scala/org/apache/spark/sql/connector/TestV2SessionCatalogBase.scala:
##########
@@ -64,6 +64,15 @@ private[connector] trait TestV2SessionCatalogBase[T <: 
Table] extends Delegating
     }
   }
 
+  override def createTable(
+      ident: Identifier,
+      columns: Array[Column],
+      partitions: Array[Transform],
+      properties: java.util.Map[String, String]): Table = {
+    createTable(ident, CatalogV2Util.v2ColumnsToStructType(columns), 
partitions, properties)
+  }
+
+  // TODO: remove it when no tests calling this deprecated method.

Review Comment:
   There are a lot of method changes like this in this PR. Would it be better 
to clean up the code by updating the call sites? Or should we do that in a 
separate PR?



##########
sql/core/src/test/scala/org/apache/spark/sql/sources/InsertSuite.scala:
##########
@@ -1982,47 +1970,7 @@ class InsertSuite extends DataSourceTest with 
SharedSparkSession {
     ).foreach { query =>
       assert(intercept[AnalysisException] {
         sql(query)
-      }.getMessage.contains(
-        
QueryCompilationErrors.defaultValuesMayNotContainSubQueryExpressions().getMessage))
-    }
-  }
-
-  test("SPARK-39844 Restrict adding DEFAULT columns for existing tables to 
certain sources") {

Review Comment:
   Per response to that comment, it looks likely we'll have to retain this 
functionality.



##########
sql/core/src/test/scala/org/apache/spark/sql/sources/InsertSuite.scala:
##########
@@ -1058,21 +1057,21 @@ class InsertSuite extends DataSourceTest with 
SharedSparkSession {
       assert(intercept[AnalysisException] {
         sql("create table t(i boolean, s bigint default (select min(x) from 
badtable)) " +
           "using parquet")
-      }.getMessage.contains(Errors.BAD_SUBQUERY))

Review Comment:
   this no longer returns an error that subquery expressions are not allowed in 
default values. Can we have a test that checks this case?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to