You are viewing a plain text version of this content. The canonical link for it is here.
Posted to reviews@spark.apache.org by "LuciferYang (via GitHub)" <gi...@apache.org> on 2023/03/31 09:47:36 UTC

[GitHub] [spark] LuciferYang commented on a diff in pull request #40611: [SPARK-42981][CONNECT] Add direct arrow serialization

LuciferYang commented on code in PR #40611:
URL: https://github.com/apache/spark/pull/40611#discussion_r1154265174


##########
connector/connect/client/jvm/src/main/scala/org/apache/spark/sql/connect/client/arrow/ArrowSerializer.scala:
##########
@@ -0,0 +1,529 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.spark.sql.connect.client.arrow
+
+import java.io.{ByteArrayOutputStream, OutputStream}
+import java.lang.invoke.{MethodHandles, MethodType}
+import java.math.{BigDecimal => JBigDecimal, BigInteger => JBigInteger}
+import java.nio.channels.Channels
+import java.time.{Duration, Instant, LocalDate, LocalDateTime, Period}
+import java.util.{Map => JMap}
+
+import scala.collection.JavaConverters._
+import scala.collection.mutable
+
+import com.google.protobuf.ByteString
+import org.apache.arrow.memory.BufferAllocator
+import org.apache.arrow.vector.{BigIntVector, BitVector, DateDayVector, DecimalVector, DurationVector, FieldVector, Float4Vector, Float8Vector, IntervalYearVector, IntVector, NullVector, SmallIntVector, TimeStampMicroTZVector, TimeStampMicroVector, TinyIntVector, VarBinaryVector, VarCharVector, VectorSchemaRoot, VectorUnloader}
+import org.apache.arrow.vector.complex.{ListVector, MapVector, StructVector}
+import org.apache.arrow.vector.ipc.{ArrowStreamWriter, WriteChannel}
+import org.apache.arrow.vector.ipc.message.{IpcOption, MessageSerializer}
+import org.apache.arrow.vector.util.Text
+
+import org.apache.spark.sql.Row
+import org.apache.spark.sql.catalyst.DefinedByConstructorParams
+import org.apache.spark.sql.catalyst.encoders.AgnosticEncoder
+import org.apache.spark.sql.catalyst.encoders.AgnosticEncoders._
+import org.apache.spark.sql.catalyst.util.{DateTimeUtils, IntervalUtils}
+import org.apache.spark.sql.errors.QueryExecutionErrors
+import org.apache.spark.sql.types.Decimal
+import org.apache.spark.sql.util.ArrowUtils
+
+/**
+ * Helper class for converting user objects into arrow batches.
+ */
+class ArrowSerializer[T](
+    private[this] val enc: AgnosticEncoder[T],
+    private[this] val allocator: BufferAllocator,
+    private[this] val timeZoneId: String) {
+  private val (root, serializer) = ArrowSerializer.serializerFor(enc, allocator, timeZoneId)
+  private val vectors = root.getFieldVectors.asScala
+  private val unloader = new VectorUnloader(root)
+  private val schemaBytes = {
+    // Only serialize the schema once.
+    val bytes = new ByteArrayOutputStream()
+    MessageSerializer.serialize(newChannel(bytes), root.getSchema)
+    bytes.toByteArray
+  }
+  private var i: Int = 0
+
+  private def newChannel(output: OutputStream): WriteChannel = {
+    new WriteChannel(Channels.newChannel(output))
+  }
+
+  /**
+   * The size of the current batch.
+   *
+   * The size computed consist of the size of the schema and the size of the arrow buffers. The
+   * actual batch will be larger than that because of alignment, written IPC tokens, and the
+   * written record batch metadata. The size of the record batch metadata is proportional to the
+   * complexity of the schema.
+   */
+  def sizeInBytes: Long = {
+    // We need to set the row count for getBufferSize to return the actual value.
+    root.setRowCount(i)
+    schemaBytes.length + vectors.map(_.getBufferSize).sum
+  }
+
+  /**
+   * Append a record to the current batch.
+   */
+  def append(record: T): Unit = {
+    serializer.write(i, record)
+    i += 1
+  }
+
+  /**
+   * Write the schema and the current batch in Arrow IPC stream format to the [[OutputStream]].
+   */
+  def writeIpcStream(output: OutputStream): Unit = {
+    val channel = newChannel(output)
+    root.setRowCount(i)
+    val batch = unloader.getRecordBatch
+    try {
+      channel.write(schemaBytes)
+      MessageSerializer.serialize(channel, batch)
+      ArrowStreamWriter.writeEndOfStream(channel, IpcOption.DEFAULT)
+    } finally {
+      batch.close()
+    }
+  }
+
+  /**
+   * Reset the serializer.
+   */
+  def reset(): Unit = {
+    i = 0
+    vectors.foreach(_.reset())
+  }
+
+  /**
+   * Close the serializer.
+   */
+  def close(): Unit = root.close()
+}
+
+object ArrowSerializer {
+  import ArrowEncoderUtils._
+
+  /**
+   * Create an [[Iterator]] that converts the input [[Iterator]] of type `T` into an [[Iterator]]
+   * of Arrow IPC Streams.
+   */
+  def serialize[T](
+      input: Iterator[T],
+      enc: AgnosticEncoder[T],
+      allocator: BufferAllocator,
+      maxRecordsPerBatch: Int,
+      maxBatchSize: Long,
+      timeZoneId: String,
+      batchSizeCheckInterval: Int = 128): CloseableIterator[Array[Byte]] = {
+    assert(maxRecordsPerBatch > 0)
+    assert(maxBatchSize > 0)
+    assert(batchSizeCheckInterval > 0)
+    new CloseableIterator[Array[Byte]] {
+      private val serializer = new ArrowSerializer[T](enc, allocator, timeZoneId)
+      private val bytes = new ByteArrayOutputStream
+      private var hasWrittenFirstBatch = false
+
+      /**
+       * Periodical check to make sure we don't go over the size threshold by too much.
+       */
+      private def sizeOk(i: Int): Boolean = {
+        if (i > 0 && i % batchSizeCheckInterval == 0) {
+          return serializer.sizeInBytes < maxBatchSize
+        }
+        true
+      }
+
+      override def hasNext: Boolean = input.hasNext || !hasWrittenFirstBatch
+
+      override def next(): Array[Byte] = {
+        if (!hasNext) {
+          throw new NoSuchElementException()
+        }
+        serializer.reset()
+        bytes.reset()
+        var i = 0
+        while (i < maxRecordsPerBatch && input.hasNext && sizeOk(i)) {
+          serializer.append(input.next())
+          i += 1
+        }
+        serializer.writeIpcStream(bytes)
+        hasWrittenFirstBatch = true
+        bytes.toByteArray
+      }
+
+      override def close(): Unit = serializer.close()
+    }
+  }
+
+  def serialize[T](
+      input: Iterator[T],
+      enc: AgnosticEncoder[T],
+      allocator: BufferAllocator,
+      timeZoneId: String): ByteString = {
+    val serializer = new ArrowSerializer[T](enc, allocator, timeZoneId)
+    serializer.reset()
+    input.foreach(serializer.append)
+    val output = ByteString.newOutput()
+    serializer.writeIpcStream(output)
+    output.toByteString
+  }
+
+  /**
+   * Create a (root) [[Serializer]] for [[AgnosticEncoder]] `encoder`.
+   *
+   * The serializer returned by this method is NOT thread-safe.
+   */
+  def serializerFor[T](
+      encoder: AgnosticEncoder[T],
+      allocator: BufferAllocator,
+      timeZoneId: String): (VectorSchemaRoot, Serializer) = {
+    val arrowSchema = ArrowUtils.toArrowSchema(encoder.schema, timeZoneId)
+    val root = VectorSchemaRoot.create(arrowSchema, allocator)
+    val serializer = if (encoder.schema != encoder.dataType) {
+      assert(root.getSchema.getFields.size() == 1)
+      serializerFor(encoder, root.getVector(0))
+    } else {
+      serializerFor(encoder, root)
+    }
+    root -> serializer
+  }
+
+  // TODO throw better errors on class cast exceptions.
+  private[arrow] def serializerFor[E](encoder: AgnosticEncoder[E], v: AnyRef): Serializer = {
+    (encoder, v) match {
+      case (PrimitiveBooleanEncoder | BoxedBooleanEncoder, v: BitVector) =>
+        new FieldSerializer[Boolean, BitVector](v) {
+          override def set(index: Int, value: Boolean): Unit =
+            vector.setSafe(index, if (value) 1 else 0)
+        }
+      case (PrimitiveByteEncoder | BoxedByteEncoder, v: TinyIntVector) =>
+        new FieldSerializer[Byte, TinyIntVector](v) {
+          override def set(index: Int, value: Byte): Unit = vector.setSafe(index, value)
+        }
+      case (PrimitiveShortEncoder | BoxedShortEncoder, v: SmallIntVector) =>
+        new FieldSerializer[Short, SmallIntVector](v) {
+          override def set(index: Int, value: Short): Unit = vector.setSafe(index, value)
+        }
+      case (PrimitiveIntEncoder | BoxedIntEncoder, v: IntVector) =>
+        new FieldSerializer[Int, IntVector](v) {
+          override def set(index: Int, value: Int): Unit = vector.setSafe(index, value)
+        }
+      case (PrimitiveLongEncoder | BoxedLongEncoder, v: BigIntVector) =>
+        new FieldSerializer[Long, BigIntVector](v) {
+          override def set(index: Int, value: Long): Unit = vector.setSafe(index, value)
+        }
+      case (PrimitiveFloatEncoder | BoxedFloatEncoder, v: Float4Vector) =>
+        new FieldSerializer[Float, Float4Vector](v) {
+          override def set(index: Int, value: Float): Unit = vector.setSafe(index, value)
+        }
+      case (PrimitiveDoubleEncoder | BoxedDoubleEncoder, v: Float8Vector) =>
+        new FieldSerializer[Double, Float8Vector](v) {
+          override def set(index: Int, value: Double): Unit = vector.setSafe(index, value)
+        }
+      case (NullEncoder, v: NullVector) =>
+        new FieldSerializer[Unit, NullVector](v) {
+          override def set(index: Int, value: Unit): Unit = vector.setNull(index)
+        }
+      case (StringEncoder, v: VarCharVector) =>
+        new FieldSerializer[String, VarCharVector](v) {
+          override def set(index: Int, value: String): Unit = setString(v, index, value)
+        }
+      case (JavaEnumEncoder(_), v: VarCharVector) =>
+        new FieldSerializer[Enum[_], VarCharVector](v) {
+          override def set(index: Int, value: Enum[_]): Unit = setString(v, index, value.name())
+        }
+      case (ScalaEnumEncoder(_, _), v: VarCharVector) =>
+        new FieldSerializer[Enumeration#Value, VarCharVector](v) {
+          override def set(index: Int, value: Enumeration#Value): Unit =
+            setString(v, index, value.toString)
+        }
+      case (BinaryEncoder, v: VarBinaryVector) =>
+        new FieldSerializer[Array[Byte], VarBinaryVector](v) {
+          override def set(index: Int, value: Array[Byte]): Unit = vector.setSafe(index, value)
+        }
+      case (SparkDecimalEncoder(_), v: DecimalVector) =>
+        new FieldSerializer[Decimal, DecimalVector](v) {
+          override def set(index: Int, value: Decimal): Unit =
+            setDecimal(vector, index, value.toJavaBigDecimal)
+        }
+      case (ScalaDecimalEncoder(_), v: DecimalVector) =>
+        new FieldSerializer[BigDecimal, DecimalVector](v) {
+          override def set(index: Int, value: BigDecimal): Unit =
+            setDecimal(vector, index, value.bigDecimal)
+        }
+      case (JavaDecimalEncoder(_, false), v: DecimalVector) =>
+        new FieldSerializer[JBigDecimal, DecimalVector](v) {
+          override def set(index: Int, value: JBigDecimal): Unit =
+            setDecimal(vector, index, value)
+        }
+      case (JavaDecimalEncoder(_, true), v: DecimalVector) =>
+        new FieldSerializer[Any, DecimalVector](v) {
+          override def set(index: Int, value: Any): Unit = {
+            val decimal = value match {
+              case j: JBigDecimal => j
+              case d: BigDecimal => d.bigDecimal
+              case k: BigInt => new JBigDecimal(k.bigInteger)
+              case l: JBigInteger => new JBigDecimal(l)
+              case d: Decimal => d.toJavaBigDecimal
+            }
+            setDecimal(vector, index, decimal)
+          }
+        }
+      case (ScalaBigIntEncoder, v: DecimalVector) =>
+        new FieldSerializer[BigInt, DecimalVector](v) {
+          override def set(index: Int, value: BigInt): Unit =
+            setDecimal(vector, index, new JBigDecimal(value.bigInteger))
+        }
+      case (JavaBigIntEncoder, v: DecimalVector) =>
+        new FieldSerializer[JBigInteger, DecimalVector](v) {
+          override def set(index: Int, value: JBigInteger): Unit =
+            setDecimal(vector, index, new JBigDecimal(value))
+        }
+      case (DayTimeIntervalEncoder, v: DurationVector) =>
+        new FieldSerializer[Duration, DurationVector](v) {
+          override def set(index: Int, value: Duration): Unit =
+            vector.setSafe(index, IntervalUtils.durationToMicros(value))
+        }
+      case (YearMonthIntervalEncoder, v: IntervalYearVector) =>
+        new FieldSerializer[Period, IntervalYearVector](v) {
+          override def set(index: Int, value: Period): Unit =
+            vector.setSafe(index, IntervalUtils.periodToMonths(value))
+        }
+      case (DateEncoder(true) | LocalDateEncoder(true), v: DateDayVector) =>
+        new FieldSerializer[Any, DateDayVector](v) {
+          override def set(index: Int, value: Any): Unit =
+            vector.setSafe(index, DateTimeUtils.anyToDays(value))
+        }
+      case (DateEncoder(false), v: DateDayVector) =>
+        new FieldSerializer[java.sql.Date, DateDayVector](v) {
+          override def set(index: Int, value: java.sql.Date): Unit =
+            vector.setSafe(index, DateTimeUtils.fromJavaDate(value))
+        }
+      case (LocalDateEncoder(false), v: DateDayVector) =>
+        new FieldSerializer[LocalDate, DateDayVector](v) {
+          override def set(index: Int, value: LocalDate): Unit =
+            vector.setSafe(index, DateTimeUtils.localDateToDays(value))
+        }
+      case (TimestampEncoder(true) | InstantEncoder(true), v: TimeStampMicroTZVector) =>
+        new FieldSerializer[Any, TimeStampMicroTZVector](v) {
+          override def set(index: Int, value: Any): Unit =
+            vector.setSafe(index, DateTimeUtils.anyToMicros(value))
+        }
+      case (TimestampEncoder(false), v: TimeStampMicroTZVector) =>
+        new FieldSerializer[java.sql.Timestamp, TimeStampMicroTZVector](v) {
+          override def set(index: Int, value: java.sql.Timestamp): Unit =
+            vector.setSafe(index, DateTimeUtils.fromJavaTimestamp(value))
+        }
+      case (InstantEncoder(false), v: TimeStampMicroTZVector) =>
+        new FieldSerializer[Instant, TimeStampMicroTZVector](v) {
+          override def set(index: Int, value: Instant): Unit =
+            vector.setSafe(index, DateTimeUtils.instantToMicros(value))
+        }
+      case (LocalDateTimeEncoder, v: TimeStampMicroVector) =>
+        new FieldSerializer[LocalDateTime, TimeStampMicroVector](v) {
+          override def set(index: Int, value: LocalDateTime): Unit =
+            vector.setSafe(index, DateTimeUtils.localDateTimeToMicros(value))
+        }
+
+      case (OptionEncoder(value), v) =>
+        new Serializer {
+          private[this] val delegate: Serializer = serializerFor(value, v)
+          override def write(index: Int, value: Any): Unit = value match {
+            case Some(value) => delegate.write(index, value)
+            case _ => delegate.write(index, null)
+          }
+        }
+
+      case (ArrayEncoder(element, _), v: ListVector) =>
+        val elementSerializer = serializerFor(element, v.getDataVector)
+        val toIterator = { array: Any =>
+          mutable.WrappedArray.make(array.asInstanceOf[AnyRef]).iterator

Review Comment:
   ```suggestion
             mutable.WrappedArray.make(array.asInstanceOf[Array[_]]).iterator
   ```



##########
connector/connect/client/jvm/src/main/scala/org/apache/spark/sql/connect/client/arrow/ArrowEncoderUtils.scala:
##########
@@ -0,0 +1,53 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.spark.sql.connect.client.arrow
+
+import scala.collection.JavaConverters._
+import scala.reflect.ClassTag
+
+import org.apache.arrow.vector.{FieldVector, VectorSchemaRoot}
+import org.apache.arrow.vector.complex.StructVector
+
+private[arrow] object ArrowEncoderUtils {
+  object Classes {
+    val WRAPPED_ARRAY: Class[_] = classOf[scala.collection.mutable.WrappedArray[_]]
+    val ITERABLE: Class[_] = classOf[scala.collection.Iterable[_]]
+    val SEQ: Class[_] = classOf[scala.collection.Seq[_]]
+    val SET: Class[_] = classOf[scala.collection.Set[_]]
+    val MAP: Class[_] = classOf[scala.collection.Map[_, _]]
+    val JLIST: Class[_] = classOf[java.util.List[_]]
+    val JMAP: Class[_] = classOf[java.util.Map[_, _]]
+  }
+
+  def isSubClass(cls: Class[_], tag: ClassTag[_]): Boolean = {
+    cls.isAssignableFrom(tag.runtimeClass)
+  }
+
+  def unsupportedCollectionType(cls: Class[_]): Nothing = {
+    throw new RuntimeException(s"Unsupported collection type: $cls")
+  }
+}
+
+trait CloseableIterator[E] extends Iterator[E] with AutoCloseable
+
+private[arrow] object StructVectors {
+  def unapply(v: AnyRef): Option[(StructVector, Seq[FieldVector])] = v match {
+    case root: VectorSchemaRoot => Option((null, root.getFieldVectors.asScala))
+    case struct: StructVector => Option((struct, struct.getChildrenFromFields.asScala))

Review Comment:
   ```suggestion
       case struct: StructVector => Option((struct, struct.getChildrenFromFields.asScala.toSeq))
   ```



##########
connector/connect/client/jvm/src/test/scala/org/apache/spark/sql/connect/client/arrow/ArrowEncoderSuite.scala:
##########
@@ -0,0 +1,837 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.spark.sql.connect.client.arrow
+
+import java.util
+import java.util.{Collections, Objects}
+
+import scala.collection.JavaConverters._
+import scala.collection.mutable
+import scala.reflect.classTag
+import scala.util.control.NonFatal
+
+import com.google.protobuf.ByteString
+import org.apache.arrow.memory.{BufferAllocator, RootAllocator}
+import org.apache.arrow.vector.VarBinaryVector
+import org.scalatest.BeforeAndAfterAll
+
+import org.apache.spark.SparkUnsupportedOperationException
+import org.apache.spark.connect.proto
+import org.apache.spark.sql.Row
+import org.apache.spark.sql.catalyst.{DefinedByConstructorParams, DummyBean, FooEnum, JavaTypeInference, PrimitiveData, ScalaReflection}
+import org.apache.spark.sql.catalyst.FooEnum.FooEnum
+import org.apache.spark.sql.catalyst.encoders.{AgnosticEncoder, BoxedData, UDTForCaseClass}
+import org.apache.spark.sql.catalyst.encoders.AgnosticEncoders.{BoxedIntEncoder, CalendarIntervalEncoder, DateEncoder, EncoderField, InstantEncoder, IterableEncoder, JavaDecimalEncoder, LocalDateEncoder, PrimitiveDoubleEncoder, PrimitiveFloatEncoder, RowEncoder, StringEncoder, TimestampEncoder, UDTEncoder}
+import org.apache.spark.sql.catalyst.encoders.RowEncoder.{encoderFor => toRowEncoder}
+import org.apache.spark.sql.connect.client.SparkResult
+import org.apache.spark.sql.connect.client.util.ConnectFunSuite
+import org.apache.spark.sql.types.{ArrayType, Decimal, DecimalType, Metadata, StructType}
+
+/**
+ * Tests for encoding external data to and from arrow.
+ */
+class ArrowEncoderSuite extends ConnectFunSuite with BeforeAndAfterAll {
+  private val allocator = new RootAllocator()
+
+  private def newAllocator(name: String): BufferAllocator = {
+    allocator.newChildAllocator(name, 0, allocator.getLimit)
+  }
+
+  protected override def afterAll(): Unit = {
+    super.afterAll()
+    allocator.close()
+  }
+
+  private def withAllocator[T](f: BufferAllocator => T): T = {
+    val allocator = newAllocator("allocator")
+    try f(allocator)
+    finally {
+      allocator.close()
+    }
+  }
+
+  private def roundTrip[T](
+      encoder: AgnosticEncoder[T],
+      iterator: Iterator[T],
+      maxRecordsPerBatch: Int = 4 * 1024,
+      maxBatchSize: Long = 16 * 1024,
+      batchSizeCheckInterval: Int = 128,
+      inspectBatch: Array[Byte] => Unit = null): CloseableIterator[T] = {
+    // Use different allocators so we can pinpoint memory leaks better.
+    val serializerAllocator = newAllocator("serialization")
+    val deserializerAllocator = newAllocator("deserialization")
+
+    val arrowIterator = ArrowSerializer.serialize(
+      input = iterator,
+      enc = encoder,
+      allocator = serializerAllocator,
+      maxRecordsPerBatch = maxRecordsPerBatch,
+      maxBatchSize = maxBatchSize,
+      batchSizeCheckInterval = batchSizeCheckInterval,
+      timeZoneId = "UTC")
+
+    val inspectedIterator = if (inspectBatch != null) {
+      arrowIterator.map { batch =>
+        inspectBatch(batch)
+        batch
+      }
+    } else {
+      arrowIterator
+    }
+
+    val resultIterator =
+      try {
+        deserializeFromArrow(inspectedIterator, encoder, deserializerAllocator)
+      } catch {
+        case NonFatal(e) =>
+          arrowIterator.close()
+          serializerAllocator.close()
+          deserializerAllocator.close()
+          throw e
+      }
+    new CloseableIterator[T] {
+      override def close(): Unit = {
+        arrowIterator.close()
+        resultIterator.close()
+        serializerAllocator.close()
+        deserializerAllocator.close()
+      }
+      override def hasNext: Boolean = resultIterator.hasNext
+      override def next(): T = resultIterator.next()
+    }
+  }
+
+  // Temporary hack until we merge the deserializer.
+  private def deserializeFromArrow[E](
+      batches: Iterator[Array[Byte]],
+      encoder: AgnosticEncoder[E],
+      allocator: BufferAllocator): CloseableIterator[E] = {
+    val responses = batches.map { batch =>
+      val builder = proto.ExecutePlanResponse.newBuilder()
+      builder.getArrowBatchBuilder.setData(ByteString.copyFrom(batch))
+      builder.build()
+    }
+    val result = new SparkResult[E](responses.asJava, allocator, encoder)
+    new CloseableIterator[E] {
+      private val iterator = result.iterator

Review Comment:
   ```suggestion
         private val closeableIterator = result.iterator
   ```



##########
connector/connect/client/jvm/src/test/scala/org/apache/spark/sql/connect/client/arrow/ArrowEncoderSuite.scala:
##########
@@ -0,0 +1,837 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.spark.sql.connect.client.arrow
+
+import java.util
+import java.util.{Collections, Objects}
+
+import scala.collection.JavaConverters._
+import scala.collection.mutable
+import scala.reflect.classTag
+import scala.util.control.NonFatal
+
+import com.google.protobuf.ByteString
+import org.apache.arrow.memory.{BufferAllocator, RootAllocator}
+import org.apache.arrow.vector.VarBinaryVector
+import org.scalatest.BeforeAndAfterAll
+
+import org.apache.spark.SparkUnsupportedOperationException
+import org.apache.spark.connect.proto
+import org.apache.spark.sql.Row
+import org.apache.spark.sql.catalyst.{DefinedByConstructorParams, DummyBean, FooEnum, JavaTypeInference, PrimitiveData, ScalaReflection}
+import org.apache.spark.sql.catalyst.FooEnum.FooEnum
+import org.apache.spark.sql.catalyst.encoders.{AgnosticEncoder, BoxedData, UDTForCaseClass}
+import org.apache.spark.sql.catalyst.encoders.AgnosticEncoders.{BoxedIntEncoder, CalendarIntervalEncoder, DateEncoder, EncoderField, InstantEncoder, IterableEncoder, JavaDecimalEncoder, LocalDateEncoder, PrimitiveDoubleEncoder, PrimitiveFloatEncoder, RowEncoder, StringEncoder, TimestampEncoder, UDTEncoder}
+import org.apache.spark.sql.catalyst.encoders.RowEncoder.{encoderFor => toRowEncoder}
+import org.apache.spark.sql.connect.client.SparkResult
+import org.apache.spark.sql.connect.client.util.ConnectFunSuite
+import org.apache.spark.sql.types.{ArrayType, Decimal, DecimalType, Metadata, StructType}
+
+/**
+ * Tests for encoding external data to and from arrow.
+ */
+class ArrowEncoderSuite extends ConnectFunSuite with BeforeAndAfterAll {
+  private val allocator = new RootAllocator()
+
+  private def newAllocator(name: String): BufferAllocator = {
+    allocator.newChildAllocator(name, 0, allocator.getLimit)
+  }
+
+  protected override def afterAll(): Unit = {
+    super.afterAll()
+    allocator.close()
+  }
+
+  private def withAllocator[T](f: BufferAllocator => T): T = {
+    val allocator = newAllocator("allocator")
+    try f(allocator)
+    finally {
+      allocator.close()
+    }
+  }
+
+  private def roundTrip[T](
+      encoder: AgnosticEncoder[T],
+      iterator: Iterator[T],
+      maxRecordsPerBatch: Int = 4 * 1024,
+      maxBatchSize: Long = 16 * 1024,
+      batchSizeCheckInterval: Int = 128,
+      inspectBatch: Array[Byte] => Unit = null): CloseableIterator[T] = {
+    // Use different allocators so we can pinpoint memory leaks better.
+    val serializerAllocator = newAllocator("serialization")
+    val deserializerAllocator = newAllocator("deserialization")
+
+    val arrowIterator = ArrowSerializer.serialize(
+      input = iterator,
+      enc = encoder,
+      allocator = serializerAllocator,
+      maxRecordsPerBatch = maxRecordsPerBatch,
+      maxBatchSize = maxBatchSize,
+      batchSizeCheckInterval = batchSizeCheckInterval,
+      timeZoneId = "UTC")
+
+    val inspectedIterator = if (inspectBatch != null) {
+      arrowIterator.map { batch =>
+        inspectBatch(batch)
+        batch
+      }
+    } else {
+      arrowIterator
+    }
+
+    val resultIterator =
+      try {
+        deserializeFromArrow(inspectedIterator, encoder, deserializerAllocator)
+      } catch {
+        case NonFatal(e) =>
+          arrowIterator.close()
+          serializerAllocator.close()
+          deserializerAllocator.close()
+          throw e
+      }
+    new CloseableIterator[T] {
+      override def close(): Unit = {
+        arrowIterator.close()
+        resultIterator.close()
+        serializerAllocator.close()
+        deserializerAllocator.close()
+      }
+      override def hasNext: Boolean = resultIterator.hasNext
+      override def next(): T = resultIterator.next()
+    }
+  }
+
+  // Temporary hack until we merge the deserializer.
+  private def deserializeFromArrow[E](
+      batches: Iterator[Array[Byte]],
+      encoder: AgnosticEncoder[E],
+      allocator: BufferAllocator): CloseableIterator[E] = {
+    val responses = batches.map { batch =>
+      val builder = proto.ExecutePlanResponse.newBuilder()
+      builder.getArrowBatchBuilder.setData(ByteString.copyFrom(batch))
+      builder.build()
+    }
+    val result = new SparkResult[E](responses.asJava, allocator, encoder)
+    new CloseableIterator[E] {
+      private val iterator = result.iterator

Review Comment:
   `iterator`  in Scala 2.13 is a final



##########
connector/connect/client/jvm/src/main/scala/org/apache/spark/sql/connect/client/arrow/ArrowEncoderUtils.scala:
##########
@@ -0,0 +1,53 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.spark.sql.connect.client.arrow
+
+import scala.collection.JavaConverters._
+import scala.reflect.ClassTag
+
+import org.apache.arrow.vector.{FieldVector, VectorSchemaRoot}
+import org.apache.arrow.vector.complex.StructVector
+
+private[arrow] object ArrowEncoderUtils {
+  object Classes {
+    val WRAPPED_ARRAY: Class[_] = classOf[scala.collection.mutable.WrappedArray[_]]
+    val ITERABLE: Class[_] = classOf[scala.collection.Iterable[_]]
+    val SEQ: Class[_] = classOf[scala.collection.Seq[_]]
+    val SET: Class[_] = classOf[scala.collection.Set[_]]
+    val MAP: Class[_] = classOf[scala.collection.Map[_, _]]
+    val JLIST: Class[_] = classOf[java.util.List[_]]
+    val JMAP: Class[_] = classOf[java.util.Map[_, _]]
+  }
+
+  def isSubClass(cls: Class[_], tag: ClassTag[_]): Boolean = {
+    cls.isAssignableFrom(tag.runtimeClass)
+  }
+
+  def unsupportedCollectionType(cls: Class[_]): Nothing = {
+    throw new RuntimeException(s"Unsupported collection type: $cls")
+  }
+}
+
+trait CloseableIterator[E] extends Iterator[E] with AutoCloseable
+
+private[arrow] object StructVectors {
+  def unapply(v: AnyRef): Option[(StructVector, Seq[FieldVector])] = v match {
+    case root: VectorSchemaRoot => Option((null, root.getFieldVectors.asScala))
+    case struct: StructVector => Option((struct, struct.getChildrenFromFields.asScala))

Review Comment:
   for Scala 2.13



##########
connector/connect/client/jvm/src/main/scala/org/apache/spark/sql/connect/client/arrow/ArrowEncoderUtils.scala:
##########
@@ -0,0 +1,53 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.spark.sql.connect.client.arrow
+
+import scala.collection.JavaConverters._
+import scala.reflect.ClassTag
+
+import org.apache.arrow.vector.{FieldVector, VectorSchemaRoot}
+import org.apache.arrow.vector.complex.StructVector
+
+private[arrow] object ArrowEncoderUtils {
+  object Classes {
+    val WRAPPED_ARRAY: Class[_] = classOf[scala.collection.mutable.WrappedArray[_]]
+    val ITERABLE: Class[_] = classOf[scala.collection.Iterable[_]]
+    val SEQ: Class[_] = classOf[scala.collection.Seq[_]]
+    val SET: Class[_] = classOf[scala.collection.Set[_]]
+    val MAP: Class[_] = classOf[scala.collection.Map[_, _]]
+    val JLIST: Class[_] = classOf[java.util.List[_]]
+    val JMAP: Class[_] = classOf[java.util.Map[_, _]]
+  }
+
+  def isSubClass(cls: Class[_], tag: ClassTag[_]): Boolean = {
+    cls.isAssignableFrom(tag.runtimeClass)
+  }
+
+  def unsupportedCollectionType(cls: Class[_]): Nothing = {
+    throw new RuntimeException(s"Unsupported collection type: $cls")
+  }
+}
+
+trait CloseableIterator[E] extends Iterator[E] with AutoCloseable
+
+private[arrow] object StructVectors {
+  def unapply(v: AnyRef): Option[(StructVector, Seq[FieldVector])] = v match {
+    case root: VectorSchemaRoot => Option((null, root.getFieldVectors.asScala))

Review Comment:
   ```suggestion
       case root: VectorSchemaRoot => Option((null, root.getFieldVectors.asScala.toSeq))
   ```



##########
connector/connect/client/jvm/src/main/scala/org/apache/spark/sql/connect/client/arrow/ArrowSerializer.scala:
##########
@@ -0,0 +1,529 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.spark.sql.connect.client.arrow
+
+import java.io.{ByteArrayOutputStream, OutputStream}
+import java.lang.invoke.{MethodHandles, MethodType}
+import java.math.{BigDecimal => JBigDecimal, BigInteger => JBigInteger}
+import java.nio.channels.Channels
+import java.time.{Duration, Instant, LocalDate, LocalDateTime, Period}
+import java.util.{Map => JMap}
+
+import scala.collection.JavaConverters._
+import scala.collection.mutable
+
+import com.google.protobuf.ByteString
+import org.apache.arrow.memory.BufferAllocator
+import org.apache.arrow.vector.{BigIntVector, BitVector, DateDayVector, DecimalVector, DurationVector, FieldVector, Float4Vector, Float8Vector, IntervalYearVector, IntVector, NullVector, SmallIntVector, TimeStampMicroTZVector, TimeStampMicroVector, TinyIntVector, VarBinaryVector, VarCharVector, VectorSchemaRoot, VectorUnloader}
+import org.apache.arrow.vector.complex.{ListVector, MapVector, StructVector}
+import org.apache.arrow.vector.ipc.{ArrowStreamWriter, WriteChannel}
+import org.apache.arrow.vector.ipc.message.{IpcOption, MessageSerializer}
+import org.apache.arrow.vector.util.Text
+
+import org.apache.spark.sql.Row
+import org.apache.spark.sql.catalyst.DefinedByConstructorParams
+import org.apache.spark.sql.catalyst.encoders.AgnosticEncoder
+import org.apache.spark.sql.catalyst.encoders.AgnosticEncoders._
+import org.apache.spark.sql.catalyst.util.{DateTimeUtils, IntervalUtils}
+import org.apache.spark.sql.errors.QueryExecutionErrors
+import org.apache.spark.sql.types.Decimal
+import org.apache.spark.sql.util.ArrowUtils
+
+/**
+ * Helper class for converting user objects into arrow batches.
+ */
+class ArrowSerializer[T](
+    private[this] val enc: AgnosticEncoder[T],
+    private[this] val allocator: BufferAllocator,
+    private[this] val timeZoneId: String) {
+  private val (root, serializer) = ArrowSerializer.serializerFor(enc, allocator, timeZoneId)
+  private val vectors = root.getFieldVectors.asScala
+  private val unloader = new VectorUnloader(root)
+  private val schemaBytes = {
+    // Only serialize the schema once.
+    val bytes = new ByteArrayOutputStream()
+    MessageSerializer.serialize(newChannel(bytes), root.getSchema)
+    bytes.toByteArray
+  }
+  private var i: Int = 0
+
+  private def newChannel(output: OutputStream): WriteChannel = {
+    new WriteChannel(Channels.newChannel(output))
+  }
+
+  /**
+   * The size of the current batch.
+   *
+   * The size computed consist of the size of the schema and the size of the arrow buffers. The
+   * actual batch will be larger than that because of alignment, written IPC tokens, and the
+   * written record batch metadata. The size of the record batch metadata is proportional to the
+   * complexity of the schema.
+   */
+  def sizeInBytes: Long = {
+    // We need to set the row count for getBufferSize to return the actual value.
+    root.setRowCount(i)
+    schemaBytes.length + vectors.map(_.getBufferSize).sum
+  }
+
+  /**
+   * Append a record to the current batch.
+   */
+  def append(record: T): Unit = {
+    serializer.write(i, record)
+    i += 1
+  }
+
+  /**
+   * Write the schema and the current batch in Arrow IPC stream format to the [[OutputStream]].
+   */
+  def writeIpcStream(output: OutputStream): Unit = {
+    val channel = newChannel(output)
+    root.setRowCount(i)
+    val batch = unloader.getRecordBatch
+    try {
+      channel.write(schemaBytes)
+      MessageSerializer.serialize(channel, batch)
+      ArrowStreamWriter.writeEndOfStream(channel, IpcOption.DEFAULT)
+    } finally {
+      batch.close()
+    }
+  }
+
+  /**
+   * Reset the serializer.
+   */
+  def reset(): Unit = {
+    i = 0
+    vectors.foreach(_.reset())
+  }
+
+  /**
+   * Close the serializer.
+   */
+  def close(): Unit = root.close()
+}
+
+object ArrowSerializer {
+  import ArrowEncoderUtils._
+
+  /**
+   * Create an [[Iterator]] that converts the input [[Iterator]] of type `T` into an [[Iterator]]
+   * of Arrow IPC Streams.
+   */
+  def serialize[T](
+      input: Iterator[T],
+      enc: AgnosticEncoder[T],
+      allocator: BufferAllocator,
+      maxRecordsPerBatch: Int,
+      maxBatchSize: Long,
+      timeZoneId: String,
+      batchSizeCheckInterval: Int = 128): CloseableIterator[Array[Byte]] = {
+    assert(maxRecordsPerBatch > 0)
+    assert(maxBatchSize > 0)
+    assert(batchSizeCheckInterval > 0)
+    new CloseableIterator[Array[Byte]] {
+      private val serializer = new ArrowSerializer[T](enc, allocator, timeZoneId)
+      private val bytes = new ByteArrayOutputStream
+      private var hasWrittenFirstBatch = false
+
+      /**
+       * Periodical check to make sure we don't go over the size threshold by too much.
+       */
+      private def sizeOk(i: Int): Boolean = {
+        if (i > 0 && i % batchSizeCheckInterval == 0) {
+          return serializer.sizeInBytes < maxBatchSize
+        }
+        true
+      }
+
+      override def hasNext: Boolean = input.hasNext || !hasWrittenFirstBatch
+
+      override def next(): Array[Byte] = {
+        if (!hasNext) {
+          throw new NoSuchElementException()
+        }
+        serializer.reset()
+        bytes.reset()
+        var i = 0
+        while (i < maxRecordsPerBatch && input.hasNext && sizeOk(i)) {
+          serializer.append(input.next())
+          i += 1
+        }
+        serializer.writeIpcStream(bytes)
+        hasWrittenFirstBatch = true
+        bytes.toByteArray
+      }
+
+      override def close(): Unit = serializer.close()
+    }
+  }
+
+  def serialize[T](
+      input: Iterator[T],
+      enc: AgnosticEncoder[T],
+      allocator: BufferAllocator,
+      timeZoneId: String): ByteString = {
+    val serializer = new ArrowSerializer[T](enc, allocator, timeZoneId)
+    serializer.reset()
+    input.foreach(serializer.append)
+    val output = ByteString.newOutput()
+    serializer.writeIpcStream(output)
+    output.toByteString
+  }
+
+  /**
+   * Create a (root) [[Serializer]] for [[AgnosticEncoder]] `encoder`.
+   *
+   * The serializer returned by this method is NOT thread-safe.
+   */
+  def serializerFor[T](
+      encoder: AgnosticEncoder[T],
+      allocator: BufferAllocator,
+      timeZoneId: String): (VectorSchemaRoot, Serializer) = {
+    val arrowSchema = ArrowUtils.toArrowSchema(encoder.schema, timeZoneId)
+    val root = VectorSchemaRoot.create(arrowSchema, allocator)
+    val serializer = if (encoder.schema != encoder.dataType) {
+      assert(root.getSchema.getFields.size() == 1)
+      serializerFor(encoder, root.getVector(0))
+    } else {
+      serializerFor(encoder, root)
+    }
+    root -> serializer
+  }
+
+  // TODO throw better errors on class cast exceptions.
+  private[arrow] def serializerFor[E](encoder: AgnosticEncoder[E], v: AnyRef): Serializer = {
+    (encoder, v) match {
+      case (PrimitiveBooleanEncoder | BoxedBooleanEncoder, v: BitVector) =>
+        new FieldSerializer[Boolean, BitVector](v) {
+          override def set(index: Int, value: Boolean): Unit =
+            vector.setSafe(index, if (value) 1 else 0)
+        }
+      case (PrimitiveByteEncoder | BoxedByteEncoder, v: TinyIntVector) =>
+        new FieldSerializer[Byte, TinyIntVector](v) {
+          override def set(index: Int, value: Byte): Unit = vector.setSafe(index, value)
+        }
+      case (PrimitiveShortEncoder | BoxedShortEncoder, v: SmallIntVector) =>
+        new FieldSerializer[Short, SmallIntVector](v) {
+          override def set(index: Int, value: Short): Unit = vector.setSafe(index, value)
+        }
+      case (PrimitiveIntEncoder | BoxedIntEncoder, v: IntVector) =>
+        new FieldSerializer[Int, IntVector](v) {
+          override def set(index: Int, value: Int): Unit = vector.setSafe(index, value)
+        }
+      case (PrimitiveLongEncoder | BoxedLongEncoder, v: BigIntVector) =>
+        new FieldSerializer[Long, BigIntVector](v) {
+          override def set(index: Int, value: Long): Unit = vector.setSafe(index, value)
+        }
+      case (PrimitiveFloatEncoder | BoxedFloatEncoder, v: Float4Vector) =>
+        new FieldSerializer[Float, Float4Vector](v) {
+          override def set(index: Int, value: Float): Unit = vector.setSafe(index, value)
+        }
+      case (PrimitiveDoubleEncoder | BoxedDoubleEncoder, v: Float8Vector) =>
+        new FieldSerializer[Double, Float8Vector](v) {
+          override def set(index: Int, value: Double): Unit = vector.setSafe(index, value)
+        }
+      case (NullEncoder, v: NullVector) =>
+        new FieldSerializer[Unit, NullVector](v) {
+          override def set(index: Int, value: Unit): Unit = vector.setNull(index)
+        }
+      case (StringEncoder, v: VarCharVector) =>
+        new FieldSerializer[String, VarCharVector](v) {
+          override def set(index: Int, value: String): Unit = setString(v, index, value)
+        }
+      case (JavaEnumEncoder(_), v: VarCharVector) =>
+        new FieldSerializer[Enum[_], VarCharVector](v) {
+          override def set(index: Int, value: Enum[_]): Unit = setString(v, index, value.name())
+        }
+      case (ScalaEnumEncoder(_, _), v: VarCharVector) =>
+        new FieldSerializer[Enumeration#Value, VarCharVector](v) {
+          override def set(index: Int, value: Enumeration#Value): Unit =
+            setString(v, index, value.toString)
+        }
+      case (BinaryEncoder, v: VarBinaryVector) =>
+        new FieldSerializer[Array[Byte], VarBinaryVector](v) {
+          override def set(index: Int, value: Array[Byte]): Unit = vector.setSafe(index, value)
+        }
+      case (SparkDecimalEncoder(_), v: DecimalVector) =>
+        new FieldSerializer[Decimal, DecimalVector](v) {
+          override def set(index: Int, value: Decimal): Unit =
+            setDecimal(vector, index, value.toJavaBigDecimal)
+        }
+      case (ScalaDecimalEncoder(_), v: DecimalVector) =>
+        new FieldSerializer[BigDecimal, DecimalVector](v) {
+          override def set(index: Int, value: BigDecimal): Unit =
+            setDecimal(vector, index, value.bigDecimal)
+        }
+      case (JavaDecimalEncoder(_, false), v: DecimalVector) =>
+        new FieldSerializer[JBigDecimal, DecimalVector](v) {
+          override def set(index: Int, value: JBigDecimal): Unit =
+            setDecimal(vector, index, value)
+        }
+      case (JavaDecimalEncoder(_, true), v: DecimalVector) =>
+        new FieldSerializer[Any, DecimalVector](v) {
+          override def set(index: Int, value: Any): Unit = {
+            val decimal = value match {
+              case j: JBigDecimal => j
+              case d: BigDecimal => d.bigDecimal
+              case k: BigInt => new JBigDecimal(k.bigInteger)
+              case l: JBigInteger => new JBigDecimal(l)
+              case d: Decimal => d.toJavaBigDecimal
+            }
+            setDecimal(vector, index, decimal)
+          }
+        }
+      case (ScalaBigIntEncoder, v: DecimalVector) =>
+        new FieldSerializer[BigInt, DecimalVector](v) {
+          override def set(index: Int, value: BigInt): Unit =
+            setDecimal(vector, index, new JBigDecimal(value.bigInteger))
+        }
+      case (JavaBigIntEncoder, v: DecimalVector) =>
+        new FieldSerializer[JBigInteger, DecimalVector](v) {
+          override def set(index: Int, value: JBigInteger): Unit =
+            setDecimal(vector, index, new JBigDecimal(value))
+        }
+      case (DayTimeIntervalEncoder, v: DurationVector) =>
+        new FieldSerializer[Duration, DurationVector](v) {
+          override def set(index: Int, value: Duration): Unit =
+            vector.setSafe(index, IntervalUtils.durationToMicros(value))
+        }
+      case (YearMonthIntervalEncoder, v: IntervalYearVector) =>
+        new FieldSerializer[Period, IntervalYearVector](v) {
+          override def set(index: Int, value: Period): Unit =
+            vector.setSafe(index, IntervalUtils.periodToMonths(value))
+        }
+      case (DateEncoder(true) | LocalDateEncoder(true), v: DateDayVector) =>
+        new FieldSerializer[Any, DateDayVector](v) {
+          override def set(index: Int, value: Any): Unit =
+            vector.setSafe(index, DateTimeUtils.anyToDays(value))
+        }
+      case (DateEncoder(false), v: DateDayVector) =>
+        new FieldSerializer[java.sql.Date, DateDayVector](v) {
+          override def set(index: Int, value: java.sql.Date): Unit =
+            vector.setSafe(index, DateTimeUtils.fromJavaDate(value))
+        }
+      case (LocalDateEncoder(false), v: DateDayVector) =>
+        new FieldSerializer[LocalDate, DateDayVector](v) {
+          override def set(index: Int, value: LocalDate): Unit =
+            vector.setSafe(index, DateTimeUtils.localDateToDays(value))
+        }
+      case (TimestampEncoder(true) | InstantEncoder(true), v: TimeStampMicroTZVector) =>
+        new FieldSerializer[Any, TimeStampMicroTZVector](v) {
+          override def set(index: Int, value: Any): Unit =
+            vector.setSafe(index, DateTimeUtils.anyToMicros(value))
+        }
+      case (TimestampEncoder(false), v: TimeStampMicroTZVector) =>
+        new FieldSerializer[java.sql.Timestamp, TimeStampMicroTZVector](v) {
+          override def set(index: Int, value: java.sql.Timestamp): Unit =
+            vector.setSafe(index, DateTimeUtils.fromJavaTimestamp(value))
+        }
+      case (InstantEncoder(false), v: TimeStampMicroTZVector) =>
+        new FieldSerializer[Instant, TimeStampMicroTZVector](v) {
+          override def set(index: Int, value: Instant): Unit =
+            vector.setSafe(index, DateTimeUtils.instantToMicros(value))
+        }
+      case (LocalDateTimeEncoder, v: TimeStampMicroVector) =>
+        new FieldSerializer[LocalDateTime, TimeStampMicroVector](v) {
+          override def set(index: Int, value: LocalDateTime): Unit =
+            vector.setSafe(index, DateTimeUtils.localDateTimeToMicros(value))
+        }
+
+      case (OptionEncoder(value), v) =>
+        new Serializer {
+          private[this] val delegate: Serializer = serializerFor(value, v)
+          override def write(index: Int, value: Any): Unit = value match {
+            case Some(value) => delegate.write(index, value)
+            case _ => delegate.write(index, null)
+          }
+        }
+
+      case (ArrayEncoder(element, _), v: ListVector) =>
+        val elementSerializer = serializerFor(element, v.getDataVector)
+        val toIterator = { array: Any =>
+          mutable.WrappedArray.make(array.asInstanceOf[AnyRef]).iterator

Review Comment:
   for Scala 2.13



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org