gengliangwang commented on a change in pull request #35855:
URL: https://github.com/apache/spark/pull/35855#discussion_r833459944



##########
File path: 
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ResolveDefaultColumns.scala
##########
@@ -0,0 +1,366 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.catalyst.analysis
+
+import org.apache.spark.sql.AnalysisException
+import org.apache.spark.sql.catalyst.TableIdentifier
+import org.apache.spark.sql.catalyst.analysis.ResolveDefaultColumns._
+import org.apache.spark.sql.catalyst.catalog._
+import org.apache.spark.sql.catalyst.expressions._
+import org.apache.spark.sql.catalyst.optimizer.ConstantFolding
+import org.apache.spark.sql.catalyst.parser.{CatalystSqlParser, ParseException}
+import org.apache.spark.sql.catalyst.plans.logical._
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.catalyst.trees.AlwaysProcess
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.types._
+
+/**
+ * This is a rule to process DEFAULT columns in statements such as 
CREATE/REPLACE TABLE.
+ *
+ * Background: CREATE TABLE and ALTER TABLE invocations support setting column 
default values for
+ * later operations. Following INSERT, and INSERT MERGE commands may then 
reference the value
+ * using the DEFAULT keyword as needed.
+ *
+ * Example:
+ * CREATE TABLE T(a INT DEFAULT 4, b INT NOT NULL DEFAULT 5);
+ * INSERT INTO T VALUES (1, 2);
+ * INSERT INTO T VALUES (1, DEFAULT);
+ * INSERT INTO T VALUES (DEFAULT, 6);
+ * SELECT * FROM T;
+ * (1, 2)
+ * (1, 5)
+ * (4, 6)
+ *
+ * @param catalog the catalog to use for looking up the schema of INSERT INTO 
table objects.
+ * @param insert the enclosing INSERT statement for which this rule is 
processing the query, if any.
+ */
+case class ResolveDefaultColumns(
+    catalog: SessionCatalog,
+    insert: Option[InsertIntoStatement] = None) extends Rule[LogicalPlan] {
+  override def apply(plan: LogicalPlan): LogicalPlan = 
plan.resolveOperatorsWithPruning(
+    AlwaysProcess.fn, ruleId) {
+    case _ if !SQLConf.get.enableDefaultColumns => plan
+
+    case i@InsertIntoStatement(_, _, _, _, _, _)
+      if i.query.collectFirst { case u: UnresolvedInlineTable => u }.isDefined 
=>
+      // Create a helper instance of this same rule with the `insert` argument 
populated as `i`.
+      // Then recursively apply it on the `query` of `i` to transform the 
result. This recursive
+      // application lets the below case matching against 
`UnresolvedInlineTable` to trigger
+      // anywhere that operator may appear in the descendants of `i.query`.
+      val helper = ResolveDefaultColumns(catalog, Some(i))
+      val newQuery = helper.apply(i.query)
+      i.copy(query = newQuery)
+
+    case table: UnresolvedInlineTable
+      if insert.isDefined &&
+        table.rows.nonEmpty && table.rows.forall(_.size == table.rows(0).size) 
=>
+      val expanded: UnresolvedInlineTable = 
addMissingDefaultColumnValues(table).getOrElse(table)
+      replaceExplicitDefaultColumnValues(expanded).getOrElse(table)
+
+    case i@InsertIntoStatement(_, _, _, project: Project, _, _)
+      if !project.resolved =>
+      val helper = ResolveDefaultColumns(catalog, Some(i))
+      val replaced: Option[Project] = 
helper.replaceExplicitDefaultColumnValues(project)
+      if (replaced.isDefined) i.copy(query = replaced.get) else i
+
+    case i@InsertIntoStatement(_, _, _, project: Project, _, _)
+      if project.resolved =>
+      val helper = ResolveDefaultColumns(catalog, Some(i))
+      val expanded: Project = 
helper.addMissingDefaultColumnValues(project).getOrElse(project)
+      val replaced: Option[Project] = 
helper.replaceExplicitDefaultColumnValues(expanded)
+      if (replaced.isDefined) i.copy(query = replaced.get) else i
+  }
+
+  // Helper method to check if an expression is an explicit DEFAULT column 
reference.
+  private def isExplicitDefaultColumn(expr: Expression): Boolean = expr match {
+    case u: UnresolvedAttribute if 
u.name.equalsIgnoreCase(CURRENT_DEFAULT_COLUMN_NAME) => true
+    case _ => false
+  }
+
+  // Each of the following methods adds a projection over the input plan to 
generate missing default
+  // column values.
+  private def addMissingDefaultColumnValues(
+      table: UnresolvedInlineTable): Option[UnresolvedInlineTable] = {
+    assert(insert.isDefined)
+    val numQueryOutputs: Int = table.rows(0).size
+    val schema: StructType = getInsertTableSchema.getOrElse(return None)
+    val schemaWithoutPartitionCols =
+      StructType(schema.fields.dropRight(insert.get.partitionSpec.size))
+    val newDefaultExprs: Seq[Expression] =
+      getDefaultExprs(numQueryOutputs, schema, schemaWithoutPartitionCols)
+    val newNames: Seq[String] =
+      schemaWithoutPartitionCols.fields.drop(numQueryOutputs).map { _.name }
+    if (newDefaultExprs.isEmpty) return None
+    Some(table.copy(names = table.names ++ newNames,
+      rows = table.rows.map { row => row ++ newDefaultExprs }))
+  }
+
+  private def addMissingDefaultColumnValues(project: Project): Option[Project] 
= {
+    val numQueryOutputs: Int = project.projectList.size
+    val schema: StructType = getInsertTableSchema.getOrElse(return None)
+    val schemaWithoutPartitionCols =
+      StructType(schema.fields.dropRight(insert.get.partitionSpec.size))
+    val newDefaultExprs: Seq[Expression] =
+      getDefaultExprs(numQueryOutputs, schema, schemaWithoutPartitionCols)
+    val newAliases: Seq[NamedExpression] =
+      newDefaultExprs.zip(schemaWithoutPartitionCols.fields).map {
+        case (expr, field) => Alias(expr, field.name)()
+      }
+    if (newDefaultExprs.isEmpty) return None
+    Some(project.copy(projectList = project.projectList ++ newAliases))
+  }
+
+  // This is a helper for the addMissingDefaultColumnValues methods above.
+  private def getDefaultExprs(numQueryOutputs: Int, schema: StructType,

Review comment:
       param schema is not used

##########
File path: 
sql/core/src/test/scala/org/apache/spark/sql/sources/InsertSuite.scala
##########
@@ -846,6 +854,238 @@ class InsertSuite extends DataSourceTest with 
SharedSparkSession {
     }
   }
 
+  test("INSERT INTO statements with tables with default columns") {
+    // For most of these cases, the test table 't' has two columns:
+    // (1) name 'i' with boolean type and no default value
+    // (2) name 's' with long integer type and a default value of 42L.
+    //
+    // Positive tests:
+    // When the USE_NULLS_FOR_MISSING_DEFAULT_COLUMN_VALUES configuration is 
enabled, and no
+    // explicit DEFAULT value is available when the INSERT INTO statement 
provides fewer
+    // values than expected, NULL values are appended in their place.
+    withSQLConf(SQLConf.USE_NULLS_FOR_MISSING_DEFAULT_COLUMN_VALUES.key -> 
"true") {
+      withTable("t") {
+        sql("create table t(i boolean, s bigint) using parquet")
+        sql("insert into t values(true)")
+        checkAnswer(sql("select s from t where i = true"), Seq(null).map(i => 
Row(i)))
+      }
+    }
+    // The default value for the DEFAULT keyword is the NULL literal.
+    withTable("t") {
+      sql("create table t(i boolean, s bigint) using parquet")
+      sql("insert into t values(true, default)")
+      checkAnswer(sql("select s from t where i = true"), Seq(null).map(i => 
Row(i)))
+    }
+    // There is a complex expression in the default value.
+    withTable("t") {
+      sql("create table t(i boolean, s string default concat('abc', 'def')) 
using parquet")
+      sql("insert into t values(true, default)")
+      checkAnswer(sql("select s from t where i = true"), Seq("abcdef").map(i 
=> Row(i)))
+    }
+    // The default value parses correctly and the provided value type is 
different but coercible.
+    withTable("t") {
+      sql("create table t(i boolean, s bigint default 42) using parquet")
+      sql("insert into t values(false)")
+      checkAnswer(sql("select s from t where i = false"), Seq(42L).map(i => 
Row(i)))
+    }
+    // There are two trailing default values referenced implicitly by the 
INSERT INTO statement.
+    withTable("t") {
+      sql("create table t(i int, s bigint default 42, x bigint default 43) 
using parquet")
+      sql("insert into t values(1)")
+      checkAnswer(sql("select s + x from t where i = 1"), Seq(85L).map(i => 
Row(i)))
+    }
+    // The table has a partitioning column and a default value is injected.

Review comment:
       Do partition columns support default values? If yes, shall we add such a 
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