You are viewing a plain text version of this content. The canonical link for it is here.
Posted to reviews@spark.apache.org by "davidm-db (via GitHub)" <gi...@apache.org> on 2026/03/19 14:06:36 UTC

[PR] supporting various clients thorugh types framework [spark]

davidm-db opened a new pull request, #54905:
URL: https://github.com/apache/spark/pull/54905

   <!--
   Thanks for sending a pull request!  Here are some tips for you:
     1. If this is your first time, please read our contributor guidelines: https://spark.apache.org/contributing.html
     2. Ensure you have added or run the appropriate tests for your PR: https://spark.apache.org/developer-tools.html
     3. If the PR is unfinished, add '[WIP]' in your PR title, e.g., '[WIP][SPARK-XXXX] Your PR title ...'.
     4. Be sure to keep the PR description updated to reflect all changes.
     5. Please write your PR title to summarize what this PR proposes.
     6. If possible, provide a concise example to reproduce the issue for a faster review.
     7. If you want to add a new configuration, please read the guideline first for naming configurations in
        'core/src/main/scala/org/apache/spark/internal/config/ConfigEntry.scala'.
     8. If you want to add or modify an error type or message, please read the guideline first in
        'common/utils/src/main/resources/error/README.md'.
   -->
   
   ### What changes were proposed in this pull request?
   <!--
   Please clarify what changes you are proposing. The purpose of this section is to outline the changes and how this PR fixes the issue. 
   If possible, please consider writing useful notes for better and faster reviews in your PR. See the examples below.
     1. If you refactor some codes with changing classes, showing the class hierarchy will help reviewers.
     2. If you fix some SQL features, you can provide some references of other DBMSes.
     3. If there is design documentation, please add the link.
     4. If there is a discussion in the mailing list, please add the link.
   -->
   
   Extends the Types Framework (Phase 1a: #54223) with optional traits for client-facing infrastructure dispatch. Adds 4 new traits and integrates 13 files so that new framework-managed types get client support automatically — zero edits to infrastructure files.
   
   New traits:
   - `CatalystTypeOps` (catalyst) — serializer/deserializer expression building, Arrow field writers
   - `ClientTypeOps` (sql/api) — Arrow conversion, JDBC mapping, Python interop, Hive formatting, Thrift type ID
   - `ProtoTypeOps` (connect/common) — Spark Connect proto DataType and Literal conversions
   - `ConnectArrowTypeOps` (connect/common) — Connect Arrow serde (no feature flag — client must handle whatever the server sends)
   
   TimeType serves as the reference implementation. One new per-type class (`TimeTypeConnectOps`) handles both Connect traits; the existing `TimeTypeApiOps` and `TimeTypeOps` gain mix-ins
   for `ClientTypeOps` and `CatalystTypeOps` respectively.
   
   All changes follow the established `getOrElse` pattern — framework dispatch before existing branches, existing code stays as fallback.
   
   ### Why are the changes needed?
   <!--
   Please clarify why the changes are needed. For instance,
     1. If you propose a new API, clarify the use case for a new API.
     2. If you fix a bug, you can clarify why it is a bug.
   -->
   Without this, adding a new data type requires manually editing 13+ client integration files with diverse patterns. With these traits, a new type implements the relevant ops methods and all client infrastructure dispatches through the framework automatically.
   
   ### Does this PR introduce _any_ user-facing change?
   <!--
   Note that it means *any* user-facing change including all aspects such as new features, bug fixes, or other behavior changes. Documentation-only updates are not considered user-facing changes.
   
   If yes, please clarify the previous behavior and the change this PR proposes - provide the console output, description and/or an example to show the behavior difference if possible.
   If possible, please also clarify if this is a user-facing change compared to the released Spark versions or within the unreleased branches such as master.
   If no, write 'No'.
   -->
   No.
   
   ### How was this patch tested?
   <!--
   If tests were added, say they were added here. Please make sure to add some test cases that check the changes thoroughly including negative and positive cases if possible.
   If it was tested in a way different from regular unit tests, please clarify how you tested step by step, ideally copy and paste-able, so that other reviewers can test and check, and descendants can verify in the future.
   If tests were not added, please describe why they were not added and/or why it was difficult to add.
   If benchmark tests were added, please run the benchmarks in GitHub Actions for the consistent environment, and the instructions could accord to: https://spark.apache.org/developer-tools.html#github-workflow-benchmarks.
   -->
   The feature flag is enabled by default in test environments (`Utils.isTesting`), so the entire existing test suite validates the framework code path. No new tests are added in this PR because the framework delegates to the same underlying logic that existing tests already cover.
   
   In subsequent phases, the testing focus will be on:
   - Testing the framework itself (Ops interface contracts, roundtrip correctness, edge cases)
   - Designing a generalized testing mechanism that enforces proper test coverage for each type added through the framework
   
   
   ### Was this patch authored or co-authored using generative AI tooling?
   <!--
   If generative AI tooling has been used in the process of authoring this patch, please include the
   phrase: 'Generated-by: ' followed by the name of the tool and its version.
   If no, write 'No'.
   Please refer to the [ASF Generative Tooling Guidance](https://www.apache.org/legal/generative-tooling.html) for details.
   -->
   
   Co-authored with: claude-opus-4-6


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


Re: [PR] [SPARK-55441][SQL] Types Framework - Phase 1c - Client Integration [spark]

Posted by "davidm-db (via GitHub)" <gi...@apache.org>.
davidm-db commented on code in PR #54905:
URL: https://github.com/apache/spark/pull/54905#discussion_r2965093982


##########
sql/connect/common/src/main/scala/org/apache/spark/sql/connect/client/arrow/ArrowDeserializer.scala:
##########
@@ -200,6 +201,9 @@ object ArrowDeserializers {
         new LeafFieldDeserializer[LocalDateTime](encoder, v, timeZoneId) {
           override def value(i: Int): LocalDateTime = reader.getLocalDateTime(i)
         }
+      case (enc, v: FieldVector) if ConnectArrowTypeOps(enc).isDefined =>
+        ConnectArrowTypeOps(enc).get
+          .createArrowDeserializer(enc, v, timeZoneId).asInstanceOf[Deserializer[Any]]

Review Comment:
   it looks like we are not using the `*TypeOps(...).map(...).getOrElse(...)` pattern almost anywhere in the code. Why? Please check other framework invocation places as well!
   
   The current approach is constructing (executing `apply`) twice, which is less efficient.



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


Re: [PR] [SPARK-55441][SQL] Types Framework - Phase 1c - Client Integration [spark]

Posted by "davidm-db (via GitHub)" <gi...@apache.org>.
davidm-db commented on code in PR #54905:
URL: https://github.com/apache/spark/pull/54905#discussion_r2965342223


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/types/ops/CatalystTypeOps.scala:
##########
@@ -0,0 +1,106 @@
+/*
+ * 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.catalyst.types.ops
+
+import org.apache.arrow.vector.ValueVector
+
+import org.apache.spark.sql.catalyst.expressions.Expression
+import org.apache.spark.sql.execution.arrow.ArrowFieldWriter
+import org.apache.spark.sql.types.DataType
+
+/**
+ * Optional catalyst-layer type operations for the Types Framework.
+ *
+ * This trait extends TypeOps with operations needed by catalyst-level client infrastructure:
+ * serializer/deserializer expression building (SerializerBuildHelper, DeserializerBuildHelper)
+ * and Arrow field writer creation (ArrowWriter).
+ *
+ * USAGE - integration points use CatalystTypeOps(dt) which returns Option[CatalystTypeOps]:
+ * {{{
+ * // DataType-keyed (ArrowWriter):
+ * CatalystTypeOps(dt).map(_.createArrowFieldWriter(vector)).getOrElse { ... }
+ *
+ * // Encoder-keyed (SerializerBuildHelper): use enc.dataType to get the DataType
+ * CatalystTypeOps(enc.dataType).map(_.createSerializer(input)).getOrElse { ... }
+ * }}}
+ *
+ * @see
+ *   TimeTypeOps for a reference implementation
+ * @since 4.2.0
+ */
+trait CatalystTypeOps { self: TypeOps =>
+
+  /**
+   * Creates a serializer expression that converts an external value to its internal
+   * Catalyst representation.
+   *
+   * Used by SerializerBuildHelper for Dataset[T] serialization.
+   *
+   * @param input
+   *   the input expression representing the external value
+   * @return
+   *   an Expression that performs the conversion
+   */
+  def createSerializer(input: Expression): Expression
+
+  /**
+   * Creates a deserializer expression that converts an internal Catalyst value
+   * to its external representation.
+   *
+   * Used by DeserializerBuildHelper for Dataset[T] deserialization.
+   *
+   * @param path
+   *   the expression representing the internal value
+   * @return
+   *   an Expression that performs the conversion
+   */
+  def createDeserializer(path: Expression): Expression
+
+  /**
+   * Creates an ArrowFieldWriter for writing values of this type to an Arrow vector.
+   *
+   * Used by ArrowWriter for Arrow-based data exchange.
+   *
+   * @param vector
+   *   the Arrow ValueVector to write to (must be the correct vector type for this data type)
+   * @return
+   *   an ArrowFieldWriter configured for this type
+   */
+  def createArrowFieldWriter(vector: ValueVector): ArrowFieldWriter

Review Comment:
   Same reasoning as the fromArrowType comment — ArrowWriter is in the catalyst module alongside CatalystTypeOps, so a separate trait for one method seemed unnecessary.



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


Re: [PR] [SPARK-55441][SQL] Types Framework - Phase 1c - Client Integration [spark]

Posted by "MaxGekk (via GitHub)" <gi...@apache.org>.
MaxGekk commented on code in PR #54905:
URL: https://github.com/apache/spark/pull/54905#discussion_r3093176879


##########
sql/api/src/main/scala/org/apache/spark/sql/types/ops/TypeApiOps.scala:
##########
@@ -123,4 +163,18 @@ object TypeApiOps {
       case _ => None
     }
   }
+
+  /**
+   * Reverse lookup: converts an Arrow type to a Spark DataType.
+   */
+  def fromArrowType(at: ArrowType): Option[DataType] = {
+    import org.apache.arrow.vector.types.TimeUnit
+    if (!SqlApiConf.get.typesFrameworkEnabled) return None

Review Comment:
   Should we store the config to lazy val to avoid performance regression?



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/types/ops/TimeTypeOps.scala:
##########
@@ -48,7 +54,8 @@ import org.apache.spark.sql.types.ops.TimeTypeApiOps
  *   The TimeType with precision information
  * @since 4.2.0
  */
-case class TimeTypeOps(override val t: TimeType) extends TimeTypeApiOps(t) with TypeOps {
+case class TimeTypeOps(override val t: TimeType)
+    extends TimeTypeApiOps(t) with TypeOps {

Review Comment:
   ```suggestion
     extends TimeTypeApiOps(t) with TypeOps {
   ```
   see https://github.com/databricks/scala-style-guide?tab=readme-ov-file#spacing-and-indentation



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


Re: [PR] [SPARK-55441][SQL] Types Framework - Phase 1c - Client Integration [spark]

Posted by "dejankrak-db (via GitHub)" <gi...@apache.org>.
dejankrak-db commented on PR #54905:
URL: https://github.com/apache/spark/pull/54905#issuecomment-4169498043

   Surface Areas Detected
   
     - Types Framework — 4 new traits (ClientTypeOps, CatalystTypeOps, ProtoTypeOps, ConnectArrowTypeOps) + 1 implementation (TimeTypeConnectOps)
     - Spark Connect — Proto converters, Arrow serde (7 files)
     - sql/core — HiveResult, JdbcUtils, EvaluatePython, SparkExecuteStatementOperation (4 files)
     - sql/catalyst — SerializerBuildHelper, DeserializerBuildHelper, ArrowWriter (3 files)
     - sql/api — ArrowUtils, TimeTypeApiOps (2 files)
     - DBR Analyzer / Parser / Reyden (0 files)
   
     ---
     Findings
   
     Finding 1: Arrow NANOSECOND unit maps to MICROS_PRECISION — semantic mismatch
   
     - Severity: High
     - Category: Behavioral Correctness
     - File: ClientTypeOps.scala:196 (fromArrowType)
     - Issue: fromArrowType matches ArrowType.Time with TimeUnit.NANOSECOND and 64-bit width but returns TimeType(TimeType.MICROS_PRECISION). Meanwhile, toArrowType in TimeTypeApiOps always emits ArrowType.Time(TimeUnit.NANOSECOND, 64) regardless of the
     TimeType's actual precision. A roundtrip TimeType(NANOS_PRECISION) -> Arrow -> TimeType silently loses precision metadata.
     - Impact: Precision metadata is silently discarded on the Arrow deserialization path. If a TimeType with non-default precision is sent through Arrow (e.g., via PySpark or Connect), it will come back as MICROS_PRECISION.
     - Suggested fix: Either encode precision in Arrow field metadata, derive precision from the Arrow time unit, or document as a known lossy conversion with a TODO. toArrowType should arguably vary its TimeUnit based on t.precision.
   
     Finding 2: Per-row object allocation in HiveResult hot path
   
     - Severity: High
     - Category: Performance
     - File: HiveResult.scala:113-123
     - Issue: ClientTypeOps(dt) is called on every (value, dt) pair in the result set, creating a new TimeTypeApiOps instance per call. Additionally, it's called for ALL non-null values of ALL types (not just TimeType), returning None for standard types —
     adding overhead to every row of every query.
     - Impact: Significant performance regression on large result sets, especially for non-TimeType columns.
     - Suggested fix: Pre-compute the formatting function per column at the schema level (once per query), not per row. At minimum, restructure the match so the catch-all only triggers after all built-in types fail.
   
     Finding 3: toLiteralProto hardcodes DEFAULT_PRECISION instead of using instance precision
   
     - Severity: High
     - Category: Behavioral Correctness
     - File: TimeTypeConnectOps.scala:763
     - Issue: toLiteralProto (the "generic, no DataType context" version) sets .setPrecision(TimeType.DEFAULT_PRECISION) instead of t.precision. The instance is constructed with a specific TimeType(precision), but this method ignores it. Meanwhile,
     toLiteralProtoWithType correctly uses dt.asInstanceOf[TimeType].precision.
     - Impact: Literal precision metadata is lost when going through the "untyped" literal conversion path.
     - Suggested fix: Use t.precision instead of TimeType.DEFAULT_PRECISION.
   
     Finding 4: ConnectArrowTypeOps uses Any throughout — type safety completely lost
   
     - Severity: Medium
     - Category: API and Interface Design
     - File: ConnectArrowTypeOps.scala:50-56
     - Issue: All three methods (createArrowSerializer, createArrowDeserializer, createArrowVectorReader) accept Any and return Any. Implementation does unchecked asInstanceOf casts — a wrong vector type produces a ClassCastException at runtime.
     - Impact: No compile-time protection for implementers or callers.
     - Suggested fix: Widen ArrowSerializer.Serializer, ArrowDeserializers.Deserializer, and ArrowVectorReader from private[arrow] to private[connect] to enable proper type signatures.
   
     Finding 5: Null safety gap in HiveResult framework dispatch
   
     - Severity: Medium
     - Category: Behavioral Correctness
     - File: HiveResult.scala:113-129
     - Issue: The outer match handles (null, _) first, then dispatches to the framework for all other values. If ClientTypeOps(dt) matches, formatExternal calls value.asInstanceOf[LocalTime]. The null guard is solely in the outer match — if the dispatch
     order is ever refactored, a NPE will occur.
     - Impact: Fragile null safety that depends on match ordering.
     - Suggested fix: Add a null guard in the ClientTypeOps(dt).map(...) call or in formatExternal.
   
     Finding 6: Redundant TimeType branches in *Default methods — no verification of equivalence
   
     - Severity: Medium
     - Category: Rollout Safety
     - Files: EvaluatePython.scala (_: TimeType in needConversionInPythonDefault), LiteralValueProtoConverter.scala (TIME case in getProtoDataTypeDefault)
     - Issue: When framework is ON, TimeType hits the framework path and default branches are dead code. When OFF, default branches handle it. This is intentional for rollout safety, but there is no test verifying both paths produce identical results.
     - Impact: Silent behavioral divergence between framework-ON and framework-OFF would be undetectable until production rollout.
     - Suggested fix: Add a parameterized test that toggles spark.sql.types.framework.enabled and asserts identical results.
   
     Finding 7: SerializerBuildHelper / DeserializerBuildHelper dispatch by enc.dataType ignoring encoder type
   
     - Severity: Medium
     - Category: Behavioral Correctness
     - Files: SerializerBuildHelper.scala:361, DeserializerBuildHelper.scala:336
     - Issue: Framework dispatch uses CatalystTypeOps(enc.dataType) before checking the encoder. The original code dispatches on the encoder — the same data type could have different encoders (e.g., AgnosticExpressionPathEncoder is handled first in
     createSerializerDefault). The framework could intercept an encoder that should have been handled differently.
     - Impact: If a TimeType encoder appears as an AgnosticExpressionPathEncoder in the future, the framework path would incorrectly override it.
     - Suggested fix: Move framework dispatch after the AgnosticExpressionPathEncoder and isNativeEncoder checks, or have the framework dispatch also check encoder type.
   
     Finding 8: Undocumented JDBC behavior change for TimeType
   
     - Severity: Medium
     - Category: Rollout Safety
     - File: JdbcUtils.scala:1411-1413
     - Issue: getCommonJDBCType(TimeType) previously returned None. With the framework enabled, it now returns Some(JdbcType("TIME", java.sql.Types.TIME)). The PR description says "No user-facing change."
     - Impact: Functional behavior change for JDBC operations with TimeType columns.
     - Suggested fix: Acknowledge this as a new capability in the PR description. Verify JDBC TIME handling across common drivers.
   
     Finding 9: Repeated new TimeTypeConnectOps(TimeType()) allocations across 5+ sites
   
     - Severity: Medium
     - Category: Performance
     - File: ProtoTypeOps.scala (5 factory methods), ConnectArrowTypeOps.scala (2 factory methods)
     - Issue: Each factory method creates a new TimeTypeConnectOps instance per invocation. These are stateless and could be cached.
     - Impact: Unnecessary GC pressure during result deserialization.
     - Suggested fix: Cache a singleton TimeTypeConnectOps instance and reuse across all factory methods.
   
     Finding 10: No new tests despite 966 lines of new code
   
     - Severity: Medium
     - Category: Test Quality
     - Issue: 5 new files and 15 modified files but zero new tests. The framework path includes new dispatch logic, new asInstanceOf casts, and new Arrow/proto conversion code. There are no tests verifying framework-ON/OFF equivalence.
     - Impact: Subtle bugs (wrong precision, wrong cast, wrong null handling) would go undetected until production rollout.
     - Suggested fix: Add: (1) roundtrip tests for each trait, (2) framework flag toggle tests, (3) fromArrowType reverse lookup test.
   
     Finding 11: ClientTypeOps.apply does not check feature flag — inconsistent gating
   
     - Severity: Medium
     - Category: Rollout Safety
     - File: ClientTypeOps.scala:177
     - Issue: ClientTypeOps.apply(dt) delegates to TypeApiOps(dt) which presumably checks the flag. But ClientTypeOps.fromArrowType(at) explicitly checks the flag. This inconsistency makes the gating contract implicit and fragile.
     - Suggested fix: Add an explicit flag check in ClientTypeOps.apply or document that TypeApiOps is the gating layer.
   
     Finding 12: createFieldWriterDefault unnecessarily private[sql]
   
     - Severity: Low
     - Category: Code Style
     - File: ArrowWriter.scala:586
     - Issue: createFieldWriterDefault is private[sql] but only called from within ArrowWriter. Should be private.
   
     Finding 13: ProtoTypeOps companion has 5 separate registration points per type
   
     - Severity: Low
     - Category: API Design
     - File: ProtoTypeOps.scala
     - Issue: Adding a second framework type requires modifying 5 separate match clauses. Three dispatch by proto enum case and could be consolidated.
     - Suggested fix: Extract a shared opsForKindCase lookup.
   
     ---
     Summary
   
     ┌──────────┬───────┐
     │ Severity │ Count │
     ├──────────┼───────┤
     │ Critical │ 0     │
     ├──────────┼───────┤
     │ High     │ 3     │
     ├──────────┼───────┤
     │ Medium   │ 7     │
     ├──────────┼───────┤
     │ Low      │ 3     │
     └──────────┴───────┘
   
     Total findings: 13
   
     Recommended Actions
   
     1. Fix Arrow precision mismatch — fromArrowType should not hardcode MICROS_PRECISION (Finding 1)
     2. Fix toLiteralProto precision — use t.precision not DEFAULT_PRECISION (Finding 3)
     3. Move HiveResult dispatch out of per-row loop — pre-compute per column (Finding 2)
     4. Add framework flag toggle tests — verify ON/OFF equivalence for TimeType (Findings 6, 10)
     5. Fix serializer dispatch order — framework should not intercept AgnosticExpressionPathEncoder (Finding 7)


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


Re: [PR] [SPARK-55441][SQL] Types Framework - Phase 1c - Client Integration [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on code in PR #54905:
URL: https://github.com/apache/spark/pull/54905#discussion_r3079126636


##########
sql/connect/common/src/main/scala/org/apache/spark/sql/connect/client/arrow/types/ops/TimeTypeConnectOps.scala:
##########
@@ -0,0 +1,123 @@
+/*
+ * 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.types.ops
+
+import java.time.LocalTime
+
+import org.apache.arrow.vector.{FieldVector, TimeNanoVector}
+
+import org.apache.spark.connect.proto
+import org.apache.spark.sql.catalyst.encoders.AgnosticEncoder
+import org.apache.spark.sql.catalyst.encoders.AgnosticEncoders.LocalTimeEncoder
+import org.apache.spark.sql.catalyst.util.SparkDateTimeUtils
+import org.apache.spark.sql.connect.client.arrow.{ArrowDeserializers, ArrowSerializer, ArrowVectorReader, TimeVectorReader}
+import org.apache.spark.sql.connect.common.types.ops.ConnectTypeOps
+import org.apache.spark.sql.types.{DataType, TimeType}
+
+/**
+ * Combined Connect operations for TimeType.
+ *
+ * Implements ConnectTypeOps for TimeType, providing both proto DataType/Literal conversions and
+ * Arrow serialization/deserialization.
+ *
+ * Lives under the arrow.types.ops sub-package to access arrow-private types (TimeVectorReader,
+ * ArrowSerializer.Serializer, ArrowDeserializers.LeafFieldDeserializer) while keeping ops
+ * implementations separate from core arrow infrastructure.

Review Comment:
   Nit: these types were widened to `private[connect]` in this PR, so "arrow-private" is stale.
   ```suggestion
    * Lives under the arrow.types.ops sub-package to co-locate with Arrow infrastructure while
    * keeping ops implementations separate from core arrow classes.
   ```



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


Re: [PR] [SPARK-55441][SQL] Types Framework - Phase 1c - Client Integration [spark]

Posted by "davidm-db (via GitHub)" <gi...@apache.org>.
davidm-db commented on code in PR #54905:
URL: https://github.com/apache/spark/pull/54905#discussion_r3136339845


##########
sql/connect/common/src/main/scala/org/apache/spark/sql/connect/common/types/ops/ConnectTypeOps.scala:
##########
@@ -0,0 +1,175 @@
+/*
+ * 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.common.types.ops
+
+import org.apache.arrow.vector.FieldVector
+
+import org.apache.spark.connect.proto
+import org.apache.spark.sql.catalyst.encoders.AgnosticEncoder
+import org.apache.spark.sql.catalyst.encoders.AgnosticEncoders.LocalTimeEncoder
+import org.apache.spark.sql.connect.client.arrow.{ArrowDeserializers, ArrowSerializer, ArrowVectorReader}
+import org.apache.spark.sql.connect.client.arrow.types.ops.TimeTypeConnectOps
+import org.apache.spark.sql.internal.SqlApiConf
+import org.apache.spark.sql.types.{DataType, TimeType}
+
+/**
+ * Optional type operations for Spark Connect infrastructure.
+ *
+ * Consolidates both proto conversions (DataTypeProtoConverter, LiteralValueProtoConverter) and
+ * Arrow serialization/deserialization (ArrowSerializer, ArrowDeserializer, ArrowVectorReader) for
+ * framework-managed types.
+ *
+ * @since 4.2.0
+ */
+trait ConnectTypeOps extends Serializable {
+
+  def dataType: DataType
+
+  def encoder: AgnosticEncoder[_]
+
+  // ==================== Proto Conversions ====================
+
+  /** Converts this DataType to its Connect proto representation. */
+  def toConnectProtoType: proto.DataType
+
+  /** Converts a value to a proto literal builder (generic, no DataType context). */
+  def toLiteralProto(
+      value: Any,
+      builder: proto.Expression.Literal.Builder): proto.Expression.Literal.Builder
+
+  /** Converts a value to a proto literal builder (with DataType context). */
+  def toLiteralProtoWithType(
+      value: Any,
+      dt: DataType,
+      builder: proto.Expression.Literal.Builder): proto.Expression.Literal.Builder
+
+  /**
+   * Returns a converter from proto literal to Scala value. The returned converter assumes
+   * non-null input - null handling is done by the caller (LiteralValueProtoConverter wraps with
+   * `if (v.hasNull) null`).
+   */
+  def getScalaConverter: proto.Expression.Literal => Any
+
+  /** Returns a proto DataType inferred from a proto literal (for type inference). */
+  def getProtoDataTypeFromLiteral(literal: proto.Expression.Literal): proto.DataType
+
+  /** Converts a proto DataType to a Spark DataType (reverse of toConnectProtoType). */
+  def toCatalystTypeFromProto(t: proto.DataType): DataType
+
+  // ==================== Arrow Serialization ====================
+
+  /** Creates an Arrow serializer for writing values to a vector. */
+  def createArrowSerializer(vector: AnyRef): ArrowSerializer.Serializer
+
+  /** Creates an Arrow deserializer for reading values from a vector. */
+  def createArrowDeserializer(
+      enc: AgnosticEncoder[_],
+      data: AnyRef,
+      timeZoneId: String): ArrowDeserializers.Deserializer[Any]
+
+  /** Creates an ArrowVectorReader for this type's vector. */
+  def createArrowVectorReader(vector: FieldVector): ArrowVectorReader
+}
+
+/**
+ * Factory object for ConnectTypeOps lookup.
+ *
+ * Provides separate factory methods for proto (server-side, feature-flag-gated) and Arrow
+ * (client-side, no flag) dispatch.
+ */
+object ConnectTypeOps {
+
+  // ==================== Proto Dispatch (server-side, flag-gated) ====================
+
+  /** DataType-keyed dispatch for proto conversions. Checks feature flag. */
+  def apply(dt: DataType): Option[ConnectTypeOps] = {
+    if (!SqlApiConf.get.typesFrameworkEnabled) return None

Review Comment:
   same reply as in https://github.com/apache/spark/pull/54905#discussion_r3136338496



##########
sql/connect/common/src/main/scala/org/apache/spark/sql/connect/common/types/ops/ConnectTypeOps.scala:
##########
@@ -0,0 +1,175 @@
+/*
+ * 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.common.types.ops
+
+import org.apache.arrow.vector.FieldVector
+
+import org.apache.spark.connect.proto
+import org.apache.spark.sql.catalyst.encoders.AgnosticEncoder
+import org.apache.spark.sql.catalyst.encoders.AgnosticEncoders.LocalTimeEncoder
+import org.apache.spark.sql.connect.client.arrow.{ArrowDeserializers, ArrowSerializer, ArrowVectorReader}
+import org.apache.spark.sql.connect.client.arrow.types.ops.TimeTypeConnectOps
+import org.apache.spark.sql.internal.SqlApiConf
+import org.apache.spark.sql.types.{DataType, TimeType}
+
+/**
+ * Optional type operations for Spark Connect infrastructure.
+ *
+ * Consolidates both proto conversions (DataTypeProtoConverter, LiteralValueProtoConverter) and
+ * Arrow serialization/deserialization (ArrowSerializer, ArrowDeserializer, ArrowVectorReader) for
+ * framework-managed types.
+ *
+ * @since 4.2.0
+ */
+trait ConnectTypeOps extends Serializable {
+
+  def dataType: DataType
+
+  def encoder: AgnosticEncoder[_]
+
+  // ==================== Proto Conversions ====================
+
+  /** Converts this DataType to its Connect proto representation. */
+  def toConnectProtoType: proto.DataType
+
+  /** Converts a value to a proto literal builder (generic, no DataType context). */
+  def toLiteralProto(
+      value: Any,
+      builder: proto.Expression.Literal.Builder): proto.Expression.Literal.Builder
+
+  /** Converts a value to a proto literal builder (with DataType context). */
+  def toLiteralProtoWithType(
+      value: Any,
+      dt: DataType,
+      builder: proto.Expression.Literal.Builder): proto.Expression.Literal.Builder
+
+  /**
+   * Returns a converter from proto literal to Scala value. The returned converter assumes
+   * non-null input - null handling is done by the caller (LiteralValueProtoConverter wraps with
+   * `if (v.hasNull) null`).
+   */
+  def getScalaConverter: proto.Expression.Literal => Any
+
+  /** Returns a proto DataType inferred from a proto literal (for type inference). */
+  def getProtoDataTypeFromLiteral(literal: proto.Expression.Literal): proto.DataType
+
+  /** Converts a proto DataType to a Spark DataType (reverse of toConnectProtoType). */
+  def toCatalystTypeFromProto(t: proto.DataType): DataType
+
+  // ==================== Arrow Serialization ====================
+
+  /** Creates an Arrow serializer for writing values to a vector. */
+  def createArrowSerializer(vector: AnyRef): ArrowSerializer.Serializer
+
+  /** Creates an Arrow deserializer for reading values from a vector. */
+  def createArrowDeserializer(
+      enc: AgnosticEncoder[_],
+      data: AnyRef,
+      timeZoneId: String): ArrowDeserializers.Deserializer[Any]
+
+  /** Creates an ArrowVectorReader for this type's vector. */
+  def createArrowVectorReader(vector: FieldVector): ArrowVectorReader
+}
+
+/**
+ * Factory object for ConnectTypeOps lookup.
+ *
+ * Provides separate factory methods for proto (server-side, feature-flag-gated) and Arrow
+ * (client-side, no flag) dispatch.
+ */
+object ConnectTypeOps {
+
+  // ==================== Proto Dispatch (server-side, flag-gated) ====================
+
+  /** DataType-keyed dispatch for proto conversions. Checks feature flag. */
+  def apply(dt: DataType): Option[ConnectTypeOps] = {
+    if (!SqlApiConf.get.typesFrameworkEnabled) return None
+    dt match {
+      case tt: TimeType => Some(new TimeTypeConnectOps(tt))
+      // Add new framework types here
+      case _ => None
+    }
+  }
+
+  /** Reverse lookup by value class for the generic literal builder. Checks feature flag. */
+  def toLiteralProtoForValue(
+      value: Any,
+      builder: proto.Expression.Literal.Builder): Option[proto.Expression.Literal.Builder] = {
+    if (!SqlApiConf.get.typesFrameworkEnabled) return None

Review Comment:
   https://github.com/apache/spark/pull/54905#discussion_r3136338496



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


Re: [PR] [SPARK-55441][SQL] Types Framework - Phase 1c - Client Integration [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on code in PR #54905:
URL: https://github.com/apache/spark/pull/54905#discussion_r3016114751


##########
sql/connect/common/src/main/scala/org/apache/spark/sql/connect/common/types/ops/ProtoTypeOps.scala:
##########
@@ -0,0 +1,132 @@
+/*
+ * 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.common.types.ops
+
+import org.apache.spark.connect.proto
+import org.apache.spark.sql.connect.client.arrow.types.ops.TimeTypeConnectOps
+import org.apache.spark.sql.internal.SqlApiConf
+import org.apache.spark.sql.types.{DataType, TimeType}
+
+/**
+ * Optional type operations for Spark Connect protobuf conversions.
+ *
+ * Handles bidirectional DataType <-> proto and Literal <-> proto conversions for
+ * framework-managed types in DataTypeProtoConverter and LiteralValueProtoConverter.
+ *
+ * @since 4.2.0
+ */
+trait ProtoTypeOps extends Serializable {
+
+  def dataType: DataType
+
+  /** Converts this DataType to its Connect proto representation. */
+  def toConnectProtoType: proto.DataType
+
+  /** Converts a value to a proto literal builder (generic, no DataType context). */
+  def toLiteralProto(
+      value: Any,
+      builder: proto.Expression.Literal.Builder): proto.Expression.Literal.Builder
+
+  /** Converts a value to a proto literal builder (with DataType context). */
+  def toLiteralProtoWithType(
+      value: Any,
+      dt: DataType,
+      builder: proto.Expression.Literal.Builder): proto.Expression.Literal.Builder
+
+  /**
+   * Returns a converter from proto literal to Scala value. The returned converter assumes
+   * non-null input - null handling is done by the caller (LiteralValueProtoConverter wraps with
+   * `if (v.hasNull) null`).
+   */
+  def getScalaConverter: proto.Expression.Literal => Any
+
+  /** Returns a proto DataType inferred from a proto literal (for type inference). */
+  def getProtoDataTypeFromLiteral(literal: proto.Expression.Literal): proto.DataType
+}
+
+/**
+ * Factory object for ProtoTypeOps lookup.
+ */
+object ProtoTypeOps {
+
+  def apply(dt: DataType): Option[ProtoTypeOps] = {

Review Comment:
   Adding a second framework-managed type requires 5 separate match-clause additions in this file (`apply`, `toLiteralProtoForValue`, `toCatalystType`, `getScalaConverterForKind`, `getProtoDataTypeFromLiteral`). Three of those dispatch by proto enum cases and can be consolidated.
   
   Concrete suggestion — extract a shared `opsForKindCase` lookup and add a `toCatalystTypeFromProto` method to the trait:
   
   ```scala
   // Add to ProtoTypeOps trait:
   def toCatalystTypeFromProto(t: proto.DataType): DataType
   
   // In companion object — single KindCase → ops mapping:
   private def opsForKindCase(
       kindCase: proto.DataType.KindCase): Option[ProtoTypeOps] = kindCase match {
     case proto.DataType.KindCase.TIME => Some(new TimeTypeConnectOps(TimeType()))
     // Add new framework types here — single registration for all KindCase lookups
     case _ => None
   }
   
   // Then toCatalystType, getScalaConverterForKind, getProtoDataTypeFromLiteral all delegate:
   def toCatalystType(t: proto.DataType): Option[DataType] = {
     if (!SqlApiConf.get.typesFrameworkEnabled) return None
     opsForKindCase(t.getKindCase).map(_.toCatalystTypeFromProto(t))
   }
   
   def getScalaConverterForKind(
       kindCase: proto.DataType.KindCase): Option[proto.Expression.Literal => Any] = {
     if (!SqlApiConf.get.typesFrameworkEnabled) return None
     opsForKindCase(kindCase).map(_.getScalaConverter)
   }
   
   def getProtoDataTypeFromLiteral(literal: proto.Expression.Literal): Option[proto.DataType] = {
     if (!SqlApiConf.get.typesFrameworkEnabled) return None
     // LiteralTypeCase maps 1:1 to KindCase for framework types
     opsForKindCase(literalCaseToKindCase(literal.getLiteralTypeCase))
       .map(_.getProtoDataTypeFromLiteral(literal))
   }
   ```
   
   This reduces per-type registration in this file from 5 match points to 3 (`apply`, `opsForKindCase`, `toLiteralProtoForValue`).



##########
sql/connect/common/src/main/scala/org/apache/spark/sql/connect/common/types/ops/ConnectArrowTypeOps.scala:
##########
@@ -0,0 +1,81 @@
+/*
+ * 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.common.types.ops
+
+import org.apache.spark.sql.catalyst.encoders.AgnosticEncoder
+import org.apache.spark.sql.catalyst.encoders.AgnosticEncoders.LocalTimeEncoder
+import org.apache.spark.sql.connect.client.arrow.types.ops.TimeTypeConnectOps
+import org.apache.spark.sql.types.{DataType, TimeType}
+
+/**
+ * Optional type operations for Spark Connect Arrow serialization/deserialization.
+ *
+ * Handles Arrow-based data exchange on the Connect client side for framework-managed types. Used
+ * by ArrowSerializer, ArrowDeserializer, and ArrowVectorReader.
+ *
+ * NOTE: No feature flag check -the Connect client must handle whatever types the server sends.
+ * The feature flag controls server-side engine behavior; the client always needs to handle types
+ * that exist in the encoder.
+ *
+ * Methods return Any to avoid referencing arrow-private types from the types.ops package. Call
+ * sites in the arrow package cast to the expected types.
+ *
+ * @since 4.2.0
+ */
+trait ConnectArrowTypeOps extends Serializable {
+
+  def encoder: AgnosticEncoder[_]
+
+  // Note: Methods use Any parameter/return types because the concrete Arrow types
+  // (ArrowSerializer.Serializer, ArrowDeserializers.Deserializer, ArrowVectorReader) are
+  // private[arrow] and cannot be referenced from the types.ops package. Call sites in
+  // the arrow package cast to the expected types.
+
+  /** Creates an Arrow serializer for writing values to a vector. Returns a Serializer. */
+  def createArrowSerializer(vector: Any): Any

Review Comment:
   All three methods use `Any` for both parameters and return types — type mismatches between the ops implementation and the call site (e.g., casting to the wrong vector type) are only caught at runtime as `ClassCastException`. `CatalystTypeOps` avoided this by widening `ArrowFieldWriter`/`TimeWriter` to `private[sql]`. Could the Connect Arrow types (`Serializer`, `Deserializer`, `ArrowVectorReader`) similarly be widened to `private[connect]`?



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/jdbc/JdbcUtils.scala:
##########
@@ -145,7 +146,12 @@ object JdbcUtils extends Logging with SQLConfHelper {
    * @param dt The datatype (e.g. [[org.apache.spark.sql.types.StringType]])
    * @return The default JdbcType for this DataType
    */
-  def getCommonJDBCType(dt: DataType): Option[JdbcType] = {
+  // Uses .orElse (not .getOrElse) because this method returns Option[JdbcType].
+  def getCommonJDBCType(dt: DataType): Option[JdbcType] =
+    ClientTypeOps(dt).map(ops => JdbcType(ops.jdbcTypeName, ops.getJdbcType))

Review Comment:
   When the framework is enabled, `getCommonJDBCType(TimeType)` now returns `Some(JdbcType("TIME", java.sql.Types.TIME))`. Before this PR, the default path had no TimeType case and returned `None`. This is a new capability (not a regression), but the PR description's "Does this PR introduce any user-facing change?" says No. Since the flag defaults to `true` in tests, this changes test-environment behavior.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/HiveResult.scala:
##########
@@ -112,6 +113,17 @@ object HiveResult extends SQLConfHelper {
       formatters: TimeFormatters,
       binaryFormatter: BinaryFormatter): String = a match {
     case (null, _) => if (nested) "null" else "NULL"
+    case (value, dt) =>
+      ClientTypeOps(dt).map(_.formatExternal(value, nested)).getOrElse {

Review Comment:
   Two concerns with this dispatch:
   
   1. **Bypasses session formatters.** `formatExternal` uses the ops instance's own `FractionTimeFormatter`, ignoring the `formatters: TimeFormatters` parameter. Currently both use the same `new FractionTimeFormatter()` so output matches, but if session-level time formatting becomes configurable the framework path would silently ignore it.
   
   2. **Per-value allocation.** `ClientTypeOps(dt)` → `TypeApiOps(dt)` creates a new `TimeTypeApiOps` (including a new `@transient lazy val timeFormatter`) on every call. For a result set with N TimeType values, that's N instances + N formatters vs. the original code which reuses a single `formatters.time` for all values.
   
   Consider passing the session formatter through the ops interface, or caching the ops instance per DataType.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/types/ops/CatalystTypeOps.scala:
##########
@@ -0,0 +1,116 @@
+/*
+ * 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.catalyst.types.ops
+
+import org.apache.arrow.vector.ValueVector
+
+import org.apache.spark.sql.catalyst.WalkedTypePath
+import org.apache.spark.sql.catalyst.expressions.Expression
+import org.apache.spark.sql.execution.arrow.ArrowFieldWriter
+import org.apache.spark.sql.types.DataType
+
+/**
+ * Optional catalyst-layer type operations for the Types Framework.
+ *
+ * This trait extends TypeOps with operations needed by catalyst-level client infrastructure:

Review Comment:
   Nit: "Catalyst" is a proper noun.
   ```suggestion
    * This trait extends TypeOps with operations needed by Catalyst-level client infrastructure:
   ```



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


Re: [PR] [SPARK-55441][SQL] Types Framework - Phase 1c - Client Integration [spark]

Posted by "davidm-db (via GitHub)" <gi...@apache.org>.
davidm-db commented on code in PR #54905:
URL: https://github.com/apache/spark/pull/54905#discussion_r2965336614


##########
sql/api/src/main/scala/org/apache/spark/sql/types/ops/ClientTypeOps.scala:
##########
@@ -0,0 +1,177 @@
+/*
+ * 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.types.ops
+
+import org.apache.arrow.vector.types.pojo.ArrowType
+
+import org.apache.spark.sql.internal.SqlApiConf
+import org.apache.spark.sql.types.{DataType, TimeType}
+
+/**
+ * Optional client-side type operations for the Types Framework.
+ *
+ * This trait extends TypeApiOps with operations needed by client-facing infrastructure:
+ * Arrow conversion (ArrowUtils), JDBC mapping (JdbcUtils), Python interop (EvaluatePython),
+ * Hive formatting (HiveResult), and Thrift type mapping (SparkExecuteStatementOperation).
+ *
+ * Lives in sql/api so it's visible from sql/core and sql/hive-thriftserver.
+ *
+ * USAGE - integration points use ClientTypeOps(dt) which returns Option[ClientTypeOps]:
+ * {{{
+ * // Forward lookup (most files):
+ * ClientTypeOps(dt).map(_.toArrowType(timeZoneId)).getOrElse { ... }
+ *
+ * // Reverse lookup (ArrowUtils.fromArrowType):
+ * ClientTypeOps.fromArrowType(at).getOrElse { ... }
+ * }}}
+ *
+ * @see
+ *   TimeTypeApiOps for a reference implementation
+ * @since 4.2.0
+ */
+trait ClientTypeOps { self: TypeApiOps =>
+
+  // ==================== Arrow Conversion ====================
+
+  /**
+   * Converts this DataType to its Arrow representation.
+   *
+   * Used by ArrowUtils.toArrowType.
+   *
+   * @param timeZoneId
+   *   the session timezone (needed by some temporal types)
+   * @return
+   *   the corresponding ArrowType
+   */
+  def toArrowType(timeZoneId: String): ArrowType
+
+  // ==================== JDBC Mapping ====================
+
+  /**
+   * Returns the java.sql.Types constant for this type.
+   *
+   * Used by JdbcUtils.getCommonJDBCType for JDBC write path.
+   *
+   * @return
+   *   java.sql.Types constant (e.g., java.sql.Types.TIME)
+   */
+  def getJdbcType: Int
+
+  /**
+   * Returns the DDL type name string for this type.
+   *
+   * Used by JdbcUtils for CREATE TABLE DDL generation.
+   *
+   * @return
+   *   DDL type string (e.g., "TIME")
+   */
+  def jdbcTypeName: String
+
+  // ==================== Python Interop ====================
+
+  /**
+   * Returns true if values of this type need conversion when passed to/from Python.
+   *
+   * Used by EvaluatePython.needConversionInPython.
+   */
+  def needConversionInPython: Boolean
+
+  /**
+   * Creates a converter function for Python/Py4J interop.
+   *
+   * Used by EvaluatePython.makeFromJava. The returned function handles null-safe
+   * conversion of Java/Py4J values to the internal Catalyst representation.
+   *
+   * @return
+   *   a function that converts a Java value to the internal representation
+   */
+  def makeFromJava: Any => Any
+
+  // ==================== Hive Formatting ====================
+
+  /**
+   * Formats an external-type value for Hive output.
+   *
+   * Used by HiveResult.toHiveString. The input is an external-type value
+   * (e.g., java.time.LocalTime for TimeType), NOT the internal representation.
+   *
+   * @param value
+   *   the external-type value to format
+   * @return
+   *   formatted string representation
+   */
+  def formatExternal(value: Any): String
+
+  // ==================== Thrift Mapping ====================
+
+  /**
+   * Returns the Thrift TTypeId name for this type.
+   *
+   * Used by SparkExecuteStatementOperation.toTTypeId. Returns a String that maps
+   * to a TTypeId enum value (e.g., "STRING_TYPE") since TTypeId is only available
+   * in the hive-thriftserver module.
+   *
+   * @return
+   *   TTypeId enum name (e.g., "STRING_TYPE")
+   */
+  def thriftTypeName: String

Review Comment:
   Same dependency issue as the JDBC comment — TTypeId is from org.apache.hive.service.rpc.thrift, only available in hive-thriftserver, so we use a String that the call site resolves via TTypeId.valueOf().



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


Re: [PR] [SPARK-55441][SQL] Types Framework - Phase 1c - Client Integration [spark]

Posted by "davidm-db (via GitHub)" <gi...@apache.org>.
davidm-db commented on code in PR #54905:
URL: https://github.com/apache/spark/pull/54905#discussion_r2965343718


##########
sql/api/src/main/scala/org/apache/spark/sql/types/ops/ClientTypeOps.scala:
##########
@@ -0,0 +1,177 @@
+/*
+ * 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.types.ops
+
+import org.apache.arrow.vector.types.pojo.ArrowType
+
+import org.apache.spark.sql.internal.SqlApiConf
+import org.apache.spark.sql.types.{DataType, TimeType}
+
+/**
+ * Optional client-side type operations for the Types Framework.
+ *
+ * This trait extends TypeApiOps with operations needed by client-facing infrastructure:
+ * Arrow conversion (ArrowUtils), JDBC mapping (JdbcUtils), Python interop (EvaluatePython),
+ * Hive formatting (HiveResult), and Thrift type mapping (SparkExecuteStatementOperation).
+ *
+ * Lives in sql/api so it's visible from sql/core and sql/hive-thriftserver.
+ *
+ * USAGE - integration points use ClientTypeOps(dt) which returns Option[ClientTypeOps]:
+ * {{{
+ * // Forward lookup (most files):
+ * ClientTypeOps(dt).map(_.toArrowType(timeZoneId)).getOrElse { ... }
+ *
+ * // Reverse lookup (ArrowUtils.fromArrowType):
+ * ClientTypeOps.fromArrowType(at).getOrElse { ... }
+ * }}}
+ *
+ * @see
+ *   TimeTypeApiOps for a reference implementation
+ * @since 4.2.0
+ */
+trait ClientTypeOps { self: TypeApiOps =>
+
+  // ==================== Arrow Conversion ====================
+
+  /**
+   * Converts this DataType to its Arrow representation.
+   *
+   * Used by ArrowUtils.toArrowType.
+   *
+   * @param timeZoneId
+   *   the session timezone (needed by some temporal types)
+   * @return
+   *   the corresponding ArrowType
+   */
+  def toArrowType(timeZoneId: String): ArrowType
+
+  // ==================== JDBC Mapping ====================
+
+  /**
+   * Returns the java.sql.Types constant for this type.
+   *
+   * Used by JdbcUtils.getCommonJDBCType for JDBC write path.
+   *
+   * @return
+   *   java.sql.Types constant (e.g., java.sql.Types.TIME)
+   */
+  def getJdbcType: Int
+
+  /**
+   * Returns the DDL type name string for this type.
+   *
+   * Used by JdbcUtils for CREATE TABLE DDL generation.
+   *
+   * @return
+   *   DDL type string (e.g., "TIME")
+   */
+  def jdbcTypeName: String
+
+  // ==================== Python Interop ====================
+
+  /**
+   * Returns true if values of this type need conversion when passed to/from Python.
+   *
+   * Used by EvaluatePython.needConversionInPython.
+   */
+  def needConversionInPython: Boolean
+
+  /**
+   * Creates a converter function for Python/Py4J interop.
+   *
+   * Used by EvaluatePython.makeFromJava. The returned function handles null-safe
+   * conversion of Java/Py4J values to the internal Catalyst representation.
+   *
+   * @return
+   *   a function that converts a Java value to the internal representation
+   */
+  def makeFromJava: Any => Any
+
+  // ==================== Hive Formatting ====================
+
+  /**
+   * Formats an external-type value for Hive output.
+   *
+   * Used by HiveResult.toHiveString. The input is an external-type value
+   * (e.g., java.time.LocalTime for TimeType), NOT the internal representation.
+   *
+   * @param value
+   *   the external-type value to format
+   * @return
+   *   formatted string representation
+   */
+  def formatExternal(value: Any): String
+
+  // ==================== Thrift Mapping ====================
+
+  /**
+   * Returns the Thrift TTypeId name for this type.
+   *
+   * Used by SparkExecuteStatementOperation.toTTypeId. Returns a String that maps
+   * to a TTypeId enum value (e.g., "STRING_TYPE") since TTypeId is only available
+   * in the hive-thriftserver module.
+   *
+   * @return
+   *   TTypeId enum name (e.g., "STRING_TYPE")
+   */
+  def thriftTypeName: String
+}
+
+/**
+ * Factory object for ClientTypeOps lookup.
+ *
+ * Delegates to TypeApiOps and narrows via collect to find implementations that mix in
+ * ClientTypeOps.
+ */
+object ClientTypeOps {
+
+  /**
+   * Returns a ClientTypeOps instance for the given DataType, if available.
+   *
+   * @param dt
+   *   the DataType to get operations for
+   * @return
+   *   Some(ClientTypeOps) if supported, None otherwise
+   */
+  def apply(dt: DataType): Option[ClientTypeOps] =
+    TypeApiOps(dt).collect { case co: ClientTypeOps => co }

Review Comment:
   The collect pattern is correct for incremental trait adoption (returns None if a type implements TypeApiOps but not ClientTypeOps) — added inline comments explaining the delegation logic. 



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


Re: [PR] [SPARK-55441][SQL] Types Framework - Phase 1c - Client Integration [spark]

Posted by "davidm-db (via GitHub)" <gi...@apache.org>.
davidm-db commented on code in PR #54905:
URL: https://github.com/apache/spark/pull/54905#discussion_r2965019201


##########
sql/api/src/main/scala/org/apache/spark/sql/types/ops/ClientTypeOps.scala:
##########
@@ -0,0 +1,177 @@
+/*
+ * 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.types.ops
+
+import org.apache.arrow.vector.types.pojo.ArrowType
+
+import org.apache.spark.sql.internal.SqlApiConf
+import org.apache.spark.sql.types.{DataType, TimeType}
+
+/**
+ * Optional client-side type operations for the Types Framework.
+ *
+ * This trait extends TypeApiOps with operations needed by client-facing infrastructure:
+ * Arrow conversion (ArrowUtils), JDBC mapping (JdbcUtils), Python interop (EvaluatePython),
+ * Hive formatting (HiveResult), and Thrift type mapping (SparkExecuteStatementOperation).
+ *
+ * Lives in sql/api so it's visible from sql/core and sql/hive-thriftserver.
+ *
+ * USAGE - integration points use ClientTypeOps(dt) which returns Option[ClientTypeOps]:
+ * {{{
+ * // Forward lookup (most files):
+ * ClientTypeOps(dt).map(_.toArrowType(timeZoneId)).getOrElse { ... }
+ *
+ * // Reverse lookup (ArrowUtils.fromArrowType):
+ * ClientTypeOps.fromArrowType(at).getOrElse { ... }
+ * }}}
+ *
+ * @see
+ *   TimeTypeApiOps for a reference implementation
+ * @since 4.2.0
+ */
+trait ClientTypeOps { self: TypeApiOps =>
+
+  // ==================== Arrow Conversion ====================
+
+  /**
+   * Converts this DataType to its Arrow representation.
+   *
+   * Used by ArrowUtils.toArrowType.
+   *
+   * @param timeZoneId
+   *   the session timezone (needed by some temporal types)
+   * @return
+   *   the corresponding ArrowType
+   */
+  def toArrowType(timeZoneId: String): ArrowType
+
+  // ==================== JDBC Mapping ====================
+
+  /**
+   * Returns the java.sql.Types constant for this type.
+   *
+   * Used by JdbcUtils.getCommonJDBCType for JDBC write path.
+   *
+   * @return
+   *   java.sql.Types constant (e.g., java.sql.Types.TIME)
+   */
+  def getJdbcType: Int
+
+  /**
+   * Returns the DDL type name string for this type.
+   *
+   * Used by JdbcUtils for CREATE TABLE DDL generation.
+   *
+   * @return
+   *   DDL type string (e.g., "TIME")
+   */
+  def jdbcTypeName: String
+
+  // ==================== Python Interop ====================
+
+  /**
+   * Returns true if values of this type need conversion when passed to/from Python.
+   *
+   * Used by EvaluatePython.needConversionInPython.
+   */
+  def needConversionInPython: Boolean
+
+  /**
+   * Creates a converter function for Python/Py4J interop.
+   *
+   * Used by EvaluatePython.makeFromJava. The returned function handles null-safe
+   * conversion of Java/Py4J values to the internal Catalyst representation.
+   *
+   * @return
+   *   a function that converts a Java value to the internal representation
+   */
+  def makeFromJava: Any => Any
+
+  // ==================== Hive Formatting ====================
+
+  /**
+   * Formats an external-type value for Hive output.
+   *
+   * Used by HiveResult.toHiveString. The input is an external-type value
+   * (e.g., java.time.LocalTime for TimeType), NOT the internal representation.
+   *
+   * @param value
+   *   the external-type value to format
+   * @return
+   *   formatted string representation
+   */
+  def formatExternal(value: Any): String
+
+  // ==================== Thrift Mapping ====================
+
+  /**
+   * Returns the Thrift TTypeId name for this type.
+   *
+   * Used by SparkExecuteStatementOperation.toTTypeId. Returns a String that maps
+   * to a TTypeId enum value (e.g., "STRING_TYPE") since TTypeId is only available
+   * in the hive-thriftserver module.
+   *
+   * @return
+   *   TTypeId enum name (e.g., "STRING_TYPE")
+   */
+  def thriftTypeName: String

Review Comment:
   why don't we return `TTypeId` here directly?



##########
sql/connect/common/src/main/scala/org/apache/spark/sql/connect/client/arrow/TimeTypeConnectOps.scala:
##########
@@ -0,0 +1,124 @@
+/*
+ * 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.time.LocalTime
+
+import org.apache.arrow.vector.{FieldVector, TimeNanoVector}
+
+import org.apache.spark.connect.proto
+import org.apache.spark.sql.catalyst.encoders.AgnosticEncoder
+import org.apache.spark.sql.catalyst.encoders.AgnosticEncoders.LocalTimeEncoder
+import org.apache.spark.sql.catalyst.util.SparkDateTimeUtils
+import org.apache.spark.sql.connect.common.types.ops.{ConnectArrowTypeOps, ProtoTypeOps}
+import org.apache.spark.sql.types.{DataType, TimeType}
+
+/**
+ * Combined Connect operations for TimeType.
+ *
+ * Implements both ProtoTypeOps (proto DataType/Literal conversions) and ConnectArrowTypeOps
+ * (Arrow serialization/deserialization) in a single class.
+ *
+ * Lives in the arrow package to access arrow-private types (ArrowVectorReader, TimeVectorReader,
+ * ArrowSerializer.Serializer, ArrowDeserializers.LeafFieldDeserializer).
+ *
+ * @param t
+ *   The TimeType with precision information
+ * @since 4.2.0
+ */
+private[connect] class TimeTypeConnectOps(val t: TimeType)

Review Comment:
   why is this file not on the `types/ops` path? 



##########
sql/connect/common/src/main/scala/org/apache/spark/sql/connect/common/LiteralValueProtoConverter.scala:
##########
@@ -548,6 +555,8 @@ object LiteralValueProtoConverter {
             builder.setYearMonthInterval(proto.DataType.YearMonthInterval.newBuilder().build())
           case proto.Expression.Literal.LiteralTypeCase.DAY_TIME_INTERVAL =>
             builder.setDayTimeInterval(proto.DataType.DayTimeInterval.newBuilder().build())
+          case litCase if ProtoTypeOps.buildProtoDataTypeForLiteral(literal, builder) =>
+            // Framework handled

Review Comment:
   this is not exactly the same pattern as in my last comment, but might still fit into the case of wrong invoking of the framework



##########
sql/api/src/main/scala/org/apache/spark/sql/types/ops/ClientTypeOps.scala:
##########
@@ -0,0 +1,177 @@
+/*
+ * 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.types.ops
+
+import org.apache.arrow.vector.types.pojo.ArrowType
+
+import org.apache.spark.sql.internal.SqlApiConf
+import org.apache.spark.sql.types.{DataType, TimeType}
+
+/**
+ * Optional client-side type operations for the Types Framework.
+ *
+ * This trait extends TypeApiOps with operations needed by client-facing infrastructure:
+ * Arrow conversion (ArrowUtils), JDBC mapping (JdbcUtils), Python interop (EvaluatePython),
+ * Hive formatting (HiveResult), and Thrift type mapping (SparkExecuteStatementOperation).
+ *
+ * Lives in sql/api so it's visible from sql/core and sql/hive-thriftserver.
+ *
+ * USAGE - integration points use ClientTypeOps(dt) which returns Option[ClientTypeOps]:
+ * {{{
+ * // Forward lookup (most files):
+ * ClientTypeOps(dt).map(_.toArrowType(timeZoneId)).getOrElse { ... }
+ *
+ * // Reverse lookup (ArrowUtils.fromArrowType):
+ * ClientTypeOps.fromArrowType(at).getOrElse { ... }
+ * }}}
+ *
+ * @see
+ *   TimeTypeApiOps for a reference implementation
+ * @since 4.2.0
+ */
+trait ClientTypeOps { self: TypeApiOps =>
+
+  // ==================== Arrow Conversion ====================
+
+  /**
+   * Converts this DataType to its Arrow representation.
+   *
+   * Used by ArrowUtils.toArrowType.
+   *
+   * @param timeZoneId
+   *   the session timezone (needed by some temporal types)
+   * @return
+   *   the corresponding ArrowType
+   */
+  def toArrowType(timeZoneId: String): ArrowType
+
+  // ==================== JDBC Mapping ====================
+
+  /**
+   * Returns the java.sql.Types constant for this type.
+   *
+   * Used by JdbcUtils.getCommonJDBCType for JDBC write path.
+   *
+   * @return
+   *   java.sql.Types constant (e.g., java.sql.Types.TIME)
+   */
+  def getJdbcType: Int
+
+  /**
+   * Returns the DDL type name string for this type.
+   *
+   * Used by JdbcUtils for CREATE TABLE DDL generation.
+   *
+   * @return
+   *   DDL type string (e.g., "TIME")
+   */
+  def jdbcTypeName: String
+
+  // ==================== Python Interop ====================
+
+  /**
+   * Returns true if values of this type need conversion when passed to/from Python.
+   *
+   * Used by EvaluatePython.needConversionInPython.
+   */
+  def needConversionInPython: Boolean
+
+  /**
+   * Creates a converter function for Python/Py4J interop.
+   *
+   * Used by EvaluatePython.makeFromJava. The returned function handles null-safe
+   * conversion of Java/Py4J values to the internal Catalyst representation.
+   *
+   * @return
+   *   a function that converts a Java value to the internal representation
+   */
+  def makeFromJava: Any => Any
+
+  // ==================== Hive Formatting ====================
+
+  /**
+   * Formats an external-type value for Hive output.
+   *
+   * Used by HiveResult.toHiveString. The input is an external-type value
+   * (e.g., java.time.LocalTime for TimeType), NOT the internal representation.
+   *
+   * @param value
+   *   the external-type value to format
+   * @return
+   *   formatted string representation
+   */
+  def formatExternal(value: Any): String
+
+  // ==================== Thrift Mapping ====================
+
+  /**
+   * Returns the Thrift TTypeId name for this type.
+   *
+   * Used by SparkExecuteStatementOperation.toTTypeId. Returns a String that maps
+   * to a TTypeId enum value (e.g., "STRING_TYPE") since TTypeId is only available
+   * in the hive-thriftserver module.
+   *
+   * @return
+   *   TTypeId enum name (e.g., "STRING_TYPE")
+   */
+  def thriftTypeName: String
+}
+
+/**
+ * Factory object for ClientTypeOps lookup.
+ *
+ * Delegates to TypeApiOps and narrows via collect to find implementations that mix in
+ * ClientTypeOps.
+ */
+object ClientTypeOps {
+
+  /**
+   * Returns a ClientTypeOps instance for the given DataType, if available.
+   *
+   * @param dt
+   *   the DataType to get operations for
+   * @return
+   *   Some(ClientTypeOps) if supported, None otherwise
+   */
+  def apply(dt: DataType): Option[ClientTypeOps] =
+    TypeApiOps(dt).collect { case co: ClientTypeOps => co }
+
+  /**
+   * Reverse lookup: converts an Arrow type to a Spark DataType, if it belongs to a
+   * framework-managed type.
+   *
+   * Used by ArrowUtils.fromArrowType. Returns None if the Arrow type doesn't correspond
+   * to any framework-managed type, or the framework is disabled.
+   *
+   * @param at
+   *   the ArrowType to convert
+   * @return
+   *   Some(DataType) if recognized, None otherwise
+   */
+  def fromArrowType(at: ArrowType): Option[DataType] = {

Review Comment:
   why is this not in arrow specific ops? dependencies or something else?



##########
sql/api/src/main/scala/org/apache/spark/sql/types/ops/ClientTypeOps.scala:
##########
@@ -0,0 +1,177 @@
+/*
+ * 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.types.ops
+
+import org.apache.arrow.vector.types.pojo.ArrowType
+
+import org.apache.spark.sql.internal.SqlApiConf
+import org.apache.spark.sql.types.{DataType, TimeType}
+
+/**
+ * Optional client-side type operations for the Types Framework.
+ *
+ * This trait extends TypeApiOps with operations needed by client-facing infrastructure:
+ * Arrow conversion (ArrowUtils), JDBC mapping (JdbcUtils), Python interop (EvaluatePython),
+ * Hive formatting (HiveResult), and Thrift type mapping (SparkExecuteStatementOperation).
+ *
+ * Lives in sql/api so it's visible from sql/core and sql/hive-thriftserver.
+ *
+ * USAGE - integration points use ClientTypeOps(dt) which returns Option[ClientTypeOps]:
+ * {{{
+ * // Forward lookup (most files):
+ * ClientTypeOps(dt).map(_.toArrowType(timeZoneId)).getOrElse { ... }
+ *
+ * // Reverse lookup (ArrowUtils.fromArrowType):
+ * ClientTypeOps.fromArrowType(at).getOrElse { ... }
+ * }}}
+ *
+ * @see
+ *   TimeTypeApiOps for a reference implementation
+ * @since 4.2.0
+ */
+trait ClientTypeOps { self: TypeApiOps =>
+
+  // ==================== Arrow Conversion ====================
+
+  /**
+   * Converts this DataType to its Arrow representation.
+   *
+   * Used by ArrowUtils.toArrowType.
+   *
+   * @param timeZoneId
+   *   the session timezone (needed by some temporal types)
+   * @return
+   *   the corresponding ArrowType
+   */
+  def toArrowType(timeZoneId: String): ArrowType
+
+  // ==================== JDBC Mapping ====================
+
+  /**
+   * Returns the java.sql.Types constant for this type.
+   *
+   * Used by JdbcUtils.getCommonJDBCType for JDBC write path.
+   *
+   * @return
+   *   java.sql.Types constant (e.g., java.sql.Types.TIME)
+   */
+  def getJdbcType: Int
+
+  /**
+   * Returns the DDL type name string for this type.
+   *
+   * Used by JdbcUtils for CREATE TABLE DDL generation.
+   *
+   * @return
+   *   DDL type string (e.g., "TIME")
+   */
+  def jdbcTypeName: String
+
+  // ==================== Python Interop ====================
+
+  /**
+   * Returns true if values of this type need conversion when passed to/from Python.
+   *
+   * Used by EvaluatePython.needConversionInPython.
+   */
+  def needConversionInPython: Boolean
+
+  /**
+   * Creates a converter function for Python/Py4J interop.
+   *
+   * Used by EvaluatePython.makeFromJava. The returned function handles null-safe
+   * conversion of Java/Py4J values to the internal Catalyst representation.
+   *
+   * @return
+   *   a function that converts a Java value to the internal representation
+   */
+  def makeFromJava: Any => Any
+
+  // ==================== Hive Formatting ====================
+
+  /**
+   * Formats an external-type value for Hive output.
+   *
+   * Used by HiveResult.toHiveString. The input is an external-type value
+   * (e.g., java.time.LocalTime for TimeType), NOT the internal representation.
+   *
+   * @param value
+   *   the external-type value to format
+   * @return
+   *   formatted string representation
+   */
+  def formatExternal(value: Any): String
+
+  // ==================== Thrift Mapping ====================
+
+  /**
+   * Returns the Thrift TTypeId name for this type.
+   *
+   * Used by SparkExecuteStatementOperation.toTTypeId. Returns a String that maps
+   * to a TTypeId enum value (e.g., "STRING_TYPE") since TTypeId is only available
+   * in the hive-thriftserver module.
+   *
+   * @return
+   *   TTypeId enum name (e.g., "STRING_TYPE")
+   */
+  def thriftTypeName: String
+}
+
+/**
+ * Factory object for ClientTypeOps lookup.
+ *
+ * Delegates to TypeApiOps and narrows via collect to find implementations that mix in
+ * ClientTypeOps.
+ */
+object ClientTypeOps {
+
+  /**
+   * Returns a ClientTypeOps instance for the given DataType, if available.
+   *
+   * @param dt
+   *   the DataType to get operations for
+   * @return
+   *   Some(ClientTypeOps) if supported, None otherwise
+   */
+  def apply(dt: DataType): Option[ClientTypeOps] =
+    TypeApiOps(dt).collect { case co: ClientTypeOps => co }

Review Comment:
   is this all right to do? we want to support incremental implementation of ops classes - shouldn't we have a separate list/match here instead of relying on `TypeApiOps`?
   
   check for other ops traits as well.



##########
sql/api/src/main/scala/org/apache/spark/sql/types/ops/ClientTypeOps.scala:
##########
@@ -0,0 +1,177 @@
+/*
+ * 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.types.ops
+
+import org.apache.arrow.vector.types.pojo.ArrowType
+
+import org.apache.spark.sql.internal.SqlApiConf
+import org.apache.spark.sql.types.{DataType, TimeType}
+
+/**
+ * Optional client-side type operations for the Types Framework.
+ *
+ * This trait extends TypeApiOps with operations needed by client-facing infrastructure:
+ * Arrow conversion (ArrowUtils), JDBC mapping (JdbcUtils), Python interop (EvaluatePython),
+ * Hive formatting (HiveResult), and Thrift type mapping (SparkExecuteStatementOperation).
+ *
+ * Lives in sql/api so it's visible from sql/core and sql/hive-thriftserver.
+ *
+ * USAGE - integration points use ClientTypeOps(dt) which returns Option[ClientTypeOps]:
+ * {{{
+ * // Forward lookup (most files):
+ * ClientTypeOps(dt).map(_.toArrowType(timeZoneId)).getOrElse { ... }
+ *
+ * // Reverse lookup (ArrowUtils.fromArrowType):
+ * ClientTypeOps.fromArrowType(at).getOrElse { ... }
+ * }}}
+ *
+ * @see
+ *   TimeTypeApiOps for a reference implementation
+ * @since 4.2.0
+ */
+trait ClientTypeOps { self: TypeApiOps =>
+
+  // ==================== Arrow Conversion ====================
+
+  /**
+   * Converts this DataType to its Arrow representation.
+   *
+   * Used by ArrowUtils.toArrowType.
+   *
+   * @param timeZoneId
+   *   the session timezone (needed by some temporal types)
+   * @return
+   *   the corresponding ArrowType
+   */
+  def toArrowType(timeZoneId: String): ArrowType
+
+  // ==================== JDBC Mapping ====================
+
+  /**
+   * Returns the java.sql.Types constant for this type.
+   *
+   * Used by JdbcUtils.getCommonJDBCType for JDBC write path.
+   *
+   * @return
+   *   java.sql.Types constant (e.g., java.sql.Types.TIME)
+   */
+  def getJdbcType: Int
+
+  /**
+   * Returns the DDL type name string for this type.
+   *
+   * Used by JdbcUtils for CREATE TABLE DDL generation.
+   *
+   * @return
+   *   DDL type string (e.g., "TIME")
+   */
+  def jdbcTypeName: String

Review Comment:
   why don't we replace these two with returning just `org.apache.spark.sql.jdbc.JdbcType`?



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/types/ops/CatalystTypeOps.scala:
##########
@@ -0,0 +1,106 @@
+/*
+ * 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.catalyst.types.ops
+
+import org.apache.arrow.vector.ValueVector
+
+import org.apache.spark.sql.catalyst.expressions.Expression
+import org.apache.spark.sql.execution.arrow.ArrowFieldWriter
+import org.apache.spark.sql.types.DataType
+
+/**
+ * Optional catalyst-layer type operations for the Types Framework.
+ *
+ * This trait extends TypeOps with operations needed by catalyst-level client infrastructure:
+ * serializer/deserializer expression building (SerializerBuildHelper, DeserializerBuildHelper)
+ * and Arrow field writer creation (ArrowWriter).
+ *
+ * USAGE - integration points use CatalystTypeOps(dt) which returns Option[CatalystTypeOps]:
+ * {{{
+ * // DataType-keyed (ArrowWriter):
+ * CatalystTypeOps(dt).map(_.createArrowFieldWriter(vector)).getOrElse { ... }
+ *
+ * // Encoder-keyed (SerializerBuildHelper): use enc.dataType to get the DataType
+ * CatalystTypeOps(enc.dataType).map(_.createSerializer(input)).getOrElse { ... }
+ * }}}
+ *
+ * @see
+ *   TimeTypeOps for a reference implementation
+ * @since 4.2.0
+ */
+trait CatalystTypeOps { self: TypeOps =>
+
+  /**
+   * Creates a serializer expression that converts an external value to its internal
+   * Catalyst representation.
+   *
+   * Used by SerializerBuildHelper for Dataset[T] serialization.
+   *
+   * @param input
+   *   the input expression representing the external value
+   * @return
+   *   an Expression that performs the conversion
+   */
+  def createSerializer(input: Expression): Expression
+
+  /**
+   * Creates a deserializer expression that converts an internal Catalyst value
+   * to its external representation.
+   *
+   * Used by DeserializerBuildHelper for Dataset[T] deserialization.
+   *
+   * @param path
+   *   the expression representing the internal value
+   * @return
+   *   an Expression that performs the conversion
+   */
+  def createDeserializer(path: Expression): Expression
+
+  /**
+   * Creates an ArrowFieldWriter for writing values of this type to an Arrow vector.
+   *
+   * Used by ArrowWriter for Arrow-based data exchange.
+   *
+   * @param vector
+   *   the Arrow ValueVector to write to (must be the correct vector type for this data type)
+   * @return
+   *   an ArrowFieldWriter configured for this type
+   */
+  def createArrowFieldWriter(vector: ValueVector): ArrowFieldWriter

Review Comment:
   same here, why is this not in an arrow specific ops? 



##########
sql/connect/common/src/main/scala/org/apache/spark/sql/connect/client/arrow/ArrowDeserializer.scala:
##########
@@ -200,6 +201,9 @@ object ArrowDeserializers {
         new LeafFieldDeserializer[LocalDateTime](encoder, v, timeZoneId) {
           override def value(i: Int): LocalDateTime = reader.getLocalDateTime(i)
         }
+      case (enc, v: FieldVector) if ConnectArrowTypeOps(enc).isDefined =>
+        ConnectArrowTypeOps(enc).get
+          .createArrowDeserializer(enc, v, timeZoneId).asInstanceOf[Deserializer[Any]]

Review Comment:
   it looks like we are not using the *TypeOps(...).map(...).getOrElse(...) pattern almost anywhere in the code. Why? Please check other framework invocation places as well!
   
   The current approach is constructing (executing `apply`) twice, which is less efficient.



##########
sql/api/src/main/scala/org/apache/spark/sql/types/ops/TimeTypeApiOps.scala:
##########
@@ -56,4 +68,36 @@ class TimeTypeApiOps(val t: TimeType) extends TypeApiOps {
   // ==================== Row Encoding ====================
 
   override def getEncoder: AgnosticEncoder[_] = LocalTimeEncoder
+
+  // ==================== Client Type Operations (ClientTypeOps) ====================
+
+  override def toArrowType(timeZoneId: String): ArrowType = {
+    new ArrowType.Time(TimeUnit.NANOSECOND, 8 * 8)
+  }
+
+  override def getJdbcType: Int = java.sql.Types.TIME
+
+  override def jdbcTypeName: String = "TIME"
+
+  override def needConversionInPython: Boolean = true
+
+  override def makeFromJava: Any => Any = (obj: Any) => {
+    if (obj == null) {
+      null
+    } else {

Review Comment:
   can we generalize this as a `nullSafeConvert` or something similar as in original `makeFromJava`? we can have utility functions in the parent ops class?



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


Re: [PR] [SPARK-55441][SQL] Types Framework - Phase 1c - Client Integration [spark]

Posted by "davidm-db (via GitHub)" <gi...@apache.org>.
davidm-db commented on code in PR #54905:
URL: https://github.com/apache/spark/pull/54905#discussion_r2965333206


##########
sql/api/src/main/scala/org/apache/spark/sql/types/ops/ClientTypeOps.scala:
##########
@@ -0,0 +1,177 @@
+/*
+ * 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.types.ops
+
+import org.apache.arrow.vector.types.pojo.ArrowType
+
+import org.apache.spark.sql.internal.SqlApiConf
+import org.apache.spark.sql.types.{DataType, TimeType}
+
+/**
+ * Optional client-side type operations for the Types Framework.
+ *
+ * This trait extends TypeApiOps with operations needed by client-facing infrastructure:
+ * Arrow conversion (ArrowUtils), JDBC mapping (JdbcUtils), Python interop (EvaluatePython),
+ * Hive formatting (HiveResult), and Thrift type mapping (SparkExecuteStatementOperation).
+ *
+ * Lives in sql/api so it's visible from sql/core and sql/hive-thriftserver.
+ *
+ * USAGE - integration points use ClientTypeOps(dt) which returns Option[ClientTypeOps]:
+ * {{{
+ * // Forward lookup (most files):
+ * ClientTypeOps(dt).map(_.toArrowType(timeZoneId)).getOrElse { ... }
+ *
+ * // Reverse lookup (ArrowUtils.fromArrowType):
+ * ClientTypeOps.fromArrowType(at).getOrElse { ... }
+ * }}}
+ *
+ * @see
+ *   TimeTypeApiOps for a reference implementation
+ * @since 4.2.0
+ */
+trait ClientTypeOps { self: TypeApiOps =>
+
+  // ==================== Arrow Conversion ====================
+
+  /**
+   * Converts this DataType to its Arrow representation.
+   *
+   * Used by ArrowUtils.toArrowType.
+   *
+   * @param timeZoneId
+   *   the session timezone (needed by some temporal types)
+   * @return
+   *   the corresponding ArrowType
+   */
+  def toArrowType(timeZoneId: String): ArrowType
+
+  // ==================== JDBC Mapping ====================
+
+  /**
+   * Returns the java.sql.Types constant for this type.
+   *
+   * Used by JdbcUtils.getCommonJDBCType for JDBC write path.
+   *
+   * @return
+   *   java.sql.Types constant (e.g., java.sql.Types.TIME)
+   */
+  def getJdbcType: Int
+
+  /**
+   * Returns the DDL type name string for this type.
+   *
+   * Used by JdbcUtils for CREATE TABLE DDL generation.
+   *
+   * @return
+   *   DDL type string (e.g., "TIME")
+   */
+  def jdbcTypeName: String

Review Comment:
   JdbcType is defined in sql/core and ClientTypeOps lives in sql/api, so we use two primitives to avoid the cross-module dependency.



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


Re: [PR] [SPARK-55441][SQL] Types Framework - Phase 1c - Client Integration [spark]

Posted by "davidm-db (via GitHub)" <gi...@apache.org>.
davidm-db commented on code in PR #54905:
URL: https://github.com/apache/spark/pull/54905#discussion_r3136338496


##########
sql/api/src/main/scala/org/apache/spark/sql/types/ops/TypeApiOps.scala:
##########
@@ -123,4 +163,18 @@ object TypeApiOps {
       case _ => None
     }
   }
+
+  /**
+   * Reverse lookup: converts an Arrow type to a Spark DataType.
+   */
+  def fromArrowType(at: ArrowType): Option[DataType] = {
+    import org.apache.arrow.vector.types.TimeUnit
+    if (!SqlApiConf.get.typesFrameworkEnabled) return None

Review Comment:
   I will do that. I will create a follow-up PR as soon as this one is merged, to address this issue in all relevant framework traits.
   
   As we agreed offline, I will do the approach with `lazy val` since it's least invasive to mitigate the perf issue immediately. And afterwards, I'll follow up with a more thorough benchmarking to check if the `supports` approach is more efficient. For now, there's no evidence based on the benchmarks I ran, but I'll confirm better.
   
   That's why I think a separate PR would be nice, to document this topic in the PR description nicely.



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


Re: [PR] [SPARK-55441][SQL] Types Framework - Phase 1c - Client Integration [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on code in PR #54905:
URL: https://github.com/apache/spark/pull/54905#discussion_r3057785227


##########
sql/api/src/main/scala/org/apache/spark/sql/types/ops/ClientTypeOps.scala:
##########
@@ -0,0 +1,174 @@
+/*
+ * 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.types.ops
+
+import org.apache.arrow.vector.types.pojo.ArrowType
+
+import org.apache.spark.sql.internal.SqlApiConf
+import org.apache.spark.sql.types.{DataType, TimeType}
+
+/**
+ * Optional client-side type operations for the Types Framework.
+ *
+ * This trait extends TypeApiOps with operations needed by client-facing infrastructure: Arrow
+ * conversion (ArrowUtils), Python interop (EvaluatePython), Hive formatting (HiveResult), and
+ * Thrift type mapping (SparkExecuteStatementOperation).
+ *
+ * Lives in sql/api so it's visible from sql/core and sql/hive-thriftserver.
+ *
+ * USAGE - integration points use ClientTypeOps(dt) which returns Option[ClientTypeOps]:
+ * {{{
+ * // Forward lookup (most files):
+ * ClientTypeOps(dt).map(_.toArrowType(timeZoneId)).getOrElse { ... }
+ *
+ * // Reverse lookup (ArrowUtils.fromArrowType):
+ * ClientTypeOps.fromArrowType(at).getOrElse { ... }
+ * }}}
+ *
+ * @see
+ *   TimeTypeApiOps for a reference implementation
+ * @since 4.2.0
+ */
+trait ClientTypeOps { self: TypeApiOps =>

Review Comment:
   `TypeApiOps` and `ClientTypeOps` are both for client side? shall we merge them into one? I'm ok to leave  additional work for followup PRs, but not commit a draft version and rewrite it in followup.



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


Re: [PR] [SPARK-55441][SQL] Types Framework - Phase 1c - Client Integration [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on PR #54905:
URL: https://github.com/apache/spark/pull/54905#issuecomment-4193605807

   if the final design is to have one interface per module, then shall we merge `ProtoTypeOps` and `ConnectArrowTypeOps` as they are both in `connect/common`?


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


Re: [PR] [SPARK-55441][SQL] Types Framework - Phase 1c - Client Integration [spark]

Posted by "MaxGekk (via GitHub)" <gi...@apache.org>.
MaxGekk closed pull request #54905: [SPARK-55441][SQL] Types Framework - Phase 1c - Client Integration
URL: https://github.com/apache/spark/pull/54905


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


Re: [PR] [SPARK-55441][SQL] Types Framework - Phase 1c - Client Integration [spark]

Posted by "davidm-db (via GitHub)" <gi...@apache.org>.
davidm-db commented on code in PR #54905:
URL: https://github.com/apache/spark/pull/54905#discussion_r3136324688


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/types/ops/TimeTypeOps.scala:
##########
@@ -48,7 +54,8 @@ import org.apache.spark.sql.types.ops.TimeTypeApiOps
  *   The TimeType with precision information
  * @since 4.2.0
  */
-case class TimeTypeOps(override val t: TimeType) extends TimeTypeApiOps(t) with TypeOps {
+case class TimeTypeOps(override val t: TimeType)
+    extends TimeTypeApiOps(t) with TypeOps {

Review Comment:
   done



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


Re: [PR] [SPARK-55441][SQL] Types Framework - Phase 1c - Client Integration [spark]

Posted by "davidm-db (via GitHub)" <gi...@apache.org>.
davidm-db commented on code in PR #54905:
URL: https://github.com/apache/spark/pull/54905#discussion_r3027789001


##########
sql/connect/common/src/main/scala/org/apache/spark/sql/connect/common/types/ops/ProtoTypeOps.scala:
##########
@@ -0,0 +1,132 @@
+/*
+ * 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.common.types.ops
+
+import org.apache.spark.connect.proto
+import org.apache.spark.sql.connect.client.arrow.types.ops.TimeTypeConnectOps
+import org.apache.spark.sql.internal.SqlApiConf
+import org.apache.spark.sql.types.{DataType, TimeType}
+
+/**
+ * Optional type operations for Spark Connect protobuf conversions.
+ *
+ * Handles bidirectional DataType <-> proto and Literal <-> proto conversions for
+ * framework-managed types in DataTypeProtoConverter and LiteralValueProtoConverter.
+ *
+ * @since 4.2.0
+ */
+trait ProtoTypeOps extends Serializable {
+
+  def dataType: DataType
+
+  /** Converts this DataType to its Connect proto representation. */
+  def toConnectProtoType: proto.DataType
+
+  /** Converts a value to a proto literal builder (generic, no DataType context). */
+  def toLiteralProto(
+      value: Any,
+      builder: proto.Expression.Literal.Builder): proto.Expression.Literal.Builder
+
+  /** Converts a value to a proto literal builder (with DataType context). */
+  def toLiteralProtoWithType(
+      value: Any,
+      dt: DataType,
+      builder: proto.Expression.Literal.Builder): proto.Expression.Literal.Builder
+
+  /**
+   * Returns a converter from proto literal to Scala value. The returned converter assumes
+   * non-null input - null handling is done by the caller (LiteralValueProtoConverter wraps with
+   * `if (v.hasNull) null`).
+   */
+  def getScalaConverter: proto.Expression.Literal => Any
+
+  /** Returns a proto DataType inferred from a proto literal (for type inference). */
+  def getProtoDataTypeFromLiteral(literal: proto.Expression.Literal): proto.DataType
+}
+
+/**
+ * Factory object for ProtoTypeOps lookup.
+ */
+object ProtoTypeOps {
+
+  def apply(dt: DataType): Option[ProtoTypeOps] = {

Review Comment:
   Applied your suggestion. Extracted a shared `opsForKindCase` lookup and added `toCatalystTypeFromProto` to the trait. `toCatalystType`, `getScalaConverterForKind`, and `getProtoDataTypeFromLiteral` all delegate through the single `opsForKindCase` registration point now. Per-type registration in this file reduced from 5 match blocks to 3 (`apply`, `opsForKindCase`, `toLiteralProtoForValue`). Added `literalCaseToKindCase` helper for the LiteralTypeCase-to-KindCase mapping.



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


Re: [PR] [SPARK-55441][SQL] Types Framework - Phase 1c - Client Integration [spark]

Posted by "davidm-db (via GitHub)" <gi...@apache.org>.
davidm-db commented on code in PR #54905:
URL: https://github.com/apache/spark/pull/54905#discussion_r2968127343


##########
sql/connect/common/src/main/scala/org/apache/spark/sql/connect/common/LiteralValueProtoConverter.scala:
##########
@@ -500,102 +528,9 @@ object LiteralValueProtoConverter {
       if (literal.getLiteralTypeCase == proto.Expression.Literal.LiteralTypeCase.NULL) {
         literal.getNull
       } else {
-        val builder = proto.DataType.newBuilder()
-        literal.getLiteralTypeCase match {
-          case proto.Expression.Literal.LiteralTypeCase.BINARY =>
-            builder.setBinary(proto.DataType.Binary.newBuilder().build())
-          case proto.Expression.Literal.LiteralTypeCase.BOOLEAN =>
-            builder.setBoolean(proto.DataType.Boolean.newBuilder().build())
-          case proto.Expression.Literal.LiteralTypeCase.BYTE =>
-            builder.setByte(proto.DataType.Byte.newBuilder().build())
-          case proto.Expression.Literal.LiteralTypeCase.SHORT =>
-            builder.setShort(proto.DataType.Short.newBuilder().build())
-          case proto.Expression.Literal.LiteralTypeCase.INTEGER =>
-            builder.setInteger(proto.DataType.Integer.newBuilder().build())
-          case proto.Expression.Literal.LiteralTypeCase.LONG =>
-            builder.setLong(proto.DataType.Long.newBuilder().build())
-          case proto.Expression.Literal.LiteralTypeCase.FLOAT =>
-            builder.setFloat(proto.DataType.Float.newBuilder().build())
-          case proto.Expression.Literal.LiteralTypeCase.DOUBLE =>
-            builder.setDouble(proto.DataType.Double.newBuilder().build())
-          case proto.Expression.Literal.LiteralTypeCase.DECIMAL =>
-            val decimal = Decimal.apply(literal.getDecimal.getValue)
-            var precision = decimal.precision
-            if (literal.getDecimal.hasPrecision) {
-              precision = math.max(precision, literal.getDecimal.getPrecision)
-            }
-            var scale = decimal.scale
-            if (literal.getDecimal.hasScale) {
-              scale = math.max(scale, literal.getDecimal.getScale)
-            }
-            builder.setDecimal(
-              proto.DataType.Decimal
-                .newBuilder()
-                .setPrecision(math.max(precision, scale))
-                .setScale(scale)
-                .build())
-          case proto.Expression.Literal.LiteralTypeCase.STRING =>
-            builder.setString(proto.DataType.String.newBuilder().build())
-          case proto.Expression.Literal.LiteralTypeCase.DATE =>
-            builder.setDate(proto.DataType.Date.newBuilder().build())
-          case proto.Expression.Literal.LiteralTypeCase.TIMESTAMP =>
-            builder.setTimestamp(proto.DataType.Timestamp.newBuilder().build())
-          case proto.Expression.Literal.LiteralTypeCase.TIMESTAMP_NTZ =>
-            builder.setTimestampNtz(proto.DataType.TimestampNTZ.newBuilder().build())
-          case proto.Expression.Literal.LiteralTypeCase.CALENDAR_INTERVAL =>
-            builder.setCalendarInterval(proto.DataType.CalendarInterval.newBuilder().build())
-          case proto.Expression.Literal.LiteralTypeCase.YEAR_MONTH_INTERVAL =>
-            builder.setYearMonthInterval(proto.DataType.YearMonthInterval.newBuilder().build())
-          case proto.Expression.Literal.LiteralTypeCase.DAY_TIME_INTERVAL =>
-            builder.setDayTimeInterval(proto.DataType.DayTimeInterval.newBuilder().build())
-          case proto.Expression.Literal.LiteralTypeCase.TIME =>
-            val timeBuilder = proto.DataType.Time.newBuilder()
-            if (literal.getTime.hasPrecision) {
-              timeBuilder.setPrecision(literal.getTime.getPrecision)
-            }
-            builder.setTime(timeBuilder.build())
-          case proto.Expression.Literal.LiteralTypeCase.ARRAY =>
-            if (literal.getArray.hasElementType) {
-              builder.setArray(
-                proto.DataType.Array
-                  .newBuilder()
-                  .setElementType(literal.getArray.getElementType)
-                  .setContainsNull(true)
-                  .build())
-            } else {
-              throw InvalidPlanInput(
-                "CONNECT_INVALID_PLAN.ARRAY_LITERAL_MISSING_DATA_TYPE",
-                Map.empty)
-            }
-          case proto.Expression.Literal.LiteralTypeCase.MAP =>
-            if (literal.getMap.hasKeyType && literal.getMap.hasValueType) {
-              builder.setMap(
-                proto.DataType.Map
-                  .newBuilder()
-                  .setKeyType(literal.getMap.getKeyType)
-                  .setValueType(literal.getMap.getValueType)
-                  .setValueContainsNull(true)
-                  .build())
-            } else {
-              throw InvalidPlanInput(
-                "CONNECT_INVALID_PLAN.MAP_LITERAL_MISSING_DATA_TYPE",
-                Map.empty)
-            }
-          case proto.Expression.Literal.LiteralTypeCase.STRUCT =>
-            if (literal.getStruct.hasStructType) {
-              builder.setStruct(literal.getStruct.getStructType.getStruct)
-            } else {
-              throw InvalidPlanInput(
-                "CONNECT_INVALID_PLAN.STRUCT_LITERAL_MISSING_DATA_TYPE",
-                Map.empty)
-            }
-          case _ =>
-            val literalCase = literal.getLiteralTypeCase
-            throw InvalidPlanInput(
-              "CONNECT_INVALID_PLAN.UNSUPPORTED_LITERAL_TYPE",
-              Map("typeInfo" -> s"${literalCase.name}(${literalCase.getNumber})"))
-        }
-        builder.build()
+        ProtoTypeOps

Review Comment:
   there doesn't seem to be a way to nicely/cleanly reduce the diff here



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


Re: [PR] [SPARK-55441][SQL] Types Framework - Phase 1c - Client Integration [spark]

Posted by "davidm-db (via GitHub)" <gi...@apache.org>.
davidm-db commented on PR #54905:
URL: https://github.com/apache/spark/pull/54905#issuecomment-4213290968

   > if the final design is to have one interface per module, then shall we merge `ProtoTypeOps` and `ConnectArrowTypeOps` as they are both in `connect/common`?
   
   @cloud-fan merged two ops classes into a single one


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


Re: [PR] [SPARK-55441][SQL] Types Framework - Phase 1c - Client Integration [spark]

Posted by "MaxGekk (via GitHub)" <gi...@apache.org>.
MaxGekk commented on code in PR #54905:
URL: https://github.com/apache/spark/pull/54905#discussion_r3093088217


##########
sql/connect/common/src/main/scala/org/apache/spark/sql/connect/client/arrow/ArrowSerializer.scala:
##########
@@ -562,7 +569,8 @@ object ArrowSerializer {
     def write(index: Int, value: Any): Unit
   }
 
-  private abstract class FieldSerializer[E, V <: FieldVector](val vector: V) extends Serializer {
+  private[connect] abstract class FieldSerializer[E, V <: FieldVector](val vector: V)
+      extends Serializer {

Review Comment:
   Should be 2 spaces indentation, see https://github.com/databricks/scala-style-guide?tab=readme-ov-file#spacing-and-indentation



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


Re: [PR] [SPARK-55441][SQL] Types Framework - Phase 1c - Client Integration [spark]

Posted by "MaxGekk (via GitHub)" <gi...@apache.org>.
MaxGekk commented on code in PR #54905:
URL: https://github.com/apache/spark/pull/54905#discussion_r3093578326


##########
sql/connect/common/src/main/scala/org/apache/spark/sql/connect/common/types/ops/ConnectTypeOps.scala:
##########
@@ -0,0 +1,175 @@
+/*
+ * 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.common.types.ops
+
+import org.apache.arrow.vector.FieldVector
+
+import org.apache.spark.connect.proto
+import org.apache.spark.sql.catalyst.encoders.AgnosticEncoder
+import org.apache.spark.sql.catalyst.encoders.AgnosticEncoders.LocalTimeEncoder
+import org.apache.spark.sql.connect.client.arrow.{ArrowDeserializers, ArrowSerializer, ArrowVectorReader}
+import org.apache.spark.sql.connect.client.arrow.types.ops.TimeTypeConnectOps
+import org.apache.spark.sql.internal.SqlApiConf
+import org.apache.spark.sql.types.{DataType, TimeType}
+
+/**
+ * Optional type operations for Spark Connect infrastructure.
+ *
+ * Consolidates both proto conversions (DataTypeProtoConverter, LiteralValueProtoConverter) and
+ * Arrow serialization/deserialization (ArrowSerializer, ArrowDeserializer, ArrowVectorReader) for
+ * framework-managed types.
+ *
+ * @since 4.2.0
+ */
+trait ConnectTypeOps extends Serializable {
+
+  def dataType: DataType
+
+  def encoder: AgnosticEncoder[_]
+
+  // ==================== Proto Conversions ====================
+
+  /** Converts this DataType to its Connect proto representation. */
+  def toConnectProtoType: proto.DataType
+
+  /** Converts a value to a proto literal builder (generic, no DataType context). */
+  def toLiteralProto(
+      value: Any,
+      builder: proto.Expression.Literal.Builder): proto.Expression.Literal.Builder
+
+  /** Converts a value to a proto literal builder (with DataType context). */
+  def toLiteralProtoWithType(
+      value: Any,
+      dt: DataType,
+      builder: proto.Expression.Literal.Builder): proto.Expression.Literal.Builder
+
+  /**
+   * Returns a converter from proto literal to Scala value. The returned converter assumes
+   * non-null input - null handling is done by the caller (LiteralValueProtoConverter wraps with
+   * `if (v.hasNull) null`).
+   */
+  def getScalaConverter: proto.Expression.Literal => Any
+
+  /** Returns a proto DataType inferred from a proto literal (for type inference). */
+  def getProtoDataTypeFromLiteral(literal: proto.Expression.Literal): proto.DataType
+
+  /** Converts a proto DataType to a Spark DataType (reverse of toConnectProtoType). */
+  def toCatalystTypeFromProto(t: proto.DataType): DataType
+
+  // ==================== Arrow Serialization ====================
+
+  /** Creates an Arrow serializer for writing values to a vector. */
+  def createArrowSerializer(vector: AnyRef): ArrowSerializer.Serializer
+
+  /** Creates an Arrow deserializer for reading values from a vector. */
+  def createArrowDeserializer(
+      enc: AgnosticEncoder[_],
+      data: AnyRef,
+      timeZoneId: String): ArrowDeserializers.Deserializer[Any]
+
+  /** Creates an ArrowVectorReader for this type's vector. */
+  def createArrowVectorReader(vector: FieldVector): ArrowVectorReader
+}
+
+/**
+ * Factory object for ConnectTypeOps lookup.
+ *
+ * Provides separate factory methods for proto (server-side, feature-flag-gated) and Arrow
+ * (client-side, no flag) dispatch.
+ */
+object ConnectTypeOps {
+
+  // ==================== Proto Dispatch (server-side, flag-gated) ====================
+
+  /** DataType-keyed dispatch for proto conversions. Checks feature flag. */
+  def apply(dt: DataType): Option[ConnectTypeOps] = {
+    if (!SqlApiConf.get.typesFrameworkEnabled) return None

Review Comment:
   Would this cause a perf regression?



##########
sql/connect/common/src/main/scala/org/apache/spark/sql/connect/common/types/ops/ConnectTypeOps.scala:
##########
@@ -0,0 +1,175 @@
+/*
+ * 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.common.types.ops
+
+import org.apache.arrow.vector.FieldVector
+
+import org.apache.spark.connect.proto
+import org.apache.spark.sql.catalyst.encoders.AgnosticEncoder
+import org.apache.spark.sql.catalyst.encoders.AgnosticEncoders.LocalTimeEncoder
+import org.apache.spark.sql.connect.client.arrow.{ArrowDeserializers, ArrowSerializer, ArrowVectorReader}
+import org.apache.spark.sql.connect.client.arrow.types.ops.TimeTypeConnectOps
+import org.apache.spark.sql.internal.SqlApiConf
+import org.apache.spark.sql.types.{DataType, TimeType}
+
+/**
+ * Optional type operations for Spark Connect infrastructure.
+ *
+ * Consolidates both proto conversions (DataTypeProtoConverter, LiteralValueProtoConverter) and
+ * Arrow serialization/deserialization (ArrowSerializer, ArrowDeserializer, ArrowVectorReader) for
+ * framework-managed types.
+ *
+ * @since 4.2.0
+ */
+trait ConnectTypeOps extends Serializable {
+
+  def dataType: DataType
+
+  def encoder: AgnosticEncoder[_]
+
+  // ==================== Proto Conversions ====================
+
+  /** Converts this DataType to its Connect proto representation. */
+  def toConnectProtoType: proto.DataType
+
+  /** Converts a value to a proto literal builder (generic, no DataType context). */
+  def toLiteralProto(
+      value: Any,
+      builder: proto.Expression.Literal.Builder): proto.Expression.Literal.Builder
+
+  /** Converts a value to a proto literal builder (with DataType context). */
+  def toLiteralProtoWithType(
+      value: Any,
+      dt: DataType,
+      builder: proto.Expression.Literal.Builder): proto.Expression.Literal.Builder
+
+  /**
+   * Returns a converter from proto literal to Scala value. The returned converter assumes
+   * non-null input - null handling is done by the caller (LiteralValueProtoConverter wraps with
+   * `if (v.hasNull) null`).
+   */
+  def getScalaConverter: proto.Expression.Literal => Any
+
+  /** Returns a proto DataType inferred from a proto literal (for type inference). */
+  def getProtoDataTypeFromLiteral(literal: proto.Expression.Literal): proto.DataType
+
+  /** Converts a proto DataType to a Spark DataType (reverse of toConnectProtoType). */
+  def toCatalystTypeFromProto(t: proto.DataType): DataType
+
+  // ==================== Arrow Serialization ====================
+
+  /** Creates an Arrow serializer for writing values to a vector. */
+  def createArrowSerializer(vector: AnyRef): ArrowSerializer.Serializer
+
+  /** Creates an Arrow deserializer for reading values from a vector. */
+  def createArrowDeserializer(
+      enc: AgnosticEncoder[_],
+      data: AnyRef,
+      timeZoneId: String): ArrowDeserializers.Deserializer[Any]
+
+  /** Creates an ArrowVectorReader for this type's vector. */
+  def createArrowVectorReader(vector: FieldVector): ArrowVectorReader
+}
+
+/**
+ * Factory object for ConnectTypeOps lookup.
+ *
+ * Provides separate factory methods for proto (server-side, feature-flag-gated) and Arrow
+ * (client-side, no flag) dispatch.
+ */
+object ConnectTypeOps {
+
+  // ==================== Proto Dispatch (server-side, flag-gated) ====================
+
+  /** DataType-keyed dispatch for proto conversions. Checks feature flag. */
+  def apply(dt: DataType): Option[ConnectTypeOps] = {
+    if (!SqlApiConf.get.typesFrameworkEnabled) return None
+    dt match {
+      case tt: TimeType => Some(new TimeTypeConnectOps(tt))
+      // Add new framework types here
+      case _ => None
+    }
+  }
+
+  /** Reverse lookup by value class for the generic literal builder. Checks feature flag. */
+  def toLiteralProtoForValue(
+      value: Any,
+      builder: proto.Expression.Literal.Builder): Option[proto.Expression.Literal.Builder] = {
+    if (!SqlApiConf.get.typesFrameworkEnabled) return None

Review Comment:
   ditto



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


Re: [PR] [SPARK-55441][SQL] Types Framework - Phase 1c - Client Integration [spark]

Posted by "MaxGekk (via GitHub)" <gi...@apache.org>.
MaxGekk commented on code in PR #54905:
URL: https://github.com/apache/spark/pull/54905#discussion_r3136915021


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/types/ops/TimeTypeOps.scala:
##########
@@ -48,7 +54,8 @@ import org.apache.spark.sql.types.ops.TimeTypeApiOps
  *   The TimeType with precision information
  * @since 4.2.0
  */
-case class TimeTypeOps(override val t: TimeType) extends TimeTypeApiOps(t) with TypeOps {
+case class TimeTypeOps(override val t: TimeType)
+    extends TimeTypeApiOps(t) with TypeOps {

Review Comment:
   ahh, ok. Let's accept the the diff and fix scalafmt later (please, open an JIRA to adjust behaviour of scalafmt)



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


Re: [PR] [SPARK-55441][SQL] Types Framework - Phase 1c - Client Integration [spark]

Posted by "davidm-db (via GitHub)" <gi...@apache.org>.
davidm-db commented on code in PR #54905:
URL: https://github.com/apache/spark/pull/54905#discussion_r3027834283


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/HiveResult.scala:
##########
@@ -112,6 +113,17 @@ object HiveResult extends SQLConfHelper {
       formatters: TimeFormatters,
       binaryFormatter: BinaryFormatter): String = a match {
     case (null, _) => if (nested) "null" else "NULL"
+    case (value, dt) =>
+      ClientTypeOps(dt).map(_.formatExternal(value, nested)).getOrElse {

Review Comment:
   1. TimeType currently has two parallel implementations — the original hardcoded branches and the framework ops. The framework implementation is how a new type would be built from scratch (formatter owned by the ops class, no dependency on external formatter pipelines). This should be the correct design for new types going forward.
       - The concern about bypassing session formatters doesn't apply here — `FractionTimeFormatter` is fully stateless (no session configuration, no timezone, no legacy parser policy). Unlike `TimestampFormatter` (which takes `sessionLocalTimeZone`) or `DateFormatter` (which checks `legacyTimeParserPolicy`), the time formatter has zero session state. Both paths — the original `formatters.time.format(lt)` and the framework's `formatExternal` — create the same stateless `FractionTimeFormatter` and produce identical output.
       - For future types that DO need session-configurable formatting, the ops can read session state inside `formatExternal` at call time via `SqlApiConf.get`, matching how `HiveResult.getTimeFormatters` reads `SQLConf.get.sessionLocalTimeZone`. The framework design handles this without API changes.
   
   3. Re allocation: tracked for Phase 1d — singleton caching of ops instances across all factory companions uniform. This was already noted down during work on other phases and I'll fix it all together in the upcoming phase.



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


Re: [PR] [SPARK-55441][SQL] Types Framework - Phase 1c - Client Integration [spark]

Posted by "MaxGekk (via GitHub)" <gi...@apache.org>.
MaxGekk commented on PR #54905:
URL: https://github.com/apache/spark/pull/54905#issuecomment-4260605764

   > Finding 2: Per-row object allocation in HiveResult hot path
   > Issue: ClientTypeOps(dt) is called on every (value, dt) pair in the result set, creating a new TimeTypeApiOps instance per call. Additionally, it's called for ALL non-null values of ALL types (not just TimeType), returning None for standard types — adding overhead to every row of every query.
   
   This is also my main concern regarding the current approach. In my original PR https://github.com/apache/spark/pull/51467, I tried to minimize impact on existing types. Definitely it will need benchmarking when enabling the framework by default. 


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


Re: [PR] [SPARK-55441][SQL] Types Framework - Phase 1c - Client Integration [spark]

Posted by "davidm-db (via GitHub)" <gi...@apache.org>.
davidm-db commented on code in PR #54905:
URL: https://github.com/apache/spark/pull/54905#discussion_r3136864815


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/types/ops/TimeTypeOps.scala:
##########
@@ -48,7 +54,8 @@ import org.apache.spark.sql.types.ops.TimeTypeApiOps
  *   The TimeType with precision information
  * @since 4.2.0
  */
-case class TimeTypeOps(override val t: TimeType) extends TimeTypeApiOps(t) with TypeOps {
+case class TimeTypeOps(override val t: TimeType)
+    extends TimeTypeApiOps(t) with TypeOps {

Review Comment:
   @MaxGekk linter is failing and scalafmt is correcting me to do more spaces...
   <img width="1482" height="416" alt="image" src="https://github.com/user-attachments/assets/1a2c9ec4-41d3-44e0-83d7-9eec7877b05c" />
   
   so I guess there really isn't a choice for this PR, but we should either:
   - look into fixing scalafmt - this probably has a lot of consequences for the already existing code...
   - or accepting the diff



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


Re: [PR] [SPARK-55441][SQL] Types Framework - Phase 1c - Client Integration [spark]

Posted by "davidm-db (via GitHub)" <gi...@apache.org>.
davidm-db commented on code in PR #54905:
URL: https://github.com/apache/spark/pull/54905#discussion_r3137118661


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/types/ops/TimeTypeOps.scala:
##########
@@ -48,7 +54,8 @@ import org.apache.spark.sql.types.ops.TimeTypeApiOps
  *   The TimeType with precision information
  * @since 4.2.0
  */
-case class TimeTypeOps(override val t: TimeType) extends TimeTypeApiOps(t) with TypeOps {
+case class TimeTypeOps(override val t: TimeType)
+    extends TimeTypeApiOps(t) with TypeOps {

Review Comment:
   sure, will do.
   do you know if there is any parent JIRA for such issues, I cannot seem to find anything relevant, or should I just create under Spark?



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


Re: [PR] [SPARK-55441][SQL] Types Framework - Phase 1c - Client Integration [spark]

Posted by "davidm-db (via GitHub)" <gi...@apache.org>.
davidm-db commented on code in PR #54905:
URL: https://github.com/apache/spark/pull/54905#discussion_r3136318456


##########
sql/connect/common/src/main/scala/org/apache/spark/sql/connect/client/arrow/types/ops/TimeTypeConnectOps.scala:
##########
@@ -0,0 +1,123 @@
+/*
+ * 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.types.ops
+
+import java.time.LocalTime
+
+import org.apache.arrow.vector.{FieldVector, TimeNanoVector}
+
+import org.apache.spark.connect.proto
+import org.apache.spark.sql.catalyst.encoders.AgnosticEncoder
+import org.apache.spark.sql.catalyst.encoders.AgnosticEncoders.LocalTimeEncoder
+import org.apache.spark.sql.catalyst.util.SparkDateTimeUtils
+import org.apache.spark.sql.connect.client.arrow.{ArrowDeserializers, ArrowSerializer, ArrowVectorReader, TimeVectorReader}
+import org.apache.spark.sql.connect.common.types.ops.ConnectTypeOps
+import org.apache.spark.sql.types.{DataType, TimeType}
+
+/**
+ * Combined Connect operations for TimeType.
+ *
+ * Implements ConnectTypeOps for TimeType, providing both proto DataType/Literal conversions and
+ * Arrow serialization/deserialization.
+ *
+ * Lives under the arrow.types.ops sub-package to access arrow-private types (TimeVectorReader,
+ * ArrowSerializer.Serializer, ArrowDeserializers.LeafFieldDeserializer) while keeping ops
+ * implementations separate from core arrow infrastructure.

Review Comment:
   done



##########
sql/connect/common/src/main/scala/org/apache/spark/sql/connect/client/arrow/ArrowSerializer.scala:
##########
@@ -562,7 +569,8 @@ object ArrowSerializer {
     def write(index: Int, value: Any): Unit
   }
 
-  private abstract class FieldSerializer[E, V <: FieldVector](val vector: V) extends Serializer {
+  private[connect] abstract class FieldSerializer[E, V <: FieldVector](val vector: V)
+      extends Serializer {

Review Comment:
   done



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


Re: [PR] [SPARK-55441][SQL] Types Framework - Phase 1c - Client Integration [spark]

Posted by "davidm-db (via GitHub)" <gi...@apache.org>.
davidm-db commented on code in PR #54905:
URL: https://github.com/apache/spark/pull/54905#discussion_r2965334178


##########
sql/api/src/main/scala/org/apache/spark/sql/types/ops/TimeTypeApiOps.scala:
##########
@@ -56,4 +68,36 @@ class TimeTypeApiOps(val t: TimeType) extends TypeApiOps {
   // ==================== Row Encoding ====================
 
   override def getEncoder: AgnosticEncoder[_] = LocalTimeEncoder
+
+  // ==================== Client Type Operations (ClientTypeOps) ====================
+
+  override def toArrowType(timeZoneId: String): ArrowType = {
+    new ArrowType.Time(TimeUnit.NANOSECOND, 8 * 8)
+  }
+
+  override def getJdbcType: Int = java.sql.Types.TIME
+
+  override def jdbcTypeName: String = "TIME"
+
+  override def needConversionInPython: Boolean = true
+
+  override def makeFromJava: Any => Any = (obj: Any) => {
+    if (obj == null) {
+      null
+    } else {

Review Comment:
   Added nullSafeConvert utility to the ClientTypeOps trait and updated TimeTypeApiOps.makeFromJava to use it.



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


Re: [PR] [SPARK-55441][SQL] Types Framework - Phase 1c - Client Integration [spark]

Posted by "davidm-db (via GitHub)" <gi...@apache.org>.
davidm-db commented on code in PR #54905:
URL: https://github.com/apache/spark/pull/54905#discussion_r2965335303


##########
sql/api/src/main/scala/org/apache/spark/sql/types/ops/ClientTypeOps.scala:
##########
@@ -0,0 +1,177 @@
+/*
+ * 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.types.ops
+
+import org.apache.arrow.vector.types.pojo.ArrowType
+
+import org.apache.spark.sql.internal.SqlApiConf
+import org.apache.spark.sql.types.{DataType, TimeType}
+
+/**
+ * Optional client-side type operations for the Types Framework.
+ *
+ * This trait extends TypeApiOps with operations needed by client-facing infrastructure:
+ * Arrow conversion (ArrowUtils), JDBC mapping (JdbcUtils), Python interop (EvaluatePython),
+ * Hive formatting (HiveResult), and Thrift type mapping (SparkExecuteStatementOperation).
+ *
+ * Lives in sql/api so it's visible from sql/core and sql/hive-thriftserver.
+ *
+ * USAGE - integration points use ClientTypeOps(dt) which returns Option[ClientTypeOps]:
+ * {{{
+ * // Forward lookup (most files):
+ * ClientTypeOps(dt).map(_.toArrowType(timeZoneId)).getOrElse { ... }
+ *
+ * // Reverse lookup (ArrowUtils.fromArrowType):
+ * ClientTypeOps.fromArrowType(at).getOrElse { ... }
+ * }}}
+ *
+ * @see
+ *   TimeTypeApiOps for a reference implementation
+ * @since 4.2.0
+ */
+trait ClientTypeOps { self: TypeApiOps =>
+
+  // ==================== Arrow Conversion ====================
+
+  /**
+   * Converts this DataType to its Arrow representation.
+   *
+   * Used by ArrowUtils.toArrowType.
+   *
+   * @param timeZoneId
+   *   the session timezone (needed by some temporal types)
+   * @return
+   *   the corresponding ArrowType
+   */
+  def toArrowType(timeZoneId: String): ArrowType
+
+  // ==================== JDBC Mapping ====================
+
+  /**
+   * Returns the java.sql.Types constant for this type.
+   *
+   * Used by JdbcUtils.getCommonJDBCType for JDBC write path.
+   *
+   * @return
+   *   java.sql.Types constant (e.g., java.sql.Types.TIME)
+   */
+  def getJdbcType: Int
+
+  /**
+   * Returns the DDL type name string for this type.
+   *
+   * Used by JdbcUtils for CREATE TABLE DDL generation.
+   *
+   * @return
+   *   DDL type string (e.g., "TIME")
+   */
+  def jdbcTypeName: String
+
+  // ==================== Python Interop ====================
+
+  /**
+   * Returns true if values of this type need conversion when passed to/from Python.
+   *
+   * Used by EvaluatePython.needConversionInPython.
+   */
+  def needConversionInPython: Boolean
+
+  /**
+   * Creates a converter function for Python/Py4J interop.
+   *
+   * Used by EvaluatePython.makeFromJava. The returned function handles null-safe
+   * conversion of Java/Py4J values to the internal Catalyst representation.
+   *
+   * @return
+   *   a function that converts a Java value to the internal representation
+   */
+  def makeFromJava: Any => Any
+
+  // ==================== Hive Formatting ====================
+
+  /**
+   * Formats an external-type value for Hive output.
+   *
+   * Used by HiveResult.toHiveString. The input is an external-type value
+   * (e.g., java.time.LocalTime for TimeType), NOT the internal representation.
+   *
+   * @param value
+   *   the external-type value to format
+   * @return
+   *   formatted string representation
+   */
+  def formatExternal(value: Any): String
+
+  // ==================== Thrift Mapping ====================
+
+  /**
+   * Returns the Thrift TTypeId name for this type.
+   *
+   * Used by SparkExecuteStatementOperation.toTTypeId. Returns a String that maps
+   * to a TTypeId enum value (e.g., "STRING_TYPE") since TTypeId is only available
+   * in the hive-thriftserver module.
+   *
+   * @return
+   *   TTypeId enum name (e.g., "STRING_TYPE")
+   */
+  def thriftTypeName: String
+}
+
+/**
+ * Factory object for ClientTypeOps lookup.
+ *
+ * Delegates to TypeApiOps and narrows via collect to find implementations that mix in
+ * ClientTypeOps.
+ */
+object ClientTypeOps {
+
+  /**
+   * Returns a ClientTypeOps instance for the given DataType, if available.
+   *
+   * @param dt
+   *   the DataType to get operations for
+   * @return
+   *   Some(ClientTypeOps) if supported, None otherwise
+   */
+  def apply(dt: DataType): Option[ClientTypeOps] =
+    TypeApiOps(dt).collect { case co: ClientTypeOps => co }
+
+  /**
+   * Reverse lookup: converts an Arrow type to a Spark DataType, if it belongs to a
+   * framework-managed type.
+   *
+   * Used by ArrowUtils.fromArrowType. Returns None if the Arrow type doesn't correspond
+   * to any framework-managed type, or the framework is disabled.
+   *
+   * @param at
+   *   the ArrowType to convert
+   * @return
+   *   Some(DataType) if recognized, None otherwise
+   */
+  def fromArrowType(at: ArrowType): Option[DataType] = {

Review Comment:
   ArrowUtils.fromArrowType lives in sql/api (same module as ClientTypeOps), so a separate arrow ops trait for one method seemed like over-splitting.



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


Re: [PR] [SPARK-55441][SQL] Types Framework - Phase 1c - Client Integration [spark]

Posted by "davidm-db (via GitHub)" <gi...@apache.org>.
davidm-db commented on code in PR #54905:
URL: https://github.com/apache/spark/pull/54905#discussion_r2965346264


##########
sql/connect/common/src/main/scala/org/apache/spark/sql/connect/common/LiteralValueProtoConverter.scala:
##########
@@ -548,6 +555,8 @@ object LiteralValueProtoConverter {
             builder.setYearMonthInterval(proto.DataType.YearMonthInterval.newBuilder().build())
           case proto.Expression.Literal.LiteralTypeCase.DAY_TIME_INTERVAL =>
             builder.setDayTimeInterval(proto.DataType.DayTimeInterval.newBuilder().build())
+          case litCase if ProtoTypeOps.buildProtoDataTypeForLiteral(literal, builder) =>
+            // Framework handled

Review Comment:
   Fixed as part of the invocation pattern cleanup — restructured to avoid side effects in match guards.  



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


Re: [PR] [SPARK-55441][SQL] Types Framework - Phase 1c - Client Integration [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on code in PR #54905:
URL: https://github.com/apache/spark/pull/54905#discussion_r3063515098


##########
sql/api/src/main/scala/org/apache/spark/sql/types/ops/ClientTypeOps.scala:
##########
@@ -0,0 +1,174 @@
+/*
+ * 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.types.ops
+
+import org.apache.arrow.vector.types.pojo.ArrowType
+
+import org.apache.spark.sql.internal.SqlApiConf
+import org.apache.spark.sql.types.{DataType, TimeType}
+
+/**
+ * Optional client-side type operations for the Types Framework.
+ *
+ * This trait extends TypeApiOps with operations needed by client-facing infrastructure: Arrow
+ * conversion (ArrowUtils), Python interop (EvaluatePython), Hive formatting (HiveResult), and
+ * Thrift type mapping (SparkExecuteStatementOperation).
+ *
+ * Lives in sql/api so it's visible from sql/core and sql/hive-thriftserver.
+ *
+ * USAGE - integration points use ClientTypeOps(dt) which returns Option[ClientTypeOps]:
+ * {{{
+ * // Forward lookup (most files):
+ * ClientTypeOps(dt).map(_.toArrowType(timeZoneId)).getOrElse { ... }
+ *
+ * // Reverse lookup (ArrowUtils.fromArrowType):
+ * ClientTypeOps.fromArrowType(at).getOrElse { ... }
+ * }}}
+ *
+ * @see
+ *   TimeTypeApiOps for a reference implementation
+ * @since 4.2.0
+ */
+trait ClientTypeOps { self: TypeApiOps =>

Review Comment:
   If we want to go with optional methods (return None by default), let's do it now and abandon the optional trait approach.



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


Re: [PR] [SPARK-55441][SQL] Types Framework - Phase 1c - Client Integration [spark]

Posted by "davidm-db (via GitHub)" <gi...@apache.org>.
davidm-db commented on code in PR #54905:
URL: https://github.com/apache/spark/pull/54905#discussion_r3057934158


##########
sql/api/src/main/scala/org/apache/spark/sql/types/ops/ClientTypeOps.scala:
##########
@@ -0,0 +1,174 @@
+/*
+ * 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.types.ops
+
+import org.apache.arrow.vector.types.pojo.ArrowType
+
+import org.apache.spark.sql.internal.SqlApiConf
+import org.apache.spark.sql.types.{DataType, TimeType}
+
+/**
+ * Optional client-side type operations for the Types Framework.
+ *
+ * This trait extends TypeApiOps with operations needed by client-facing infrastructure: Arrow
+ * conversion (ArrowUtils), Python interop (EvaluatePython), Hive formatting (HiveResult), and
+ * Thrift type mapping (SparkExecuteStatementOperation).
+ *
+ * Lives in sql/api so it's visible from sql/core and sql/hive-thriftserver.
+ *
+ * USAGE - integration points use ClientTypeOps(dt) which returns Option[ClientTypeOps]:
+ * {{{
+ * // Forward lookup (most files):
+ * ClientTypeOps(dt).map(_.toArrowType(timeZoneId)).getOrElse { ... }
+ *
+ * // Reverse lookup (ArrowUtils.fromArrowType):
+ * ClientTypeOps.fromArrowType(at).getOrElse { ... }
+ * }}}
+ *
+ * @see
+ *   TimeTypeApiOps for a reference implementation
+ * @since 4.2.0
+ */
+trait ClientTypeOps { self: TypeApiOps =>

Review Comment:
   That's true. It's also true for `CatalystTypeOps` and `TypeOps` who are both on the catalyst side. However, in both cases, one is optional and the other is mandatory. I thought of merging it like this to enable functionality, and follow-up with a refactor, where I would introduce the concept of optional functions (returning `Options`) in the ops classes, since it's a framework design, rather than enabling functionality.
   If you think however that we should do it here, I can, I was just explaining my reasoning.



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


Re: [PR] [SPARK-55441][SQL] Types Framework - Phase 1c - Client Integration [spark]

Posted by "davidm-db (via GitHub)" <gi...@apache.org>.
davidm-db commented on code in PR #54905:
URL: https://github.com/apache/spark/pull/54905#discussion_r3071991997


##########
sql/api/src/main/scala/org/apache/spark/sql/types/ops/ClientTypeOps.scala:
##########
@@ -0,0 +1,174 @@
+/*
+ * 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.types.ops
+
+import org.apache.arrow.vector.types.pojo.ArrowType
+
+import org.apache.spark.sql.internal.SqlApiConf
+import org.apache.spark.sql.types.{DataType, TimeType}
+
+/**
+ * Optional client-side type operations for the Types Framework.
+ *
+ * This trait extends TypeApiOps with operations needed by client-facing infrastructure: Arrow
+ * conversion (ArrowUtils), Python interop (EvaluatePython), Hive formatting (HiveResult), and
+ * Thrift type mapping (SparkExecuteStatementOperation).
+ *
+ * Lives in sql/api so it's visible from sql/core and sql/hive-thriftserver.
+ *
+ * USAGE - integration points use ClientTypeOps(dt) which returns Option[ClientTypeOps]:
+ * {{{
+ * // Forward lookup (most files):
+ * ClientTypeOps(dt).map(_.toArrowType(timeZoneId)).getOrElse { ... }
+ *
+ * // Reverse lookup (ArrowUtils.fromArrowType):
+ * ClientTypeOps.fromArrowType(at).getOrElse { ... }
+ * }}}
+ *
+ * @see
+ *   TimeTypeApiOps for a reference implementation
+ * @since 4.2.0
+ */
+trait ClientTypeOps { self: TypeApiOps =>

Review Comment:
   done. removed optional traits in favor of functions returning `Option`



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


Re: [PR] [SPARK-55441][SQL] Types Framework - Phase 1c - Client Integration [spark]

Posted by "davidm-db (via GitHub)" <gi...@apache.org>.
davidm-db commented on code in PR #54905:
URL: https://github.com/apache/spark/pull/54905#discussion_r3027836292


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/jdbc/JdbcUtils.scala:
##########
@@ -145,7 +146,12 @@ object JdbcUtils extends Logging with SQLConfHelper {
    * @param dt The datatype (e.g. [[org.apache.spark.sql.types.StringType]])
    * @return The default JdbcType for this DataType
    */
-  def getCommonJDBCType(dt: DataType): Option[JdbcType] = {
+  // Uses .orElse (not .getOrElse) because this method returns Option[JdbcType].
+  def getCommonJDBCType(dt: DataType): Option[JdbcType] =
+    ClientTypeOps(dt).map(ops => JdbcType(ops.jdbcTypeName, ops.getJdbcType))

Review Comment:
   Removed JDBC entirely from this PR. `getCommonJDBCType` reverted to original code (no framework dispatch), JDBC methods removed from `ClientTypeOps`. The framework should be a transparent refactoring with no behavior change. JDBC requires types from `sql/core` that `ClientTypeOps` (in `sql/api`) can't reference, and partial support (DDL without getter/setter) is worse than no support. A separate `JdbcTypeOps` trait in `sql/core` is planned for when full JDBC support is ready.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/types/ops/CatalystTypeOps.scala:
##########
@@ -0,0 +1,116 @@
+/*
+ * 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.catalyst.types.ops
+
+import org.apache.arrow.vector.ValueVector
+
+import org.apache.spark.sql.catalyst.WalkedTypePath
+import org.apache.spark.sql.catalyst.expressions.Expression
+import org.apache.spark.sql.execution.arrow.ArrowFieldWriter
+import org.apache.spark.sql.types.DataType
+
+/**
+ * Optional catalyst-layer type operations for the Types Framework.
+ *
+ * This trait extends TypeOps with operations needed by catalyst-level client infrastructure:

Review Comment:
   Fixed.



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


Re: [PR] [SPARK-55441][SQL] Types Framework - Phase 1c - Client Integration [spark]

Posted by "MaxGekk (via GitHub)" <gi...@apache.org>.
MaxGekk commented on PR #54905:
URL: https://github.com/apache/spark/pull/54905#issuecomment-4327398570

   +1, LGTM. Merging to master.
   Thank you, @davidm-db and @dejankrak-db @cloud-fan for review.


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


Re: [PR] [SPARK-55441][SQL] Types Framework - Phase 1c - Client Integration [spark]

Posted by "davidm-db (via GitHub)" <gi...@apache.org>.
davidm-db commented on code in PR #54905:
URL: https://github.com/apache/spark/pull/54905#discussion_r2966309607


##########
sql/api/src/main/scala/org/apache/spark/sql/util/ArrowUtils.scala:
##########
@@ -39,35 +40,43 @@ private[sql] object ArrowUtils {
 
   /** Maps data type from Spark to Arrow. NOTE: timeZoneId required for TimestampTypes */
   def toArrowType(dt: DataType, timeZoneId: String, largeVarTypes: Boolean = false): ArrowType =
-    dt match {
-      case BooleanType => ArrowType.Bool.INSTANCE
-      case ByteType => new ArrowType.Int(8, true)
-      case ShortType => new ArrowType.Int(8 * 2, true)
-      case IntegerType => new ArrowType.Int(8 * 4, true)
-      case LongType => new ArrowType.Int(8 * 8, true)
-      case FloatType => new ArrowType.FloatingPoint(FloatingPointPrecision.SINGLE)
-      case DoubleType => new ArrowType.FloatingPoint(FloatingPointPrecision.DOUBLE)
-      case _: StringType if !largeVarTypes => ArrowType.Utf8.INSTANCE
-      case BinaryType if !largeVarTypes => ArrowType.Binary.INSTANCE
-      case _: StringType if largeVarTypes => ArrowType.LargeUtf8.INSTANCE
-      case BinaryType if largeVarTypes => ArrowType.LargeBinary.INSTANCE
-      case DecimalType.Fixed(precision, scale) => new ArrowType.Decimal(precision, scale, 8 * 16)
-      case DateType => new ArrowType.Date(DateUnit.DAY)
-      case TimestampType if timeZoneId == null =>
-        throw SparkException.internalError("Missing timezoneId where it is mandatory.")
-      case TimestampType => new ArrowType.Timestamp(TimeUnit.MICROSECOND, timeZoneId)
-      case TimestampNTZType =>
-        new ArrowType.Timestamp(TimeUnit.MICROSECOND, null)
-      case _: TimeType => new ArrowType.Time(TimeUnit.NANOSECOND, 8 * 8)
-      case NullType => ArrowType.Null.INSTANCE
-      case _: YearMonthIntervalType => new ArrowType.Interval(IntervalUnit.YEAR_MONTH)
-      case _: DayTimeIntervalType => new ArrowType.Duration(TimeUnit.MICROSECOND)
-      case CalendarIntervalType => new ArrowType.Interval(IntervalUnit.MONTH_DAY_NANO)
-      case _ =>
-        throw ExecutionErrors.unsupportedDataTypeError(dt)
-    }
+    ClientTypeOps(dt).map(_.toArrowType(timeZoneId))
+      .getOrElse(toArrowTypeDefault(dt, timeZoneId, largeVarTypes))
+
+  private def toArrowTypeDefault(
+      dt: DataType, timeZoneId: String, largeVarTypes: Boolean): ArrowType = dt match {
+    case BooleanType => ArrowType.Bool.INSTANCE

Review Comment:
   if we do it like:
   ```suggestion
     private def toArrowTypeDefault(
         dt: DataType, timeZoneId: String, largeVarTypes: Boolean): ArrowType =
       dt match {
         case BooleanType => ArrowType.Bool.INSTANCE
   ```
   we still follow the scala conventions, but reduce the diff significantly!
   
   do it in the other places in code as well.



##########
sql/connect/common/src/main/scala/org/apache/spark/sql/connect/client/arrow/ArrowDeserializer.scala:
##########
@@ -200,6 +201,10 @@ object ArrowDeserializers {
         new LeafFieldDeserializer[LocalDateTime](encoder, v, timeZoneId) {
           override def value(i: Int): LocalDateTime = reader.getLocalDateTime(i)
         }
+      case (enc, v: FieldVector) if ConnectArrowTypeOps(enc).isDefined =>

Review Comment:
   why didn't we follow the framework invocation patter here as well? with .map().getorelse()?



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/execution/arrow/ArrowWriter.scala:
##########
@@ -52,60 +53,66 @@ object ArrowWriter {
 
   private[sql] def createFieldWriter(vector: ValueVector): ArrowFieldWriter = {
     val field = vector.getField()
-    (ArrowUtils.fromArrowField(field), vector) match {
-      case (BooleanType, vector: BitVector) => new BooleanWriter(vector)
-      case (ByteType, vector: TinyIntVector) => new ByteWriter(vector)
-      case (ShortType, vector: SmallIntVector) => new ShortWriter(vector)
-      case (IntegerType, vector: IntVector) => new IntegerWriter(vector)
-      case (LongType, vector: BigIntVector) => new LongWriter(vector)
-      case (FloatType, vector: Float4Vector) => new FloatWriter(vector)
-      case (DoubleType, vector: Float8Vector) => new DoubleWriter(vector)
-      case (DecimalType.Fixed(precision, scale), vector: DecimalVector) =>
-        new DecimalWriter(vector, precision, scale)
-      case (StringType, vector: VarCharVector) => new StringWriter(vector)
-      case (StringType, vector: LargeVarCharVector) => new LargeStringWriter(vector)
-      case (BinaryType, vector: VarBinaryVector) => new BinaryWriter(vector)
-      case (BinaryType, vector: LargeVarBinaryVector) => new LargeBinaryWriter(vector)
-      case (DateType, vector: DateDayVector) => new DateWriter(vector)
-      case (TimestampType, vector: TimeStampMicroTZVector) => new TimestampWriter(vector)
-      case (TimestampNTZType, vector: TimeStampMicroVector) => new TimestampNTZWriter(vector)
-      case (_: TimeType, vector: TimeNanoVector) => new TimeWriter(vector)
-      case (ArrayType(_, _), vector: ListVector) =>
-        val elementVector = createFieldWriter(vector.getDataVector())
-        new ArrayWriter(vector, elementVector)
-      case (MapType(_, _, _), vector: MapVector) =>
-        val structVector = vector.getDataVector.asInstanceOf[StructVector]
-        val keyWriter = createFieldWriter(structVector.getChild(MapVector.KEY_NAME))
-        val valueWriter = createFieldWriter(structVector.getChild(MapVector.VALUE_NAME))
-        new MapWriter(vector, structVector, keyWriter, valueWriter)
-      case (StructType(_), vector: StructVector) =>
-        val children = (0 until vector.size()).map { ordinal =>
-          createFieldWriter(vector.getChildByOrdinal(ordinal))
-        }
-        new StructWriter(vector, children.toArray)
-      case (NullType, vector: NullVector) => new NullWriter(vector)
-      case (_: YearMonthIntervalType, vector: IntervalYearVector) => new IntervalYearWriter(vector)
-      case (_: DayTimeIntervalType, vector: DurationVector) => new DurationWriter(vector)
-      case (CalendarIntervalType, vector: IntervalMonthDayNanoVector) =>
-        new IntervalMonthDayNanoWriter(vector)
-      case (VariantType, vector: StructVector) =>
-        val children = (0 until vector.size()).map { ordinal =>
-          createFieldWriter(vector.getChildByOrdinal(ordinal))
-        }
-        new StructWriter(vector, children.toArray)
-      case (dt: GeometryType, vector: StructVector) =>
-        val children = (0 until vector.size()).map { ordinal =>
-          createFieldWriter(vector.getChildByOrdinal(ordinal))
-        }
-        new GeometryWriter(dt, vector, children.toArray)
-      case (dt: GeographyType, vector: StructVector) =>
-        val children = (0 until vector.size()).map { ordinal =>
-          createFieldWriter(vector.getChildByOrdinal(ordinal))
-        }
-        new GeographyWriter(dt, vector, children.toArray)
-      case (dt, _) =>
-        throw ExecutionErrors.unsupportedDataTypeError(dt)
-    }
+    val dt = ArrowUtils.fromArrowField(field)
+    CatalystTypeOps(dt).map(_.createArrowFieldWriter(vector))
+      .getOrElse(createFieldWriterDefault(dt, vector))
+  }
+
+  private[sql] def createFieldWriterDefault(
+      dt: DataType, vector: ValueVector): ArrowFieldWriter = (dt, vector) match {
+    case (BooleanType, vector: BitVector) => new BooleanWriter(vector)

Review Comment:
   same thought as in https://github.com/apache/spark/pull/54905/changes#r2966309607
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/execution/arrow/ArrowWriter.scala:
##########
@@ -146,7 +153,7 @@ class ArrowWriter(val root: VectorSchemaRoot, fields: Array[ArrowFieldWriter]) {
   }
 }
 
-private[arrow] abstract class ArrowFieldWriter {
+private[sql] abstract class ArrowFieldWriter {

Review Comment:
   why do we need this change? can we avoid it?



##########
sql/connect/common/src/main/scala/org/apache/spark/sql/connect/common/LiteralValueProtoConverter.scala:
##########
@@ -501,99 +509,101 @@ object LiteralValueProtoConverter {
         literal.getNull
       } else {
         val builder = proto.DataType.newBuilder()

Review Comment:
   any better way to rewrite this part to reduce diff?



##########
sql/connect/common/src/main/scala/org/apache/spark/sql/connect/common/DataTypeProtoConverter.scala:
##########
@@ -174,225 +176,229 @@ object DataTypeProtoConverter {
     toConnectProtoTypeInternal(t, bytesToBinary)
   }
 
-  private def toConnectProtoTypeInternal(t: DataType, bytesToBinary: Boolean): proto.DataType = {
-    t match {
-      case NullType => ProtoDataTypes.NullType
+  private def toConnectProtoTypeInternal(t: DataType, bytesToBinary: Boolean): proto.DataType =
+    ProtoTypeOps(t).map(_.toConnectProtoType)
+      .getOrElse(toConnectProtoTypeDefault(t, bytesToBinary))
 
-      case BooleanType => ProtoDataTypes.BooleanType
+  private def toConnectProtoTypeDefault(
+      t: DataType, bytesToBinary: Boolean): proto.DataType = t match {
+    case NullType => ProtoDataTypes.NullType
 

Review Comment:
   same thought as in https://github.com/apache/spark/pull/54905/changes#r2966309607 to minimize the diff



##########
sql/connect/common/src/main/scala/org/apache/spark/sql/connect/common/LiteralValueProtoConverter.scala:
##########
@@ -110,10 +111,12 @@ object LiteralValueProtoConverter {
       case v: Duration => builder.setDayTimeInterval(SparkIntervalUtils.durationToMicros(v))
       case v: Period => builder.setYearMonthInterval(SparkIntervalUtils.periodToMonths(v))
       case v: LocalTime =>
-        builder.setTime(
-          builder.getTimeBuilder
-            .setNano(SparkDateTimeUtils.localTimeToNanos(v))
-            .setPrecision(TimeType.DEFAULT_PRECISION))
+        ProtoTypeOps(TimeType()).map(_.toLiteralProto(v, builder)).getOrElse {

Review Comment:
   why can't we figure out a way to follow the regular invocation pattern here?



##########
sql/connect/common/src/main/scala/org/apache/spark/sql/connect/common/LiteralValueProtoConverter.scala:
##########
@@ -217,10 +220,12 @@ object LiteralValueProtoConverter {
       case (v, structType: StructType) =>
         builder.setStruct(structBuilder(v, structType))
       case (v: LocalTime, timeType: TimeType) =>
-        builder.setTime(
-          builder.getTimeBuilder
-            .setNano(SparkDateTimeUtils.localTimeToNanos(v))
-            .setPrecision(timeType.precision))
+        ProtoTypeOps(timeType).map(_.toLiteralProtoWithType(v, timeType, builder)).getOrElse {

Review Comment:
   why can't we figure out a way to follow the regular invocation pattern here?



##########
sql/connect/common/src/main/scala/org/apache/spark/sql/connect/client/arrow/ArrowSerializer.scala:
##########
@@ -391,6 +392,8 @@ object ArrowSerializer {
           override def set(index: Int, value: LocalDateTime): Unit =
             vector.setSafe(index, SparkDateTimeUtils.localDateTimeToMicros(value))
         }
+      case (enc, v) if ConnectArrowTypeOps(enc).isDefined =>

Review Comment:
   same thought as in https://github.com/apache/spark/pull/54905/changes#r2966342973



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/jdbc/JdbcUtils.scala:
##########
@@ -145,29 +146,31 @@ object JdbcUtils extends Logging with SQLConfHelper {
    * @param dt The datatype (e.g. [[org.apache.spark.sql.types.StringType]])
    * @return The default JdbcType for this DataType
    */
-  def getCommonJDBCType(dt: DataType): Option[JdbcType] = {
-    dt match {
-      case IntegerType => Option(JdbcType("INTEGER", java.sql.Types.INTEGER))
-      case LongType => Option(JdbcType("BIGINT", java.sql.Types.BIGINT))
-      case DoubleType => Option(JdbcType("DOUBLE PRECISION", java.sql.Types.DOUBLE))
-      case FloatType => Option(JdbcType("REAL", java.sql.Types.FLOAT))
-      case ShortType => Option(JdbcType("INTEGER", java.sql.Types.SMALLINT))
-      case ByteType => Option(JdbcType("BYTE", java.sql.Types.TINYINT))
-      case BooleanType => Option(JdbcType("BIT(1)", java.sql.Types.BIT))
-      case StringType => Option(JdbcType("TEXT", java.sql.Types.CLOB))
-      case BinaryType => Option(JdbcType("BLOB", java.sql.Types.BLOB))
-      case c: CharType => Option(JdbcType(s"CHAR(${c.length})", java.sql.Types.CHAR))
-      case v: VarcharType => Option(JdbcType(s"VARCHAR(${v.length})", java.sql.Types.VARCHAR))
-      case TimestampType => Option(JdbcType("TIMESTAMP", java.sql.Types.TIMESTAMP))
-      // This is a common case of timestamp without time zone. Most of the databases either only
-      // support TIMESTAMP type or use TIMESTAMP as an alias for TIMESTAMP WITHOUT TIME ZONE.
-      // Note that some dialects override this setting, e.g. as SQL Server.
-      case TimestampNTZType => Option(JdbcType("TIMESTAMP", java.sql.Types.TIMESTAMP))
-      case DateType => Option(JdbcType("DATE", java.sql.Types.DATE))
-      case t: DecimalType => Option(
-        JdbcType(s"DECIMAL(${t.precision},${t.scale})", java.sql.Types.DECIMAL))
-      case _ => None
-    }
+  def getCommonJDBCType(dt: DataType): Option[JdbcType] =
+    ClientTypeOps(dt).map(ops => JdbcType(ops.jdbcTypeName, ops.getJdbcType))
+      .orElse(getCommonJDBCTypeDefault(dt))
+
+  private def getCommonJDBCTypeDefault(dt: DataType): Option[JdbcType] = dt match {
+    case IntegerType => Option(JdbcType("INTEGER", java.sql.Types.INTEGER))

Review Comment:
   same thought as in: https://github.com/apache/spark/pull/54905/changes#r2966309607



##########
sql/connect/common/src/main/scala/org/apache/spark/sql/connect/client/arrow/ArrowVectorReader.scala:
##########
@@ -92,6 +93,10 @@ object ArrowVectorReader {
       case v: DateDayVector => new DateDayVectorReader(v, timeZoneId)
       case v: TimeStampMicroTZVector => new TimeStampMicroTZVectorReader(v)
       case v: TimeStampMicroVector => new TimeStampMicroVectorReader(v, timeZoneId)
+      case v if ConnectArrowTypeOps(targetDataType).isDefined =>

Review Comment:
   same thought as in https://github.com/apache/spark/pull/54905/changes#r2966342973



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/python/EvaluatePython.scala:
##########
@@ -41,16 +42,19 @@ object EvaluatePython {
    */
   private[python] class BytesWrapper(val data: Array[Byte])
 
-  def needConversionInPython(dt: DataType): Boolean = dt match {
-    case DateType | TimestampType | TimestampNTZType | VariantType | _: DayTimeIntervalType
-         | _: TimeType | _: GeometryType | _: GeographyType => true
-    case _: StructType => true
-    case _: UserDefinedType[_] => true
-    case ArrayType(elementType, _) => needConversionInPython(elementType)
-    case MapType(keyType, valueType, _) =>
-      needConversionInPython(keyType) || needConversionInPython(valueType)
-    case _ => false
-  }
+  def needConversionInPython(dt: DataType): Boolean =

Review Comment:
   i know it's short, but add a *Default method here as well and follow the guidelines as in https://github.com/apache/spark/pull/54905/changes#r2966309607 to minimize the diff



##########
sql/connect/common/src/main/scala/org/apache/spark/sql/connect/common/LiteralValueProtoConverter.scala:
##########
@@ -385,49 +390,52 @@ object LiteralValueProtoConverter {
   }
 
   private def getScalaConverter(dataType: proto.DataType): proto.Expression.Literal => Any = {
-    val converter: proto.Expression.Literal => Any = dataType.getKindCase match {
-      case proto.DataType.KindCase.NULL =>
-        v =>
-          throw InvalidPlanInput(
-            "CONNECT_INVALID_PLAN.EXPECTED_NULL_VALUE",
-            Map("literalTypeCase" -> v.getLiteralTypeCase.toString))
-      case proto.DataType.KindCase.SHORT => v => v.getShort.toShort
-      case proto.DataType.KindCase.INTEGER => v => v.getInteger
-      case proto.DataType.KindCase.LONG => v => v.getLong
-      case proto.DataType.KindCase.DOUBLE => v => v.getDouble
-      case proto.DataType.KindCase.BYTE => v => v.getByte.toByte
-      case proto.DataType.KindCase.FLOAT => v => v.getFloat
-      case proto.DataType.KindCase.BOOLEAN => v => v.getBoolean
-      case proto.DataType.KindCase.STRING => v => v.getString
-      case proto.DataType.KindCase.BINARY => v => v.getBinary.toByteArray
-      case proto.DataType.KindCase.DATE =>
-        v => SparkDateTimeUtils.toJavaDate(v.getDate)
-      case proto.DataType.KindCase.TIMESTAMP =>
-        v => SparkDateTimeUtils.toJavaTimestamp(v.getTimestamp)
-      case proto.DataType.KindCase.TIMESTAMP_NTZ =>
-        v => SparkDateTimeUtils.microsToLocalDateTime(v.getTimestampNtz)
-      case proto.DataType.KindCase.DAY_TIME_INTERVAL =>
-        v => SparkIntervalUtils.microsToDuration(v.getDayTimeInterval)
-      case proto.DataType.KindCase.YEAR_MONTH_INTERVAL =>
-        v => SparkIntervalUtils.monthsToPeriod(v.getYearMonthInterval)
-      case proto.DataType.KindCase.TIME =>
-        v => SparkDateTimeUtils.nanosToLocalTime(v.getTime.getNano)
-      case proto.DataType.KindCase.DECIMAL => v => Decimal(v.getDecimal.getValue)
-      case proto.DataType.KindCase.CALENDAR_INTERVAL =>
-        v =>
-          val interval = v.getCalendarInterval
-          new CalendarInterval(interval.getMonths, interval.getDays, interval.getMicroseconds)
-      case proto.DataType.KindCase.ARRAY =>
-        v => toScalaArrayInternal(v, dataType.getArray)
-      case proto.DataType.KindCase.MAP =>
-        v => toScalaMapInternal(v, dataType.getMap)
-      case proto.DataType.KindCase.STRUCT =>
-        v => toScalaStructInternal(v, dataType.getStruct)
-      case _ =>
-        throw InvalidPlanInput(
-          "CONNECT_INVALID_PLAN.UNSUPPORTED_LITERAL_TYPE",
-          Map("typeInfo" -> dataType.getKindCase.toString))
-    }
+    val converter: proto.Expression.Literal => Any =
+      ProtoTypeOps.getScalaConverterForKind(dataType.getKindCase).getOrElse {
+        dataType.getKindCase match {

Review Comment:
   same thought as in https://github.com/apache/spark/pull/54905/changes#r2966309607 to minimize the diff



##########
sql/connect/common/src/main/scala/org/apache/spark/sql/connect/common/DataTypeProtoConverter.scala:
##########
@@ -29,70 +30,71 @@ import org.apache.spark.util.SparkClassUtils
  * Helper class for conversions between [[DataType]] and [[proto.DataType]].
  */
 object DataTypeProtoConverter {
-  def toCatalystType(t: proto.DataType): DataType = {
-    t.getKindCase match {
-      case proto.DataType.KindCase.NULL => NullType
-
-      case proto.DataType.KindCase.BINARY => BinaryType
-
-      case proto.DataType.KindCase.BOOLEAN => BooleanType
-
-      case proto.DataType.KindCase.BYTE => ByteType
-      case proto.DataType.KindCase.SHORT => ShortType
-      case proto.DataType.KindCase.INTEGER => IntegerType
-      case proto.DataType.KindCase.LONG => LongType
-
-      case proto.DataType.KindCase.FLOAT => FloatType
-      case proto.DataType.KindCase.DOUBLE => DoubleType
-      case proto.DataType.KindCase.DECIMAL => toCatalystDecimalType(t.getDecimal)
-
-      case proto.DataType.KindCase.STRING => toCatalystStringType(t.getString)
-      case proto.DataType.KindCase.CHAR => CharType(t.getChar.getLength)
-      case proto.DataType.KindCase.VAR_CHAR => VarcharType(t.getVarChar.getLength)
-
-      case proto.DataType.KindCase.DATE => DateType
-      case proto.DataType.KindCase.TIMESTAMP => TimestampType
-      case proto.DataType.KindCase.TIMESTAMP_NTZ => TimestampNTZType
-      case proto.DataType.KindCase.TIME =>
-        if (t.getTime.hasPrecision) {
-          TimeType(t.getTime.getPrecision)
-        } else {
-          TimeType()
-        }
-
-      case proto.DataType.KindCase.CALENDAR_INTERVAL => CalendarIntervalType
-      case proto.DataType.KindCase.YEAR_MONTH_INTERVAL =>
-        toCatalystYearMonthIntervalType(t.getYearMonthInterval)
-      case proto.DataType.KindCase.DAY_TIME_INTERVAL =>
-        toCatalystDayTimeIntervalType(t.getDayTimeInterval)
-
-      case proto.DataType.KindCase.ARRAY => toCatalystArrayType(t.getArray)
-      case proto.DataType.KindCase.STRUCT => toCatalystStructType(t.getStruct)
-      case proto.DataType.KindCase.MAP => toCatalystMapType(t.getMap)
-      case proto.DataType.KindCase.VARIANT => VariantType
-
-      case proto.DataType.KindCase.GEOMETRY =>
-        val srid = t.getGeometry.getSrid
-        if (srid == GeometryType.MIXED_SRID) {
-          GeometryType("ANY")
-        } else {
-          GeometryType(srid)
-        }
-      case proto.DataType.KindCase.GEOGRAPHY =>
-        val srid = t.getGeography.getSrid
-        if (srid == GeographyType.MIXED_SRID) {
-          GeographyType("ANY")
-        } else {
-          GeographyType(srid)
-        }
-
-      case proto.DataType.KindCase.UDT => toCatalystUDT(t.getUdt)
-
-      case _ =>
-        throw InvalidPlanInput(
-          "CONNECT_INVALID_PLAN.DATA_TYPE_UNSUPPORTED_PROTO_TO_CATALYST",
-          Map("kindCase" -> t.getKindCase.toString))
-    }
+  def toCatalystType(t: proto.DataType): DataType =
+    ProtoTypeOps.toCatalystType(t).getOrElse(toCatalystTypeDefault(t))
+
+  private def toCatalystTypeDefault(t: proto.DataType): DataType = t.getKindCase match {
+    case proto.DataType.KindCase.NULL => NullType

Review Comment:
   same thought as in https://github.com/apache/spark/pull/54905/changes#r2966309607 to minimize the diff



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


Re: [PR] [SPARK-55441][SQL] Types Framework - Phase 1c - Client Integration [spark]

Posted by "davidm-db (via GitHub)" <gi...@apache.org>.
davidm-db commented on code in PR #54905:
URL: https://github.com/apache/spark/pull/54905#discussion_r2968127343


##########
sql/connect/common/src/main/scala/org/apache/spark/sql/connect/common/LiteralValueProtoConverter.scala:
##########
@@ -500,102 +528,9 @@ object LiteralValueProtoConverter {
       if (literal.getLiteralTypeCase == proto.Expression.Literal.LiteralTypeCase.NULL) {
         literal.getNull
       } else {
-        val builder = proto.DataType.newBuilder()
-        literal.getLiteralTypeCase match {
-          case proto.Expression.Literal.LiteralTypeCase.BINARY =>
-            builder.setBinary(proto.DataType.Binary.newBuilder().build())
-          case proto.Expression.Literal.LiteralTypeCase.BOOLEAN =>
-            builder.setBoolean(proto.DataType.Boolean.newBuilder().build())
-          case proto.Expression.Literal.LiteralTypeCase.BYTE =>
-            builder.setByte(proto.DataType.Byte.newBuilder().build())
-          case proto.Expression.Literal.LiteralTypeCase.SHORT =>
-            builder.setShort(proto.DataType.Short.newBuilder().build())
-          case proto.Expression.Literal.LiteralTypeCase.INTEGER =>
-            builder.setInteger(proto.DataType.Integer.newBuilder().build())
-          case proto.Expression.Literal.LiteralTypeCase.LONG =>
-            builder.setLong(proto.DataType.Long.newBuilder().build())
-          case proto.Expression.Literal.LiteralTypeCase.FLOAT =>
-            builder.setFloat(proto.DataType.Float.newBuilder().build())
-          case proto.Expression.Literal.LiteralTypeCase.DOUBLE =>
-            builder.setDouble(proto.DataType.Double.newBuilder().build())
-          case proto.Expression.Literal.LiteralTypeCase.DECIMAL =>
-            val decimal = Decimal.apply(literal.getDecimal.getValue)
-            var precision = decimal.precision
-            if (literal.getDecimal.hasPrecision) {
-              precision = math.max(precision, literal.getDecimal.getPrecision)
-            }
-            var scale = decimal.scale
-            if (literal.getDecimal.hasScale) {
-              scale = math.max(scale, literal.getDecimal.getScale)
-            }
-            builder.setDecimal(
-              proto.DataType.Decimal
-                .newBuilder()
-                .setPrecision(math.max(precision, scale))
-                .setScale(scale)
-                .build())
-          case proto.Expression.Literal.LiteralTypeCase.STRING =>
-            builder.setString(proto.DataType.String.newBuilder().build())
-          case proto.Expression.Literal.LiteralTypeCase.DATE =>
-            builder.setDate(proto.DataType.Date.newBuilder().build())
-          case proto.Expression.Literal.LiteralTypeCase.TIMESTAMP =>
-            builder.setTimestamp(proto.DataType.Timestamp.newBuilder().build())
-          case proto.Expression.Literal.LiteralTypeCase.TIMESTAMP_NTZ =>
-            builder.setTimestampNtz(proto.DataType.TimestampNTZ.newBuilder().build())
-          case proto.Expression.Literal.LiteralTypeCase.CALENDAR_INTERVAL =>
-            builder.setCalendarInterval(proto.DataType.CalendarInterval.newBuilder().build())
-          case proto.Expression.Literal.LiteralTypeCase.YEAR_MONTH_INTERVAL =>
-            builder.setYearMonthInterval(proto.DataType.YearMonthInterval.newBuilder().build())
-          case proto.Expression.Literal.LiteralTypeCase.DAY_TIME_INTERVAL =>
-            builder.setDayTimeInterval(proto.DataType.DayTimeInterval.newBuilder().build())
-          case proto.Expression.Literal.LiteralTypeCase.TIME =>
-            val timeBuilder = proto.DataType.Time.newBuilder()
-            if (literal.getTime.hasPrecision) {
-              timeBuilder.setPrecision(literal.getTime.getPrecision)
-            }
-            builder.setTime(timeBuilder.build())
-          case proto.Expression.Literal.LiteralTypeCase.ARRAY =>
-            if (literal.getArray.hasElementType) {
-              builder.setArray(
-                proto.DataType.Array
-                  .newBuilder()
-                  .setElementType(literal.getArray.getElementType)
-                  .setContainsNull(true)
-                  .build())
-            } else {
-              throw InvalidPlanInput(
-                "CONNECT_INVALID_PLAN.ARRAY_LITERAL_MISSING_DATA_TYPE",
-                Map.empty)
-            }
-          case proto.Expression.Literal.LiteralTypeCase.MAP =>
-            if (literal.getMap.hasKeyType && literal.getMap.hasValueType) {
-              builder.setMap(
-                proto.DataType.Map
-                  .newBuilder()
-                  .setKeyType(literal.getMap.getKeyType)
-                  .setValueType(literal.getMap.getValueType)
-                  .setValueContainsNull(true)
-                  .build())
-            } else {
-              throw InvalidPlanInput(
-                "CONNECT_INVALID_PLAN.MAP_LITERAL_MISSING_DATA_TYPE",
-                Map.empty)
-            }
-          case proto.Expression.Literal.LiteralTypeCase.STRUCT =>
-            if (literal.getStruct.hasStructType) {
-              builder.setStruct(literal.getStruct.getStructType.getStruct)
-            } else {
-              throw InvalidPlanInput(
-                "CONNECT_INVALID_PLAN.STRUCT_LITERAL_MISSING_DATA_TYPE",
-                Map.empty)
-            }
-          case _ =>
-            val literalCase = literal.getLiteralTypeCase
-            throw InvalidPlanInput(
-              "CONNECT_INVALID_PLAN.UNSUPPORTED_LITERAL_TYPE",
-              Map("typeInfo" -> s"${literalCase.name}(${literalCase.getNumber})"))
-        }
-        builder.build()
+        ProtoTypeOps

Review Comment:
   there doesn't seem to be a way to nicely reduce the diff here



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


Re: [PR] [SPARK-55441][SQL] Types Framework - Phase 1c - Client Integration [spark]

Posted by "davidm-db (via GitHub)" <gi...@apache.org>.
davidm-db commented on code in PR #54905:
URL: https://github.com/apache/spark/pull/54905#discussion_r2965344936


##########
sql/connect/common/src/main/scala/org/apache/spark/sql/connect/client/arrow/TimeTypeConnectOps.scala:
##########
@@ -0,0 +1,124 @@
+/*
+ * 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.time.LocalTime
+
+import org.apache.arrow.vector.{FieldVector, TimeNanoVector}
+
+import org.apache.spark.connect.proto
+import org.apache.spark.sql.catalyst.encoders.AgnosticEncoder
+import org.apache.spark.sql.catalyst.encoders.AgnosticEncoders.LocalTimeEncoder
+import org.apache.spark.sql.catalyst.util.SparkDateTimeUtils
+import org.apache.spark.sql.connect.common.types.ops.{ConnectArrowTypeOps, ProtoTypeOps}
+import org.apache.spark.sql.types.{DataType, TimeType}
+
+/**
+ * Combined Connect operations for TimeType.
+ *
+ * Implements both ProtoTypeOps (proto DataType/Literal conversions) and ConnectArrowTypeOps
+ * (Arrow serialization/deserialization) in a single class.
+ *
+ * Lives in the arrow package to access arrow-private types (ArrowVectorReader, TimeVectorReader,
+ * ArrowSerializer.Serializer, ArrowDeserializers.LeafFieldDeserializer).
+ *
+ * @param t
+ *   The TimeType with precision information
+ * @since 4.2.0
+ */
+private[connect] class TimeTypeConnectOps(val t: TimeType)

Review Comment:
   Moved to client/arrow/types/ops/ subdirectory — keeps the arrow package declaration (needed for arrow-private type access) while separating ops implementations from core arrow infrastructure.



##########
sql/connect/common/src/main/scala/org/apache/spark/sql/connect/client/arrow/ArrowDeserializer.scala:
##########
@@ -200,6 +201,9 @@ object ArrowDeserializers {
         new LeafFieldDeserializer[LocalDateTime](encoder, v, timeZoneId) {
           override def value(i: Int): LocalDateTime = reader.getLocalDateTime(i)
         }
+      case (enc, v: FieldVector) if ConnectArrowTypeOps(enc).isDefined =>
+        ConnectArrowTypeOps(enc).get
+          .createArrowDeserializer(enc, v, timeZoneId).asInstanceOf[Deserializer[Any]]

Review Comment:
   Fixed all 13 dispatch points to use the .map(...).getOrElse { ... } pattern consistent with Phase 1a — single factory call, no double construction.



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


Re: [PR] [SPARK-55441][SQL] Types Framework - Phase 1c - Client Integration [spark]

Posted by "davidm-db (via GitHub)" <gi...@apache.org>.
davidm-db commented on code in PR #54905:
URL: https://github.com/apache/spark/pull/54905#discussion_r3027790320


##########
sql/connect/common/src/main/scala/org/apache/spark/sql/connect/common/types/ops/ConnectArrowTypeOps.scala:
##########
@@ -0,0 +1,81 @@
+/*
+ * 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.common.types.ops
+
+import org.apache.spark.sql.catalyst.encoders.AgnosticEncoder
+import org.apache.spark.sql.catalyst.encoders.AgnosticEncoders.LocalTimeEncoder
+import org.apache.spark.sql.connect.client.arrow.types.ops.TimeTypeConnectOps
+import org.apache.spark.sql.types.{DataType, TimeType}
+
+/**
+ * Optional type operations for Spark Connect Arrow serialization/deserialization.
+ *
+ * Handles Arrow-based data exchange on the Connect client side for framework-managed types. Used
+ * by ArrowSerializer, ArrowDeserializer, and ArrowVectorReader.
+ *
+ * NOTE: No feature flag check -the Connect client must handle whatever types the server sends.
+ * The feature flag controls server-side engine behavior; the client always needs to handle types
+ * that exist in the encoder.
+ *
+ * Methods return Any to avoid referencing arrow-private types from the types.ops package. Call
+ * sites in the arrow package cast to the expected types.
+ *
+ * @since 4.2.0
+ */
+trait ConnectArrowTypeOps extends Serializable {
+
+  def encoder: AgnosticEncoder[_]
+
+  // Note: Methods use Any parameter/return types because the concrete Arrow types
+  // (ArrowSerializer.Serializer, ArrowDeserializers.Deserializer, ArrowVectorReader) are
+  // private[arrow] and cannot be referenced from the types.ops package. Call sites in
+  // the arrow package cast to the expected types.
+
+  /** Creates an Arrow serializer for writing values to a vector. Returns a Serializer. */
+  def createArrowSerializer(vector: Any): Any

Review Comment:
   Widened `FieldSerializer` to `private[connect]`, `ArrowVectorReader` and `TimeVectorReader` to `private[connect]`. All three **return types** are now proper: `ArrowSerializer.Serializer`, `ArrowDeserializers.Deserializer[Any]`, `ArrowVectorReader`. Call sites no longer need `.asInstanceOf` casts on the return value.
   
   For **parameters**, 1 of 3 is also proper (`createArrowVectorReader` takes `FieldVector`). The other 2 (`createArrowSerializer`, `createArrowDeserializer`) take `AnyRef` because the existing caller APIs (`serializerFor(encoder, v: AnyRef)`, `deserializerFor(encoder, data: AnyRef)`) use `AnyRef` — these signatures predate our work and use pattern matching to determine the concrete vector type. Using `AnyRef` avoids an unnecessary intermediate cast.
   
   Net result: 6 `Any` positions reduced to 2 `AnyRef` parameters. The remaining 2 are constrained by the existing caller APIs, not by visibility.



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


Re: [PR] [SPARK-55441][SQL] Types Framework - Phase 1c - Client Integration [spark]

Posted by "davidm-db (via GitHub)" <gi...@apache.org>.
davidm-db commented on PR #54905:
URL: https://github.com/apache/spark/pull/54905#issuecomment-4177656111

   @dejankrak-db All findings should be either addressed or replied to now.
   
   **Finding 1 (Arrow precision mismatch):** Pre-existing behavior — the original `ArrowUtils.fromArrowType` also returns `TimeType(MICROS_PRECISION)` for nanosecond Arrow time vectors. Not introduced by this PR. It is tracked among the issues with TIME we discovered during the work on the framework and will be addressed separately.
   
   **Finding 2 (Per-row allocation in HiveResult):** Valid concern. Singleton caching of ops instances across all factory companions is tracked for Phase 1d (Validation & Performance).
   
   **Finding 3 (toLiteralProto DEFAULT_PRECISION):** Not a bug. The "generic" literal path receives a `LocalTime` value with no DataType context. `LocalTime` doesn't carry precision metadata — precision is a property of the column (DataType), not the value. `DEFAULT_PRECISION` is the correct choice here, same as the original code. The typed overload (`toLiteralProtoWithType`) correctly uses the DataType's precision.
   
   **Finding 4 (ConnectArrowTypeOps Any types):** Already fixed in a previous iteration — widened `FieldSerializer`, `ArrowVectorReader`, and `TimeVectorReader` to `private[connect]`. The trait now uses proper return types and all `asInstanceOf` casts are removed from call sites.
   
   **Finding 5 (Null safety in HiveResult):** The null case is the first match arm and always runs before framework dispatch. This ordering is structural (same as all other type cases in the match) — not something that can be accidentally refactored away without changing the entire method signature.
   
   **Finding 6 (Redundant TimeType in defaults):** Intentional — project guideline: "Don't remove existing TimeType code. Its explicit case branches remain as safety net and fallback when the feature flag is off." Equivalence testing is tracked for Phase 1d/Phase 2.
   
   **Finding 7 (Serializer dispatch order vs. encoder type):** `AgnosticExpressionPathEncoder` is a migration shim (its own Scaladoc says so), and `isNativeEncoder` handles primitives (Boolean, Int, Long, etc.). Framework types use dedicated leaf encoders (e.g., `LocalTimeEncoder`), never migration shims or native primitives. Added a comment at both dispatch sites documenting this.
   
   **Finding 8 (JDBC behavior change):** Removed JDBC from this PR entirely — `getCommonJDBCType` reverted to original, JDBC methods removed from `ClientTypeOps`. A separate `JdbcTypeOps` trait in `sql/core` is planned for when full JDBC support (DDL + getter + setter) is ready.
   
   **Finding 9 (Repeated allocations):** Tracked for Phase 1d — singleton caching across all factory companions uniformly.
   
   **Finding 10 (No new tests):** Tracked for Phase 2 (Testing Framework). The feature flag is enabled by default in tests, so the entire existing test suite validates the framework path.
   
   **Finding 11 (ClientTypeOps.apply flag check):** By design — `ClientTypeOps(dt)` delegates to `TypeApiOps(dt)` which checks the flag. The inline comment explains: "Delegates to TypeApiOps and narrows: a type must implement TypeApiOps AND mix in ClientTypeOps to be found here." `fromArrowType` checks explicitly because it's a reverse lookup that doesn't go through TypeApiOps.
   
   **Finding 12 (createFieldWriterDefault visibility):** Fixed — changed from `private[sql]` to `private`.
   
   **Finding 13 (ProtoTypeOps 5 registration points):** Already fixed while addressing one of the Wenchen's comments — consolidated to 3 via a shared `opsForKindCase` lookup. `toCatalystType`, `getScalaConverterForKind`, and `getProtoDataTypeFromLiteral` all delegate through a single KindCase registration point.


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


Re: [PR] [SPARK-55441][SQL] Types Framework - Phase 1c - Client Integration [spark]

Posted by "davidm-db (via GitHub)" <gi...@apache.org>.
davidm-db commented on code in PR #54905:
URL: https://github.com/apache/spark/pull/54905#discussion_r3027790320


##########
sql/connect/common/src/main/scala/org/apache/spark/sql/connect/common/types/ops/ConnectArrowTypeOps.scala:
##########
@@ -0,0 +1,81 @@
+/*
+ * 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.common.types.ops
+
+import org.apache.spark.sql.catalyst.encoders.AgnosticEncoder
+import org.apache.spark.sql.catalyst.encoders.AgnosticEncoders.LocalTimeEncoder
+import org.apache.spark.sql.connect.client.arrow.types.ops.TimeTypeConnectOps
+import org.apache.spark.sql.types.{DataType, TimeType}
+
+/**
+ * Optional type operations for Spark Connect Arrow serialization/deserialization.
+ *
+ * Handles Arrow-based data exchange on the Connect client side for framework-managed types. Used
+ * by ArrowSerializer, ArrowDeserializer, and ArrowVectorReader.
+ *
+ * NOTE: No feature flag check -the Connect client must handle whatever types the server sends.
+ * The feature flag controls server-side engine behavior; the client always needs to handle types
+ * that exist in the encoder.
+ *
+ * Methods return Any to avoid referencing arrow-private types from the types.ops package. Call
+ * sites in the arrow package cast to the expected types.
+ *
+ * @since 4.2.0
+ */
+trait ConnectArrowTypeOps extends Serializable {
+
+  def encoder: AgnosticEncoder[_]
+
+  // Note: Methods use Any parameter/return types because the concrete Arrow types
+  // (ArrowSerializer.Serializer, ArrowDeserializers.Deserializer, ArrowVectorReader) are
+  // private[arrow] and cannot be referenced from the types.ops package. Call sites in
+  // the arrow package cast to the expected types.
+
+  /** Creates an Arrow serializer for writing values to a vector. Returns a Serializer. */
+  def createArrowSerializer(vector: Any): Any

Review Comment:
   Agreed. Widened `FieldSerializer` to `private[connect]`, `ArrowVectorReader` and `TimeVectorReader` to `private[connect]`. The trait now uses proper return types (`ArrowSerializer.Serializer`, `ArrowDeserializers.Deserializer[Any]`, `ArrowVectorReader`) and `asInstanceOf` casts are removed from call sites. `TimeTypeConnectOps` uses `FieldSerializer` directly for type-safe null handling.



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