Zouxxyy commented on code in PR #5531: URL: https://github.com/apache/paimon/pull/5531#discussion_r2061138946
########## paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/SparkV2Write.scala: ########## @@ -0,0 +1,180 @@ +/* + * 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.paimon.spark.source + +import org.apache.paimon.CoreOptions +import org.apache.paimon.spark.{SparkInternalRowWrapper, SparkUtils, SparkWriteRequirement} +import org.apache.paimon.table.FileStoreTable +import org.apache.paimon.table.sink.{BatchTableWrite, BatchWriteBuilder, CommitMessage, CommitMessageSerializer} + +import org.apache.spark.internal.Logging +import org.apache.spark.sql.catalyst.InternalRow +import org.apache.spark.sql.connector.distributions.Distribution +import org.apache.spark.sql.connector.expressions.SortOrder +import org.apache.spark.sql.connector.write._ +import org.apache.spark.sql.types.StructType + +import java.io.{IOException, UncheckedIOException} + +import scala.jdk.CollectionConverters._ +import scala.util.{Failure, Success, Try} + +class SparkV2Write( Review Comment: you can create a package `write` and move the related classes into it ########## paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/SparkV2Write.scala: ########## @@ -0,0 +1,180 @@ +/* + * 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.paimon.spark.source + +import org.apache.paimon.CoreOptions +import org.apache.paimon.spark.{SparkInternalRowWrapper, SparkUtils, SparkWriteRequirement} +import org.apache.paimon.table.FileStoreTable +import org.apache.paimon.table.sink.{BatchTableWrite, BatchWriteBuilder, CommitMessage, CommitMessageSerializer} + +import org.apache.spark.internal.Logging +import org.apache.spark.sql.catalyst.InternalRow +import org.apache.spark.sql.connector.distributions.Distribution +import org.apache.spark.sql.connector.expressions.SortOrder +import org.apache.spark.sql.connector.write._ +import org.apache.spark.sql.types.StructType + +import java.io.{IOException, UncheckedIOException} + +import scala.jdk.CollectionConverters._ +import scala.util.{Failure, Success, Try} + +class SparkV2Write( + storeTable: FileStoreTable, + overwriteDynamic: Boolean, + overwritePartitions: Map[String, String], Review Comment: Use Option ########## paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/SparkV2Write.scala: ########## @@ -0,0 +1,180 @@ +/* + * 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.paimon.spark.source + +import org.apache.paimon.CoreOptions +import org.apache.paimon.spark.{SparkInternalRowWrapper, SparkUtils, SparkWriteRequirement} +import org.apache.paimon.table.FileStoreTable +import org.apache.paimon.table.sink.{BatchTableWrite, BatchWriteBuilder, CommitMessage, CommitMessageSerializer} + +import org.apache.spark.internal.Logging +import org.apache.spark.sql.catalyst.InternalRow +import org.apache.spark.sql.connector.distributions.Distribution +import org.apache.spark.sql.connector.expressions.SortOrder +import org.apache.spark.sql.connector.write._ +import org.apache.spark.sql.types.StructType + +import java.io.{IOException, UncheckedIOException} + +import scala.jdk.CollectionConverters._ +import scala.util.{Failure, Success, Try} + +class SparkV2Write( + storeTable: FileStoreTable, + overwriteDynamic: Boolean, + overwritePartitions: Map[String, String], + writeSchema: StructType +) extends Write + with RequiresDistributionAndOrdering + with Logging { + + assert( + !(overwriteDynamic && overwritePartitions != null), + "Cannot overwrite dynamically and by filter both") + + private val table = + storeTable.copy( + Map(CoreOptions.DYNAMIC_PARTITION_OVERWRITE.key -> overwriteDynamic.toString).asJava) + + private val batchWriteBuilder = { + val builder = table.newBatchWriteBuilder() + Option(overwritePartitions).foreach(partitions => builder.withOverwrite(partitions.asJava)) + builder + } + + private val writeRequirement = SparkWriteRequirement(table) + + override def requiredDistribution(): Distribution = { + val distribution = writeRequirement.distribution + log.info(s"Requesting $distribution as write distribution for table ${table.name()}") Review Comment: use logInfo ########## paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/SparkV2Write.scala: ########## @@ -0,0 +1,180 @@ +/* + * 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.paimon.spark.source + +import org.apache.paimon.CoreOptions +import org.apache.paimon.spark.{SparkInternalRowWrapper, SparkUtils, SparkWriteRequirement} +import org.apache.paimon.table.FileStoreTable +import org.apache.paimon.table.sink.{BatchTableWrite, BatchWriteBuilder, CommitMessage, CommitMessageSerializer} + +import org.apache.spark.internal.Logging +import org.apache.spark.sql.catalyst.InternalRow +import org.apache.spark.sql.connector.distributions.Distribution +import org.apache.spark.sql.connector.expressions.SortOrder +import org.apache.spark.sql.connector.write._ +import org.apache.spark.sql.types.StructType + +import java.io.{IOException, UncheckedIOException} + +import scala.jdk.CollectionConverters._ +import scala.util.{Failure, Success, Try} + +class SparkV2Write( + storeTable: FileStoreTable, + overwriteDynamic: Boolean, + overwritePartitions: Map[String, String], + writeSchema: StructType +) extends Write + with RequiresDistributionAndOrdering + with Logging { + + assert( + !(overwriteDynamic && overwritePartitions != null), + "Cannot overwrite dynamically and by filter both") + + private val table = + storeTable.copy( + Map(CoreOptions.DYNAMIC_PARTITION_OVERWRITE.key -> overwriteDynamic.toString).asJava) + + private val batchWriteBuilder = { + val builder = table.newBatchWriteBuilder() + Option(overwritePartitions).foreach(partitions => builder.withOverwrite(partitions.asJava)) + builder + } + + private val writeRequirement = SparkWriteRequirement(table) + + override def requiredDistribution(): Distribution = { + val distribution = writeRequirement.distribution + log.info(s"Requesting $distribution as write distribution for table ${table.name()}") + distribution + } + + override def requiredOrdering(): Array[SortOrder] = { + val ordering = writeRequirement.ordering + log.info(s"Requesting ${ordering.mkString(",")} as write ordering for table ${table.name()}") + ordering + } + + override def toBatch: BatchWrite = new PaimonBatchWrite + + override def toString: String = + if (overwriteDynamic) + s"PaimonWrite(table=${table.fullName()}, overwriteDynamic=true)" + else + s"PaimonWrite(table=${table.fullName()}, overwritePartitions=$overwritePartitions)" + + private class PaimonBatchWrite extends BatchWrite { + override def createBatchWriterFactory(info: PhysicalWriteInfo): DataWriterFactory = + WriterFactory(writeSchema, batchWriteBuilder) + + override def useCommitCoordinator(): Boolean = false + + override def commit(messages: Array[WriterCommitMessage]): Unit = { + log.info(s"Committing to table ${table.name()}") + val batchTableCommit = batchWriteBuilder.newCommit() + + val commitMessages = + messages.filter(_ != null).map(_.asInstanceOf[TaskCommit].commitMessages).flatten.toList + + try { + val start = System.currentTimeMillis() + batchTableCommit.commit(commitMessages.asJava) + log.info(s"Committed in ${System.currentTimeMillis() - start} ms") + } finally { + batchTableCommit.close() + } + } + + override def abort(messages: Array[WriterCommitMessage]): Unit = { + // TODO clean uncommitted files + } + } +} + +private case class WriterFactory(writeSchema: StructType, batchWriteBuilder: BatchWriteBuilder) + extends DataWriterFactory { + + override def createWriter(partitionId: Int, taskId: Long): DataWriter[InternalRow] = { + val batchTableWrite = batchWriteBuilder.newWrite() + new PaimonDataWriter(batchTableWrite, writeSchema) + } +} + +private class PaimonDataWriter(batchTableWrite: BatchTableWrite, writeSchema: StructType) + extends DataWriter[InternalRow] { + + private val ioManager = SparkUtils.createIOManager() + batchTableWrite.withIOManager(ioManager) + + override def write(record: InternalRow): Unit = { + val wrappedRow = new SparkInternalRowWrapper(record, -1, writeSchema, writeSchema.fields.length) + batchTableWrite.write(wrappedRow) + } + + override def commit(): WriterCommitMessage = { + try { + val commitMessages = batchTableWrite.prepareCommit().asScala.toList + TaskCommit(commitMessages) + } finally { + close() + } + } + + override def abort(): Unit = close() + + override def close(): Unit = { + try { + batchTableWrite.close() + ioManager.close() + } catch { + case e: Exception => throw new RuntimeException(e) + } + } +} + +private case class TaskCommit(commitMessagesList: List[CommitMessage]) extends WriterCommitMessage { + private val serializedMessageList: List[Array[Byte]] = { + Option(commitMessagesList).filter(_.nonEmpty) match { + case Some(messages) => + val serializer = new CommitMessageSerializer() + messages.map { + msg => + Try(serializer.serialize(msg)) match { + case Success(serializedBytes) => serializedBytes + case Failure(e: IOException) => throw new UncheckedIOException(e) + case Failure(e) => throw e + } + } + case None => Nil + } + } + + def commitMessages(): List[CommitMessage] = { + val deserializer = new CommitMessageSerializer() + serializedMessageList.map { Review Comment: Can not quiet understand the purpose of serialization and deserialization here ########## paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/SparkVersionSupport.scala: ########## @@ -23,6 +23,8 @@ import org.apache.spark.SPARK_VERSION trait SparkVersionSupport { lazy val sparkVersion: String = SPARK_VERSION + lazy val gteqSpark3_2: Boolean = sparkVersion >= "3.2" Review Comment: Currently, the lowest version supported by Paimon is Spark 3.2, so this has no effect ########## paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/catalog/functions/PaimonFunctions.scala: ########## @@ -98,6 +102,32 @@ class BucketFunction extends UnboundFunction { override def name: String = BUCKET } +object BucketFunction { + private val SPARK_TIMESTAMP_PRECISION = 6 + + def supportsTable(table: FileStoreTable): Boolean = { + table.bucketMode match { + case BucketMode.HASH_FIXED => + table.schema().logicalBucketKeyType().getFieldTypes.asScala.forall(supportsType) + case _ => false + } + } + + private def supportsType(t: PaimonDataType): Boolean = t match { + case arrayType: ArrayType => + supportsType(arrayType.getElementType) + case mapType: MapType => + supportsType(mapType.getKeyType) && supportsType(mapType.getValueType) + case rowType: RowType => + rowType.getFieldTypes.asScala.forall(supportsType) + case timestamp: TimestampType => Review Comment: Is this check necessary (is there a test case), and can Spark currently output timestamp types with precision other than 6? ########## paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/SparkV2Write.scala: ########## @@ -0,0 +1,180 @@ +/* + * 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.paimon.spark.source + +import org.apache.paimon.CoreOptions +import org.apache.paimon.spark.{SparkInternalRowWrapper, SparkUtils, SparkWriteRequirement} +import org.apache.paimon.table.FileStoreTable +import org.apache.paimon.table.sink.{BatchTableWrite, BatchWriteBuilder, CommitMessage, CommitMessageSerializer} + +import org.apache.spark.internal.Logging +import org.apache.spark.sql.catalyst.InternalRow +import org.apache.spark.sql.connector.distributions.Distribution +import org.apache.spark.sql.connector.expressions.SortOrder +import org.apache.spark.sql.connector.write._ +import org.apache.spark.sql.types.StructType + +import java.io.{IOException, UncheckedIOException} + +import scala.jdk.CollectionConverters._ +import scala.util.{Failure, Success, Try} + +class SparkV2Write( + storeTable: FileStoreTable, + overwriteDynamic: Boolean, + overwritePartitions: Map[String, String], + writeSchema: StructType +) extends Write + with RequiresDistributionAndOrdering + with Logging { + + assert( + !(overwriteDynamic && overwritePartitions != null), + "Cannot overwrite dynamically and by filter both") + + private val table = + storeTable.copy( + Map(CoreOptions.DYNAMIC_PARTITION_OVERWRITE.key -> overwriteDynamic.toString).asJava) + + private val batchWriteBuilder = { + val builder = table.newBatchWriteBuilder() + Option(overwritePartitions).foreach(partitions => builder.withOverwrite(partitions.asJava)) + builder + } + + private val writeRequirement = SparkWriteRequirement(table) + + override def requiredDistribution(): Distribution = { + val distribution = writeRequirement.distribution + log.info(s"Requesting $distribution as write distribution for table ${table.name()}") + distribution + } + + override def requiredOrdering(): Array[SortOrder] = { + val ordering = writeRequirement.ordering + log.info(s"Requesting ${ordering.mkString(",")} as write ordering for table ${table.name()}") + ordering + } + + override def toBatch: BatchWrite = new PaimonBatchWrite + + override def toString: String = + if (overwriteDynamic) + s"PaimonWrite(table=${table.fullName()}, overwriteDynamic=true)" + else + s"PaimonWrite(table=${table.fullName()}, overwritePartitions=$overwritePartitions)" + + private class PaimonBatchWrite extends BatchWrite { + override def createBatchWriterFactory(info: PhysicalWriteInfo): DataWriterFactory = + WriterFactory(writeSchema, batchWriteBuilder) + + override def useCommitCoordinator(): Boolean = false + + override def commit(messages: Array[WriterCommitMessage]): Unit = { + log.info(s"Committing to table ${table.name()}") + val batchTableCommit = batchWriteBuilder.newCommit() + + val commitMessages = + messages.filter(_ != null).map(_.asInstanceOf[TaskCommit].commitMessages).flatten.toList + + try { + val start = System.currentTimeMillis() + batchTableCommit.commit(commitMessages.asJava) + log.info(s"Committed in ${System.currentTimeMillis() - start} ms") + } finally { + batchTableCommit.close() + } + } + + override def abort(messages: Array[WriterCommitMessage]): Unit = { + // TODO clean uncommitted files + } + } +} + +private case class WriterFactory(writeSchema: StructType, batchWriteBuilder: BatchWriteBuilder) + extends DataWriterFactory { + + override def createWriter(partitionId: Int, taskId: Long): DataWriter[InternalRow] = { + val batchTableWrite = batchWriteBuilder.newWrite() + new PaimonDataWriter(batchTableWrite, writeSchema) + } +} + +private class PaimonDataWriter(batchTableWrite: BatchTableWrite, writeSchema: StructType) + extends DataWriter[InternalRow] { + + private val ioManager = SparkUtils.createIOManager() + batchTableWrite.withIOManager(ioManager) + + override def write(record: InternalRow): Unit = { + val wrappedRow = new SparkInternalRowWrapper(record, -1, writeSchema, writeSchema.fields.length) + batchTableWrite.write(wrappedRow) + } + + override def commit(): WriterCommitMessage = { + try { + val commitMessages = batchTableWrite.prepareCommit().asScala.toList + TaskCommit(commitMessages) + } finally { + close() + } + } + + override def abort(): Unit = close() + + override def close(): Unit = { + try { + batchTableWrite.close() + ioManager.close() + } catch { + case e: Exception => throw new RuntimeException(e) + } + } +} + +private case class TaskCommit(commitMessagesList: List[CommitMessage]) extends WriterCommitMessage { Review Comment: Confirm whether this class can be serialized by Kryo ########## paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/SparkV2Write.scala: ########## @@ -0,0 +1,180 @@ +/* + * 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.paimon.spark.source + +import org.apache.paimon.CoreOptions +import org.apache.paimon.spark.{SparkInternalRowWrapper, SparkUtils, SparkWriteRequirement} +import org.apache.paimon.table.FileStoreTable +import org.apache.paimon.table.sink.{BatchTableWrite, BatchWriteBuilder, CommitMessage, CommitMessageSerializer} + +import org.apache.spark.internal.Logging +import org.apache.spark.sql.catalyst.InternalRow +import org.apache.spark.sql.connector.distributions.Distribution +import org.apache.spark.sql.connector.expressions.SortOrder +import org.apache.spark.sql.connector.write._ +import org.apache.spark.sql.types.StructType + +import java.io.{IOException, UncheckedIOException} + +import scala.jdk.CollectionConverters._ +import scala.util.{Failure, Success, Try} + +class SparkV2Write( + storeTable: FileStoreTable, + overwriteDynamic: Boolean, + overwritePartitions: Map[String, String], + writeSchema: StructType +) extends Write + with RequiresDistributionAndOrdering + with Logging { + + assert( + !(overwriteDynamic && overwritePartitions != null), + "Cannot overwrite dynamically and by filter both") + + private val table = + storeTable.copy( + Map(CoreOptions.DYNAMIC_PARTITION_OVERWRITE.key -> overwriteDynamic.toString).asJava) + + private val batchWriteBuilder = { + val builder = table.newBatchWriteBuilder() + Option(overwritePartitions).foreach(partitions => builder.withOverwrite(partitions.asJava)) + builder + } + + private val writeRequirement = SparkWriteRequirement(table) + + override def requiredDistribution(): Distribution = { + val distribution = writeRequirement.distribution + log.info(s"Requesting $distribution as write distribution for table ${table.name()}") + distribution + } + + override def requiredOrdering(): Array[SortOrder] = { + val ordering = writeRequirement.ordering + log.info(s"Requesting ${ordering.mkString(",")} as write ordering for table ${table.name()}") + ordering + } + + override def toBatch: BatchWrite = new PaimonBatchWrite + + override def toString: String = + if (overwriteDynamic) + s"PaimonWrite(table=${table.fullName()}, overwriteDynamic=true)" + else + s"PaimonWrite(table=${table.fullName()}, overwritePartitions=$overwritePartitions)" + + private class PaimonBatchWrite extends BatchWrite { + override def createBatchWriterFactory(info: PhysicalWriteInfo): DataWriterFactory = + WriterFactory(writeSchema, batchWriteBuilder) + + override def useCommitCoordinator(): Boolean = false + + override def commit(messages: Array[WriterCommitMessage]): Unit = { + log.info(s"Committing to table ${table.name()}") + val batchTableCommit = batchWriteBuilder.newCommit() + + val commitMessages = + messages.filter(_ != null).map(_.asInstanceOf[TaskCommit].commitMessages).flatten.toList Review Comment: use match ########## paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/SparkV2Write.scala: ########## @@ -0,0 +1,180 @@ +/* + * 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.paimon.spark.source + +import org.apache.paimon.CoreOptions +import org.apache.paimon.spark.{SparkInternalRowWrapper, SparkUtils, SparkWriteRequirement} +import org.apache.paimon.table.FileStoreTable +import org.apache.paimon.table.sink.{BatchTableWrite, BatchWriteBuilder, CommitMessage, CommitMessageSerializer} + +import org.apache.spark.internal.Logging +import org.apache.spark.sql.catalyst.InternalRow +import org.apache.spark.sql.connector.distributions.Distribution +import org.apache.spark.sql.connector.expressions.SortOrder +import org.apache.spark.sql.connector.write._ +import org.apache.spark.sql.types.StructType + +import java.io.{IOException, UncheckedIOException} + +import scala.jdk.CollectionConverters._ +import scala.util.{Failure, Success, Try} + +class SparkV2Write( + storeTable: FileStoreTable, + overwriteDynamic: Boolean, + overwritePartitions: Map[String, String], + writeSchema: StructType +) extends Write + with RequiresDistributionAndOrdering + with Logging { + + assert( + !(overwriteDynamic && overwritePartitions != null), + "Cannot overwrite dynamically and by filter both") + + private val table = + storeTable.copy( + Map(CoreOptions.DYNAMIC_PARTITION_OVERWRITE.key -> overwriteDynamic.toString).asJava) + + private val batchWriteBuilder = { + val builder = table.newBatchWriteBuilder() + Option(overwritePartitions).foreach(partitions => builder.withOverwrite(partitions.asJava)) + builder + } + + private val writeRequirement = SparkWriteRequirement(table) + + override def requiredDistribution(): Distribution = { + val distribution = writeRequirement.distribution + log.info(s"Requesting $distribution as write distribution for table ${table.name()}") + distribution + } + + override def requiredOrdering(): Array[SortOrder] = { + val ordering = writeRequirement.ordering + log.info(s"Requesting ${ordering.mkString(",")} as write ordering for table ${table.name()}") + ordering + } + + override def toBatch: BatchWrite = new PaimonBatchWrite + + override def toString: String = + if (overwriteDynamic) + s"PaimonWrite(table=${table.fullName()}, overwriteDynamic=true)" + else + s"PaimonWrite(table=${table.fullName()}, overwritePartitions=$overwritePartitions)" + + private class PaimonBatchWrite extends BatchWrite { + override def createBatchWriterFactory(info: PhysicalWriteInfo): DataWriterFactory = + WriterFactory(writeSchema, batchWriteBuilder) + + override def useCommitCoordinator(): Boolean = false + + override def commit(messages: Array[WriterCommitMessage]): Unit = { + log.info(s"Committing to table ${table.name()}") + val batchTableCommit = batchWriteBuilder.newCommit() + + val commitMessages = + messages.filter(_ != null).map(_.asInstanceOf[TaskCommit].commitMessages).flatten.toList + + try { + val start = System.currentTimeMillis() + batchTableCommit.commit(commitMessages.asJava) + log.info(s"Committed in ${System.currentTimeMillis() - start} ms") + } finally { + batchTableCommit.close() + } + } + + override def abort(messages: Array[WriterCommitMessage]): Unit = { + // TODO clean uncommitted files + } + } +} + +private case class WriterFactory(writeSchema: StructType, batchWriteBuilder: BatchWriteBuilder) + extends DataWriterFactory { + + override def createWriter(partitionId: Int, taskId: Long): DataWriter[InternalRow] = { + val batchTableWrite = batchWriteBuilder.newWrite() + new PaimonDataWriter(batchTableWrite, writeSchema) + } +} + +private class PaimonDataWriter(batchTableWrite: BatchTableWrite, writeSchema: StructType) + extends DataWriter[InternalRow] { + + private val ioManager = SparkUtils.createIOManager() + batchTableWrite.withIOManager(ioManager) + + override def write(record: InternalRow): Unit = { + val wrappedRow = new SparkInternalRowWrapper(record, -1, writeSchema, writeSchema.fields.length) Review Comment: using `public SparkInternalRowWrapper replace(org.apache.spark.sql.catalyst.InternalRow internalRow)` ########## paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/SparkV2Write.scala: ########## @@ -0,0 +1,180 @@ +/* + * 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.paimon.spark.source + +import org.apache.paimon.CoreOptions +import org.apache.paimon.spark.{SparkInternalRowWrapper, SparkUtils, SparkWriteRequirement} +import org.apache.paimon.table.FileStoreTable +import org.apache.paimon.table.sink.{BatchTableWrite, BatchWriteBuilder, CommitMessage, CommitMessageSerializer} + +import org.apache.spark.internal.Logging +import org.apache.spark.sql.catalyst.InternalRow +import org.apache.spark.sql.connector.distributions.Distribution +import org.apache.spark.sql.connector.expressions.SortOrder +import org.apache.spark.sql.connector.write._ +import org.apache.spark.sql.types.StructType + +import java.io.{IOException, UncheckedIOException} + +import scala.jdk.CollectionConverters._ +import scala.util.{Failure, Success, Try} + +class SparkV2Write( + storeTable: FileStoreTable, + overwriteDynamic: Boolean, + overwritePartitions: Map[String, String], + writeSchema: StructType +) extends Write + with RequiresDistributionAndOrdering + with Logging { + + assert( + !(overwriteDynamic && overwritePartitions != null), + "Cannot overwrite dynamically and by filter both") + + private val table = + storeTable.copy( + Map(CoreOptions.DYNAMIC_PARTITION_OVERWRITE.key -> overwriteDynamic.toString).asJava) + + private val batchWriteBuilder = { + val builder = table.newBatchWriteBuilder() + Option(overwritePartitions).foreach(partitions => builder.withOverwrite(partitions.asJava)) + builder + } + + private val writeRequirement = SparkWriteRequirement(table) + + override def requiredDistribution(): Distribution = { + val distribution = writeRequirement.distribution + log.info(s"Requesting $distribution as write distribution for table ${table.name()}") + distribution + } + + override def requiredOrdering(): Array[SortOrder] = { + val ordering = writeRequirement.ordering + log.info(s"Requesting ${ordering.mkString(",")} as write ordering for table ${table.name()}") + ordering + } + + override def toBatch: BatchWrite = new PaimonBatchWrite + + override def toString: String = + if (overwriteDynamic) + s"PaimonWrite(table=${table.fullName()}, overwriteDynamic=true)" + else + s"PaimonWrite(table=${table.fullName()}, overwritePartitions=$overwritePartitions)" + + private class PaimonBatchWrite extends BatchWrite { + override def createBatchWriterFactory(info: PhysicalWriteInfo): DataWriterFactory = + WriterFactory(writeSchema, batchWriteBuilder) + + override def useCommitCoordinator(): Boolean = false + + override def commit(messages: Array[WriterCommitMessage]): Unit = { + log.info(s"Committing to table ${table.name()}") + val batchTableCommit = batchWriteBuilder.newCommit() + + val commitMessages = + messages.filter(_ != null).map(_.asInstanceOf[TaskCommit].commitMessages).flatten.toList + + try { + val start = System.currentTimeMillis() + batchTableCommit.commit(commitMessages.asJava) + log.info(s"Committed in ${System.currentTimeMillis() - start} ms") + } finally { + batchTableCommit.close() + } + } + + override def abort(messages: Array[WriterCommitMessage]): Unit = { + // TODO clean uncommitted files + } + } +} + +private case class WriterFactory(writeSchema: StructType, batchWriteBuilder: BatchWriteBuilder) + extends DataWriterFactory { + + override def createWriter(partitionId: Int, taskId: Long): DataWriter[InternalRow] = { + val batchTableWrite = batchWriteBuilder.newWrite() + new PaimonDataWriter(batchTableWrite, writeSchema) + } +} + +private class PaimonDataWriter(batchTableWrite: BatchTableWrite, writeSchema: StructType) + extends DataWriter[InternalRow] { + + private val ioManager = SparkUtils.createIOManager() + batchTableWrite.withIOManager(ioManager) + + override def write(record: InternalRow): Unit = { + val wrappedRow = new SparkInternalRowWrapper(record, -1, writeSchema, writeSchema.fields.length) + batchTableWrite.write(wrappedRow) + } + + override def commit(): WriterCommitMessage = { + try { + val commitMessages = batchTableWrite.prepareCommit().asScala.toList + TaskCommit(commitMessages) + } finally { + close() + } + } + + override def abort(): Unit = close() + + override def close(): Unit = { + try { + batchTableWrite.close() + ioManager.close() + } catch { + case e: Exception => throw new RuntimeException(e) + } + } +} + +private case class TaskCommit(commitMessagesList: List[CommitMessage]) extends WriterCommitMessage { Review Comment: use scala type instead of java list ########## paimon-spark/paimon-spark-common/src/main/java/org/apache/paimon/spark/SparkSQLProperties.java: ########## @@ -0,0 +1,27 @@ +/* + * 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.paimon.spark; + +/** Spark SQL properties for Paimon. */ +public class SparkSQLProperties { + private SparkSQLProperties() {} + + public static final String USE_V2_WRITE = "spark.sql.paimon.use-v2-write"; Review Comment: add conf to `SparkConnectorOptions`, like `requiredSparkConfsCheck.enabled`, and use `def getOptionString(option: ConfigOption[_])` to get it by spark.paimon.xxx ########## paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/SparkWriteRequirement.scala: ########## @@ -0,0 +1,67 @@ +/* + * 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.paimon.spark + +import org.apache.paimon.table.{BucketMode, FileStoreTable} + +import org.apache.spark.sql.connector.distributions.{ClusteredDistribution, Distribution, Distributions} +import org.apache.spark.sql.connector.expressions.{Expression, Expressions, SortOrder} + +import scala.collection.JavaConverters._ + +/** Distribution requirements of Spark write. */ +case class SparkWriteRequirement(distribution: Distribution, ordering: Array[SortOrder]) + +object SparkWriteRequirement { + private val EMPTY_ORDERING: Array[SortOrder] = Array.empty + private val EMPTY: SparkWriteRequirement = + SparkWriteRequirement(Distributions.unspecified(), EMPTY_ORDERING) + + def apply(table: FileStoreTable): SparkWriteRequirement = { + val bucketSpec = table.bucketSpec() + val bucketExpr = bucketSpec.getBucketMode match { + case BucketMode.HASH_FIXED => + Seq( + Expressions.bucket( + bucketSpec.getNumBuckets, + bucketSpec.getBucketKeys.asScala.map(quote).toArray: _*)) + case BucketMode.BUCKET_UNAWARE => + Seq.empty + case _ => + throw new UnsupportedOperationException( + s"Unsupported bucket mode ${bucketSpec.getBucketMode}") + } + + val partitionExprs = + table.schema().partitionKeys().asScala.map(key => Expressions.identity(quote(key))) + + val clusteringExpressions: Seq[Expression] = partitionExprs ++ bucketExpr Review Comment: Please double-check whether the behavior here is correct because our bucket function operates on the bucket key and does not include partition columns -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
