dejankrak-db commented on code in PR #59640:
URL: https://github.com/apache/spark/pull/59640#discussion_r4382942184


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/CheckAnalysis.scala:
##########
@@ -998,6 +1021,25 @@ trait CheckAnalysis extends LookupCatalog with 
QueryErrorsBase with PlanToString
             create.tableSchema.foreach(f => 
TypeUtils.failWithIntervalType(f.dataType))
             TypeUtils.failUnsupportedDataType(create.tableSchema, SQLConf.get)
             SchemaUtils.checkIndeterminateCollationInSchema(create.tableSchema)
+            create match {
+              // The columns of CREATE TABLE AS SELECT come from its query, 
not from DDL.
+              case ctas: V2CreateTableAsSelectPlan =>
+                TypeUtils.checkNoUnknownFileTypeWrite(ctas.query.output)

Review Comment:
   Thanks. The nested add and the `FILE EXTERNAL` positive control are in 
7ce087d5061; details in the test thread.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/rules.scala:
##########
@@ -293,6 +295,8 @@ case class PreprocessTableCreation(catalog: SessionCatalog) 
extends Rule[Logical
 
         c.copy(tableDesc = normalizedTable, query = Some(reorderedQuery))
       } else {
+        checkFileTypeHasQualifier(tableDesc.schema)

Review Comment:
   Will do. The follow-ups are now listed in the description, with pipelines 
and `ACCEPT_ANY_SCHEMA` writes marked as blockers for enabling 
`spark.sql.fileType.enabled` by default, and I will link the JIRA once it is 
filed.



##########
sql/core/src/test/scala/org/apache/spark/sql/FileTypeRestrictionsSuite.scala:
##########
@@ -0,0 +1,357 @@
+/*
+ * 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
+
+import org.apache.spark.SparkConf
+import org.apache.spark.api.python.{PythonBroadcast, PythonEvalType, 
SimplePythonFunction}
+import org.apache.spark.broadcast.Broadcast
+import org.apache.spark.sql.api.java.UDF1
+import org.apache.spark.sql.catalyst.TableIdentifier
+import org.apache.spark.sql.catalyst.catalog.{CatalogStorageFormat, 
CatalogTable, CatalogTableType}
+import org.apache.spark.sql.connector.catalog.InMemoryCatalog
+import org.apache.spark.sql.execution.python.{UserDefinedPythonFunction, 
UserDefinedPythonTableFunction}
+import org.apache.spark.sql.functions.{col, udf}
+import org.apache.spark.sql.test.SharedSparkSession
+import org.apache.spark.sql.types.{DataType, FileType, IntegerType, MapType, 
StructType}
+
+/**
+ * Tests the rules on where the FILE type can be used: table columns must be 
FILE EXTERNAL,
+ * routines declare a plain FILE, and FILE has no defined ordering.
+ */
+class FileTypeRestrictionsSuite extends QueryTest with SharedSparkSession {
+
+  override protected def sparkConf: SparkConf =
+    super.sparkConf.set("spark.sql.catalog.testcat", 
classOf[InMemoryCatalog].getName)
+
+  // A FILE without a qualifier, at the top level and nested.
+  private val unqualifiedFileTypes = Seq(
+    "FILE",
+    "ARRAY<FILE>",
+    "MAP<STRING, FILE>",
+    "STRUCT<f1: FILE>",
+    "STRUCT<f1: INT, f2: STRUCT<f3: ARRAY<FILE>>>")
+
+  private val externalFile = "SELECT CAST(NULL AS FILE EXTERNAL) AS f"
+
+  test("a table column definition requires FILE EXTERNAL") {
+    Seq("testcat.t", "t").foreach { table =>
+      val provider = if (table.startsWith("testcat")) "" else "USING parquet"
+      unqualifiedFileTypes.foreach { dataType =>
+        withTable(table) {
+          checkError(
+            exception = intercept[AnalysisException] {
+              sql(s"CREATE TABLE $table (id INT, c $dataType) $provider")
+            },
+            condition = "FILE_TYPE_MISSING_QUALIFIER")
+        }
+      }
+    }
+    withTable("testcat.t") {
+      sql("CREATE TABLE testcat.t (id INT, c STRUCT<f1: ARRAY<FILE 
EXTERNAL>>)")
+    }
+  }
+
+  test("REPLACE TABLE requires FILE EXTERNAL") {
+    withTable("testcat.t") {
+      sql("CREATE TABLE testcat.t (id INT)")
+      checkError(
+        exception = intercept[AnalysisException] {
+          sql("REPLACE TABLE testcat.t (id INT, c FILE)")
+        },
+        condition = "FILE_TYPE_MISSING_QUALIFIER")
+    }
+  }
+
+  test("ALTER TABLE ADD COLUMNS and REPLACE COLUMNS require FILE EXTERNAL") {
+    withTable("testcat.t") {
+      sql("CREATE TABLE testcat.t (id INT)")
+      unqualifiedFileTypes.foreach { dataType =>
+        checkError(
+          exception = intercept[AnalysisException] {
+            sql(s"ALTER TABLE testcat.t ADD COLUMN c $dataType")
+          },
+          condition = "FILE_TYPE_MISSING_QUALIFIER")
+        checkError(
+          exception = intercept[AnalysisException] {
+            sql(s"ALTER TABLE testcat.t REPLACE COLUMNS (id INT, c $dataType)")
+          },
+          condition = "FILE_TYPE_MISSING_QUALIFIER")
+      }
+      sql("ALTER TABLE testcat.t ADD COLUMN c FILE EXTERNAL")
+    }
+  }
+
+  test("CREATE TABLE AS SELECT cannot store a FILE without a qualifier") {
+    Seq("testcat.t", "t").foreach { table =>
+      val provider = if (table.startsWith("testcat")) "" else "USING parquet"
+      withTable(table) {
+        checkError(
+          exception = intercept[AnalysisException] {
+            sql(s"CREATE TABLE $table $provider AS SELECT 1 AS id, CAST(NULL 
AS FILE) AS f")
+          },
+          condition = "FILE_TYPE_UNKNOWN_WRITE",
+          parameters = Map("colNames" -> "[`f`]"))
+      }
+    }
+  }
+
+  test("a FILE column cannot be a partition or clustering column") {
+    Seq(
+      ("PARTITIONED BY (f)", "PARTITION_COLUMN"),
+      ("PARTITIONED BY (bucket(4, f))", "PARTITION_COLUMN"),
+      ("CLUSTER BY (f)", "CLUSTERING_COLUMN")).foreach { case (clause, usage) 
=>
+      Seq("testcat.t", "t").foreach { table =>
+        // Bucketing is only a V2 transform.
+        if (table.startsWith("testcat") || !clause.contains("bucket")) {
+          val provider = if (table.startsWith("testcat")) "" else "USING 
parquet"
+          withTable(table) {
+            checkError(
+              exception = intercept[AnalysisException] {
+                sql(s"CREATE TABLE $table (id INT, f FILE EXTERNAL) $provider 
$clause")
+              },
+              condition = s"FILE_TYPE_UNSUPPORTED_COLUMN_USAGE.$usage",
+              parameters = Map("colName" -> "`f`", "dataType" -> "\"FILE 
EXTERNAL\""))
+          }
+        }
+      }
+    }
+    Seq("testcat.t", "t").foreach { table =>
+      withTable(table) {
+        if (table.startsWith("testcat")) {
+          sql(s"CREATE TABLE $table (id INT, f FILE EXTERNAL) CLUSTER BY (id)")
+        } else {
+          // No V1 data source can store a FILE yet, so the table is created 
in the catalog.
+          spark.sessionState.catalog.createTable(CatalogTable(
+            identifier = TableIdentifier(table),
+            tableType = CatalogTableType.MANAGED,
+            storage = CatalogStorageFormat.empty,
+            schema = new StructType().add("id", IntegerType).add("f", 
FileType.external),
+            provider = Some("parquet")), ignoreIfExists = false)
+        }
+        checkError(
+          exception = intercept[AnalysisException] {
+            sql(s"ALTER TABLE $table CLUSTER BY (f)")
+          },
+          condition = "FILE_TYPE_UNSUPPORTED_COLUMN_USAGE.CLUSTERING_COLUMN",
+          parameters = Map("colName" -> "`f`", "dataType" -> "\"FILE 
EXTERNAL\""))
+      }
+    }
+  }
+
+  test("a column cannot be altered to a FILE") {
+    withTable("testcat.t") {
+      sql("CREATE TABLE testcat.t (id INT, s STRING, f FILE EXTERNAL)")
+      Seq("s", "f").foreach { column =>
+        val e = intercept[AnalysisException] {
+          sql(s"ALTER TABLE testcat.t ALTER COLUMN $column TYPE FILE")
+        }
+        assert(e.getCondition === "NOT_SUPPORTED_CHANGE_COLUMN")
+      }
+    }
+  }
+
+  test("a FILE cannot be a map key") {
+    checkError(
+      exception = intercept[AnalysisException] {
+        sql(s"SELECT map(f, 1) FROM ($externalFile)")
+      },
+      condition = "DATATYPE_MISMATCH.INVALID_MAP_KEY_TYPE",
+      parameters = Map("sqlExpr" -> "\"map(f, 1)\"", "keyType" -> "\"FILE 
EXTERNAL\""),
+      context = ExpectedContext(fragment = "map(f, 1)", start = 7, stop = 15))
+    sql(s"SELECT map(1, f) FROM ($externalFile)")
+  }
+
+  test("a FILE cannot be a grouping expression") {
+    val query = s"SELECT count(*) FROM ($externalFile) GROUP BY f"
+    checkError(
+      exception = intercept[AnalysisException](sql(query)),
+      condition = "GROUP_EXPRESSION_TYPE_IS_NOT_ORDERABLE",
+      parameters = Map("sqlExpr" -> "\"f\"", "dataType" -> "\"FILE 
EXTERNAL\""),
+      context = ExpectedContext(
+        fragment = "f", start = query.length - 1, stop = query.length - 1))
+  }
+
+  test("a FILE cannot be in INTERSECT, EXCEPT or DISTINCT") {

Review Comment:
   Both are fixed in 7ce087d5061: the guard is gone, so the V1 `PARTITIONED BY` 
and `CLUSTER BY` cases run for `CREATE TABLE` and CTAS, and the query-time 
Python UDF and the UDAF class registered by name are tested.



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