This is an automated email from the ASF dual-hosted git repository.
uros-b pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/spark.git
The following commit(s) were added to refs/heads/master by this push:
new 8ddbea49bf3a [SPARK-60386][SQL] Enforce FILE EXTERNAL in table columns
and reject FILE where it would need equality or an ordering
8ddbea49bf3a is described below
commit 8ddbea49bf3af89918b159f99c74abafe3e71427
Author: Dejan Krakovic <[email protected]>
AuthorDate: Thu Nov 12 12:29:21 2026 +0000
[SPARK-60386][SQL] Enforce FILE EXTERNAL in table columns and reject FILE
where it would need equality or an ordering
### What changes were proposed in this pull request?
Part 2 of the FileType SPIP
([SPARK-59132](https://issues.apache.org/jira/browse/SPARK-59132)), following
the Catalyst type added in #59305. The SPIP requires the `EXTERNAL` keyword
when a FILE column is declared in a table, and defines FileType as not
comparable: it has neither equality nor an ordering. This PR enforces both at
analysis time, except for `CREATE TABLE ... LIKE` when the target and source
are both in the session catalog, which is checked when the command runs.
Table columns:
- A FILE in a table column definition, including one nested in a struct,
array or map, must be `FILE EXTERNAL`: `CREATE TABLE`, `REPLACE TABLE`, `ALTER
TABLE ADD COLUMNS`, `ALTER TABLE REPLACE COLUMNS` and `ALTER TABLE ALTER COLUMN
... TYPE` fail with `FILE_TYPE_MISSING_QUALIFIER`. The check is in
`CheckAnalysis` for V2 tables, in `PreprocessTableCreation` for V1 tables, and
next to the existing `failUnsupportedDataType` call in
`AddColumns`/`ReplaceColumns`, and in `AlterColumns`.
- `CREATE TABLE AS SELECT` cannot store a FILE without a qualifier, as one
produced by `CAST(... AS FILE)` (`FILE_TYPE_UNKNOWN_WRITE`). Neither can schema
evolution (`INSERT`/`MERGE WITH SCHEMA EVOLUTION` and `withSchemaEvolution()`),
which is checked in `ResolveSchemaEvolution` before the catalog changes the
table, nor `CREATE TABLE ... LIKE` a view or table that holds one. As with
CTAS, `IF NOT EXISTS` does not skip the check when the table exists. The source
schema is checked in `C [...]
- A FILE column cannot be a partition or clustering column, in `CREATE
TABLE` for V1 and V2 tables (including V2 transforms such as `bucket` and V1
bucket columns) and in `ALTER TABLE ... CLUSTER BY` for V1 and V2 tables
(`FILE_TYPE_UNSUPPORTED_COLUMN_USAGE.PARTITION_COLUMN` and
`.CLUSTERING_COLUMN`). Nor can it be a write-ordering column of a V2 table
(`ORDERED BY` and `LOCALLY ORDERED BY`, `.WRITE_ORDERING_COLUMN`), in `CREATE
TABLE`, `REPLACE TABLE`, CTAS and RTAS; a catalog cannot [...]
Routines:
- Functions declare a plain `FILE`, as the SPIP specifies. `CREATE
FUNCTION` rejects `FILE EXTERNAL` in its parameter or return types
(`FILE_TYPE_IN_ROUTINE_SIGNATURE_UNSUPPORTED_QUALIFIER`), and a FILE in a map
key of its return type (`FILE_TYPE_IN_ROUTINE_SIGNATURE_UNSUPPORTED_MAP_KEY`).
Without a `RETURNS` clause, or with a bare `RETURNS TABLE`, the return type
inferred from the function body is checked the same way.
- The same applies to the return type of UDFs, when they are registered
(Scala and Java UDFs and UDAFs through `spark.udf.register`, Python UDFs and
UDTFs through `registerPython`) and, for UDFs that are not registered, when
`CheckAnalysis` sees them in a query. A non-scalar Python UDF is skipped, as
its data type is the schema of the rows it returns. The errors quote the
routine name, as `CREATE FUNCTION` does.
No equality or ordering, following the existing checks for VARIANT:
- Map key of a map built in a query: `TypeUtils.checkForMapKeyType`
(`DATATYPE_MISMATCH.INVALID_MAP_KEY_TYPE`). A table column of type `MAP<FILE
EXTERNAL, ...>` is still accepted.
- Grouping: `ExprUtils.checkValidGroupingExprs`
(`GROUP_EXPRESSION_TYPE_IS_NOT_ORDERABLE`).
- `INTERSECT`, `EXCEPT`, `DISTINCT` (including `UNION DISTINCT`), and the
keys of `dropDuplicates` and `dropDuplicatesWithinWatermark`: `CheckAnalysis`
and `OperatorWithUncomparableTypeValidator` of the single-pass resolver
(`UNSUPPORTED_FEATURE.SET_OPERATION_ON_FILE_TYPE`). `UNION ALL` is allowed, as
for VARIANT.
- `DISTRIBUTE BY`/`repartition` and the `REBALANCE` hint: `CheckAnalysis`,
which matches `HasPartitionExpressions`
(`UNSUPPORTED_FEATURE.PARTITION_BY_FILE`). `RepartitionByExpressionResolver`
has the same check, for parity with VARIANT, but the single-pass resolver does
not dispatch to it yet.
- Hash functions such as `hash` and `xxhash64`:
`HashExpression.checkInputDataTypes` (`DATATYPE_MISMATCH.HASH_FILE_TYPE`).
- Join keys, comparisons, sorting and window `PARTITION BY`/`ORDER BY` need
no change: FileType is not orderable, so they already fail with
`DATATYPE_MISMATCH.INVALID_ORDERING_TYPE` or
`EXPRESSION_TYPE_IS_NOT_ORDERABLE`. This PR adds tests for these.
- Aggregates that deduplicate or hash their input, such as `count(DISTINCT
f)`, `collect_set(f)`, `approx_count_distinct(f)`, `mode(f)` and
`collect_union`, are not rejected here. They cannot run before FILE has a
physical representation, and whether to reject them is left to that part.
Tracked in [SPARK-61304](https://issues.apache.org/jira/browse/SPARK-61304).
The `FileType` Scaladoc is updated to describe these rules as current
rather than planned, and to describe its fields as the Parquet `FILE` logical
type defines them (`uri` may be relative, and `size` is the length of the
referenced byte range).
Not covered here, left to follow-ups (sub-tasks of SPARK-59132):
- [SPARK-61297](https://issues.apache.org/jira/browse/SPARK-61297): tables
created by Declarative Pipelines skip the `V2CreateTablePlan` checks, and
writes to a table with `ACCEPT_ANY_SCHEMA` skip schema resolution, so both can
still store a bare FILE. **This must be fixed before
`spark.sql.fileType.enabled` is enabled by default.**
- [SPARK-61298](https://issues.apache.org/jira/browse/SPARK-61298): one
rule for FILE in the output of row-returning Python functions.
- [SPARK-61299](https://issues.apache.org/jira/browse/SPARK-61299): a
type-level way to declare equality and ordering support, shared checks for MAP,
VARIANT and FILE, and extending the VARIANT checks to `REBALANCE` and
`dropDuplicatesWithinWatermark`.
- [SPARK-61300](https://issues.apache.org/jira/browse/SPARK-61300):
reporting set-operation errors one type at a time over all columns, in both
analyzers.
- [SPARK-61301](https://issues.apache.org/jira/browse/SPARK-61301): the
FILE error messages, SQLSTATEs and helpers.
- [SPARK-61302](https://issues.apache.org/jira/browse/SPARK-61302): whether
FileType should ever define equality.
- [SPARK-61303](https://issues.apache.org/jira/browse/SPARK-61303): the
return type of V2 catalog functions, checked today only when they are bound as
an `ApplyFunctionExpression`.
### Why are the changes needed?
The SPIP defines a FILE column of a table as an external file reference,
and a bare `FILE` (the unknown mode) as the type of an expression or a UDF
result, so a table should never store a bare `FILE`. FileType is not
comparable, as it is not clear what equality of two files should mean, so
operations that need equality or an ordering, such as comparing, grouping,
deduplicating, hashing or sorting values, must fail clearly rather than operate
on the underlying struct.
### Does this PR introduce _any_ user-facing change?
No relative to released versions. The FILE type is only recognized when
`spark.sql.fileType.enabled` is true, which is the default only in tests.
Relative to master, the statements and operations listed above now fail with
the errors listed above when the type is enabled.
### How was this patch tested?
Added `FileTypeRestrictionsSuite`, covering each rule for V1 and V2 tables
where both apply, nested FILE types, schema evolution (including a nested add
and that the table is not changed), `CREATE TABLE LIKE` a view or a table (at
analysis, including `IF NOT EXISTS`), every partition and clustering clause for
both `CREATE TABLE` and CTAS, CTAS with `IF NOT EXISTS`, write-ordering
columns, type changes to and from FILE, inferred SQL function return types,
UDF, UDAF, Python UDF and UDTF [...]
### Was this patch authored or co-authored using generative AI tooling?
Generated-by: Claude Opus 5.5
This pull request and its description were written by Isaac.
Closes #59640 from dejankrak-db/SPARK-59132-file-type-ddl.
Authored-by: Dejan Krakovic <[email protected]>
Signed-off-by: Uros Bojanic <[email protected]>
skip-checks: true
---
.../src/main/resources/error/error-conditions.json | 62 ++
.../spark/sql/errors/CompilationErrors.scala | 6 +
.../org/apache/spark/sql/types/FileType.scala | 33 +-
.../catalyst/analysis/AlterTableValidation.scala | 8 +-
.../sql/catalyst/analysis/CheckAnalysis.scala | 85 ++-
.../catalyst/analysis/CreateTableValidation.scala | 32 +-
.../catalyst/analysis/ResolveSchemaEvolution.scala | 10 +-
.../OperatorWithUncomparableTypeValidator.scala | 28 +-
.../resolver/RepartitionByExpressionResolver.scala | 23 +-
.../sql/catalyst/analysis/resolver/Resolver.scala | 2 +-
.../spark/sql/catalyst/expressions/ExprUtils.scala | 6 +-
.../spark/sql/catalyst/expressions/hash.scala | 10 +
.../plans/logical/v2AlterTableCommands.scala | 4 +
.../apache/spark/sql/catalyst/util/TypeUtils.scala | 144 +++-
.../spark/sql/errors/QueryCompilationErrors.scala | 41 ++
.../org/apache/spark/sql/UDTFRegistration.scala | 4 +
.../catalyst/analysis/ResolveSessionCatalog.scala | 5 +-
.../apache/spark/sql/classic/UDFRegistration.scala | 17 +
.../command/CreateSQLFunctionCommand.scala | 14 +
.../spark/sql/execution/command/tables.scala | 4 +-
.../spark/sql/execution/datasources/rules.scala | 17 +
.../spark/sql/FileTypeRestrictionsSuite.scala | 731 +++++++++++++++++++++
22 files changed, 1252 insertions(+), 34 deletions(-)
diff --git a/common/utils/src/main/resources/error/error-conditions.json
b/common/utils/src/main/resources/error/error-conditions.json
index 4e83544ebddf..52516143f552 100644
--- a/common/utils/src/main/resources/error/error-conditions.json
+++ b/common/utils/src/main/resources/error/error-conditions.json
@@ -2059,6 +2059,11 @@
"Filter expression <filter> of type <type> is not a boolean."
]
},
+ "HASH_FILE_TYPE" : {
+ "message" : [
+ "The function <functionName> does not support elements of the
\"FILE\" type."
+ ]
+ },
"HASH_MAP_TYPE" : {
"message" : [
"Input to the function <functionName> cannot contain elements of the
\"MAP\" type. In Spark, same maps may have different hashcode, thus hash
expressions are prohibited on \"MAP\" elements. To restore previous behavior
set \"spark.sql.legacy.allowHashOnMapType\" to \"true\"."
@@ -3210,6 +3215,53 @@
],
"sqlState" : "42704"
},
+ "FILE_TYPE_IN_ROUTINE_SIGNATURE_UNSUPPORTED_MAP_KEY" : {
+ "message" : [
+ "The FILE type cannot be a map key in the return type of <routineType>
<routineName>. Use FILE only as a map value, array element, or struct field."
+ ],
+ "sqlState" : "42601"
+ },
+ "FILE_TYPE_IN_ROUTINE_SIGNATURE_UNSUPPORTED_QUALIFIER" : {
+ "message" : [
+ "The FILE type in <routineType> <routineName> does not support the
EXTERNAL qualifier. Use FILE without a qualifier."
+ ],
+ "sqlState" : "42601"
+ },
+ "FILE_TYPE_MISSING_QUALIFIER" : {
+ "message" : [
+ "FILE type requires the EXTERNAL qualifier in a column definition. Use
FILE EXTERNAL."
+ ],
+ "sqlState" : "42601"
+ },
+ "FILE_TYPE_UNKNOWN_WRITE" : {
+ "message" : [
+ "Column(s) <colNames> contain a FILE without the EXTERNAL qualifier,
which a table cannot store."
+ ],
+ "sqlState" : "42K01"
+ },
+ "FILE_TYPE_UNSUPPORTED_COLUMN_USAGE" : {
+ "message" : [
+ "The column <colName> of type <dataType> holds a FILE, which is not
comparable."
+ ],
+ "subClass" : {
+ "CLUSTERING_COLUMN" : {
+ "message" : [
+ "It cannot be a clustering column."
+ ]
+ },
+ "PARTITION_COLUMN" : {
+ "message" : [
+ "It cannot be a partition column."
+ ]
+ },
+ "WRITE_ORDERING_COLUMN" : {
+ "message" : [
+ "It cannot be a write-ordering column."
+ ]
+ }
+ },
+ "sqlState" : "0A000"
+ },
"FLATMAPGROUPSWITHSTATE_USER_FUNCTION_ERROR" : {
"message" : [
"An error occurred in the user provided function in
flatMapGroupsWithState. Reason: <reason>"
@@ -9695,6 +9747,11 @@
"Parameter markers are not allowed in <statement>."
]
},
+ "PARTITION_BY_FILE" : {
+ "message" : [
+ "Cannot use FILE type expressions to partition a DataFrame, but the
type of expression <expr> is <dataType>."
+ ]
+ },
"PARTITION_BY_VARIANT" : {
"message" : [
"Cannot use VARIANT producing expressions to partition a DataFrame,
but the type of expression <expr> is <dataType>."
@@ -9767,6 +9824,11 @@
"<property> is a reserved namespace property, <msg>."
]
},
+ "SET_OPERATION_ON_FILE_TYPE" : {
+ "message" : [
+ "Cannot have FILE type columns in a DataFrame that calls set
operations (INTERSECT, EXCEPT, etc.), but the type of column <colName> is
<dataType>."
+ ]
+ },
"SET_OPERATION_ON_MAP_TYPE" : {
"message" : [
"Cannot have MAP type columns in a set operation (INTERSECT, EXCEPT,
etc.), but the type of column <colName> is <dataType>."
diff --git
a/sql/api/src/main/scala/org/apache/spark/sql/errors/CompilationErrors.scala
b/sql/api/src/main/scala/org/apache/spark/sql/errors/CompilationErrors.scala
index 8ddf82225ca5..f369c3eea968 100644
--- a/sql/api/src/main/scala/org/apache/spark/sql/errors/CompilationErrors.scala
+++ b/sql/api/src/main/scala/org/apache/spark/sql/errors/CompilationErrors.scala
@@ -149,6 +149,12 @@ private[sql] trait CompilationErrors extends
DataTypeErrorsBase {
errorClass = "CANNOT_MODIFY_CONFIG",
messageParameters = Map("key" -> toSQLConf(key), "docroot" -> docroot))
}
+
+ def fileTypeMissingQualifierError(): Throwable = {
+ new AnalysisException(
+ errorClass = "FILE_TYPE_MISSING_QUALIFIER",
+ messageParameters = Map.empty)
+ }
}
private[sql] object CompilationErrors extends CompilationErrors
diff --git a/sql/api/src/main/scala/org/apache/spark/sql/types/FileType.scala
b/sql/api/src/main/scala/org/apache/spark/sql/types/FileType.scala
index 42ae683d8fc2..0071fba5eb66 100644
--- a/sql/api/src/main/scala/org/apache/spark/sql/types/FileType.scala
+++ b/sql/api/src/main/scala/org/apache/spark/sql/types/FileType.scala
@@ -25,30 +25,35 @@ import org.apache.spark.annotation.Unstable
/**
* The data type representing a reference to a file, with metadata describing
the file.
*
- * In SQL the type is named `FILE`, and the `EXTERNAL` keyword is planned to
be required when
- * declaring a table column, as in `CREATE TABLE t (f FILE EXTERNAL)`; until
then a bare `FILE` is
- * accepted wherever a type is. Its JSON representation is `"file external"`
for
- * `FileType.external` and `"file unknown"` for `FileType()`, except that an
external file in a
- * struct field is the plain `"file"`. A bare `"file"` is read as external
inside a struct field
- * and as unknown elsewhere.
+ * In SQL the type is named `FILE`. A table column must be declared with the
`EXTERNAL` keyword,
+ * as in `CREATE TABLE t (f FILE EXTERNAL)`, while the signature of a function
declares a bare
+ * `FILE`. Its JSON representation is `"file external"` for
`FileType.external` and
+ * `"file unknown"` for `FileType()`, except that an external file in a struct
field is the plain
+ * `"file"`. A bare `"file"` is read as external inside a struct field and as
unknown elsewhere.
*
* FileType is planned to be physically stored as a struct with the following
fields (see
* `FileType.FIELDS`), but it deliberately does not extend [[StructType]]:
- * - uri (STRING): the opaque URI to the file
+ * - uri (STRING): the URI of the referenced file, which may be absolute or
relative
* - offset (BIGINT): the start of the referenced byte range
- * - size (BIGINT): the size of the file in bytes
- * - content_type (STRING): the MIME/content type of the file
- * - checksum (STRING): an algorithm-tagged integrity token for the file,
e.g. "ETAG:{etag}"
+ * - size (BIGINT): the length of the referenced byte range
+ * - content_type (STRING): the MIME/content type of the referenced bytes
+ * - checksum (STRING): an algorithm-tagged integrity token for the
referenced bytes, e.g.
+ * "MD5:{digest}", or "ETAG:{etag}" for the whole file
* - inline (BINARY): the referenced bytes stored inline in the value
*
* FileType may be EXTERNAL (simple references, lifecycle independent of the
table) or UNKNOWN
* (mode not yet determined, such as the result of a cast or of a UDF). Mode
is part of type
* identity - files with different modes are distinct under `equals`.
*
- * FileType is planned to be not comparable -- it cannot be used in join
expressions, grouping
- * expressions, or as a partition/clustering column. Users can extract the uri
field for such
- * operations. This type currently only guarantees the schema-level pieces
(DDL and JSON); the
- * physical representation and most of the restrictions are added by later
parts.
+ * FileType is not comparable: it defines neither equality nor an ordering, as
it is not clear
+ * what equality of two files should mean. These uses of a FILE fail at
analysis: a join,
+ * grouping, sort or window key, `DISTINCT`, `INTERSECT`, `EXCEPT` and `UNION`
without `ALL`, the
+ * keys of `dropDuplicates`, a repartition or `REBALANCE` key, hash functions
such as `hash` and
+ * `xxhash64`, the key of a map built in a query or of a map in the return
type of a function, and
+ * a partition, bucket, clustering or write-ordering column of a table.
Aggregates that
+ * deduplicate or hash their input, such as `count(DISTINCT f)`, `collect_set`,
+ * `approx_count_distinct` and `mode`, are not rejected yet. Accessing the
fields of a FILE, such
+ * as `uri`, is planned together with its physical representation.
*
* @param mode
* the mode for this FileType column
diff --git
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/AlterTableValidation.scala
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/AlterTableValidation.scala
index a7ee3b6a6777..aed6f413039e 100644
---
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/AlterTableValidation.scala
+++
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/AlterTableValidation.scala
@@ -18,8 +18,8 @@
package org.apache.spark.sql.catalyst.analysis
import org.apache.spark.sql.catalyst.expressions.Cast
-import org.apache.spark.sql.catalyst.plans.logical.{AddColumns, AlterColumns,
AlterColumnSpec, AlterTableCommand, QualifiedColType, RenameColumn,
ReplaceColumns}
-import org.apache.spark.sql.catalyst.util.CharVarcharUtils
+import org.apache.spark.sql.catalyst.plans.logical.{AddColumns, AlterColumns,
AlterColumnSpec, AlterTableClusterBy, AlterTableCommand, QualifiedColType,
RenameColumn, ReplaceColumns}
+import org.apache.spark.sql.catalyst.util.{CharVarcharUtils, TypeUtils}
import
org.apache.spark.sql.connector.catalog.CatalogV2Implicits.MultipartIdentifierHelper
import org.apache.spark.sql.errors.QueryErrorsBase
import org.apache.spark.sql.types._
@@ -142,6 +142,10 @@ private[sql] object AlterTableValidation {
}
case _ =>
}
+
+ // FILE is not comparable, so it cannot be a clustering column.
+ case AlterTableClusterBy(table: ResolvedTable, Some(clusterBySpec)) =>
+ TypeUtils.checkNoFileTypeClusteringColumn(table.schema, clusterBySpec,
alter.conf.resolver)
case _ =>
}
}
diff --git
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/CheckAnalysis.scala
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/CheckAnalysis.scala
index 0a90dc3e7dae..39d5aeb5494d 100644
---
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/CheckAnalysis.scala
+++
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/CheckAnalysis.scala
@@ -29,7 +29,7 @@ import org.apache.spark.sql.catalyst.optimizer.InlineCTE
import org.apache.spark.sql.catalyst.plans.logical._
import
org.apache.spark.sql.catalyst.trees.TreePattern.{LATERAL_COLUMN_ALIAS_REFERENCE,
PLAN_EXPRESSION, UNRESOLVED_WINDOW_EXPRESSION}
import org.apache.spark.sql.catalyst.util.{CharVarcharUtils, StringUtils,
TypeUtils}
-import org.apache.spark.sql.connector.catalog.{CatalogManager, LookupCatalog}
+import org.apache.spark.sql.connector.catalog.{CatalogManager, CatalogV2Util,
LookupCatalog}
import org.apache.spark.sql.errors.{QueryCompilationErrors, QueryErrorsBase}
import org.apache.spark.sql.internal.SQLConf
import org.apache.spark.sql.types._
@@ -142,6 +142,10 @@ trait CheckAnalysis extends LookupCatalog with
QueryErrorsBase with PlanToString
dt.existsRecursively(_.isInstanceOf[VariantType])
}
+ protected def hasFileType(dt: DataType): Boolean = {
+ dt.existsRecursively(_.isInstanceOf[FileType])
+ }
+
protected def mapColumnInSetOperation(plan: LogicalPlan): Option[Attribute]
= plan match {
case _: Intersect | _: Except | _: Distinct =>
plan.output.find(a => hasMapType(a.dataType))
@@ -158,6 +162,16 @@ trait CheckAnalysis extends LookupCatalog with
QueryErrorsBase with PlanToString
case _ => None
}
+ protected def fileColumnInSetOperation(plan: LogicalPlan): Option[Attribute]
= plan match {
+ case _: Intersect | _: Except | _: Distinct =>
+ plan.output.find(a => hasFileType(a.dataType))
+ case d: Deduplicate =>
+ d.keys.find(a => hasFileType(a.dataType))
+ case d: DeduplicateWithinWatermark =>
+ d.keys.find(a => hasFileType(a.dataType))
+ case _ => None
+ }
+
protected def variantExprInPartitionExpression(plan: LogicalPlan):
Option[Expression] =
plan match {
case r: RepartitionByExpression =>
@@ -165,6 +179,14 @@ trait CheckAnalysis extends LookupCatalog with
QueryErrorsBase with PlanToString
case _ => None
}
+ // Covers both REPARTITION / DISTRIBUTE BY and the REBALANCE hint.
+ protected def fileExprInPartitionExpression(plan: LogicalPlan):
Option[Expression] =
+ plan match {
+ case r: HasPartitionExpressions =>
+ r.partitionExpressions.find(e => hasFileType(e.dataType))
+ case _ => None
+ }
+
private def checkLimitLikeClause(name: String, limitExpr: Expression): Unit
= {
limitExpr match {
case e if !e.foldable => limitExpr.failAnalysis(
@@ -973,6 +995,22 @@ trait CheckAnalysis extends LookupCatalog with
QueryErrorsBase with PlanToString
case create: V2CreateTablePlan =>
CreateTableValidation.validateV2CreateTablePlan(create,
SQLConf.get)
+ // A view can hold a FILE without a qualifier, which a table cannot
store. When the
+ // target and source are both in the session catalog,
`ResolveSessionCatalog` has
+ // already rewritten this into `CreateTableLikeCommand`, which
checks the source when
+ // it runs.
+ case CreateTableLike(_: ResolvedIdentifier, source, _, _, _, _, _) =>
+ source match {
+ case ResolvedTable(_, _, table, _) =>
+ TypeUtils.checkNoUnknownFileTypeInTableSchema(
+ CatalogV2Util.v2ColumnsToStructType(table.columns))
+ case view: ResolvedPersistentView =>
+ TypeUtils.checkNoUnknownFileTypeInTableSchema(view.info.schema)
+ case ResolvedTempView(_, metadata) =>
+ TypeUtils.checkNoUnknownFileTypeInTableSchema(metadata.schema)
+ case _ =>
+ }
+
case write: V2WriteCommand if write.resolved =>
write.query.schema.foreach(f =>
TypeUtils.failWithIntervalType(f.dataType))
@@ -1103,6 +1141,14 @@ trait CheckAnalysis extends LookupCatalog with
QueryErrorsBase with PlanToString
origin = operator.origin
)
+ // FILE is not comparable (it has no defined equality), so it cannot
be in a set
+ // operation.
+ case o if fileColumnInSetOperation(o).isDefined =>
+ throw QueryCompilationErrors.unsupportedSetOperationOnFileType(
+ fileCol = fileColumnInSetOperation(o).get,
+ origin = operator.origin
+ )
+
case o if variantExprInPartitionExpression(o).isDefined =>
val variantExpr = variantExprInPartitionExpression(o).get
o.failAnalysis(
@@ -1111,6 +1157,15 @@ trait CheckAnalysis extends LookupCatalog with
QueryErrorsBase with PlanToString
"expr" -> toSQLExpr(variantExpr),
"dataType" -> toSQLType(variantExpr.dataType)))
+ // FILE is not comparable, so it cannot be a partitioning/DISTRIBUTE
BY key.
+ case o if fileExprInPartitionExpression(o).isDefined =>
+ val fileExpr = fileExprInPartitionExpression(o).get
+ o.failAnalysis(
+ errorClass = "UNSUPPORTED_FEATURE.PARTITION_BY_FILE",
+ messageParameters = Map(
+ "expr" -> toSQLExpr(fileExpr),
+ "dataType" -> toSQLType(fileExpr.dataType)))
+
case o if o.expressions.exists(!_.deterministic) &&
!operatorAllowsNonDeterministicExpressions(o) &&
!o.isInstanceOf[Project] &&
@@ -1171,6 +1226,7 @@ trait CheckAnalysis extends LookupCatalog with
QueryErrorsBase with PlanToString
NanosTimestampSubtractionCheck.checkOperator(operator)
}
checkCollectedMetrics(plan)
+ checkFileTypeInUserDefinedRoutines(plan)
extendedCheckRules.foreach(_(plan))
plan.foreachUp {
case o if !o.resolved =>
@@ -1186,6 +1242,33 @@ trait CheckAnalysis extends LookupCatalog with
QueryErrorsBase with PlanToString
}
}
+ /**
+ * Checks that the [[UserDefinedExpression]]s in a query declare only a
plain FILE in their
+ * return type, as
[[TypeUtils.checkNoQualifierInRegisteredRoutineReturnType]] does when a
+ * routine is registered. This covers routines whose signature is not
checked when they are
+ * created, such as UDFs that are not registered and UDAF classes registered
with
+ * `CREATE FUNCTION ... AS`. SQL functions are checked by `CREATE FUNCTION`.
V2 catalog functions
+ * are covered only when they are bound as an [[ApplyFunctionExpression]]. A
non-scalar Python
+ * UDF is skipped, as its data type is the schema of the rows it returns. As
in
+ * `checkAnalysis0`, sub-plans that are already analyzed are skipped, as
they were checked when
+ * they were analyzed.
+ */
+ private def checkFileTypeInUserDefinedRoutines(plan: LogicalPlan): Unit = {
+ def check(operator: LogicalPlan): Unit = if (!operator.analyzed) {
+ operator.expressions.foreach(_.foreach {
+ case udf: PythonUDF if !PythonUDF.isScalarPythonUDF(udf) =>
+ case routine: UserDefinedExpression
+ if routine.dataType.existsRecursively(_.isInstanceOf[FileType]) =>
+
TypeUtils.checkNoQualifierInRegisteredRoutineReturnType(routine.dataType,
routine.name)
+ case _ =>
+ })
+ operator.children.foreach(check)
+ }
+ if (SQLConf.get.isFileTypeEnabled) {
+ check(plan)
+ }
+ }
+
private def getAllExpressions(plan: LogicalPlan): Seq[Expression] = {
plan match {
// We only resolve `groupingExpressions` if `aggregateExpressions` is
resolved first (See
diff --git
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/CreateTableValidation.scala
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/CreateTableValidation.scala
index 4fd52da14f2b..7aeedde1b0e5 100644
---
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/CreateTableValidation.scala
+++
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/CreateTableValidation.scala
@@ -18,15 +18,19 @@
package org.apache.spark.sql.catalyst.analysis
import org.apache.spark.sql.AnalysisException
-import org.apache.spark.sql.catalyst.plans.logical.V2CreateTablePlan
+import org.apache.spark.sql.catalyst.plans.logical.{V2CreateTableAsSelectPlan,
V2CreateTablePlan}
import org.apache.spark.sql.catalyst.util.{TypeUtils,
WriteDistributionAndOrdering}
import org.apache.spark.sql.connector.catalog.CatalogV2Implicits._
+import org.apache.spark.sql.connector.expressions.ClusterByTransform
import org.apache.spark.sql.errors.DataTypeErrors.toSQLId
import org.apache.spark.sql.internal.SQLConf
import org.apache.spark.sql.util.SchemaUtils
import org.apache.spark.util.ArrayImplicits._
-/** Validates partition references, column types, write ordering and generated
columns. */
+/**
+ * Validates partition references, column types (including the FILE type
rules), write ordering
+ * and generated columns.
+ */
private[sql] object CreateTableValidation {
def validateV2CreateTablePlan(create: V2CreateTablePlan, conf: SQLConf):
Unit = {
val references = create.partitioning.flatMap(_.references).toSet
@@ -61,6 +65,30 @@ private[sql] object CreateTableValidation {
create.tableSchema.foreach(f => TypeUtils.failWithIntervalType(f.dataType))
TypeUtils.failUnsupportedDataType(create.tableSchema, conf)
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)
+ case _ =>
+ TypeUtils.checkFileTypeHasQualifier(create.tableSchema)
+ }
+ // FILE is not comparable, so it cannot be a partition, clustering or
write-ordering column.
+ create.partitioning.foreach { transform =>
+ val usage = transform match {
+ case _: ClusterByTransform => "CLUSTERING_COLUMN"
+ case _ => "PARTITION_COLUMN"
+ }
+ transform.references.foreach { ref =>
+
create.tableSchema.findNestedField(ref.fieldNames.toImmutableArraySeq).foreach {
+ case (_, field) => TypeUtils.checkNoFileTypeInColumnUsage(field,
usage)
+ }
+ }
+ }
+ create.writeOrdering.flatMap(_.expression.references).foreach { ref =>
+
create.tableSchema.findNestedField(ref.fieldNames.toImmutableArraySeq).foreach {
+ case (_, field) => TypeUtils.checkNoFileTypeInColumnUsage(field,
"WRITE_ORDERING_COLUMN")
+ }
+ }
// Validate generated column expressions
create.columns.foreach { col =>
diff --git
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ResolveSchemaEvolution.scala
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ResolveSchemaEvolution.scala
index 2f7e9f81129b..785c55c584e9 100644
---
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ResolveSchemaEvolution.scala
+++
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ResolveSchemaEvolution.scala
@@ -26,7 +26,7 @@ import org.apache.spark.sql.catalyst.plans.logical._
import org.apache.spark.sql.catalyst.rules.Rule
import org.apache.spark.sql.catalyst.trees.TreePattern.COMMAND
import org.apache.spark.sql.catalyst.types.DataTypeUtils
-import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.sql.catalyst.util.{CaseInsensitiveMap, TypeUtils}
import org.apache.spark.sql.connector.catalog.{CatalogV2Util, Identifier,
SupportsSchemaEvolution, Table, TableCatalog, TableChange}
import org.apache.spark.sql.connector.catalog.TableChange.ColumnChange
import org.apache.spark.sql.errors.{QueryCompilationErrors,
QueryExecutionErrors}
@@ -50,6 +50,14 @@ object ResolveSchemaEvolution extends Rule[LogicalPlan] {
case write: WriteWithSchemaEvolution if
write.pendingSchemaChanges.nonEmpty =>
write.table match {
case relation @ ExtractV2CatalogAndIdentifier(catalog, ident) =>
+ // A table cannot store a FILE without a qualifier, so schema
evolution cannot add one.
+ // This is checked before the catalog changes the table.
+
TypeUtils.checkNoUnknownFileTypeInColumns(write.pendingSchemaChanges.collect {
+ case add: TableChange.AddColumn =>
+ add.fieldNames.toImmutableArraySeq -> add.dataType
+ case update: TableChange.UpdateColumnType =>
+ update.fieldNames.toImmutableArraySeq -> update.newDataType
+ })
if (relation.skipSchemaResolution && relation.autoSchemaEvolution) {
val dataSource = relation.table.properties().getOrDefault(
TableCatalog.PROP_PROVIDER, relation.table.getClass.getName)
diff --git
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/resolver/OperatorWithUncomparableTypeValidator.scala
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/resolver/OperatorWithUncomparableTypeValidator.scala
index 512dd45b5da6..59dc0e4967cd 100644
---
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/resolver/OperatorWithUncomparableTypeValidator.scala
+++
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/resolver/OperatorWithUncomparableTypeValidator.scala
@@ -20,20 +20,21 @@ package org.apache.spark.sql.catalyst.analysis.resolver
import org.apache.spark.sql.catalyst.expressions.Attribute
import org.apache.spark.sql.catalyst.plans.logical.{Distinct, LogicalPlan,
SetOperation}
import org.apache.spark.sql.errors.QueryCompilationErrors
-import org.apache.spark.sql.types.{DataType, MapType, VariantType}
+import org.apache.spark.sql.types.{DataType, FileType, MapType, VariantType}
/**
* [[OperatorWithUncomparableTypeValidator]] performs the validation of a
logical plan to ensure
* that it (if it is [[Distinct]] or [[SetOperation]]) does not contain any
uncomparable types:
- * [[VariantType]] or [[MapType]].
+ * [[VariantType]], [[MapType]] or [[FileType]].
*/
object OperatorWithUncomparableTypeValidator {
/**
* Validates that the provided logical plan does not contain any
uncomparable types:
- * [[VariantType]] or [[MapType]] (throws a specific user-facing error if it
does). Operators
- * that are not supported are [[Distinct]] and [[SetOperation]] ([[Union]],
[[Except]],
- * [[Intersect]]).
+ * [[VariantType]], [[MapType]] or [[FileType]] (throws a specific
user-facing error if it
+ * does). Operators that are not supported are [[Distinct]] and
[[SetOperation]] ([[Except]],
+ * [[Intersect]]). [[Union]] is not a [[SetOperation]], so UNION ALL is
allowed, while UNION
+ * DISTINCT is rejected through the [[Distinct]] above it.
*/
def validate(operator: LogicalPlan, output: Seq[Attribute]): Unit = {
operator match {
@@ -46,6 +47,10 @@ object OperatorWithUncomparableTypeValidator {
if (hasVariantType(element.dataType)) {
throwUnsupportedSetOperationOnVariantType(element,
unsupportedOperator)
}
+
+ if (hasFileType(element.dataType)) {
+ throwUnsupportedSetOperationOnFileType(element,
unsupportedOperator)
+ }
}
case _ =>
}
@@ -59,6 +64,10 @@ object OperatorWithUncomparableTypeValidator {
dt.existsRecursively(_.isInstanceOf[VariantType])
}
+ private def hasFileType(dt: DataType): Boolean = {
+ dt.existsRecursively(_.isInstanceOf[FileType])
+ }
+
private def throwUnsupportedSetOperationOnMapType(
mapCol: Attribute,
unresolvedPlan: LogicalPlan): Unit = {
@@ -76,4 +85,13 @@ object OperatorWithUncomparableTypeValidator {
origin = unresolvedPlan.origin
)
}
+
+ private def throwUnsupportedSetOperationOnFileType(
+ fileCol: Attribute,
+ unresolvedPlan: LogicalPlan): Unit = {
+ throw QueryCompilationErrors.unsupportedSetOperationOnFileType(
+ fileCol = fileCol,
+ origin = unresolvedPlan.origin
+ )
+ }
}
diff --git
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/resolver/RepartitionByExpressionResolver.scala
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/resolver/RepartitionByExpressionResolver.scala
index 01636f35f2c5..32328356aa9b 100644
---
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/resolver/RepartitionByExpressionResolver.scala
+++
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/resolver/RepartitionByExpressionResolver.scala
@@ -20,7 +20,7 @@ package org.apache.spark.sql.catalyst.analysis.resolver
import org.apache.spark.sql.catalyst.analysis.AnalysisErrorAt
import org.apache.spark.sql.catalyst.expressions.Attribute
import org.apache.spark.sql.catalyst.plans.logical.{LogicalPlan,
RepartitionByExpression}
-import org.apache.spark.sql.types.{DataType, VariantType}
+import org.apache.spark.sql.types.{DataType, FileType, VariantType}
/**
* Resolver class that resolves [[RepartitionByExpression]] operators.
@@ -97,6 +97,7 @@ class RepartitionByExpressionResolver(resolver: Resolver,
expressionResolver: Ex
)
validateRepartitionByVariant(resolvedRepartitionByExpression)
+ validateRepartitionByFile(resolvedRepartitionByExpression)
if (!resolvedChildWithMissingAttributes.eq(resolvedChild)) {
retainOriginalOutput(
@@ -128,4 +129,24 @@ class RepartitionByExpressionResolver(resolver: Resolver,
expressionResolver: Ex
private def hasVariantType(dt: DataType): Boolean = {
dt.existsRecursively(_.isInstanceOf[VariantType])
}
+
+ // FILE is not comparable, so it cannot be a DISTRIBUTE BY / repartition key.
+ private def validateRepartitionByFile(
+ repartitionByExpression: RepartitionByExpression): Unit = {
+ val fileExpressionInPartitionExpression =
+ repartitionByExpression.partitionExpressions.find(e =>
hasFileType(e.dataType))
+
+ if (fileExpressionInPartitionExpression.isDefined) {
+ val fileExpr = fileExpressionInPartitionExpression.get
+ repartitionByExpression.failAnalysis(
+ errorClass = "UNSUPPORTED_FEATURE.PARTITION_BY_FILE",
+ messageParameters =
+ Map("expr" -> toSQLExpr(fileExpr), "dataType" ->
toSQLType(fileExpr.dataType))
+ )
+ }
+ }
+
+ private def hasFileType(dt: DataType): Boolean = {
+ dt.existsRecursively(_.isInstanceOf[FileType])
+ }
}
diff --git
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/resolver/Resolver.scala
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/resolver/Resolver.scala
index 61c7170af464..d9f1b750b480 100644
---
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/resolver/Resolver.scala
+++
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/resolver/Resolver.scala
@@ -549,7 +549,7 @@ class Resolver(
/**
* [[Distinct]] operator doesn't require any special resolution.
* We validate results of the resolution using the
[[OperatorWithUncomparableTypeValidator]]
- * ([[MapType]] and [[VariantType]] are not supported under [[Distinct]]
operator).
+ * ([[MapType]], [[VariantType]] and [[FileType]] are not supported under
[[Distinct]] operator).
*
* `hiddenOutput` and `availableAliases` are reset when [[Distinct]] is
reached during tree
* traversal.
diff --git
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/ExprUtils.scala
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/ExprUtils.scala
index 1320f614ac7d..0f4d617408cf 100644
---
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/ExprUtils.scala
+++
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/ExprUtils.scala
@@ -225,8 +225,10 @@ object ExprUtils extends EvalHelper with QueryErrorsBase {
messageParameters = Map("sqlExpr" -> expr.sql))
}
- // Check if the data type of expr is orderable.
- if (expr.dataType.existsRecursively(_.isInstanceOf[VariantType])) {
+ // VARIANT and FILE have no defined equality or ordering, so they cannot
be grouping keys.
+ // Other types that are not orderable, such as MAP, are handled
elsewhere.
+ if (expr.dataType.existsRecursively(
+ t => t.isInstanceOf[VariantType] || t.isInstanceOf[FileType])) {
expr.failAnalysis(
errorClass = "GROUP_EXPRESSION_TYPE_IS_NOT_ORDERABLE",
messageParameters = Map(
diff --git
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/hash.scala
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/hash.scala
index eb4004f34f29..56d324fc2a6d 100644
---
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/hash.scala
+++
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/hash.scala
@@ -378,6 +378,10 @@ abstract class HashExpression[E] extends Expression {
dt.existsRecursively(_.isInstanceOf[VariantType])
}
+ private def hasFileType(dt: DataType): Boolean = {
+ dt.existsRecursively(_.isInstanceOf[FileType])
+ }
+
override def checkInputDataTypes(): TypeCheckResult = {
if (children.length < 1) {
throw QueryCompilationErrors.wrongNumArgsError(
@@ -392,6 +396,12 @@ abstract class HashExpression[E] extends Expression {
DataTypeMismatch(
errorSubClass = "HASH_VARIANT_TYPE",
messageParameters = Map("functionName" -> toSQLId(prettyName)))
+ } else if (children.exists(child => hasFileType(child.dataType))) {
+ // FILE is not comparable, so hashing it with a hash function such as
`hash` or `xxhash64` is
+ // rejected. Grouping, joining and partitioning by a FILE are rejected
by the analyzer.
+ DataTypeMismatch(
+ errorSubClass = "HASH_FILE_TYPE",
+ messageParameters = Map("functionName" -> toSQLId(prettyName)))
} else {
TypeCheckResult.TypeCheckSuccess
}
diff --git
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/v2AlterTableCommands.scala
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/v2AlterTableCommands.scala
index 7097eee07056..8a424fa876f1 100644
---
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/v2AlterTableCommands.scala
+++
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/v2AlterTableCommands.scala
@@ -113,6 +113,7 @@ case class AddColumns(
columnsToAdd.foreach { c =>
TypeUtils.failWithIntervalType(c.dataType)
TypeUtils.failUnsupportedDataType(c.dataType, conf)
+ TypeUtils.checkFileTypeHasQualifier(c.dataType)
}
override lazy val resolved: Boolean = table.resolved &&
columnsToAdd.forall(_.resolved)
@@ -146,6 +147,7 @@ case class ReplaceColumns(
columnsToAdd.foreach { c =>
TypeUtils.failWithIntervalType(c.dataType)
TypeUtils.failUnsupportedDataType(c.dataType, conf)
+ TypeUtils.checkFileTypeHasQualifier(c.dataType)
}
override lazy val resolved: Boolean = table.resolved &&
columnsToAdd.forall(_.resolved)
@@ -272,6 +274,8 @@ case class AlterColumns(
table: LogicalPlan,
specs: Seq[AlterColumnSpec],
fromCommentOn: Boolean = false) extends AlterTableCommand {
+ specs.foreach(_.newDataType.foreach(TypeUtils.checkFileTypeHasQualifier))
+
override def changes: Seq[TableChange] = {
specs.flatMap { spec =>
val column = spec.column
diff --git
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/TypeUtils.scala
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/TypeUtils.scala
index 23a880f15540..bedf3c529af2 100644
---
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/TypeUtils.scala
+++
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/TypeUtils.scala
@@ -17,14 +17,16 @@
package org.apache.spark.sql.catalyst.util
-import org.apache.spark.sql.catalyst.analysis.{AnalysisErrorAt,
TypeCheckResult, TypeCoercion}
+import org.apache.spark.sql.catalyst.analysis.{AnalysisErrorAt, Resolver,
TypeCheckResult, TypeCoercion}
import org.apache.spark.sql.catalyst.analysis.TypeCheckResult.DataTypeMismatch
-import org.apache.spark.sql.catalyst.expressions.{Expression, RowOrdering}
+import org.apache.spark.sql.catalyst.catalog.ClusterBySpec
+import org.apache.spark.sql.catalyst.expressions.{Attribute, Expression,
RowOrdering}
import
org.apache.spark.sql.catalyst.expressions.st.STExpressionUtils.isGeoSpatialType
import org.apache.spark.sql.catalyst.types.{PhysicalDataType,
PhysicalNumericType}
import org.apache.spark.sql.errors.{DataTypeErrors, QueryCompilationErrors,
QueryErrorsBase}
import org.apache.spark.sql.internal.SQLConf
import org.apache.spark.sql.types._
+import org.apache.spark.util.ArrayImplicits._
/**
* Functions to help with checking for valid data types and value comparison
of various types.
@@ -70,7 +72,8 @@ object TypeUtils extends QueryErrorsBase {
}
def checkForMapKeyType(keyType: DataType): TypeCheckResult = {
- if (keyType.existsRecursively(dt => dt.isInstanceOf[MapType] ||
dt.isInstanceOf[VariantType])) {
+ if (keyType.existsRecursively(dt => dt.isInstanceOf[MapType] ||
dt.isInstanceOf[VariantType] ||
+ dt.isInstanceOf[FileType])) {
DataTypeMismatch(
errorSubClass = "INVALID_MAP_KEY_TYPE",
messageParameters = Map(
@@ -162,4 +165,139 @@ object TypeUtils extends QueryErrorsBase {
messageParameters = scala.collection.immutable.Map.empty)
}
}
+
+ private def containsUnknownFileType(dataType: DataType): Boolean = {
+ dataType.existsRecursively {
+ case ft: FileType => ft.mode == FileTypeMode.UNKNOWN
+ case _ => false
+ }
+ }
+
+ /**
+ * Fails if a FILE in `dataType`, at any nesting depth, has no qualifier, as
a FILE in a table
+ * column definition must be declared `FILE EXTERNAL`.
+ */
+ def checkFileTypeHasQualifier(dataType: DataType): Unit = {
+ if (containsUnknownFileType(dataType)) {
+ throw QueryCompilationErrors.fileTypeMissingQualifierError()
+ }
+ }
+
+ /**
+ * Fails if any of `columns`, which a write such as CREATE TABLE AS SELECT
stores in a table,
+ * holds a FILE without a qualifier, as a table cannot store one.
+ */
+ def checkNoUnknownFileTypeWrite(columns: Seq[Attribute]): Unit = {
+ checkNoUnknownFileTypeInColumns(columns.map(c => Seq(c.name) ->
c.dataType))
+ }
+
+ /**
+ * Fails if a column of `schema`, which a command such as CREATE TABLE LIKE
stores in a new
+ * table, holds a FILE without a qualifier.
+ */
+ def checkNoUnknownFileTypeInTableSchema(schema: StructType): Unit = {
+ checkNoUnknownFileTypeInColumns(schema.fields.toSeq.map(f => Seq(f.name)
-> f.dataType))
+ }
+
+ /**
+ * Fails if any of `columns`, given as the path of a column and the type it
would be stored
+ * with, holds a FILE without a qualifier.
+ */
+ def checkNoUnknownFileTypeInColumns(columns: Seq[(Seq[String], DataType)]):
Unit = {
+ val unknownCols = columns.collect {
+ case (path, dataType) if containsUnknownFileType(dataType) => path
+ }
+ if (unknownCols.nonEmpty) {
+ throw QueryCompilationErrors.fileTypeUnknownWriteError(unknownCols)
+ }
+ }
+
+ /**
+ * Fails if `field` holds a FILE, as FILE is not comparable and so cannot be
a partition column
+ * (`usage` is `PARTITION_COLUMN`), a clustering column
(`CLUSTERING_COLUMN`) or a write-ordering
+ * column (`WRITE_ORDERING_COLUMN`).
+ */
+ def checkNoFileTypeInColumnUsage(field: StructField, usage: String): Unit = {
+ if (field.dataType.existsRecursively(_.isInstanceOf[FileType])) {
+ throw QueryCompilationErrors.fileTypeUnsupportedColumnUsageError(field,
usage)
+ }
+ }
+
+ /**
+ * Fails if a clustering column of `clusterBySpec` holds a FILE. Only a
schema that holds a FILE
+ * is checked. A column is looked up as the clustering normalizer does
+ * (`SchemaUtils.findColumnPosition`): the first match, descending into
structs and the struct
+ * elements of arrays. A column that is not found is left to the normalizer,
which reports it.
+ */
+ def checkNoFileTypeClusteringColumn(
+ schema: StructType,
+ clusterBySpec: ClusterBySpec,
+ resolver: Resolver): Unit = {
+ def find(schema: StructType, path: Seq[String]): Option[StructField] =
+ schema.fields.find(f => resolver(f.name, path.head)).flatMap { field =>
+ (path.tail, field.dataType) match {
+ case (Seq(), _) => Some(field)
+ case (tail, s: StructType) => find(s, tail)
+ case (tail, ArrayType(s: StructType, _)) => find(s, tail)
+ case _ => None
+ }
+ }
+ if (schema.existsRecursively(_.isInstanceOf[FileType])) {
+
clusterBySpec.columnNames.map(_.fieldNames.toImmutableArraySeq).filter(_.nonEmpty)
+ .flatMap(find(schema, _))
+ .foreach(checkNoFileTypeInColumnUsage(_, "CLUSTERING_COLUMN"))
+ }
+ }
+
+ /**
+ * Fails if a FILE in the parameter or return types of a routine has a
qualifier. Routines
+ * declare a plain FILE. `routineName` is quoted already.
+ */
+ def checkNoQualifierInRoutineSignature(
+ dataTypes: Seq[DataType],
+ routineType: String,
+ routineName: String): Unit = {
+ val hasQualified = dataTypes.exists(_.existsRecursively {
+ case ft: FileType => ft.mode != FileTypeMode.UNKNOWN
+ case _ => false
+ })
+ if (hasQualified) {
+ throw
QueryCompilationErrors.fileTypeInRoutineSignatureUnsupportedQualifierError(
+ routineType, routineName)
+ }
+ }
+
+ /**
+ * Fails if the return type of a function holds a FILE in a map key. Map
construction already
+ * rejects such a key through [[checkForMapKeyType]].
+ */
+ def checkNoFileTypeMapKeyInReturnType(returnType: DataType, routineName:
String): Unit = {
+ def fileTypeInMapKey(dt: DataType): Boolean = dt match {
+ case mt: MapType =>
+ mt.keyType.existsRecursively(_.isInstanceOf[FileType]) ||
fileTypeInMapKey(mt.valueType)
+ case at: ArrayType => fileTypeInMapKey(at.elementType)
+ case st: StructType => st.fields.exists(f =>
fileTypeInMapKey(f.dataType))
+ case _ => false
+ }
+ if (fileTypeInMapKey(returnType)) {
+ throw
QueryCompilationErrors.fileTypeInRoutineSignatureUnsupportedMapKeyError(
+ "function", routineName)
+ }
+ }
+
+ /**
+ * Checks the return type of a function that is not created by SQL DDL, for
example a UDF
+ * registered through `spark.udf.register`, as
[[checkNoQualifierInRoutineSignature]] and
+ * [[checkNoFileTypeMapKeyInReturnType]] do for SQL functions. `routineName`
is the unquoted
+ * name of the function. Does nothing when the FILE type is disabled.
+ */
+ def checkNoQualifierInRegisteredRoutineReturnType(
+ returnType: DataType,
+ routineName: String): Unit = {
+ if (SQLConf.get.isFileTypeEnabled) {
+ val quotedName = toSQLId(Seq(routineName))
+ checkNoQualifierInRoutineSignature(Seq(returnType), "function",
quotedName)
+ checkNoFileTypeMapKeyInReturnType(returnType, quotedName)
+ }
+ }
}
diff --git
a/sql/catalyst/src/main/scala/org/apache/spark/sql/errors/QueryCompilationErrors.scala
b/sql/catalyst/src/main/scala/org/apache/spark/sql/errors/QueryCompilationErrors.scala
index 81732e70defb..e94d4cc21e80 100644
---
a/sql/catalyst/src/main/scala/org/apache/spark/sql/errors/QueryCompilationErrors.scala
+++
b/sql/catalyst/src/main/scala/org/apache/spark/sql/errors/QueryCompilationErrors.scala
@@ -453,6 +453,17 @@ private[sql] object QueryCompilationErrors extends
QueryErrorsBase with Compilat
)
}
+ def unsupportedSetOperationOnFileType(fileCol: Attribute, origin: Origin):
Throwable = {
+ new AnalysisException(
+ errorClass = "UNSUPPORTED_FEATURE.SET_OPERATION_ON_FILE_TYPE",
+ messageParameters = Map(
+ "colName" -> toSQLId(fileCol.name),
+ "dataType" -> toSQLType(fileCol.dataType)
+ ),
+ origin = origin
+ )
+ }
+
def nonPartitionColError(partitionName: String): Throwable = {
new AnalysisException(
errorClass = "NON_PARTITION_COLUMN",
@@ -5248,6 +5259,36 @@ private[sql] object QueryCompilationErrors extends
QueryErrorsBase with Compilat
messageParameters = Map.empty)
}
+ def fileTypeUnknownWriteError(colNames: Seq[Seq[String]]): Throwable = {
+ new AnalysisException(
+ errorClass = "FILE_TYPE_UNKNOWN_WRITE",
+ messageParameters = Map("colNames" ->
colNames.map(toSQLId).mkString("[", ", ", "]")))
+ }
+
+ def fileTypeUnsupportedColumnUsageError(field: StructField, usage: String):
Throwable = {
+ new AnalysisException(
+ errorClass = s"FILE_TYPE_UNSUPPORTED_COLUMN_USAGE.$usage",
+ messageParameters = Map(
+ "colName" -> toSQLId(field.name),
+ "dataType" -> toSQLType(field.dataType)))
+ }
+
+ def fileTypeInRoutineSignatureUnsupportedQualifierError(
+ routineType: String,
+ routineName: String): Throwable = {
+ new AnalysisException(
+ errorClass = "FILE_TYPE_IN_ROUTINE_SIGNATURE_UNSUPPORTED_QUALIFIER",
+ messageParameters = Map("routineType" -> routineType, "routineName" ->
routineName))
+ }
+
+ def fileTypeInRoutineSignatureUnsupportedMapKeyError(
+ routineType: String,
+ routineName: String): Throwable = {
+ new AnalysisException(
+ errorClass = "FILE_TYPE_IN_ROUTINE_SIGNATURE_UNSUPPORTED_MAP_KEY",
+ messageParameters = Map("routineType" -> routineType, "routineName" ->
routineName))
+ }
+
def unsupportedTimeTypeError(): Throwable = {
new AnalysisException(
errorClass = "UNSUPPORTED_TIME_TYPE",
diff --git
a/sql/core/src/main/scala/org/apache/spark/sql/UDTFRegistration.scala
b/sql/core/src/main/scala/org/apache/spark/sql/UDTFRegistration.scala
index 06f103c0d69a..720ab9c11cbc 100644
--- a/sql/core/src/main/scala/org/apache/spark/sql/UDTFRegistration.scala
+++ b/sql/core/src/main/scala/org/apache/spark/sql/UDTFRegistration.scala
@@ -20,6 +20,7 @@ package org.apache.spark.sql
import org.apache.spark.annotation.Evolving
import org.apache.spark.internal.Logging
import org.apache.spark.sql.catalyst.analysis.TableFunctionRegistry
+import org.apache.spark.sql.catalyst.util.TypeUtils
import org.apache.spark.sql.execution.python.UserDefinedPythonTableFunction
/**
@@ -44,6 +45,9 @@ private[sql] class UDTFRegistration private[sql]
(tableFunctionRegistry: TableFu
| udfDeterministic: ${udtf.udfDeterministic}
""".stripMargin)
+ // A FILE in the return type cannot have a qualifier. A UDTF with an
analyze method has no
+ // static return type here; the analyzer checks it instead.
+
udtf.returnType.foreach(TypeUtils.checkNoQualifierInRegisteredRoutineReturnType(_,
name))
tableFunctionRegistry.createOrReplaceTempFunction(
name, udtf.builder(_,
SparkSession.getActiveSession.get.sessionState.sqlParser),
source = "python_udtf")
diff --git
a/sql/core/src/main/scala/org/apache/spark/sql/catalyst/analysis/ResolveSessionCatalog.scala
b/sql/core/src/main/scala/org/apache/spark/sql/catalyst/analysis/ResolveSessionCatalog.scala
index 550b8b52104f..fe9a25f30727 100644
---
a/sql/core/src/main/scala/org/apache/spark/sql/catalyst/analysis/ResolveSessionCatalog.scala
+++
b/sql/core/src/main/scala/org/apache/spark/sql/catalyst/analysis/ResolveSessionCatalog.scala
@@ -24,7 +24,7 @@ import org.apache.spark.sql.catalyst.catalog.{ClusterBySpec,
HiveTableRelation}
import org.apache.spark.sql.catalyst.expressions.{Alias, Attribute}
import org.apache.spark.sql.catalyst.plans.logical._
import org.apache.spark.sql.catalyst.rules.Rule
-import org.apache.spark.sql.catalyst.util.{quoteIfNeeded, toPrettySQL}
+import org.apache.spark.sql.catalyst.util.{quoteIfNeeded, toPrettySQL,
TypeUtils}
import org.apache.spark.sql.connector.catalog.{CatalogManager, LookupCatalog,
V1Table, ViewCatalog}
import org.apache.spark.sql.errors.QueryCompilationErrors
import org.apache.spark.sql.execution.command._
@@ -71,6 +71,9 @@ class ResolveSessionCatalog(val catalogManager:
CatalogManager)
case AlterTableClusterBy(ResolvedTable(catalog, _, table: V1Table, _),
clusterBySpecOpt)
if supportsV1Command(catalog) =>
+ // FILE is not comparable, so it cannot be a clustering column.
+ clusterBySpecOpt.foreach(
+ TypeUtils.checkNoFileTypeClusteringColumn(table.schema, _,
conf.resolver))
val prop = Map(ClusterBySpec.toProperty(table.schema,
clusterBySpecOpt.getOrElse(ClusterBySpec(Nil)), conf.resolver))
AlterTableSetPropertiesCommand(table.catalogTable.identifier, prop,
isView = false)
diff --git
a/sql/core/src/main/scala/org/apache/spark/sql/classic/UDFRegistration.scala
b/sql/core/src/main/scala/org/apache/spark/sql/classic/UDFRegistration.scala
index a35c97c455a5..af8e0e10d453 100644
--- a/sql/core/src/main/scala/org/apache/spark/sql/classic/UDFRegistration.scala
+++ b/sql/core/src/main/scala/org/apache/spark/sql/classic/UDFRegistration.scala
@@ -26,12 +26,15 @@ import org.apache.spark.sql
import org.apache.spark.sql.api.java._
import org.apache.spark.sql.catalyst.JavaTypeInference
import org.apache.spark.sql.catalyst.analysis.FunctionRegistry
+import org.apache.spark.sql.catalyst.encoders.encoderFor
import org.apache.spark.sql.catalyst.expressions.Expression
+import org.apache.spark.sql.catalyst.util.TypeUtils
import org.apache.spark.sql.classic.UserDefinedFunctionUtils.toScalaUDF
import org.apache.spark.sql.errors.QueryCompilationErrors
import org.apache.spark.sql.execution.aggregate.{ScalaAggregator, ScalaUDAF}
import org.apache.spark.sql.execution.python.UserDefinedPythonFunction
import org.apache.spark.sql.expressions.{SparkUserDefinedFunction,
UserDefinedAggregateFunction, UserDefinedAggregator, UserDefinedFunction}
+import org.apache.spark.sql.internal.SQLConf
import org.apache.spark.sql.types.DataType
/**
@@ -61,6 +64,8 @@ class UDFRegistration private[sql] (session: SparkSession,
functionRegistry: Fun
| udfDeterministic: ${udf.udfDeterministic}
""".stripMargin)
+ // A FILE in the return type cannot have a qualifier.
+ TypeUtils.checkNoQualifierInRegisteredRoutineReturnType(udf.dataType, name)
functionRegistry.createOrReplaceTempFunction(name, udf.builder,
"python_udf")
}
@@ -78,6 +83,8 @@ class UDFRegistration private[sql] (session: SparkSession,
functionRegistry: Fun
@deprecated("Aggregator[IN, BUF, OUT] should now be registered as a UDF" +
" via the functions.udaf(agg) method.", "3.0.0")
def register(name: String, udaf: UserDefinedAggregateFunction):
UserDefinedAggregateFunction = {
+ // A FILE in the return type cannot have a qualifier.
+ TypeUtils.checkNoQualifierInRegisteredRoutineReturnType(udaf.dataType,
name)
def builder(children: Seq[Expression]) = ScalaUDAF(children, udaf,
udafName = Some(name))
functionRegistry.createOrReplaceTempFunction(name, builder, "scala_udf")
udaf
@@ -89,6 +96,16 @@ class UDFRegistration private[sql] (session: SparkSession,
functionRegistry: Fun
source: String,
validateParameterCount: Boolean): UserDefinedFunction = {
val named = udf.withName(name)
+ // A FILE in the return type cannot have a qualifier. For a typed
Aggregator the return type is
+ // carried by its output encoder rather than a `dataType` field.
+ if (SQLConf.get.isFileTypeEnabled) {
+ val returnType: DataType = named match {
+ case udaf: UserDefinedAggregator[_, _, _] =>
+ encoderFor(udaf.aggregator.outputEncoder).objSerializer.dataType
+ case f: SparkUserDefinedFunction => f.dataType
+ }
+ TypeUtils.checkNoQualifierInRegisteredRoutineReturnType(returnType, name)
+ }
val builder: Seq[Expression] => Expression = named match {
case udaf: UserDefinedAggregator[_, _, _] =>
ScalaAggregator(udaf, _)
diff --git
a/sql/core/src/main/scala/org/apache/spark/sql/execution/command/CreateSQLFunctionCommand.scala
b/sql/core/src/main/scala/org/apache/spark/sql/execution/command/CreateSQLFunctionCommand.scala
index a762eceb6542..0ab8cb408eca 100644
---
a/sql/core/src/main/scala/org/apache/spark/sql/execution/command/CreateSQLFunctionCommand.scala
+++
b/sql/core/src/main/scala/org/apache/spark/sql/execution/command/CreateSQLFunctionCommand.scala
@@ -28,6 +28,7 @@ import
org.apache.spark.sql.catalyst.expressions.aggregate.AggregateExpression
import org.apache.spark.sql.catalyst.plans.Inner
import org.apache.spark.sql.catalyst.plans.logical.{LateralJoin,
LocalRelation, LogicalPlan, OneRowRelation, Project, Range, UnresolvedWith,
View}
import org.apache.spark.sql.catalyst.trees.TreePattern.UNRESOLVED_ATTRIBUTE
+import org.apache.spark.sql.catalyst.util.TypeUtils
import org.apache.spark.sql.connector.catalog.CatalogManager
import
org.apache.spark.sql.connector.catalog.CatalogV2Implicits.MultipartIdentifierHelper
import org.apache.spark.sql.errors.QueryCompilationErrors
@@ -77,6 +78,15 @@ case class CreateSQLFunctionCommand(
val inputParam =
inputParamText.map(UserDefinedFunction.parseRoutineParam(_, parser, collation))
val returnType = parseReturnTypeText(returnTypeText, isTableFunc, parser,
collation)
+ // A FILE in the signature of a function is a plain FILE, without a
qualifier, and the return
+ // type cannot hold a FILE in a map key.
+ val routineName = QueryCompilationErrors.toSQLId(name.nameParts)
+ def checkFileTypeInSignature(paramTypes: Seq[DataType], returnType:
Option[DataType]): Unit = {
+ TypeUtils.checkNoQualifierInRoutineSignature(
+ paramTypes ++ returnType, routineType = "function", routineName =
routineName)
+ returnType.foreach(TypeUtils.checkNoFileTypeMapKeyInReturnType(_,
routineName))
+ }
+ checkFileTypeInSignature(inputParam.toSeq, returnType.map(_.fold(identity,
identity)))
val function = SQLFunction(
name,
@@ -258,6 +268,10 @@ case class CreateSQLFunctionCommand(
(plan, analyzed, Right(returnParam), referredTempVarsUnderIdentifier)
}
+ // Without a RETURNS clause, or with a bare RETURNS TABLE, the return
type is inferred from
+ // the function body, so it is checked as well.
+ checkFileTypeInSignature(Nil, Option(inferredReturnType.fold(identity,
identity)))
+
// A permanent function is not allowed to reference temporary objects.
// This should be called after `qe.assertAnalyzed()` (i.e., `plan` can
be resolved).
// Like persisted views, honor
`spark.sql.legacy.allowSessionVariableInPersistedView` for the
diff --git
a/sql/core/src/main/scala/org/apache/spark/sql/execution/command/tables.scala
b/sql/core/src/main/scala/org/apache/spark/sql/execution/command/tables.scala
index 4d513b4d3b06..4c26f8c28bf7 100644
---
a/sql/core/src/main/scala/org/apache/spark/sql/execution/command/tables.scala
+++
b/sql/core/src/main/scala/org/apache/spark/sql/execution/command/tables.scala
@@ -36,7 +36,7 @@ import org.apache.spark.sql.catalyst.expressions.Attribute
import org.apache.spark.sql.catalyst.plans.DescribeCommandSchema
import org.apache.spark.sql.catalyst.plans.logical._
import org.apache.spark.sql.catalyst.types.DataTypeUtils
-import org.apache.spark.sql.catalyst.util.{escapeSingleQuotedString,
quoteIfNeeded, CaseInsensitiveMap, CharVarcharUtils, DateTimeUtils,
ResolveDefaultColumns}
+import org.apache.spark.sql.catalyst.util.{escapeSingleQuotedString,
quoteIfNeeded, CaseInsensitiveMap, CharVarcharUtils, DateTimeUtils,
ResolveDefaultColumns, TypeUtils}
import
org.apache.spark.sql.catalyst.util.ResolveDefaultColumns.CURRENT_DEFAULT_COLUMN_METADATA_KEY
import org.apache.spark.sql.classic.ClassicConversions.castToImpl
import org.apache.spark.sql.connector.catalog.{TableCatalog, V1Table, V1View}
@@ -94,6 +94,8 @@ case class CreateTableLikeCommand(
override def run(sparkSession: SparkSession): Seq[Row] = {
val catalog = sparkSession.sessionState.catalog
val sourceTableDesc =
catalog.getTempViewOrPermanentTableMetadata(sourceTable)
+ // A view can hold a FILE without a qualifier, which a table cannot store.
+ TypeUtils.checkNoUnknownFileTypeInTableSchema(sourceTableDesc.schema)
val newProvider = if (provider.isDefined) {
if (!DDLUtils.isHiveTable(provider)) {
// check the validation of provider input, invalid provider will throw
diff --git
a/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/rules.scala
b/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/rules.scala
index 46899a3272a4..213047afaafe 100644
---
a/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/rules.scala
+++
b/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/rules.scala
@@ -267,6 +267,8 @@ case class PreprocessTableCreation(catalog: SessionCatalog)
extends Rule[Logical
"Schema may not be specified in a Create Table As Select (CTAS)
statement")
val analyzedQuery = query.get
+ checkNoUnknownFileTypeWrite(analyzedQuery.output)
+ checkNoFileTypePartitionOrClusteringColumn(analyzedQuery.schema,
tableDesc)
val normalizedTable =
CreateTableHelper.normalizeCatalogTable(analyzedQuery.schema,
tableDesc)
@@ -290,6 +292,8 @@ case class PreprocessTableCreation(catalog: SessionCatalog)
extends Rule[Logical
c.copy(tableDesc = normalizedTable, query = Some(reorderedQuery))
} else {
+ checkFileTypeHasQualifier(tableDesc.schema)
+ checkNoFileTypePartitionOrClusteringColumn(tableDesc.schema, tableDesc)
CreateTableHelper.normalizeCreateTableWithoutQuery(c)
}
@@ -302,6 +306,19 @@ case class PreprocessTableCreation(catalog:
SessionCatalog) extends Rule[Logical
case f: FileDataSourceV2 => f.fallbackFileFormat
case _ => cls
}
+
+ // FILE is not comparable, so it cannot be a partition, bucket or clustering
column. A
+ // bucket column is reported as a partition column, as for the V2 `bucket`
transform.
+ private def checkNoFileTypePartitionOrClusteringColumn(
+ schema: StructType,
+ table: CatalogTable): Unit = {
+ (table.partitionColumnNames ++
table.bucketSpec.toSeq.flatMap(_.bucketColumnNames))
+ .foreach { name =>
+ schema.find(f => conf.resolver(f.name, name))
+ .foreach(checkNoFileTypeInColumnUsage(_, "PARTITION_COLUMN"))
+ }
+ table.clusterBySpec.foreach(checkNoFileTypeClusteringColumn(schema, _,
conf.resolver))
+ }
}
/**
diff --git
a/sql/core/src/test/scala/org/apache/spark/sql/FileTypeRestrictionsSuite.scala
b/sql/core/src/test/scala/org/apache/spark/sql/FileTypeRestrictionsSuite.scala
new file mode 100644
index 000000000000..e609a366eb43
--- /dev/null
+++
b/sql/core/src/test/scala/org/apache/spark/sql/FileTypeRestrictionsSuite.scala
@@ -0,0 +1,731 @@
+/*
+ * 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.{InternalRow, TableIdentifier}
+import org.apache.spark.sql.catalyst.catalog.{CatalogStorageFormat,
CatalogTable, CatalogTableType}
+import org.apache.spark.sql.catalyst.plans.logical.{Deduplicate,
DeduplicateWithinWatermark, LogicalPlan, MapInPandas}
+import org.apache.spark.sql.catalyst.types.DataTypeUtils.toAttributes
+import org.apache.spark.sql.connector.catalog.{CatalogV2Util, Identifier,
InMemoryCatalog, TableInfo}
+import org.apache.spark.sql.connector.catalog.functions.{BoundFunction,
ScalarFunction, UnboundFunction}
+import org.apache.spark.sql.execution.python.{UserDefinedPythonFunction,
UserDefinedPythonTableFunction}
+import org.apache.spark.sql.expressions.{MutableAggregationBuffer,
UserDefinedAggregateFunction}
+import org.apache.spark.sql.functions.{col, udf}
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.test.SharedSparkSession
+import org.apache.spark.sql.types.{ArrayType, DataType, FileType, IntegerType,
LongType, MapType, StringType, 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 is not comparable.
+ */
+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"
+
+ /** Analyzes `query` without running it. */
+ private def analyze(query: String): Unit =
analyze(spark.sessionState.sqlParser.parsePlan(query))
+
+ /** Analyzes `plan` without running it. */
+ private def analyze(plan: LogicalPlan): Unit =
+ spark.sessionState.executePlan(plan).assertAnalyzed()
+
+ 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`]"))
+ // IF NOT EXISTS does not skip the check when the table exists.
+ sql(s"CREATE TABLE $table (id INT) $provider")
+ checkError(
+ exception = intercept[AnalysisException] {
+ sql(s"CREATE TABLE IF NOT EXISTS $table $provider AS " +
+ "SELECT 1 AS id, CAST(NULL AS FILE) AS f")
+ },
+ condition = "FILE_TYPE_UNKNOWN_WRITE",
+ parameters = Map("colNames" -> "[`f`]"))
+ }
+ }
+ }
+
+ test("schema evolution cannot add a FILE without a qualifier") {
+ withTable("testcat.t") {
+ sql("CREATE TABLE testcat.t (id INT, s STRUCT<a: INT>)")
+ val schema = spark.table("testcat.t").schema
+ Seq(
+ "SELECT 1 AS id, named_struct('a', 1) AS s, CAST(NULL AS FILE) AS f"
-> "[`f`]",
+ "SELECT 1 AS id, named_struct('a', 1, 'f', CAST(NULL AS FILE)) AS s"
-> "[`s`.`f`]"
+ ).foreach { case (query, colNames) =>
+ checkError(
+ exception = intercept[AnalysisException] {
+ sql(s"INSERT WITH SCHEMA EVOLUTION INTO testcat.t $query")
+ },
+ condition = "FILE_TYPE_UNKNOWN_WRITE",
+ parameters = Map("colNames" -> colNames))
+ // The table is not changed.
+ assert(spark.table("testcat.t").schema === schema)
+ }
+ // A FILE EXTERNAL column can be added.
+ sql("INSERT WITH SCHEMA EVOLUTION INTO testcat.t " +
+ "SELECT 1 AS id, named_struct('a', 1) AS s, CAST(NULL AS FILE
EXTERNAL) AS f")
+ assert(spark.table("testcat.t").schema === schema.add("f",
FileType.external))
+ }
+ }
+
+ test("CREATE TABLE LIKE cannot copy a FILE without a qualifier") {
+ withTempView("v") {
+ withView("pv") {
+ sql("CREATE TEMPORARY VIEW v AS SELECT 1 AS id, CAST(NULL AS FILE) AS
f")
+ sql("CREATE VIEW pv AS SELECT 1 AS id, CAST(NULL AS FILE) AS f")
+ for (source <- Seq("v", "pv"); target <- Seq("t", "testcat.t")) {
+ withTable(target) {
+ checkError(
+ exception = intercept[AnalysisException] {
+ sql(s"CREATE TABLE $target LIKE $source")
+ },
+ condition = "FILE_TYPE_UNKNOWN_WRITE",
+ parameters = Map("colNames" -> "[`f`]"))
+ assert(!spark.catalog.tableExists(target))
+ // As with CREATE TABLE AS SELECT, IF NOT EXISTS does not skip the
check when the
+ // table exists.
+ sql(s"CREATE TABLE $target (id INT)")
+ checkError(
+ exception = intercept[AnalysisException] {
+ sql(s"CREATE TABLE IF NOT EXISTS $target LIKE $source")
+ },
+ condition = "FILE_TYPE_UNKNOWN_WRITE",
+ parameters = Map("colNames" -> "[`f`]"))
+ }
+ }
+ // A V2 target is checked at analysis.
+ checkError(
+ exception = intercept[AnalysisException](analyze("CREATE TABLE
testcat.t LIKE v")),
+ condition = "FILE_TYPE_UNKNOWN_WRITE",
+ parameters = Map("colNames" -> "[`f`]"))
+ }
+ }
+ // A table source, which only a catalog can create with a FILE without a
qualifier. A target
+ // in the session catalog is also checked at analysis, as the source is
not.
+ withTable("testcat.src") {
+
spark.sessionState.catalogManager.catalog("testcat").asInstanceOf[InMemoryCatalog]
+ .createTable(
+ Identifier.of(Array.empty, "src"),
+ new TableInfo.Builder()
+ .withColumns(CatalogV2Util.structTypeToV2Columns(
+ new StructType().add("id", IntegerType).add("f", FileType())))
+ .build())
+ Seq("testcat.t", "t").foreach { target =>
+ withTable(target) {
+ checkError(
+ exception = intercept[AnalysisException] {
+ analyze(s"CREATE TABLE $target LIKE testcat.src")
+ },
+ condition = "FILE_TYPE_UNKNOWN_WRITE",
+ parameters = Map("colNames" -> "[`f`]"))
+ }
+ }
+ }
+ // A FILE EXTERNAL can be copied.
+ withTempView("v") {
+ withTable("testcat.t") {
+ sql("CREATE TEMPORARY VIEW v AS SELECT 1 AS id, CAST(NULL AS FILE
EXTERNAL) AS f")
+ sql("CREATE TABLE testcat.t LIKE v")
+ assert(spark.table("testcat.t").schema ===
+ new StructType().add("id", IntegerType, nullable = false).add("f",
FileType.external))
+ }
+ }
+ }
+
+ test("a FILE column cannot be a write-ordering column") {
+ val columns = "(id INT, f FILE EXTERNAL)"
+ val query = "AS SELECT 1 AS id, CAST(NULL AS FILE EXTERNAL) AS f"
+ val file = ("`f`", "\"FILE EXTERNAL\"")
+ Seq(
+ s"CREATE TABLE testcat.t $columns ORDERED BY f" -> file,
+ s"CREATE TABLE testcat.t $columns LOCALLY ORDERED BY bucket(4, f)" ->
file,
+ "CREATE TABLE testcat.t (id INT, s STRUCT<f: FILE EXTERNAL>) ORDERED BY
s" ->
+ ("`s`", "\"STRUCT<f: FILE EXTERNAL>\""),
+ s"REPLACE TABLE testcat.t $columns ORDERED BY f" -> file,
+ s"CREATE TABLE testcat.t ORDERED BY f $query" -> file,
+ s"REPLACE TABLE testcat.t ORDERED BY f $query" -> file
+ ).foreach { case (statement, (colName, dataType)) =>
+ checkError(
+ exception = intercept[AnalysisException](analyze(statement)),
+ condition = "FILE_TYPE_UNSUPPORTED_COLUMN_USAGE.WRITE_ORDERING_COLUMN",
+ parameters = Map("colName" -> colName, "dataType" -> dataType))
+ }
+ // Ordering by a column that is not a FILE passes analysis.
+ analyze("CREATE TABLE testcat.t (id INT, f FILE EXTERNAL) ORDERED BY id")
+ }
+
+ test("a FILE column cannot be a partition or clustering column") {
+ Seq(
+ ("PARTITIONED BY (f)", "PARTITION_COLUMN"),
+ ("PARTITIONED BY (bucket(4, f))", "PARTITION_COLUMN"),
+ ("CLUSTERED BY (f) INTO 4 BUCKETS", "PARTITION_COLUMN"),
+ ("CLUSTER BY (f)", "CLUSTERING_COLUMN")).foreach { case (clause, usage)
=>
+ 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 (id INT, f FILE EXTERNAL) $provider
$clause")
+ },
+ condition = s"FILE_TYPE_UNSUPPORTED_COLUMN_USAGE.$usage",
+ parameters = Map("colName" -> "`f`", "dataType" -> "\"FILE
EXTERNAL\""))
+ checkError(
+ exception = intercept[AnalysisException] {
+ sql(s"CREATE TABLE $table $provider $clause AS " +
+ "SELECT 1 AS id, CAST(NULL AS FILE EXTERNAL) AS f")
+ },
+ 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("CLUSTER BY a field of an array of structs") {
+ // A schema without a FILE is not changed by the FILE checks, with the
flag on or off.
+ Seq("true", "false").foreach { enabled =>
+ withSQLConf(SQLConf.FILE_TYPE_ENABLED.key -> enabled) {
+ Seq("t", "testcat.t").foreach { table =>
+ val provider = if (table.startsWith("testcat")) "" else "USING
parquet"
+ withTable(table) {
+ sql(s"CREATE TABLE $table (id INT, arr ARRAY<STRUCT<x: INT>>)
$provider")
+ sql(s"ALTER TABLE $table CLUSTER BY (arr.x)")
+ }
+ }
+ withTable("t") {
+ sql("CREATE TABLE t (id INT, arr ARRAY<STRUCT<x: INT>>) USING
parquet CLUSTER BY (arr.x)")
+ }
+ }
+ }
+ // A FILE in a struct element of an array is found. A CTAS cannot cluster
by such a field,
+ // with or without a FILE.
+ withTable("t") {
+ checkError(
+ exception = intercept[AnalysisException] {
+ analyze("CREATE TABLE t (id INT, arr ARRAY<STRUCT<f: FILE
EXTERNAL>>) USING parquet " +
+ "CLUSTER BY (arr.f)")
+ },
+ condition = "FILE_TYPE_UNSUPPORTED_COLUMN_USAGE.CLUSTERING_COLUMN",
+ parameters = Map("colName" -> "`f`", "dataType" -> "\"FILE
EXTERNAL\""))
+ }
+ withTable("testcat.t") {
+ sql("CREATE TABLE testcat.t (id INT, arr ARRAY<STRUCT<f: FILE
EXTERNAL>>)")
+ checkError(
+ exception = intercept[AnalysisException](sql("ALTER TABLE testcat.t
CLUSTER BY (arr.f)")),
+ condition = "FILE_TYPE_UNSUPPORTED_COLUMN_USAGE.CLUSTERING_COLUMN",
+ parameters = Map("colName" -> "`f`", "dataType" -> "\"FILE
EXTERNAL\""))
+ }
+ }
+
+ test("ALTER COLUMN requires FILE EXTERNAL and cannot change the type of a
FILE column") {
+ withTable("testcat.t") {
+ sql("CREATE TABLE testcat.t (id INT, s STRING, f FILE EXTERNAL, v VOID)")
+ Seq("s", "f", "v").foreach { column =>
+ checkError(
+ exception = intercept[AnalysisException] {
+ sql(s"ALTER TABLE testcat.t ALTER COLUMN $column TYPE FILE")
+ },
+ condition = "FILE_TYPE_MISSING_QUALIFIER")
+ }
+ checkError(
+ exception = intercept[AnalysisException] {
+ sql("ALTER TABLE testcat.t ALTER COLUMN s TYPE FILE EXTERNAL")
+ },
+ condition = "NOT_SUPPORTED_CHANGE_COLUMN",
+ parameters = Map(
+ "table" -> "`testcat`.`t`",
+ "originName" -> "`s`",
+ "originType" -> "\"STRING\"",
+ "newName" -> "`s`",
+ "newType" -> "\"FILE EXTERNAL\""),
+ context = ExpectedContext(
+ fragment = "ALTER TABLE testcat.t ALTER COLUMN s TYPE FILE EXTERNAL",
+ start = 0,
+ stop = 54))
+ // Nor can a FILE column be altered to another type.
+ Seq("STRING" -> "\"STRING\"", "BINARY" -> "\"BINARY\"").foreach {
+ case (dataType, sqlType) =>
+ val query = s"ALTER TABLE testcat.t ALTER COLUMN f TYPE $dataType"
+ checkError(
+ exception = intercept[AnalysisException](sql(query)),
+ condition = "NOT_SUPPORTED_CHANGE_COLUMN",
+ parameters = Map(
+ "table" -> "`testcat`.`t`",
+ "originName" -> "`f`",
+ "originType" -> "\"FILE EXTERNAL\"",
+ "newName" -> "`f`",
+ "newType" -> sqlType),
+ context = ExpectedContext(fragment = query, start = 0, stop =
query.length - 1))
+ }
+ }
+ }
+
+ 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))
+ checkError(
+ exception = intercept[AnalysisException] {
+ sql(s"SELECT map(array(f), 1) FROM ($externalFile)")
+ },
+ condition = "DATATYPE_MISMATCH.INVALID_MAP_KEY_TYPE",
+ parameters = Map(
+ "sqlExpr" -> "\"map(array(f), 1)\"",
+ "keyType" -> "\"ARRAY<FILE EXTERNAL>\""),
+ context = ExpectedContext(fragment = "map(array(f), 1)", start = 7, stop
= 22))
+ 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))
+ val nested = s"SELECT count(*) FROM ($externalFile) GROUP BY struct(f)"
+ checkError(
+ exception = intercept[AnalysisException](sql(nested)),
+ condition = "GROUP_EXPRESSION_TYPE_IS_NOT_ORDERABLE",
+ parameters = Map(
+ "sqlExpr" -> "\"struct(f)\"",
+ "dataType" -> "\"STRUCT<f: FILE EXTERNAL>\""),
+ context = ExpectedContext(
+ fragment = "struct(f)", start = nested.length - 9, stop =
nested.length - 1))
+ }
+
+ test("a FILE cannot be in INTERSECT, EXCEPT or DISTINCT") {
+ Seq(
+ s"$externalFile INTERSECT $externalFile",
+ s"$externalFile EXCEPT $externalFile",
+ s"$externalFile UNION $externalFile",
+ s"SELECT DISTINCT f FROM ($externalFile)").foreach { query =>
+ checkError(
+ exception = intercept[AnalysisException](sql(query)),
+ condition = "UNSUPPORTED_FEATURE.SET_OPERATION_ON_FILE_TYPE",
+ parameters = Map("colName" -> "`f`", "dataType" -> "\"FILE
EXTERNAL\""),
+ context = ExpectedContext(fragment = query, start = 0, stop =
query.length - 1))
+ }
+ val nested = s"SELECT DISTINCT struct(f) AS s FROM ($externalFile)"
+ checkError(
+ exception = intercept[AnalysisException](sql(nested)),
+ condition = "UNSUPPORTED_FEATURE.SET_OPERATION_ON_FILE_TYPE",
+ parameters = Map("colName" -> "`s`", "dataType" -> "\"STRUCT<f: FILE
EXTERNAL>\""),
+ context = ExpectedContext(fragment = nested, start = 0, stop =
nested.length - 1))
+ checkError(
+ exception = intercept[AnalysisException] {
+ sql(externalFile).dropDuplicates("f")
+ },
+ condition = "UNSUPPORTED_FEATURE.SET_OPERATION_ON_FILE_TYPE",
+ parameters = Map("colName" -> "`f`", "dataType" -> "\"FILE EXTERNAL\""))
+ // UNION ALL does not compare rows.
+ sql(s"$externalFile UNION ALL $externalFile")
+ }
+
+ test("a FILE cannot be a repartition expression") {
+ checkError(
+ exception = intercept[AnalysisException] {
+ sql(externalFile).repartition(5, col("f"))
+ },
+ condition = "UNSUPPORTED_FEATURE.PARTITION_BY_FILE",
+ parameters = Map("expr" -> "\"f\"", "dataType" -> "\"FILE EXTERNAL\""))
+ checkError(
+ exception = intercept[AnalysisException] {
+ sql(s"SELECT /*+ REBALANCE(f) */ * FROM ($externalFile)")
+ },
+ condition = "UNSUPPORTED_FEATURE.PARTITION_BY_FILE",
+ parameters = Map("expr" -> "\"f\"", "dataType" -> "\"FILE EXTERNAL\""),
+ context = ExpectedContext(fragment = "/*+ REBALANCE(f) */", start = 7,
stop = 25))
+ // Partitioning by a column that is not a FILE is accepted.
+ sql("SELECT * FROM (SELECT 1 AS id, CAST(NULL AS FILE EXTERNAL) AS f)
DISTRIBUTE BY id")
+ }
+
+ test("a FILE cannot be a key of dropDuplicatesWithinWatermark") {
+ checkError(
+ exception = intercept[AnalysisException] {
+ sql(externalFile).dropDuplicatesWithinWatermark("f")
+ },
+ condition = "UNSUPPORTED_FEATURE.SET_OPERATION_ON_FILE_TYPE",
+ parameters = Map("colName" -> "`f`", "dataType" -> "\"FILE EXTERNAL\""))
+ }
+
+ test("dropDuplicates may use keys other than a FILE column") {
+ // `Dataset.dropDuplicates` needs a row encoder, which FILE does not have
yet, so the plans
+ // are analyzed directly.
+ val child = sql("SELECT 1 AS id, CAST(NULL AS FILE EXTERNAL) AS
f").queryExecution.analyzed
+ val id = child.output.head
+ analyze(Deduplicate(Seq(id), child))
+ analyze(DeduplicateWithinWatermark(Seq(id), child))
+ }
+
+ test("a FILE cannot be hashed") {
+ checkError(
+ exception = intercept[AnalysisException] {
+ sql(s"SELECT hash(f) FROM ($externalFile)")
+ },
+ condition = "DATATYPE_MISMATCH.HASH_FILE_TYPE",
+ parameters = Map("sqlExpr" -> "\"hash(f)\"", "functionName" -> "`hash`"),
+ context = ExpectedContext(fragment = "hash(f)", start = 7, stop = 13))
+ checkError(
+ exception = intercept[AnalysisException] {
+ sql(s"SELECT hash(array(f)) FROM ($externalFile)")
+ },
+ condition = "DATATYPE_MISMATCH.HASH_FILE_TYPE",
+ parameters = Map("sqlExpr" -> "\"hash(array(f))\"", "functionName" ->
"`hash`"),
+ context = ExpectedContext(fragment = "hash(array(f))", start = 7, stop =
20))
+ }
+
+ test("a FILE cannot be sorted or be a window partition") {
+ val orderBy = s"SELECT f FROM ($externalFile) ORDER BY f"
+ checkError(
+ exception = intercept[AnalysisException](sql(orderBy)),
+ condition = "DATATYPE_MISMATCH.INVALID_ORDERING_TYPE",
+ parameters = Map(
+ "sqlExpr" -> "\"f ASC NULLS FIRST\"",
+ "functionName" -> "`sortorder`",
+ "dataType" -> "\"FILE EXTERNAL\""),
+ context = ExpectedContext(
+ fragment = "f", start = orderBy.length - 1, stop = orderBy.length - 1))
+ val windowOrder = s"SELECT row_number() OVER (ORDER BY f) FROM
($externalFile)"
+ checkError(
+ exception = intercept[AnalysisException](sql(windowOrder)),
+ condition = "DATATYPE_MISMATCH.INVALID_ORDERING_TYPE",
+ parameters = Map(
+ "sqlExpr" -> "\"f ASC NULLS FIRST\"",
+ "functionName" -> "`sortorder`",
+ "dataType" -> "\"FILE EXTERNAL\""),
+ context = ExpectedContext(fragment = "f", start = 35, stop = 35))
+ val windowPartition = s"SELECT count(*) OVER (PARTITION BY f) FROM
($externalFile)"
+ checkError(
+ exception = intercept[AnalysisException](sql(windowPartition)),
+ condition = "EXPRESSION_TYPE_IS_NOT_ORDERABLE",
+ parameters = Map("expr" -> "\"f\"", "exprType" -> "\"FILE EXTERNAL\""),
+ context = ExpectedContext(fragment = "f", start = 35, stop = 35))
+ }
+
+ test("a FILE cannot be compared, so it cannot be a join key") {
+ val query = s"SELECT 1 FROM ($externalFile) l JOIN ($externalFile) r ON
l.f = r.f"
+ checkError(
+ exception = intercept[AnalysisException](sql(query)),
+ condition = "DATATYPE_MISMATCH.INVALID_ORDERING_TYPE",
+ parameters = Map(
+ "sqlExpr" -> "\"(f = f)\"",
+ "functionName" -> "`=`",
+ "dataType" -> "\"FILE EXTERNAL\""),
+ context = ExpectedContext(
+ fragment = "l.f = r.f", start = query.length - 9, stop = query.length
- 1))
+ }
+
+ test("a SQL function declares a plain FILE") {
+ Seq(
+ "(x FILE EXTERNAL) RETURNS INT RETURN 1",
+ "(x INT) RETURNS FILE EXTERNAL RETURN NULL",
+ "(x INT) RETURNS ARRAY<FILE EXTERNAL> RETURN NULL",
+ "(x INT) RETURNS TABLE (f FILE EXTERNAL) RETURN SELECT NULL",
+ // Without a RETURNS clause, or with a bare RETURNS TABLE, the return
type is inferred.
+ "(x INT) RETURN CAST(NULL AS FILE EXTERNAL)",
+ "(x INT) RETURNS TABLE RETURN SELECT CAST(NULL AS FILE EXTERNAL) AS
f").foreach { signature =>
+ checkError(
+ exception = intercept[AnalysisException] {
+ sql(s"CREATE TEMPORARY FUNCTION fn$signature")
+ },
+ condition = "FILE_TYPE_IN_ROUTINE_SIGNATURE_UNSUPPORTED_QUALIFIER",
+ parameters = Map("routineType" -> "function", "routineName" -> "`fn`"))
+ }
+ Seq(
+ "RETURNS MAP<FILE, INT> RETURN NULL",
+ "RETURN CAST(NULL AS MAP<FILE, INT>)",
+ "RETURNS TABLE (s STRUCT<m: MAP<FILE, INT>>) RETURN SELECT
NULL").foreach { body =>
+ checkError(
+ exception = intercept[AnalysisException] {
+ sql(s"CREATE TEMPORARY FUNCTION fn(x INT) $body")
+ },
+ condition = "FILE_TYPE_IN_ROUTINE_SIGNATURE_UNSUPPORTED_MAP_KEY",
+ parameters = Map("routineType" -> "function", "routineName" -> "`fn`"))
+ }
+ withUserDefinedFunction("fn" -> true) {
+ sql("CREATE TEMPORARY FUNCTION fn(x FILE) RETURNS FILE RETURN x")
+ }
+ }
+
+ test("a UDF declares a plain FILE in its return type") {
+ val fileUdf = new UDF1[Integer, AnyRef] {
+ override def call(x: Integer): AnyRef = null
+ }
+ withUserDefinedFunction("file_udf" -> true, "file_udaf" -> true) {
+ checkError(
+ exception = intercept[AnalysisException] {
+ spark.udf.register("file_udf", fileUdf, FileType.external)
+ },
+ condition = "FILE_TYPE_IN_ROUTINE_SIGNATURE_UNSUPPORTED_QUALIFIER",
+ parameters = Map("routineType" -> "function", "routineName" ->
"`file_udf`"))
+ checkError(
+ exception = intercept[AnalysisException] {
+ spark.udf.register("file_udf", fileUdf, MapType(FileType(),
IntegerType))
+ },
+ condition = "FILE_TYPE_IN_ROUTINE_SIGNATURE_UNSUPPORTED_MAP_KEY",
+ parameters = Map("routineType" -> "function", "routineName" ->
"`file_udf`"))
+ // A UDF that is not registered is checked when it is used in a query.
+ checkError(
+ exception = intercept[AnalysisException] {
+ spark.range(1).select(udf(fileUdf,
FileType.external).withName("inline_udf")(col("id")))
+ },
+ condition = "FILE_TYPE_IN_ROUTINE_SIGNATURE_UNSUPPORTED_QUALIFIER",
+ parameters = Map("routineType" -> "function", "routineName" ->
"`inline_udf`"))
+ checkError(
+ exception = intercept[AnalysisException] {
+ spark.udf.register("file_udaf", new FileTypeUDAF(FileType.external))
+ },
+ condition = "FILE_TYPE_IN_ROUTINE_SIGNATURE_UNSUPPORTED_QUALIFIER",
+ parameters = Map("routineType" -> "function", "routineName" ->
"`file_udaf`"))
+ // A FILE map key is found in an array element and in a map value.
+ Seq(
+ ArrayType(MapType(FileType(), IntegerType)),
+ MapType(StringType, MapType(FileType(), IntegerType))).foreach {
dataType =>
+ checkError(
+ exception = intercept[AnalysisException] {
+ spark.udf.register("file_udf", fileUdf, dataType)
+ },
+ condition = "FILE_TYPE_IN_ROUTINE_SIGNATURE_UNSUPPORTED_MAP_KEY",
+ parameters = Map("routineType" -> "function", "routineName" ->
"`file_udf`"))
+ }
+ spark.udf.register("file_udf", fileUdf, FileType())
+ spark.udf.register("file_udaf", new FileTypeUDAF(FileType()))
+ }
+ // Registration is not checked when the FILE type is disabled. A query
that uses the UDF then
+ // fails because the type is disabled.
+ withUserDefinedFunction("file_udf" -> true) {
+ withSQLConf(SQLConf.FILE_TYPE_ENABLED.key -> "false") {
+ spark.udf.register("file_udf", fileUdf, FileType.external)
+ }
+ }
+ // A UDAF class registered by name is checked only when it is used in a
query.
+ withUserDefinedFunction("class_udaf" -> true) {
+ sql(s"CREATE TEMPORARY FUNCTION class_udaf AS
'${classOf[ExternalFileTypeUDAF].getName}'")
+ checkError(
+ exception = intercept[AnalysisException] {
+ sql("SELECT class_udaf(id) FROM range(1)")
+ },
+ condition = "FILE_TYPE_IN_ROUTINE_SIGNATURE_UNSUPPORTED_QUALIFIER",
+ parameters = Map("routineType" -> "function", "routineName" ->
"`class_udaf`"))
+ }
+ }
+
+ test("a V2 catalog function declares a plain FILE in its return type") {
+ val catalog =
spark.sessionState.catalogManager.catalog("testcat").asInstanceOf[InMemoryCatalog]
+ val ident = Identifier.of(Array("ns"), "file_fn")
+ catalog.createFunction(ident, new FileTypeFunction(FileType.external))
+ try {
+ checkError(
+ exception = intercept[AnalysisException] {
+ analyze("SELECT testcat.ns.file_fn(id) FROM range(1)")
+ },
+ condition = "FILE_TYPE_IN_ROUTINE_SIGNATURE_UNSUPPORTED_QUALIFIER",
+ parameters = Map("routineType" -> "function", "routineName" ->
"`file_fn`"))
+ catalog.createFunction(ident, new FileTypeFunction(FileType()))
+ analyze("SELECT testcat.ns.file_fn(id) FROM range(1)")
+ } finally {
+ catalog.dropFunction(ident)
+ }
+ }
+
+ test("a Python UDF and UDTF declare a plain FILE in their return type") {
+ // Registering these functions and analyzing a call to the UDF do not run
Python, so the
+ // function body is never used.
+ val func = SimplePythonFunction(
+ command = Seq.empty[Byte],
+ envVars = new java.util.HashMap[String, String](),
+ pythonIncludes = java.util.Collections.emptyList[String](),
+ pythonExec = "python3",
+ pythonVer = "3",
+ broadcastVars =
java.util.Collections.emptyList[Broadcast[PythonBroadcast]](),
+ accumulator = null)
+ def pythonUdf(dataType: DataType): UserDefinedPythonFunction =
UserDefinedPythonFunction(
+ "py_udf", func, dataType, PythonEvalType.SQL_BATCHED_UDF,
udfDeterministic = true)
+ def pythonUdtf(returnType: Option[StructType]):
UserDefinedPythonTableFunction =
+ UserDefinedPythonTableFunction(
+ "py_udtf", func, returnType, PythonEvalType.SQL_TABLE_UDF,
udfDeterministic = true)
+
+ Seq(
+ (() => spark.udf.registerPython("py_udf", pythonUdf(FileType.external)),
"py_udf"),
+ (() => spark.udtf.registerPython("py_udtf",
+ pythonUdtf(Some(new StructType().add("f", FileType.external)))),
"py_udtf")
+ ).foreach { case (register, name) =>
+ checkError(
+ exception = intercept[AnalysisException](register()),
+ condition = "FILE_TYPE_IN_ROUTINE_SIGNATURE_UNSUPPORTED_QUALIFIER",
+ parameters = Map("routineType" -> "function", "routineName" ->
s"`$name`"))
+ }
+ checkError(
+ exception = intercept[AnalysisException] {
+ spark.udf.registerPython("py_udf", pythonUdf(MapType(FileType(),
IntegerType)))
+ },
+ condition = "FILE_TYPE_IN_ROUTINE_SIGNATURE_UNSUPPORTED_MAP_KEY",
+ parameters = Map("routineType" -> "function", "routineName" ->
"`py_udf`"))
+
+ // A Python UDF that is not registered is checked when it is used in a
query.
+ checkError(
+ exception = intercept[AnalysisException] {
+ spark.range(1).select(pythonUdf(FileType.external)(col("id")))
+ },
+ condition = "FILE_TYPE_IN_ROUTINE_SIGNATURE_UNSUPPORTED_QUALIFIER",
+ parameters = Map("routineType" -> "function", "routineName" ->
"`py_udf`"))
+
+ // A plain FILE is accepted, and a UDTF with an analyze method has no
static return type.
+ withUserDefinedFunction("py_udf" -> true, "py_udtf" -> true) {
+ spark.udf.registerPython("py_udf", pythonUdf(FileType()))
+ spark.udtf.registerPython(
+ "py_udtf", pythonUdtf(Some(new StructType().add("f", FileType()))))
+ spark.udtf.registerPython("py_udtf", pythonUdtf(None))
+ }
+
+ // A non-scalar Python UDF, such as the function of mapInPandas, returns
rows, so its data
+ // type is the schema of the rows and may hold a FILE EXTERNAL.
+ val rowSchema = new StructType().add("f", FileType.external)
+ val mapUdf = UserDefinedPythonFunction(
+ "map_udf", func, rowSchema, PythonEvalType.SQL_MAP_PANDAS_ITER_UDF,
udfDeterministic = true)
+ val child = spark.range(1).queryExecution.analyzed
+ analyze(MapInPandas(
+ mapUdf.builder(child.output), toAttributes(rowSchema), child, isBarrier
= false,
+ profile = None))
+ }
+}
+
+/** A V2 scalar function that returns `dataType`; only its return type is used
by the tests. */
+private class FileTypeFunction(dataType: DataType) extends UnboundFunction {
+ override def name(): String = "file_fn"
+ override def description(): String = name()
+ override def bind(inputType: StructType): BoundFunction = new
ScalarFunction[AnyRef] {
+ override def inputTypes(): Array[DataType] = Array(LongType)
+ override def resultType(): DataType = dataType
+ override def name(): String = "file_fn"
+ override def produceResult(input: InternalRow): AnyRef = null
+ }
+}
+
+/** A UDAF that returns `dataType`; only its return type is used by the tests.
*/
+private class FileTypeUDAF(override val dataType: DataType) extends
UserDefinedAggregateFunction {
+ override def inputSchema: StructType = new StructType().add("x", IntegerType)
+ override def bufferSchema: StructType = new StructType()
+ override def deterministic: Boolean = true
+ override def initialize(buffer: MutableAggregationBuffer): Unit = {}
+ override def update(buffer: MutableAggregationBuffer, input: Row): Unit = {}
+ override def merge(buffer1: MutableAggregationBuffer, buffer2: Row): Unit =
{}
+ override def evaluate(buffer: Row): Any = null
+}
+
+/** A UDAF that returns a FILE EXTERNAL, for registration by class name. */
+private class ExternalFileTypeUDAF extends FileTypeUDAF(FileType.external)
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]