This is an automated email from the ASF dual-hosted git repository.
JingsongLi pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/paimon.git
The following commit(s) were added to refs/heads/master by this push:
new 3431d5fd13 [spark] Match BINARY partition values by content in
partition management (#11226)
3431d5fd13 is described below
commit 3431d5fd1337d0c8408f99c985a3042eb4bba5d7
Author: YangJie <[email protected]>
AuthorDate: Sun Nov 22 06:00:19 2026 -0500
[spark] Match BINARY partition values by content in partition management
(#11226)
---
.../spark/sql/Spark42CompatibilityTest.scala | 15 ++
.../paimon/spark/PaimonPartitionManagement.scala | 232 ++++++++++++++++++---
.../spark/sql/DDLWithHiveCatalogTestBase.scala | 31 +++
.../spark/sql/PaimonPartitionManagementTest.scala | 220 ++++++++++++++++++-
4 files changed, 463 insertions(+), 35 deletions(-)
diff --git
a/paimon-spark/paimon-spark-4.2/src/test/scala/org/apache/paimon/spark/sql/Spark42CompatibilityTest.scala
b/paimon-spark/paimon-spark-4.2/src/test/scala/org/apache/paimon/spark/sql/Spark42CompatibilityTest.scala
index 45d21c3168..9f36aa10db 100644
---
a/paimon-spark/paimon-spark-4.2/src/test/scala/org/apache/paimon/spark/sql/Spark42CompatibilityTest.scala
+++
b/paimon-spark/paimon-spark-4.2/src/test/scala/org/apache/paimon/spark/sql/Spark42CompatibilityTest.scala
@@ -144,6 +144,21 @@ class Spark42CompatibilityTest extends QueryTest with
SharedSparkSession {
}
}
+ test("describe a binary partition") {
+ withTable("t") {
+ sql("CREATE TABLE t (id INT, p BINARY) PARTITIONED BY (p)")
+ sql("INSERT INTO t VALUES (1, CAST('2021' AS BINARY)), (2, CAST('2022'
AS BINARY))")
+ // Spark renders a BINARY partition value as hex bytes by default.
+ withSQLConf("spark.sql.binaryOutputStyle" -> "UTF-8") {
+ checkAnswer(
+ sql("DESCRIBE FORMATTED t PARTITION (p = '2021')")
+ .filter("col_name = 'Partition Values'")
+ .select("data_type"),
+ Seq(Row("[p=2021]")))
+ }
+ }
+ }
+
test("SQL scalar functions, builtin lookup and unsupported table function
rejection") {
try {
sql("CREATE FUNCTION add_one(x INT) RETURNS INT RETURN x + 1")
diff --git
a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/PaimonPartitionManagement.scala
b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/PaimonPartitionManagement.scala
index f53cefb93d..2232b6dd34 100644
---
a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/PaimonPartitionManagement.scala
+++
b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/PaimonPartitionManagement.scala
@@ -19,11 +19,15 @@
package org.apache.paimon.spark
import org.apache.paimon.CoreOptions
-import org.apache.paimon.partition.PartitionStatistics
+import org.apache.paimon.data.{GenericRow, InternalRow => PaimonInternalRow,
Timestamp}
+import org.apache.paimon.data.serializer.InternalRowSerializer
+import org.apache.paimon.options.Options
+import org.apache.paimon.partition.{PartitionPredicate, PartitionStatistics}
+import org.apache.paimon.predicate.PredicateBuilder
import org.apache.paimon.table.{FileStoreTable, FormatTable, Table}
import org.apache.paimon.table.source.ScanMode
-import org.apache.paimon.types.RowType
-import org.apache.paimon.utils.{InternalRowPartitionComputer, TypeUtils}
+import org.apache.paimon.types.{DataTypeChecks, RowType}
+import org.apache.paimon.utils.{DateTimeUtils, InternalRowPartitionComputer,
TypeUtils}
import org.apache.spark.internal.Logging
import org.apache.spark.sql.Row
@@ -31,8 +35,10 @@ import
org.apache.spark.sql.catalyst.{CatalystTypeConverters, InternalRow}
import org.apache.spark.sql.catalyst.util.CharVarcharUtils
import
org.apache.spark.sql.connector.catalog.{SupportsAtomicPartitionManagement,
TableCatalog}
import org.apache.spark.sql.types.StructType
+import org.apache.spark.unsafe.types.UTF8String
-import java.util.{Map => JMap, Objects}
+import java.nio.charset.StandardCharsets
+import java.util.{Arrays, LinkedHashMap => JLinkedHashMap, Map => JMap,
Objects}
import scala.collection.JavaConverters._
@@ -94,25 +100,176 @@ trait PaimonPartitionManagement extends
SupportsAtomicPartitionManagement with L
new SparkRow(currentPartitionRowType,
rowConverter(row).asInstanceOf[Row]))
}
+ /**
+ * The first partition column whose value in `spec` does not parse back to
its value in `row`. A
+ * spec holds each value as a string, and a blank one is written as the
default partition name,
+ * which parses back as NULL.
+ */
+ private def columnNotParsedBack(row: InternalRow, spec: JMap[String,
String]): Option[String] = {
+ val names = table.partitionKeys().asScala.toSeq.take(row.numFields)
+ val specRowType = TypeUtils.project(table.rowType, names.asJava)
+ val parsed = InternalRowPartitionComputer.convertSpecToInternal(
+ spec,
+ specRowType,
+ CoreOptions.fromMap(table.options()).partitionDefaultName())
+ names.zipWithIndex
+ .find {
+ case (name, index) =>
+ val parsedValue =
+ DataConverter.fromPaimon(parsed.get(name),
specRowType.getField(name).`type`())
+ !Objects.deepEquals(row.get(index, partitionSchema(name).dataType),
parsedValue)
+ }
+ .map(_._1)
+ }
+
+ /** Whether the Spark value is a STRING or BINARY value equal to `text`. */
+ private def isText(value: Any, text: String): Boolean = value match {
+ case s: UTF8String => s.toString == text
+ case b: Array[Byte] => new String(b, StandardCharsets.UTF_8) == text
+ case _ => false
+ }
+
+ /** The first column of `row` whose value is the default partition name,
which is not NULL. */
+ private def columnHoldingDefaultPartitionName(row: InternalRow):
Option[String] = {
+ val defaultPartitionName =
CoreOptions.fromMap(table.options()).partitionDefaultName()
+ partitionSchema.fields.take(row.numFields).zipWithIndex.collectFirst {
+ case (field, i) if isText(row.get(i, field.dataType),
defaultPartitionName) => field.name
+ }
+ }
+
+ /**
+ * The Paimon values of the partition columns each row holds, the first ones
of the table, with
+ * timestamps at the column's precision.
+ */
+ private def toPaimonPartitionValues(rows: Seq[InternalRow]):
Seq[Array[AnyRef]] = {
+ val converters = rows
+ .map(_.numFields)
+ .distinct
+ .map {
+ numFields =>
+ val names = table.partitionKeys().asScala.toSeq.take(numFields)
+ val rowType = TypeUtils.project(table.rowType, names.asJava)
+ val toScala = CatalystTypeConverters.createToScalaConverter(
+ CharVarcharUtils.replaceCharVarcharWithString(
+ SparkTypeUtils.fromPaimonRowType(rowType)))
+ val getters = rowType.getFields.asScala.zipWithIndex.map {
+ case (field, i) =>
+ field.`type`() ->
PaimonInternalRow.createFieldGetter(field.`type`(), i)
+ }
+ numFields -> {
+ (row: InternalRow) =>
+ val paimonRow = new SparkRow(rowType,
toScala(row).asInstanceOf[Row])
+ getters.map {
+ case (dataType, getter) =>
+ getter.getFieldOrNull(paimonRow) match {
+ case timestamp: Timestamp =>
+ DateTimeUtils.truncate(timestamp,
DataTypeChecks.getPrecision(dataType))
+ case other => other
+ }
+ }.toArray
+ }
+ }
+ .toMap
+ rows.map(row => converters(row.numFields)(row))
+ }
+
+ /**
+ * The partitions `values` address, compared by value: full values address
their own partition, a
+ * prefix every partition under it.
+ */
+ private def toPartitionPredicate(values: Seq[Array[AnyRef]]):
PartitionPredicate = {
+ if (values.forall(_.length == partitionRowType.getFieldCount)) {
+ val serializer = new InternalRowSerializer(partitionRowType)
+ PartitionPredicate.fromMultiple(
+ partitionRowType,
+ values.map(v => serializer.toBinaryRow(GenericRow.of(v:
_*)).copy()).asJava)
+ } else {
+ val names = partitionRowType.getFieldNames
+ val predicates = values.map {
+ v =>
+ val spec = new JLinkedHashMap[String, AnyRef]()
+ v.indices.foreach(i => spec.put(names.get(i), v(i)))
+ PartitionPredicate.createPartitionPredicate(partitionRowType, spec)
+ }
+ PartitionPredicate.fromPredicate(partitionRowType,
PredicateBuilder.or(predicates.asJava))
+ }
+ }
+
+ private def toPartitionPredicate(row: InternalRow): PartitionPredicate =
+ toPartitionPredicate(toPaimonPartitionValues(Seq(row)))
+
+ /** The specs of the partitions to drop by name; each must address its own
partition. */
+ private def toRemovedPaimonPartitions(rows: Array[InternalRow]):
Array[JMap[String, String]] = {
+ val specs = toPaimonPartitions(rows)
+ rows.zip(specs).foreach {
+ case (row, spec) =>
+ columnNotParsedBack(row, spec).foreach {
+ name =>
+ val nullPartitionHint = if
(columnHoldingDefaultPartitionName(row).contains(name)) {
+ s" If you meant the NULL partition, use $name = NULL."
+ } else {
+ ""
+ }
+ throw new IllegalArgumentException(
+ s"Partition spec $spec of table ${table.name()} does not name
the partition to " +
+ s"remove: the value of partition column $name does not parse
back from it." +
+ nullPartitionHint)
+ }
+ }
+ specs
+ }
+
+ /**
+ * Removes the data of the partitions the rows address. The commit matches
them by value in the
+ * snapshot it commits on, as it matches a partition spec.
+ */
+ private def truncatePartitionsByValue(
+ fileStoreTable: FileStoreTable,
+ rows: Array[InternalRow]): Unit = {
+ if (rows.isEmpty) {
+ return
+ }
+ rows.foreach {
+ row =>
+ columnHoldingDefaultPartitionName(row).foreach {
+ name =>
+ val reader =
fileStoreTable.newSnapshotReader().withMode(ScanMode.ALL)
+ if
(reader.withPartitionFilter(toPartitionPredicate(row)).partitions().isEmpty) {
+ throw new IllegalArgumentException(
+ s"No partition of table ${table.name()} has the default
partition name as the " +
+ s"value of partition column $name. If you meant the NULL
partition, use " +
+ s"$name = NULL.")
+ }
+ }
+ }
+ val values = toPaimonPartitionValues(rows.toSeq)
+ logInfo(
+ s"Try to truncate the partitions of table ${table.name()} matching " +
+ values.map(v => Arrays.deepToString(v)).mkString(", "))
+ val commit =
+ fileStoreTable.newCommit(CoreOptions.createCommitUser(new
Options(fileStoreTable.options())))
+ try {
+ commit.truncatePartitions(toPartitionPredicate(values))
+ } finally {
+ commit.close()
+ }
+ }
+
override def dropPartitions(rows: Array[InternalRow]): Boolean = {
table match {
case fileStoreTable: FileStoreTable =>
- val partitions = toPaimonPartitions(rows).toSeq.asJava
- logInfo("Try to drop partitions: " + partitions.asScala.mkString(","))
val partitionModification =
fileStoreTable.catalogEnvironment().partitionModification()
if (partitionModification != null) {
+ // The catalog drops partitions by name.
try {
+ val partitions = toRemovedPaimonPartitions(rows).toSeq.asJava
+ logInfo("Try to drop partitions: " +
partitions.asScala.mkString(","))
partitionModification.dropPartitions(partitions)
} finally {
partitionModification.close()
}
} else {
- val commit = fileStoreTable.newBatchWriteBuilder().newCommit()
- try {
- commit.truncatePartitions(partitions)
- } finally {
- commit.close()
- }
+ truncatePartitionsByValue(fileStoreTable, rows)
}
true
@@ -122,12 +279,17 @@ trait PaimonPartitionManagement extends
SupportsAtomicPartitionManagement with L
}
override def truncatePartitions(idents: Array[InternalRow]): Boolean = {
- val partitions = toPaimonPartitions(idents).toSeq.asJava
- val commit = table.newBatchWriteBuilder().newCommit()
- try {
- commit.truncatePartitions(partitions)
- } finally {
- commit.close()
+ table match {
+ case fileStoreTable: FileStoreTable =>
+ truncatePartitionsByValue(fileStoreTable, idents)
+ case _ =>
+ val partitions = toPaimonPartitions(idents).toSeq.asJava
+ val commit = table.newBatchWriteBuilder().newCommit()
+ try {
+ commit.truncatePartitions(partitions)
+ } finally {
+ commit.close()
+ }
}
true
}
@@ -145,25 +307,26 @@ trait PaimonPartitionManagement extends
SupportsAtomicPartitionManagement with L
override def loadPartitionMetadata(ident: InternalRow): JMap[String, String]
= {
table match {
case fileStoreTable: FileStoreTable =>
- val partitionSpec = toPaimonPartitions(Array(ident)).head
- val partitionEntries = fileStoreTable
+ val partitionEntry = fileStoreTable
.newSnapshotReader()
.withMode(ScanMode.ALL)
- .withPartitionFilter(partitionSpec)
+ .withPartitionFilter(toPartitionPredicate(ident))
.partitionEntries()
+ .asScala
+ .headOption
- if (!partitionEntries.isEmpty) {
- val entry = partitionEntries.get(0)
- Map(
- PartitionStatistics.FIELD_RECORD_COUNT ->
entry.recordCount().toString,
- PartitionStatistics.FIELD_FILE_SIZE_IN_BYTES ->
entry.fileSizeInBytes().toString,
- PartitionStatistics.FIELD_FILE_COUNT -> entry.fileCount().toString,
- PartitionStatistics.FIELD_LAST_FILE_CREATION_TIME -> entry
- .lastFileCreationTime()
- .toString
- ).asJava
- } else {
- Map.empty[String, String].asJava
+ partitionEntry match {
+ case Some(entry) =>
+ Map(
+ PartitionStatistics.FIELD_RECORD_COUNT ->
entry.recordCount().toString,
+ PartitionStatistics.FIELD_FILE_SIZE_IN_BYTES ->
entry.fileSizeInBytes().toString,
+ PartitionStatistics.FIELD_FILE_COUNT ->
entry.fileCount().toString,
+ PartitionStatistics.FIELD_LAST_FILE_CREATION_TIME -> entry
+ .lastFileCreationTime()
+ .toString
+ ).asJava
+ case None =>
+ Map.empty[String, String].asJava
}
case formatTable: FormatTable =>
val partitionManager = formatTable.partitionManager()
@@ -233,7 +396,8 @@ trait PaimonPartitionManagement extends
SupportsAtomicPartitionManagement with L
case (partitionName, index) =>
val internalRowIndex =
partitionSchema.fieldIndex(partitionName)
val structField = partitionSchema.fields(internalRowIndex)
- Objects.equals(
+ // `deepEquals`: a BINARY partition value is a `byte[]`.
+ Objects.deepEquals(
sparkInternalRow.get(internalRowIndex, structField.dataType),
internalRow.get(index, structField.dataType))
}
diff --git
a/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/DDLWithHiveCatalogTestBase.scala
b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/DDLWithHiveCatalogTestBase.scala
index feae8be0da..42d7c0747c 100644
---
a/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/DDLWithHiveCatalogTestBase.scala
+++
b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/DDLWithHiveCatalogTestBase.scala
@@ -138,6 +138,37 @@ abstract class DDLWithHiveCatalogTestBase extends
PaimonHiveTestBase {
}
}
+ test("Paimon DDL with hive catalog: drop a blank partition") {
+ spark.sql(s"USE $paimonHiveCatalogName")
+ withDatabase("paimon_db") {
+ spark.sql("CREATE DATABASE paimon_db")
+ Seq("false", "true").foreach {
+ inMetastore =>
+ withTable("paimon_db.blank_tbl") {
+ spark.sql(
+ "CREATE TABLE paimon_db.blank_tbl (a INT, p STRING) USING PAIMON
" +
+ "PARTITIONED BY (p) " +
+ s"TBLPROPERTIES ('metastore.partitioned-table' =
'$inMetastore')")
+ // In a metastore, blank and NULL have the same partition name, so
one commit cannot
+ // add both.
+ Seq("(1, ' ')", "(2, NULL)", "(3, 'a')").foreach {
+ row => spark.sql(s"INSERT INTO paimon_db.blank_tbl VALUES $row")
+ }
+ // The Hive catalog drops partitions by name, and a blank
partition is named as the
+ // null one is, with or without metastore partitions.
+ val e = intercept[IllegalArgumentException] {
+ spark.sql("ALTER TABLE paimon_db.blank_tbl DROP PARTITION (p = '
')")
+ }
+ assert(e.getMessage.contains("does not parse back"))
+ assert(!e.getMessage.contains("= NULL"))
+ checkAnswer(
+ spark.sql("SELECT a FROM paimon_db.blank_tbl"),
+ Row(1) :: Row(2) :: Row(3) :: Nil)
+ }
+ }
+ }
+ }
+
test(
"Paimon partition expire test with hive catalog: expire partition for
paimon table sparkCatalogName") {
spark.sql(s"USE $paimonHiveCatalogName")
diff --git
a/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/PaimonPartitionManagementTest.scala
b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/PaimonPartitionManagementTest.scala
index eebb3a8013..934cadf8fa 100644
---
a/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/PaimonPartitionManagementTest.scala
+++
b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/PaimonPartitionManagementTest.scala
@@ -18,9 +18,22 @@
package org.apache.paimon.spark.sql
-import org.apache.paimon.spark.PaimonSparkTestBase
+import org.apache.paimon.catalog.Identifier
+import org.apache.paimon.data.{GenericRow, Timestamp}
+import org.apache.paimon.partition.PartitionStatistics
+import org.apache.paimon.schema.Schema
+import org.apache.paimon.spark.{PaimonSparkTestBase, SparkTable}
+import org.apache.paimon.table.{CatalogEnvironment, FileStoreTableFactory,
PartitionModification}
+import org.apache.paimon.types.DataTypes
import org.apache.spark.sql.{AnalysisException, Row}
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.unsafe.types.UTF8String
+
+import java.time.LocalDateTime
+import java.util.{ArrayList => JArrayList, List => JList, Map => JMap}
+
+import scala.collection.JavaConverters._
class PaimonPartitionManagementTest extends PaimonSparkTestBase {
@@ -211,6 +224,211 @@ class PaimonPartitionManagementTest extends
PaimonSparkTestBase {
)
}
+ test("Paimon Partition Management: show, add and drop a binary partition") {
+ withTable("T") {
+ spark.sql("CREATE TABLE T (a INT, p BINARY) PARTITIONED BY (p)")
+ spark.sql("INSERT INTO T VALUES (1, CAST('2021' AS BINARY)), (2,
CAST('2022' AS BINARY))")
+ checkAnswer(spark.sql("SHOW PARTITIONS T PARTITION (p = '2021')"),
Row("p=2021") :: Nil)
+
+ val e = intercept[AnalysisException] {
+ spark.sql("ALTER TABLE T ADD PARTITION (p = '2021')")
+ }
+ assert(e.getMessage.contains("already exist"))
+
+ spark.sql("ALTER TABLE T DROP PARTITION (p = '2021')")
+ checkAnswer(spark.sql("SHOW PARTITIONS T"), Row("p=2022") :: Nil)
+ }
+ }
+
+ test("Paimon Partition Management: truncate with a partial binary partition
spec") {
+ withTable("T") {
+ spark.sql("CREATE TABLE T (a INT, p1 BINARY, p2 STRING) PARTITIONED BY
(p1, p2)")
+ spark.sql(
+ "INSERT INTO T VALUES (1, CAST('x' AS BINARY), 'a'), (2, CAST('x' AS
BINARY), 'b'), " +
+ "(3, CAST('y' AS BINARY), 'a')")
+ spark.sql("TRUNCATE TABLE T PARTITION (p1 = 'x')")
+ checkAnswer(spark.sql("SELECT a FROM T"), Row(3) :: Nil)
+ // A partial spec that matches no partition truncates nothing.
+ spark.sql("TRUNCATE TABLE T PARTITION (p1 = 'z')")
+ checkAnswer(spark.sql("SELECT a FROM T"), Row(3) :: Nil)
+ }
+ }
+
+ Seq("BINARY", "STRING").foreach {
+ partitionType =>
+ test(s"Paimon Partition Management: drop a blank $partitionType
partition") {
+ withTable("T") {
+ spark.sql(s"CREATE TABLE T (a INT, p $partitionType) PARTITIONED BY
(p)")
+ spark.sql(
+ s"INSERT INTO T VALUES (1, CAST(' ' AS $partitionType)), (2,
NULL), " +
+ s"(3, CAST('a' AS $partitionType))")
+ // A blank value's partition name is the null partition's.
+ spark.sql("ALTER TABLE T DROP PARTITION (p = ' ')")
+ checkAnswer(spark.sql("SELECT a FROM T"), Row(2) :: Row(3) :: Nil)
+ }
+ }
+ }
+
+ test("Paimon Partition Management: truncate binary partitions whose names do
not parse back") {
+ withTable("T") {
+ spark.sql("CREATE TABLE T (a INT, p1 BINARY, p2 STRING) PARTITIONED BY
(p1, p2)")
+ spark.sql(
+ "INSERT INTO T VALUES (1, CAST(' ' AS BINARY), 'a'), (2, NULL, 'a'), "
+
+ "(3, X'FF', 'b'), (4, CAST('x' AS BINARY), 'b')")
+ spark.sql("TRUNCATE TABLE T PARTITION (p1 = ' ')")
+ checkAnswer(spark.sql("SELECT a FROM T"), Row(2) :: Row(3) :: Row(4) ::
Nil)
+ // X'FF' is not valid UTF-8, so its partition name holds other bytes.
+ spark.sql("TRUNCATE TABLE T PARTITION (p2 = 'b')")
+ checkAnswer(spark.sql("SELECT a FROM T"), Row(2) :: Nil)
+ }
+ }
+
+ test("Paimon Partition Management: truncate a partition that a batch read
does not see") {
+ withTable("T") {
+ spark.sql(
+ "CREATE TABLE T (k INT, p STRING) PARTITIONED BY (p) TBLPROPERTIES
('primary-key' = " +
+ "'k,p', 'bucket' = '1', 'deletion-vectors.enabled' = 'true',
'write-only' = 'true')")
+ spark.sql("INSERT INTO T VALUES (1, 'a'), (2, 'b')")
+ // A batch read skips level 0 of a deletion-vector table, which holds
every file here.
+
assert(loadTable("T").newReadBuilder().newScan().listPartitions().isEmpty)
+ def partitions: Seq[String] =
+
loadTable("T").newSnapshotReader().partitions().asScala.map(_.getString(0).toString).toSeq
+ assert(partitions.sorted == Seq("a", "b"))
+ spark.sql("TRUNCATE TABLE T PARTITION (p = 'a')")
+ assert(partitions == Seq("b"))
+ }
+ }
+
+ test("Paimon Partition Management: drop and truncate leave expired
partitions alone") {
+ withTable("T") {
+ spark.sql("CREATE TABLE T (a INT, dt STRING) PARTITIONED BY (dt)")
+ spark.sql("INSERT INTO T VALUES (1, '2020-01-01'), (2, '2099-01-01'),
(3, '2099-01-02')")
+ spark.sql(
+ "ALTER TABLE T SET TBLPROPERTIES ('partition.expiration-time' = '7 d',
" +
+ "'partition.expiration-check-interval' = '0 s', " +
+ "'partition.timestamp-pattern' = '$dt',
'partition.timestamp-formatter' = 'yyyy-MM-dd')")
+ spark.sql("TRUNCATE TABLE T PARTITION (dt = '2099-01-01')")
+ checkAnswer(spark.sql("SELECT a FROM T"), Row(1) :: Row(3) :: Nil)
+ spark.sql("ALTER TABLE T DROP PARTITION (dt = '2099-01-02')")
+ checkAnswer(spark.sql("SELECT a FROM T"), Row(1) :: Nil)
+ }
+ }
+
+ test("Paimon Partition Management: drop partitions through the catalog's
partition handler") {
+ withTable("T") {
+ spark.sql("CREATE TABLE T (a INT, p STRING) PARTITIONED BY (p)")
+ spark.sql("INSERT INTO T VALUES (1, 'a'), (2, 'b')")
+ val dropped = new JArrayList[JMap[String, String]]()
+ val handler = new PartitionModification {
+ override def createPartitions(partitions: JList[JMap[String,
String]]): Unit = {}
+ override def dropPartitions(partitions: JList[JMap[String, String]]):
Unit =
+ dropped.addAll(partitions)
+ override def alterPartitions(partitions: JList[PartitionStatistics]):
Unit = {}
+ override def close(): Unit = {}
+ }
+ // A catalog with a partition handler and none of the Hive options.
+ val environment = new CatalogEnvironment(null, null, null, null, null,
null, false, true) {
+ override def partitionModification(): PartitionModification = handler
+ }
+ val table = loadTable("T")
+ val sparkTable = SparkTable(
+ FileStoreTableFactory.create(table.fileIO(), table.location(),
table.schema(), environment))
+ sparkTable.dropPartitions(Array(InternalRow(UTF8String.fromString("a"))))
+ assert(dropped.asScala.map(_.asScala.toMap) == Seq(Map("p" -> "a")))
+ // The handler drops nothing, so the rows are still there.
+ checkAnswer(spark.sql("SELECT a FROM T"), Row(1) :: Row(2) :: Nil)
+ intercept[IllegalArgumentException] {
+ sparkTable.dropPartitions(Array(InternalRow(UTF8String.fromString("
"))))
+ }
+ assert(dropped.size == 1)
+ }
+ }
+
+ test("Paimon Partition Management: drop a timestamp partition at its stored
precision") {
+ withTimeZone("UTC") {
+ withTable("T") {
+ val schema = Schema
+ .newBuilder()
+ .column("a", DataTypes.INT())
+ .column("p", DataTypes.TIMESTAMP(9))
+ .partitionKeys("p")
+ .option("partition.legacy-name", "false")
+ .build()
+ paimonCatalog.createTable(Identifier.create(dbName0, "T"), schema,
false)
+ val builder = loadTable("T").newBatchWriteBuilder()
+ val write = builder.newWrite()
+ Seq(1 -> "2024-06-01T00:00:00.123456", 2 ->
"2024-06-01T00:00:00.123456789").foreach {
+ case (a, p) =>
+ write.write(
+ GenericRow
+ .of(Integer.valueOf(a),
Timestamp.fromLocalDateTime(LocalDateTime.parse(p))))
+ }
+ val commit = builder.newCommit()
+ try {
+ commit.commit(write.prepareCommit())
+ } finally {
+ write.close()
+ commit.close()
+ }
+ // Spark holds microseconds, which both partitions share.
+ spark.sql("ALTER TABLE T DROP PARTITION (p = '2024-06-01
00:00:00.123456')")
+ checkAnswer(spark.sql("SELECT a FROM T"), Row(2) :: Nil)
+ }
+ }
+ }
+
+ test("Paimon Partition Management: drop a timestamp partition whose legacy
name is shifted") {
+ withTimeZone("America/Los_Angeles") {
+ withTable("T") {
+ spark.sql("CREATE TABLE T (a INT, p TIMESTAMP) PARTITIONED BY (p)")
+ // The legacy name of 10:30:01 is its UTC wall clock, which parses
back as 17:30:01 here.
+ spark.sql(
+ "INSERT INTO T VALUES (1, CAST('2024-06-01 10:30:01' AS TIMESTAMP)),
" +
+ "(2, CAST('2024-06-01 17:30:01' AS TIMESTAMP))")
+ spark.sql("ALTER TABLE T DROP PARTITION (p = '2024-06-01 10:30:01')")
+ checkAnswer(spark.sql("SELECT a FROM T"), Row(2) :: Nil)
+ }
+ }
+ }
+
+ test("Paimon Partition Management: address the null partition by NULL, not
its default name") {
+ withTable("T") {
+ spark.sql("CREATE TABLE T (a INT, p1 STRING, p2 STRING) PARTITIONED BY
(p1, p2)")
+ spark.sql("INSERT INTO T VALUES (1, NULL, 'x'), (2, 'b', 'x')")
+ val truncate = intercept[IllegalArgumentException] {
+ spark.sql("TRUNCATE TABLE T PARTITION (p1 = '__DEFAULT_PARTITION__',
p2 = 'x')")
+ }
+ assert(truncate.getMessage.contains("use p1 = NULL"))
+ val drop = intercept[IllegalArgumentException] {
+ spark.sql("ALTER TABLE T DROP PARTITION (p1 =
'__DEFAULT_PARTITION__')")
+ }
+ assert(drop.getMessage.contains("use p1 = NULL"))
+ checkAnswer(spark.sql("SELECT a FROM T"), Row(1) :: Row(2) :: Nil)
+
+ spark.sql("ALTER TABLE T DROP PARTITION (p1 = NULL)")
+ checkAnswer(spark.sql("SELECT a FROM T"), Row(2) :: Nil)
+ }
+ }
+
+ Seq("BINARY", "STRING").foreach {
+ partitionType =>
+ test(s"Paimon Partition Management: show the statistics of a blank
$partitionType partition") {
+ withTable("T") {
+ spark.sql(s"CREATE TABLE T (a INT, p $partitionType) PARTITIONED BY
(p)")
+ spark.sql(s"INSERT INTO T VALUES (1, CAST(' ' AS $partitionType)),
(2, NULL), (3, NULL)")
+ def information(spec: String): String =
+ spark
+ .sql(s"SHOW TABLE EXTENDED IN $dbName0 LIKE 'T' PARTITION
($spec)")
+ .select("information")
+ .collect()
+ .head
+ .getString(0)
+ assert(information("p = ' '").contains("Partition Statistics: 1
rows"))
+ assert(information("p = NULL").contains("Partition Statistics: 2
rows"))
+ }
+ }
+ }
+
test("Paimon Partition Management: timestamp partition column") {
spark.sql(s"""
|CREATE TABLE T (a INT, dt TIMESTAMP)