allisonwang-db commented on code in PR #44190:
URL: https://github.com/apache/spark/pull/44190#discussion_r1422053024


##########
sql/core/src/test/scala/org/apache/spark/sql/connector/DataSourceV2Suite.scala:
##########
@@ -723,6 +724,158 @@ class DataSourceV2Suite extends QueryTest with 
SharedSparkSession with AdaptiveS
       }
     }
   }
+
+  test("SPARK-46272: create table as select") {
+    val cls = classOf[SupportsExternalMetadataDataSource]
+    withTable("test") {
+      sql(
+        s"""
+           |CREATE TABLE test USING ${cls.getName}
+           |AS VALUES (0, 1), (1, 2)
+           |""".stripMargin)
+      checkAnswer(sql("SELECT * FROM test"), Seq(Row(0, 1), Row(1, 2)))
+      sql(
+        s"""
+           |CREATE OR REPLACE TABLE test USING ${cls.getName}
+           |AS VALUES (2, 3), (4, 5)
+           |""".stripMargin)
+      checkAnswer(sql("SELECT * FROM test"), Seq(Row(2, 3), Row(4, 5)))
+      sql(
+        s"""
+           |CREATE TABLE IF NOT EXISTS test USING ${cls.getName}
+           |AS VALUES (3, 4), (4, 5)
+           |""".stripMargin)
+      checkAnswer(sql("SELECT * FROM test"), Seq(Row(2, 3), Row(4, 5)))
+    }
+  }
+
+  test("SPARK-46272: create table as select - error cases") {
+    val cls = classOf[SupportsExternalMetadataDataSource]
+    // CTAS with too many columns
+    withTable("test") {
+      checkError(
+        exception = intercept[AnalysisException] {
+          sql(
+            s"""
+               |CREATE TABLE test USING ${cls.getName}
+               |AS VALUES (0, 1, 2), (1, 2, 3)
+               |""".stripMargin)
+        },
+        errorClass = "INSERT_COLUMN_ARITY_MISMATCH.TOO_MANY_DATA_COLUMNS",

Review Comment:
   This is actually tricky, and the behavior depends on the implementation of 
the data source.
   
   In `createTable`, we store the query's schema (col1, col2, col3) in HMS, but 
this data source's `getTable` method does not take into account the input 
`schema`.
   
   So, when the DSv2 relation is being created, it uses 
`table.columns.asSchema` which is the default implementation of the schema (i, 
j).  
   
https://github.com/apache/spark/blob/bacdb3b5fec9783f46042764eeee80eb2a0f5702/sql/catalyst/src/main/scala/org/apache/spark/sql/execution/datasources/v2/DataSourceV2Relation.scala#L210-L211
   
   However, if the data source utilize user-defined schema in `getTable`, it 
won't throw this exception.



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