diff --git a/spark/src/main/resources/error/delta-error-classes.json b/spark/src/main/resources/error/delta-error-classes.json index 794a7564dd5..80913194ef7 100644 --- a/spark/src/main/resources/error/delta-error-classes.json +++ b/spark/src/main/resources/error/delta-error-classes.json @@ -2840,6 +2840,13 @@ ], "sqlState" : "0AKDC" }, + "DELTA_REPLACE_PARTITIONED_BY_WRITE_PARTITION_COLUMNS_DISABLED" : { + "message" : [ + "Cannot rewrite the data files that do not store the partition column(s) , for example: , because the table property delta.writePartitionColumnsToParquet is false.", + "Set it to true and run ALTER TABLE REPLACE PARTITIONED BY again." + ], + "sqlState" : "55000" + }, "DELTA_REPLACE_TABLE_WITH_CATALOG_MANAGED_NOT_SUPPORTED" : { "message" : [ "REPLACE TABLE cannot enable catalog-managed on the existing non-catalog-managed table . Upgrade or recreate the table instead." diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/DeltaErrors.scala b/spark/src/main/scala/org/apache/spark/sql/delta/DeltaErrors.scala index 4dcf6bfe707..22f7d78b6d7 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/DeltaErrors.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/DeltaErrors.scala @@ -4378,6 +4378,14 @@ trait DeltaErrorsBase partitionColumns.mkString(", "), numFiles.toString, examplePaths.mkString(", "))) } + def replacePartitionedByWritePartitionColumnsDisabledException( + partitionColumns: Seq[String], + examplePaths: Seq[String]): Throwable = { + new DeltaAnalysisException( + errorClass = "DELTA_REPLACE_PARTITIONED_BY_WRITE_PARTITION_COLUMNS_DISABLED", + messageParameters = Array(partitionColumns.mkString(", "), examplePaths.mkString(", "))) + } + def createTableWithDifferentClusteringException( path: Path, specifiedClusterBySpec: Option[ClusterBySpec], diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/commands/AlterTableReplacePartitionedByWithClusterByDeltaCommand.scala b/spark/src/main/scala/org/apache/spark/sql/delta/commands/AlterTableReplacePartitionedByWithClusterByDeltaCommand.scala index f2d55da2d93..a61522250eb 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/commands/AlterTableReplacePartitionedByWithClusterByDeltaCommand.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/commands/AlterTableReplacePartitionedByWithClusterByDeltaCommand.scala @@ -26,6 +26,7 @@ import org.apache.spark.sql.delta._ import org.apache.spark.sql.delta.actions.{Action, Metadata} import org.apache.spark.sql.delta.amt.AMTUtils import org.apache.spark.sql.delta.catalog.DeltaTableV2 +import org.apache.spark.sql.delta.files.TransactionalWrite import org.apache.spark.sql.delta.schema.SchemaMergingUtils import org.apache.spark.sql.delta.sources.DeltaSQLConf import org.apache.spark.sql.delta.stats.{DeltaStatistics, SkippingEligibleDataType, StatisticsCollection} @@ -36,8 +37,8 @@ import com.fasterxml.jackson.databind.cfg.JsonNodeFeature import com.fasterxml.jackson.databind.node.{DecimalNode, LongNode, ObjectNode, TextNode} import org.apache.parquet.format.converter.ParquetMetadataConverter -import org.apache.spark.sql.{Row, SparkSession} -import org.apache.spark.sql.catalyst.analysis.UnresolvedAttribute +import org.apache.spark.sql.{Dataset, Row, SparkSession} +import org.apache.spark.sql.catalyst.analysis.{ResolvedTable, UnresolvedAttribute} import org.apache.spark.sql.catalyst.expressions.{Cast, Literal} import org.apache.spark.sql.connector.expressions.FieldReference import org.apache.spark.sql.execution.command.LeafRunnableCommand @@ -48,7 +49,7 @@ import org.apache.spark.util.SerializableConfiguration /** * Command that replaces the partitioning of a Delta table with clustering, without rewriting - * any data file: + * the data files that store the partition columns: * - ALTER TABLE .. REPLACE PARTITIONED BY WITH CLUSTER BY (col1, col2, ...) * - ALTER TABLE .. REPLACE PARTITIONED BY WITH CLUSTER BY NONE * - ALTER TABLE .. REPLACE PARTITIONED BY WITH CLUSTER BY, which clusters the table by its @@ -65,7 +66,9 @@ import org.apache.spark.util.SerializableConfiguration * After the conversion the former partition columns are read from the data files, so they must be * physically stored in every data file (see `delta.writePartitionColumnsToParquet` and the * `materializePartitionColumns` table feature). This is verified by reading the Parquet footers - * before committing. + * before committing. Files that do not store them are first rewritten by an internal REORG, in + * separate commits, unless `alterTable.replacePartitionedBy.rewriteNonMaterializedFiles` is + * disabled. The conversion commit itself only re-adds files. * * When a former partition column would not get statistics anymore, because it is after the first * `delta.dataSkippingNumIndexedCols` columns or not in `delta.dataSkippingStatsColumns`, the @@ -89,121 +92,172 @@ case class AlterTableReplacePartitionedByWithClusterByDeltaCommand( override def run(sparkSession: SparkSession): Seq[Row] = { val deltaLog = table.deltaLog recordDeltaOperation(deltaLog, "delta.ddl.alter.replacePartitionedByWithClusterBy") { - val txn = startTransaction() - val snapshot = txn.snapshot - val oldMetadata = txn.metadata - if (oldMetadata.partitionColumns.isEmpty) { - throw DeltaErrors.replacePartitionedByOnUnpartitionedTableException() + val rewriteAllowed = sparkSession.sessionState.conf.getConf( + DeltaSQLConf.DELTA_REPLACE_PARTITIONED_BY_REWRITE_NON_MATERIALIZED_FILES) + if (!replacePartitioning(sparkSession, deltaLog, rewriteAllowed)) { + // Data files were rewritten so that they store the partition columns. Drop the + // partitioning now. If files without the partition columns were added in the meantime, + // fail instead of rewriting again. + replacePartitioning(sparkSession, deltaLog, rewriteAllowed = false) } - // The commit below neither runs the IcebergCompat checks (which do not allow changing the - // partition columns) nor converts the table to Iceberg or Hudi, and the adaptive metadata - // manifest of the files records their partitioning. - IcebergCompat.anyEnabled(oldMetadata).foreach { compat => - throw DeltaErrors.replacePartitionedByUnsupportedTableFeatureException(compat.config.key) - } - if (UniversalFormat.icebergEnabled(oldMetadata) || UniversalFormat.hudiEnabled(oldMetadata)) { - throw DeltaErrors.replacePartitionedByUnsupportedTableFeatureException( - DeltaConfigs.UNIVERSAL_FORMAT_ENABLED_FORMATS.key) - } - if (AMTUtils.amtEnabled(snapshot, isPreviewCompatible = true)) { - throw DeltaErrors.replacePartitionedByUnsupportedTableFeatureException( - AdaptiveMetadataTableFeatureBase.supportedBy(snapshot.protocol) - .getOrElse(AdaptiveMetadataTableFeature).name) - } - val clusteringColumns = if (clusterByPartitionColumns) { - oldMetadata.partitionColumns.map(Seq(_)) - } else { - requestedClusteringColumns - } - ClusteredTableUtils.validateNumClusteringColumns(clusteringColumns, Some(deltaLog)) + } + Seq.empty[Row] + } - val physicalPartitionSchema = oldMetadata.physicalPartitionSchema - val conf = sparkSession.sessionState.conf + /** + * Validates the command and drops the partitioning in a single metadata-only commit. + * + * If some data files do not store the partition columns and `rewriteAllowed`, rewrites these + * files instead, with REORG commits, and returns false without dropping the partitioning. The + * conversion commit itself never adds or removes files. + */ + private def replacePartitioning( + sparkSession: SparkSession, + deltaLog: DeltaLog, + rewriteAllowed: Boolean): Boolean = { + val txn = startTransaction() + val snapshot = txn.snapshot + val oldMetadata = txn.metadata + if (oldMetadata.partitionColumns.isEmpty) { + throw DeltaErrors.replacePartitionedByOnUnpartitionedTableException() + } + // The commit below neither runs the IcebergCompat checks (which do not allow changing the + // partition columns) nor converts the table to Iceberg or Hudi, and the adaptive metadata + // manifest of the files records their partitioning. + IcebergCompat.anyEnabled(oldMetadata).foreach { compat => + throw DeltaErrors.replacePartitionedByUnsupportedTableFeatureException(compat.config.key) + } + if (UniversalFormat.icebergEnabled(oldMetadata) || UniversalFormat.hudiEnabled(oldMetadata)) { + throw DeltaErrors.replacePartitionedByUnsupportedTableFeatureException( + DeltaConfigs.UNIVERSAL_FORMAT_ENABLED_FORMATS.key) + } + if (AMTUtils.amtEnabled(snapshot, isPreviewCompatible = true)) { + throw DeltaErrors.replacePartitionedByUnsupportedTableFeatureException( + AdaptiveMetadataTableFeatureBase.supportedBy(snapshot.protocol) + .getOrElse(AdaptiveMetadataTableFeature).name) + } + val clusteringColumns = if (clusterByPartitionColumns) { + oldMetadata.partitionColumns.map(Seq(_)) + } else { + requestedClusteringColumns + } + ClusteredTableUtils.validateNumClusteringColumns(clusteringColumns, Some(deltaLog)) - // Update the metadata and validate the clustering columns before reading the footers of all - // data files below, so that invalid commands fail fast. - val newLogicalClusteringColumns = clusteringColumns.map(FieldReference(_).toString) - val baseConfiguration = oldMetadata.configuration - val clusteringConfiguration = - if (clusteringColumns.nonEmpty && !ClusteredTableUtils.isSupported(txn.protocol)) { - ClusteredTableUtils.getTableFeatureProperties(baseConfiguration) - } else { - Map.empty[String, String] - } - val unpartitionedMetadata = oldMetadata.copy( - partitionColumns = Nil, configuration = baseConfiguration ++ clusteringConfiguration) - val statsColumnsConfiguration = - ReplacePartitionedByUtils.statsColumnsConfiguration(oldMetadata, unpartitionedMetadata) - txn.updateMetadata(unpartitionedMetadata.copy( - configuration = unpartitionedMetadata.configuration ++ statsColumnsConfiguration)) + val physicalPartitionSchema = oldMetadata.physicalPartitionSchema + val conf = sparkSession.sessionState.conf - val domainMetadata = if (clusteringColumns.nonEmpty) { - ClusteredTableUtils.validateClusteringColumnsInStatsSchema( - txn.protocol, txn.metadata, ClusterBySpec(clusteringColumns)) - ClusteredTableUtils.getClusteringDomainMetadataForAlterTableClusterBy( - newLogicalClusteringColumns, txn) + // Update the metadata and validate the clustering columns before reading the footers of all + // data files below, so that invalid commands fail fast. + val newLogicalClusteringColumns = clusteringColumns.map(FieldReference(_).toString) + val baseConfiguration = oldMetadata.configuration + val clusteringConfiguration = + if (clusteringColumns.nonEmpty && !ClusteredTableUtils.isSupported(txn.protocol)) { + ClusteredTableUtils.getTableFeatureProperties(baseConfiguration) } else { - Nil + Map.empty[String, String] } + val unpartitionedMetadata = oldMetadata.copy( + partitionColumns = Nil, configuration = baseConfiguration ++ clusteringConfiguration) + val statsColumnsConfiguration = + ReplacePartitionedByUtils.statsColumnsConfiguration(oldMetadata, unpartitionedMetadata) + txn.updateMetadata(unpartitionedMetadata.copy( + configuration = unpartitionedMetadata.configuration ++ statsColumnsConfiguration)) - ReplacePartitionedByUtils.verifyPartitionColumnsMaterialized( - sparkSession, deltaLog, snapshot, oldMetadata.partitionColumns, - physicalPartitionSchema.fieldNames.toSeq) + val domainMetadata = if (clusteringColumns.nonEmpty) { + ClusteredTableUtils.validateClusteringColumnsInStatsSchema( + txn.protocol, txn.metadata, ClusterBySpec(clusteringColumns)) + ClusteredTableUtils.getClusteringDomainMetadataForAlterTableClusterBy( + newLogicalClusteringColumns, txn) + } else { + Nil + } - val stringPrefixLength = conf.getConf(DeltaSQLConf.DATA_SKIPPING_STRING_PREFIX_LENGTH) - val timeZoneId = conf.sessionLocalTimeZone - val partitionFields = physicalPartitionSchema.fields.toSeq - import org.apache.spark.sql.delta.implicits._ - val newAddFiles = snapshot.allFiles.mapPartitions { files => - files.map { file => - file.copy( - partitionValues = Map.empty, - dataChange = false, - stats = ReplacePartitionedByUtils.addPartitionValuesToStats( - file.stats, file.partitionValues, partitionFields, stringPrefixLength, timeZoneId)) - } + val filesWithoutPartitionColumns = ReplacePartitionedByUtils.filesWithoutPartitionColumns( + sparkSession, deltaLog, snapshot, physicalPartitionSchema.fieldNames.toSeq) + val examplePaths = + filesWithoutPartitionColumns.take(ReplacePartitionedByUtils.NUM_EXAMPLE_FILES).toSeq + if (examplePaths.nonEmpty) { + if (!rewriteAllowed) { + throw DeltaErrors.replacePartitionedByPartitionColumnsNotMaterializedException( + oldMetadata.partitionColumns, filesWithoutPartitionColumns.count(), examplePaths) + } + if (!TransactionalWrite.writesPartitionColumns(snapshot.metadata, snapshot.protocol)) { + throw DeltaErrors.replacePartitionedByWritePartitionColumnsDisabledException( + oldMetadata.partitionColumns, examplePaths) } + rewriteFilesWithoutPartitionColumns(sparkSession) + return false + } - val actions: Iterator[Action] = - newAddFiles.toLocalIterator().asScala ++ domainMetadata.iterator - val newProtocolOpt = - if (txn.protocol != snapshot.protocol) Some(txn.protocol) else None - txn.commitLarge( - sparkSession, - actions, - newProtocolOpt, - DeltaOperations.ReplacePartitionedByWithClusterBy( - oldMetadata.partitionColumns.mkString(","), - newLogicalClusteringColumns.mkString(",")), - context = Map.empty, - metrics = Map.empty, - dataChange = false) + val stringPrefixLength = conf.getConf(DeltaSQLConf.DATA_SKIPPING_STRING_PREFIX_LENGTH) + val timeZoneId = conf.sessionLocalTimeZone + val partitionFields = physicalPartitionSchema.fields.toSeq + import org.apache.spark.sql.delta.implicits._ + val newAddFiles = snapshot.allFiles.mapPartitions { files => + files.map { file => + file.copy( + partitionValues = Map.empty, + dataChange = false, + stats = ReplacePartitionedByUtils.addPartitionValuesToStats( + file.stats, file.partitionValues, partitionFields, stringPrefixLength, timeZoneId)) + } } - Seq.empty[Row] + + val actions: Iterator[Action] = + newAddFiles.toLocalIterator().asScala ++ domainMetadata.iterator + val newProtocolOpt = + if (txn.protocol != snapshot.protocol) Some(txn.protocol) else None + txn.commitLarge( + sparkSession, + actions, + newProtocolOpt, + DeltaOperations.ReplacePartitionedByWithClusterBy( + oldMetadata.partitionColumns.mkString(","), + newLogicalClusteringColumns.mkString(",")), + context = Map.empty, + metrics = Map.empty, + dataChange = false) + true + } + + /** + * Rewrites the data files that do not store all partition columns with an internal REORG, which + * commits like OPTIMIZE (in batches with `optimize.batchSize`) and applies deletion vectors. + */ + private def rewriteFilesWithoutPartitionColumns(spark: SparkSession): Unit = { + // Wrap `table` in a ResolvedTable that can be passed to DeltaReorgTableCommand. The catalog + // and table ID are not used by DeltaReorgTableCommand. + import org.apache.spark.sql.connector.catalog.CatalogV2Implicits._ + val catalog = spark.sessionState.catalogManager.currentCatalog.asTableCatalog + val tableId = Seq(table.name()).asIdentifier + DeltaReorgTableCommand( + target = ResolvedTable.create(catalog, tableId, table), + reorgTableSpec = + DeltaReorgTableSpec(DeltaReorgTableMode.MATERIALIZE_PARTITION_COLUMNS, None) + )(Nil).run(spark) } } object ReplacePartitionedByUtils { - private val NUM_EXAMPLE_FILES = 5 + val NUM_EXAMPLE_FILES = 5 /** - * Verifies that every active data file of the snapshot physically stores all the given - * partition columns, by reading the Parquet footers of the files. + * Returns the paths of the active data files of the snapshot that do not physically store all + * the given partition columns, by reading the Parquet footers of the files. */ - def verifyPartitionColumnsMaterialized( + def filesWithoutPartitionColumns( spark: SparkSession, deltaLog: DeltaLog, snapshot: Snapshot, - logicalPartitionColumns: Seq[String], - physicalPartitionColumns: Seq[String]): Unit = { + physicalPartitionColumns: Seq[String]): Dataset[String] = { val broadcastConf = spark.sparkContext.broadcast( new SerializableConfiguration(deltaLog.newDeltaHadoopConf())) val dataRootDir = deltaLog.dataPath.toString val requiredColumns = physicalPartitionColumns.map(_.toLowerCase(Locale.ROOT)) import org.apache.spark.sql.delta.implicits._ - val filesMissingColumns = snapshot.allFiles.select("path").as[String].mapPartitions { paths => + snapshot.allFiles.select("path").as[String].mapPartitions { paths => val conf = broadcastConf.value.value paths.filter { relativePath => val path = DeltaFileOperations.absolutePath(dataRootDir, relativePath) @@ -215,12 +269,6 @@ object ReplacePartitionedByUtils { !requiredColumns.forall(fileColumns.contains) } } - - val examples = filesMissingColumns.take(NUM_EXAMPLE_FILES) - if (examples.nonEmpty) { - throw DeltaErrors.replacePartitionedByPartitionColumnsNotMaterializedException( - logicalPartitionColumns, filesMissingColumns.count(), examples.toSeq) - } } /** diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/commands/DeltaReorgTableCommand.scala b/spark/src/main/scala/org/apache/spark/sql/delta/commands/DeltaReorgTableCommand.scala index 7a474909e6a..c2e767e92f9 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/commands/DeltaReorgTableCommand.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/commands/DeltaReorgTableCommand.scala @@ -16,6 +16,8 @@ package org.apache.spark.sql.delta.commands +import java.util.Locale + import org.apache.spark.sql.delta.{ CatalogManagedTableMaintenanceOperation, DeltaColumnMapping, @@ -27,7 +29,7 @@ import org.apache.spark.sql.{Row, SparkSession} import org.apache.spark.sql.catalyst.plans.logical.{LeafCommand, LogicalPlan, UnaryCommand} object DeltaReorgTableMode extends Enumeration { - val PURGE, UNIFORM_ICEBERG, REWRITE_TYPE_WIDENING = Value + val PURGE, UNIFORM_ICEBERG, REWRITE_TYPE_WIDENING, MATERIALIZE_PARTITION_COLUMNS = Value } case class DeltaReorgTableSpec( @@ -75,7 +77,8 @@ case class DeltaReorgTableCommand( override def run(sparkSession: SparkSession): Seq[Row] = reorgTableSpec match { case DeltaReorgTableSpec( - DeltaReorgTableMode.PURGE | DeltaReorgTableMode.REWRITE_TYPE_WIDENING, None) => + DeltaReorgTableMode.PURGE | DeltaReorgTableMode.REWRITE_TYPE_WIDENING | + DeltaReorgTableMode.MATERIALIZE_PARTITION_COLUMNS, None) => optimizeByReorg(sparkSession) case DeltaReorgTableSpec(DeltaReorgTableMode.UNIFORM_ICEBERG, Some(icebergCompatVersion)) => val table = getDeltaTable(target, "REORG") @@ -93,6 +96,8 @@ case class DeltaReorgTableCommand( new DeltaUpgradeUniformOperation(icebergCompatVersion) case DeltaReorgTableSpec(DeltaReorgTableMode.REWRITE_TYPE_WIDENING, None) => new DeltaRewriteTypeWideningOperation() + case DeltaReorgTableSpec(DeltaReorgTableMode.MATERIALIZE_PARTITION_COLUMNS, None) => + new DeltaMaterializePartitionColumnsOperation() } } @@ -168,3 +173,23 @@ class DeltaRewriteTypeWideningOperation extends DeltaReorgOperation with ReorgTa } } } + +/** + * Internal reorg operation to rewrite the files that do not store all partition columns, before + * `ALTER TABLE ... REPLACE PARTITIONED BY` drops the partitioning. The new files store them as + * long as the table writes partition columns (see `TransactionalWrite.writesPartitionColumns`). + */ +class DeltaMaterializePartitionColumnsOperation + extends DeltaReorgOperation with ReorgTableHelper { + override def filterFilesToReorg( + spark: SparkSession, + snapshot: SnapshotDescriptor, + files: Seq[AddFile]): Seq[AddFile] = { + val partitionColumns = + snapshot.metadata.physicalPartitionSchema.fieldNames.map(_.toLowerCase(Locale.ROOT)).toSeq + filterParquetFilesOnExecutors(spark, files, snapshot, ignoreCorruptFiles = false) { schema => + val fileColumns = schema.fieldNames.map(_.toLowerCase(Locale.ROOT)).toSet + !partitionColumns.forall(fileColumns.contains) + } + } +} diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/files/TransactionalWrite.scala b/spark/src/main/scala/org/apache/spark/sql/delta/files/TransactionalWrite.scala index 0cd2ecd320f..5c949b8bcb6 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/files/TransactionalWrite.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/files/TransactionalWrite.scala @@ -474,10 +474,7 @@ trait TransactionalWrite extends DeltaLogging { self: OptimisticTransactionImpl statsTrackers.append(basicWriteJobStatsTracker) } - // Iceberg spec requires partition columns in data files - val writePartitionColumns = IcebergCompat.isAnyEnabled(metadata) || - protocol.isFeatureSupported(MaterializePartitionColumnsTableFeature) || - DeltaConfigs.WRITE_PARTITION_COLUMNS_TO_PARQUET.fromMetaData(metadata).getOrElse(true) + val writePartitionColumns = TransactionalWrite.writesPartitionColumns(metadata, protocol) // Retain only a minimal selection of Spark writer options to avoid any potential // compatibility issues val filteredOptions = (writeOptions match { @@ -586,6 +583,14 @@ trait TransactionalWrite extends DeltaLogging { self: OptimisticTransactionImpl } object TransactionalWrite { + /** Whether the data files written to the table store the values of its partition columns. */ + def writesPartitionColumns(metadata: Metadata, protocol: Protocol): Boolean = { + // Iceberg spec requires partition columns in data files + IcebergCompat.isAnyEnabled(metadata) || + protocol.isFeatureSupported(MaterializePartitionColumnsTableFeature) || + DeltaConfigs.WRITE_PARTITION_COLUMNS_TO_PARQUET.fromMetaData(metadata).getOrElse(true) + } + def shouldOptimizeWrite(metadata: Metadata, sessionConf: SQLConf): Boolean = { sessionConf.getConf(DeltaSQLConf.DELTA_OPTIMIZE_WRITE_ENABLED) .orElse(DeltaConfigs.OPTIMIZE_WRITE.fromMetaData(metadata)) diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/sources/DeltaSQLConf.scala b/spark/src/main/scala/org/apache/spark/sql/delta/sources/DeltaSQLConf.scala index 87fd5abdd9d..d4246018097 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/sources/DeltaSQLConf.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/sources/DeltaSQLConf.scala @@ -2890,6 +2890,15 @@ trait DeltaSQLConfBase extends DeltaSQLConfUtils { .booleanConf .createWithDefault(true) + val DELTA_REPLACE_PARTITIONED_BY_REWRITE_NON_MATERIALIZED_FILES = + buildConf("alterTable.replacePartitionedBy.rewriteNonMaterializedFiles") + .internal() + .doc("""When true, ALTER TABLE ... REPLACE PARTITIONED BY WITH CLUSTER BY first rewrites the + |data files that do not store the partition columns, with REORG commits, and then drops + |the partitioning. When false, the command fails if such files exist.""".stripMargin) + .booleanConf + .createWithDefault(true) + val DELTA_BYPASS_CHARVARCHAR_TO_STRING_FIX = buildConf("alterTable.bypassCharVarcharToStringFix") .internal() diff --git a/spark/src/test/scala/org/apache/spark/sql/delta/skipping/clustering/ReplacePartitionedByWithClusterBySuite.scala b/spark/src/test/scala/org/apache/spark/sql/delta/skipping/clustering/ReplacePartitionedByWithClusterBySuite.scala index 363fb516a5c..3045428f4d1 100644 --- a/spark/src/test/scala/org/apache/spark/sql/delta/skipping/clustering/ReplacePartitionedByWithClusterBySuite.scala +++ b/spark/src/test/scala/org/apache/spark/sql/delta/skipping/clustering/ReplacePartitionedByWithClusterBySuite.scala @@ -21,7 +21,7 @@ import java.io.File import org.apache.spark.sql.delta.skipping.ClusteredTableTestUtils import org.apache.spark.sql.delta.skipping.clustering.temp.{AlterTableReplacePartitionedByWithClusterBy, ClusterBySpec} import org.apache.spark.sql.delta.{AdaptiveMetadataPreviewTableFeature, DeltaAnalysisException, DeltaConfigs, DeltaLog, DeltaOperations, DeltaUnsupportedOperationException} -import org.apache.spark.sql.delta.actions.{AddFile, TableFeatureProtocolUtils} +import org.apache.spark.sql.delta.actions.{AddFile, RemoveFile, TableFeatureProtocolUtils} import org.apache.spark.sql.delta.commands.ReplacePartitionedByUtils import org.apache.spark.sql.delta.coordinatedcommits.CatalogOwnedTestBaseSuite import org.apache.spark.sql.delta.sources.DeltaSQLConf @@ -302,16 +302,116 @@ class ReplacePartitionedByWithClusterBySuite } } - test("fails when data files do not store the partition columns") { + /** Paths of the active files that do not store all the given physical partition columns. */ + private def filesWithoutPartitionColumns(path: String, columns: String*): Set[String] = { + val deltaLog = DeltaLog.forTable(spark, path) + ReplacePartitionedByUtils + .filesWithoutPartitionColumns(spark, deltaLog, deltaLog.update(), columns) + .collect().toSet + } + + /** Creates a table with two files that do not store `p` and two files that do. */ + private def createTableWithFilesWithoutPartitionColumns(path: String): Unit = { + sql(s"""CREATE TABLE delta.`$path` (id BIGINT, p STRING) USING delta PARTITIONED BY (p) + |TBLPROPERTIES ('delta.writePartitionColumnsToParquet' = 'false')""".stripMargin) + sql(s"INSERT INTO delta.`$path` VALUES (1, 'a'), (2, 'b')") + sql(s"ALTER TABLE delta.`$path` SET TBLPROPERTIES " + + "('delta.writePartitionColumnsToParquet' = 'true')") + sql(s"INSERT INTO delta.`$path` VALUES (3, 'a'), (4, null)") + } + + test("rewrites the data files that do not store the partition columns before the conversion") { + withTempDir { dir => + val path = dir.getCanonicalPath + createTableWithFilesWithoutPartitionColumns(path) + val deltaLog = DeltaLog.forTable(spark, path) + val before = deltaLog.update() + val notMaterialized = filesWithoutPartitionColumns(path, "p") + assert(notMaterialized.size === 2) + val materialized = before.allFiles.collect().map(_.path).toSet -- notMaterialized + assert(materialized.size === 2) + + sql(s"ALTER TABLE delta.`$path` REPLACE PARTITIONED BY WITH CLUSTER BY NONE") + + // A REORG commit rewrites the files that do not store the partition columns, while the + // table is still partitioned. Then the partitioning is dropped. + val after = deltaLog.update() + assert(after.version === before.version + 2) + assert(deltaLog.history.getHistory(Some(2)).map(_.operation) === Seq(opName, "REORG")) + val reorgChanges = deltaLog.getChanges(before.version + 1).next()._2 + val removed = reorgChanges.collect { case r: RemoveFile => r } + assert(removed.map(_.path).toSet === notMaterialized) + assert(removed.forall(!_.dataChange)) + val rewritten = reorgChanges.collect { case a: AddFile => a } + assert(rewritten.nonEmpty) + assert(rewritten.forall(f => !f.dataChange && f.partitionValues.contains("p"))) + + // The conversion commit re-adds every file and neither adds nor removes one. + val afterFiles = after.allFiles.collect() + val afterPaths = afterFiles.map(_.path).toSet + assert(afterPaths === materialized ++ rewritten.map(_.path)) + val conversionChanges = deltaLog.getChanges(after.version).next()._2 + assert(!conversionChanges.exists(_.isInstanceOf[RemoveFile])) + assert(conversionChanges.collect { case a: AddFile => a.path }.toSet === afterPaths) + assert(afterFiles.forall(_.partitionValues.isEmpty)) + assert(filesWithoutPartitionColumns(path, "p").isEmpty) + + // The rewritten files also get statistics for the former partition column. + val rewrittenPaths = rewritten.map(_.path).toSet + val rewrittenStats = afterFiles.filter(f => rewrittenPaths(f.path)).map(statsOf) + def pStats(kind: String): Set[String] = + rewrittenStats.map(_(kind).asInstanceOf[Map[String, Any]]("p").toString).toSet + assert(pStats("minValues") === Set("a", "b")) + assert(pStats("maxValues") === Set("a", "b")) + assert(filesRead(spark, deltaLog, "p = 'b'", checkEmptyUnusedFilters = false) < + afterFiles.length) + + checkAnswer(readTable(path), Seq(Row(1L, "a"), Row(2L, "b"), Row(3L, "a"), Row(4L, null))) + checkAnswer(readTable(path).where("p = 'b'").select("id"), Row(2L)) + checkAnswer(readTable(path).where("p IS NULL").select("id"), Row(4L)) + } + } + + test("rewrite applies deletion vectors and preserves row tracking") { withTempDir { dir => val path = dir.getCanonicalPath sql(s"""CREATE TABLE delta.`$path` (id BIGINT, p STRING) USING delta PARTITIONED BY (p) - |TBLPROPERTIES ('delta.writePartitionColumnsToParquet' = 'false')""".stripMargin) - sql(s"INSERT INTO delta.`$path` VALUES (1, 'a'), (2, 'b')") + |TBLPROPERTIES ( + | 'delta.writePartitionColumnsToParquet' = 'false', + | 'delta.enableDeletionVectors' = 'true', + | 'delta.enableRowTracking' = 'true')""".stripMargin) + spark.range(0, 100, 1, 4).selectExpr("id", "cast(id % 3 as string) as p") + .write.format("delta").mode("append").save(path) + sql(s"DELETE FROM delta.`$path` WHERE id % 10 = 0") + sql(s"ALTER TABLE delta.`$path` SET TBLPROPERTIES " + + "('delta.writePartitionColumnsToParquet' = 'true')") + val deltaLog = DeltaLog.forTable(spark, path) + assert(deltaLog.update().allFiles.collect().exists(_.deletionVector != null)) + val rowTrackingColumns = Seq("*", "_metadata.row_id", "_metadata.row_commit_version") + val expected = readTable(path).selectExpr(rowTrackingColumns: _*).collect() + assert(expected.length === 90) + + sql(s"ALTER TABLE delta.`$path` REPLACE PARTITIONED BY WITH CLUSTER BY NONE") + + val after = deltaLog.update() + assert(after.metadata.partitionColumns.isEmpty) + assert(after.allFiles.collect().forall(_.deletionVector == null)) + assert(filesWithoutPartitionColumns(path, "p").isEmpty) + checkAnswer(readTable(path).selectExpr(rowTrackingColumns: _*), expected) + } + } + + test("fails when data files do not store the partition columns and the rewrite is disabled") { + withTempDir { dir => + val path = dir.getCanonicalPath + createTableWithFilesWithoutPartitionColumns(path) val deltaLog = DeltaLog.forTable(spark, path) val versionBefore = deltaLog.update().version - val e = intercept[DeltaAnalysisException] { - sql(s"ALTER TABLE delta.`$path` REPLACE PARTITIONED BY WITH CLUSTER BY NONE") + val e = withSQLConf( + DeltaSQLConf.DELTA_REPLACE_PARTITIONED_BY_REWRITE_NON_MATERIALIZED_FILES.key -> "false") { + intercept[DeltaAnalysisException] { + sql(s"ALTER TABLE delta.`$path` REPLACE PARTITIONED BY WITH CLUSTER BY NONE") + } } assert(e.getErrorClass === "DELTA_REPLACE_PARTITIONED_BY_PARTITION_COLUMNS_NOT_MATERIALIZED") @@ -321,6 +421,44 @@ class ReplacePartitionedByWithClusterBySuite } } + test("fails when the rewritten files would not store the partition columns") { + withTempDir { dir => + val path = dir.getCanonicalPath + sql(s"""CREATE TABLE delta.`$path` (id BIGINT, p STRING) USING delta PARTITIONED BY (p) + |TBLPROPERTIES ('delta.writePartitionColumnsToParquet' = 'false')""".stripMargin) + sql(s"INSERT INTO delta.`$path` VALUES (1, 'a'), (2, 'b')") + val deltaLog = DeltaLog.forTable(spark, path) + val versionBefore = deltaLog.update().version + checkError( + exception = intercept[DeltaAnalysisException] { + sql(s"ALTER TABLE delta.`$path` REPLACE PARTITIONED BY WITH CLUSTER BY NONE") + }, + condition = "DELTA_REPLACE_PARTITIONED_BY_WRITE_PARTITION_COLUMNS_DISABLED", + matchPVals = true, + parameters = Map("partitionColumns" -> "p", "examplePaths" -> ".*p=.*")) + assert(deltaLog.update().version === versionBefore) + assert(deltaLog.update().metadata.partitionColumns === Seq("p")) + } + } + + test("validates the command before rewriting any file") { + withTempDir { dir => + val path = dir.getCanonicalPath + createTableWithFilesWithoutPartitionColumns(path) + val deltaLog = DeltaLog.forTable(spark, path) + val versionBefore = deltaLog.update().version + checkError( + exception = intercept[AnalysisException] { + sql(s"ALTER TABLE delta.`$path` REPLACE PARTITIONED BY WITH CLUSTER BY (missing)") + }, + condition = "DELTA_COLUMN_NOT_FOUND_IN_SCHEMA", + matchPVals = true, + parameters = Map("columnName" -> "missing", "tableSchema" -> "(?s).*")) + assert(deltaLog.update().version === versionBefore) + assert(filesWithoutPartitionColumns(path, "p").size === 2) + } + } + test("fails on a table with IcebergCompatV2") { withTempDir { dir => val path = dir.getCanonicalPath