MaxGekk commented on code in PR #55326:
URL: https://github.com/apache/spark/pull/55326#discussion_r3384078991


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/parquet/types/ops/ParquetTypeOps.scala:
##########
@@ -0,0 +1,219 @@
+/*
+ * 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.execution.datasources.parquet.types.ops
+
+import org.apache.parquet.io.api.RecordConsumer
+import org.apache.parquet.schema.Type
+import org.apache.parquet.schema.Type.Repetition
+
+import org.apache.spark.sql.catalyst.expressions.SpecializedGetters
+import org.apache.spark.sql.catalyst.util.RebaseDateTime.RebaseSpec
+import 
org.apache.spark.sql.execution.datasources.parquet.{HasParentContainerUpdater, 
ParentContainerUpdater}
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.types.{DataType, StructType, TimeType}
+
+/**
+ * Optional trait for Parquet storage format integration in the Types 
Framework.
+ *
+ * Implement this trait to enable Parquet read/write support for a framework 
type. Each framework
+ * type that supports Parquet provides a concrete implementation and registers 
it in the companion
+ * object's apply() method.
+ *
+ * The trait covers all Parquet concerns:
+ *   - Schema conversion: Spark DataType <-> Parquet schema type
+ *   - Value write: writing values to Parquet RecordConsumer
+ *   - Row-based read: creating Parquet converters for reading into InternalRow
+ *   - Vectorized read: creating batch updaters for columnar reading
+ *   - Filter pushdown: creating Parquet filter predicates for predicate 
pushdown
+ *   - Type gates: declaring Parquet support/capability
+ *   - Schema clipping: declaring internal struct schema for column pruning
+ *
+ * DISPATCH PATTERN: Framework FIRST at all integration sites. Each Parquet 
infrastructure
+ * method wraps itself with:
+ * {{{
+ *   ParquetTypeOps(dt).map(_.method(...)).getOrElse(methodDefault(dt, ...))
+ * }}}
+ * The original code is extracted to a *Default method unchanged. When the 
framework flag is ON,
+ * the ops handles the type. When OFF, the *Default fallback executes the 
original code path.
+ *
+ * STRUCT-BACKED TYPES: Types stored as Parquet groups should override the
+ * extended newConverter overload (which provides 
schemaConverter/convertTz/rebase specs for
+ * recursive field conversion) and declare parquetStructSchema for column 
pruning.
+ *
+ * @see TimeTypeParquetOps for a reference implementation (primitive 
Long-backed type)
+ * @since 4.3.0
+ */
+private[parquet] trait ParquetTypeOps extends Serializable {
+
+  /** The DataType this Ops instance handles. */
+  def dataType: DataType
+
+  // ==================== Schema Conversion ====================
+
+  /**
+   * Converts this Spark DataType to a Parquet schema Type (for the write 
path).
+   *
+   * For primitive types: returns a PrimitiveType with the appropriate 
annotation.
+   * For struct-backed types: returns a GroupType with sub-fields and a 
logical type annotation.
+   *
+   * @param fieldName the column/field name in the Parquet schema
+   * @param repetition REQUIRED, OPTIONAL, or REPEATED
+   * @return the Parquet Type for this DataType
+   */
+  def convertToParquetType(fieldName: String, repetition: Repetition): Type

Review Comment:
   `SparkToParquetSchemaConverter.convertField` calls 
`convertToParquetType(field.name, repetition)` but drops `inShredded`. 
`convertFieldDefault` uses that flag at line 726 for timestamp types inside 
shredded Variant schemas. No current framework type needs it, but a future 
struct-backed type might differ in Parquet schema when written inside a 
shredded context.
   
   Adding a default parameter now is backward-compatible — existing impls 
ignore it, future ones opt in:
   ```suggestion
     def convertToParquetType(fieldName: String, repetition: Repetition, 
inShredded: Boolean = false): Type
   ```
   And the call site in `convertField` would forward it: 
`.map(_.convertToParquetType(field.name, repetition, inShredded))`. Avoids a 
breaking API change when the first struct-backed type lands.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/parquet/types/ops/TimeTypeParquetOps.scala:
##########
@@ -0,0 +1,119 @@
+/*
+ * 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.execution.datasources.parquet.types.ops
+
+import org.apache.parquet.io.api.RecordConsumer
+import org.apache.parquet.schema.{LogicalTypeAnnotation, Type, Types}
+import org.apache.parquet.schema.LogicalTypeAnnotation.TimeUnit
+import org.apache.parquet.schema.PrimitiveType.PrimitiveTypeName.INT64
+import org.apache.parquet.schema.Type.Repetition
+
+import org.apache.spark.sql.catalyst.expressions.SpecializedGetters
+import org.apache.spark.sql.catalyst.util.DateTimeUtils
+import org.apache.spark.sql.errors.QueryExecutionErrors
+import 
org.apache.spark.sql.execution.datasources.parquet.{HasParentContainerUpdater, 
ParentContainerUpdater, ParquetPrimitiveConverter}
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.types.{DataType, TimeType}
+
+/**
+ * Parquet operations for TimeType.
+ *
+ * TimeType is a primitive Long-backed type stored in Parquet as INT64 with the
+ * TIME(isAdjustedToUTC=false, unit=MICROS) logical type annotation.
+ *
+ * IMPORTANT - internal vs Parquet representation:
+ *   - Spark internal: nanoseconds since midnight (Long)
+ *   - Parquet storage: microseconds since midnight (INT64)
+ *   - Write path: nanos -> micros (DateTimeUtils.nanosToMicros)
+ *   - Read path: micros -> nanos (DateTimeUtils.microsToNanos)
+ *
+ * @param t the TimeType with precision information
+ * @since 4.3.0
+ */
+case class TimeTypeParquetOps(t: TimeType) extends ParquetTypeOps {
+
+  override def dataType: DataType = t
+
+  // ==================== Schema Conversion ====================
+
+  override def convertToParquetType(fieldName: String, repetition: 
Repetition): Type =
+    Types.primitive(INT64, repetition)
+      .as(LogicalTypeAnnotation.timeType(false, TimeUnit.MICROS))
+      .named(fieldName)
+
+  // ==================== Value Write ====================
+
+  override def makeWriter(
+      recordConsumer: () => RecordConsumer,
+      makeFieldWriter: DataType => (SpecializedGetters, Int) => Unit
+  ): (SpecializedGetters, Int) => Unit =
+    // Evaluate the supplier at write time (not creation time) because 
recordConsumer
+    // is null during init() and set later in prepareForWrite().
+    (row: SpecializedGetters, ordinal: Int) =>
+      
recordConsumer().addLong(DateTimeUtils.nanosToMicros(row.getLong(ordinal)))
+
+  // ==================== Row-Based Read ====================
+
+  override def newConverter(
+      parquetType: org.apache.parquet.schema.Type,
+      updater: ParentContainerUpdater
+  ): org.apache.parquet.io.api.Converter with HasParentContainerUpdater = {
+    // Framework-first dispatch in ParquetRowConverter routes here whenever the
+    // requested Spark type is TimeType, regardless of the actual Parquet 
encoding.
+    // Without this guard, files whose column is raw INT64, INT64 TIME(NANOS),
+    // INT64 TIMESTAMP(MICROS), INT32 TIME(MILLIS), etc. would silently decode 
as
+    // microsToNanos(value) and produce wrong results. Mirrors the inline guard
+    // that existed in ParquetRowConverter before the framework dispatch.
+    TimeTypeParquetOps.requireCompatibleParquetType(t, parquetType)
+    new ParquetPrimitiveConverter(updater) {
+      override def addLong(value: Long): Unit = {
+        this.updater.setLong(DateTimeUtils.microsToNanos(value))
+      }
+    }
+  }
+
+  // ==================== Vectorized Read ====================
+
+  override def isBatchReadSupported(sqlConf: SQLConf): Boolean = true
+}
+
+private[ops] object TimeTypeParquetOps {
+
+  /**
+   * Validates that a Parquet field can be decoded as TimeType. TimeType is 
stored
+   * as INT64 with TIME(MICROS, isAdjustedToUTC=false). Any other encoding (raw
+   * INT64, INT64 TIME(NANOS), INT32 TIME(MILLIS), INT64 TIMESTAMP(_), decimal-
+   * annotated, etc.) cannot be decoded as TimeType - throw the same error as
+   * the legacy ParquetRowConverter path so reads fail loudly instead of
+   * silently misinterpreting bytes.
+   */
+  private[ops] def requireCompatibleParquetType(

Review Comment:
   `requireCompatibleParquetType` is only exercised through integration tests 
for the accepted encoding. The reject paths — raw INT64 (no annotation), INT64 
TIME(NANOS), INT32 TIME(MILLIS), INT64 TIME(MICROS, isAdjustedToUTC=true) — are 
not directly tested. A small unit test (e.g. a `TimeTypeParquetOpsTest`, or 
cases in `ParquetSchemaSuite`) would:
   1. Document exactly which encodings are rejected and why.
   2. Provide a regression hook for the `isAdjustedToUTC=true` ON/OFF behavior 
difference flagged in the conversation thread — whichever resolution is chosen 
(mirror the original guard, or tighten both paths), the test pins the intended 
behavior.



-- 
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]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to