This is an automated email from the ASF dual-hosted git repository.

HyukjinKwon pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/spark-connect-rust.git


The following commit(s) were added to refs/heads/master by this push:
     new 63b6bcb9 [SPARK-61286][CONNECT] Send date, timestamp and decimal pivot 
values as typed literals in GroupedData::pivot of the Rust API
63b6bcb9 is described below

commit 63b6bcb9802ff7fd11dfd3e92048dc7439d3082d
Author: Timothy Meehan <[email protected]>
AuthorDate: Tue Nov 10 08:03:43 2026 +0900

    [SPARK-61286][CONNECT] Send date, timestamp and decimal pivot values as 
typed literals in GroupedData::pivot of the Rust API
    
    ### What changes were proposed in this pull request?
    
    [SPARK-61286](https://issues.apache.org/jira/browse/SPARK-61286): 
`GroupedData::pivot` now sends typed pivot-value literals for binary, date, 
timestamp, timestamp without time zone, time and decimal values.
    
    - `value_to_lit_expr` in `crates/spark-connect/src/group.rs` maps each of 
those `Value` variants to its `LiteralExpression`. A time gets precision 6, as 
PySpark's literal of a `datetime.time`.
    - A decimal needs both `precision` and `scale`, which the 
`LiteralExpression` requires, so a decimal without them is an error.
    - A null, a list, a map, a struct, a variant, or a decimal without 
precision or scale now makes `pivot` return an `UNSUPPORTED_OPERATION` error. 
Before, each was sent as the string of its Debug format.
    - The Python client is unchanged. It accepts only bool, float, int and str 
pivot values, as before, so its `NOT_EXPECTED_TYPE` rejection of date, 
timestamp and decimal values is unchanged.
    
    ### Why are the changes needed?
    
    The Rust API's `pivot` built each value that did not fall in the boolean, 
number, string or day-time-interval arms from its Debug format. A pivot on a 
date column with `Value::Date(19723)` therefore sent the string 
`"Date(19723)"`. The server casts that string to the column's type, so the 
query failed with `CAST_INVALID_INPUT` under ANSI mode, and without ANSI it 
silently produced a null column named `Date(19723)`.
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes, for the Rust API only. A pivot on a date, timestamp or decimal column 
with explicit values now matches the rows of those values. Before, it failed or 
returned a null column. `GroupedData::pivot` now returns an 
`UNSUPPORTED_OPERATION` error for a null, a nested value, or a decimal without 
precision or scale, where it used to send a string.
    
    ### How was this patch tested?
    
    - Offline unit tests in `crates/spark-connect/src/group.rs`:
      - `pivot_values_are_typed_literals` checks that each of the six variants 
is serialized as its typed literal in the `Aggregate` proto.
      - `pivot_values_without_a_literal_are_unsupported` checks the error and 
its `operation` parameter for a null, an array, a map, a variant and a decimal 
without precision or scale.
    - Server-gated e2e test `pivot_on_typed_values_matches_pyspark` in 
`crates/spark-connect/tests/e2e_dataframe.rs`, for a date, a timestamp and a 
decimal column. Its expected column names and counts were checked against 
PySpark 4.3.0 on the same server: pivoting each column on the same value 
written as a string gives `k=1 -> 1, k=2 -> 1` under the column named after 
that string (`2024-01-01`, `2024-01-01 00:00:00`, `1.50`).
    - With the old fall-through restored temporarily, all three new tests fail: 
the unit tests on the serialized literal type and on the missing error, and the 
e2e test with the server's `CAST_INVALID_INPUT`.
    - `cargo test -p apache-spark-connect --release --lib` (530 passed), 
`--no-run` and `--features wasm-udf --no-run`, `cargo fmt --all --check`. 
Clippy reports nothing on the changed lines.
    - Live: `e2e_dataframe`, `e2e_ops_breadth`, `e2e_coverage`, 
`plan_arg_regression_golden` and `coverage_plan_extra` pass against a Spark 
4.3.0 Connect server.
    
    ### Was this patch authored or co-authored using generative AI tooling?
    
    Generated-by: Claude Opus 5.5 and Claude Haiku 5.5
    
    This pull request and its description were written by Isaac.
    
    Closes #431 from tdcmeehan/SPARK-61286-typed-pivot-values.
    
    Authored-by: Timothy Meehan <[email protected]>
    Signed-off-by: Hyukjin Kwon <[email protected]>
---
 crates/spark-connect/src/group.rs           | 145 ++++++++++++++++++++++++++--
 crates/spark-connect/tests/e2e_dataframe.rs |  64 ++++++++++++
 2 files changed, 203 insertions(+), 6 deletions(-)

diff --git a/crates/spark-connect/src/group.rs 
b/crates/spark-connect/src/group.rs
index 72306f72..506cdd28 100644
--- a/crates/spark-connect/src/group.rs
+++ b/crates/spark-connect/src/group.rs
@@ -13,8 +13,11 @@ use crate::plan::{AggregateGroupType, LogicalPlan};
 use crate::types::DataType;
 use crate::udf::CommonInlineUserDefinedFunctionExpression;
 
-/// Convert a [`crate::row::Value`] into a literal [`Expression`] (for pivot 
values).
-fn value_to_lit_expr(v: crate::row::Value) -> Expression {
+/// Convert a [`crate::row::Value`] into a typed literal [`Expression`] (for 
pivot values).
+///
+/// A null has no type of its own, and a nested value has no literal of its 
own, so both are
+/// an `UNSUPPORTED_OPERATION` error, as is a decimal without its precision 
and scale.
+fn value_to_lit_expr(v: crate::row::Value) -> Result<Expression> {
     use crate::expression::LiteralExpression as L;
     use crate::row::Value;
     let lit = match v {
@@ -26,10 +29,43 @@ fn value_to_lit_expr(v: crate::row::Value) -> Expression {
         Value::Float(x) => L::double(x as f64),
         Value::Double(x) => L::double(x),
         Value::String(s) => L::string(s),
+        Value::Binary(b) => L::binary(b),
+        Value::Date(days) => L::Date(days),
+        Value::Timestamp(micros) => L::Timestamp(micros),
+        Value::TimestampNtz(micros) => L::TimestampNtz(micros),
+        // TIME of the default precision, as PySpark's literal of a 
`datetime.time`.
+        Value::Time(nano) => L::Time { nano, precision: 6 },
         Value::DayTimeInterval(v) => L::DayTimeInterval(v),
-        other => L::string(format!("{:?}", other)),
+        Value::Decimal {
+            value,
+            precision: Some(precision),
+            scale: Some(scale),
+        } => L::Decimal {
+            value,
+            precision,
+            scale,
+        },
+        Value::Decimal { .. } => {
+            return Err(unsupported_pivot_value(
+                "a decimal without precision or scale",
+            ))
+        }
+        Value::Null => return Err(unsupported_pivot_value("a null value")),
+        Value::List(_) => return Err(unsupported_pivot_value("an array 
value")),
+        Value::Map(_) => return Err(unsupported_pivot_value("a map value")),
+        Value::Struct(_) => return Err(unsupported_pivot_value("a struct 
value")),
+        Value::Variant { .. } => return Err(unsupported_pivot_value("a variant 
value")),
     };
-    Expression::literal(lit)
+    Ok(Expression::literal(lit))
+}
+
+/// The `UNSUPPORTED_OPERATION` error of a pivot on a value of `kind`, which 
has no literal.
+fn unsupported_pivot_value(kind: &str) -> SparkError {
+    SparkError::classed(
+        SparkErrorKind::NotImplementedError,
+        "UNSUPPORTED_OPERATION",
+        &[("operation", &format!("Pivot on {kind}"))],
+    )
 }
 
 /// Grouped data for performing aggregations.
@@ -122,9 +158,11 @@ impl GroupedData {
     /// Pivot on a column, optionally with explicit values 
(`GroupedData.pivot`).
     ///
     /// Mirrors `df.groupBy(...).pivot(col, values)`. When `values` is `None` 
the
-    /// server computes the distinct values; when supplied they are serialized 
as
+    /// server computes the distinct values; when supplied they are serialized 
as typed
     /// pivot-value literals. As PySpark's, only the grouping of `group_by` 
pivots: that of
     /// a rollup, a cube, grouping sets or a pivot is the error of 
[`GroupedData::check_pivot`].
+    /// A null, a nested value, or a decimal without its precision and scale 
is an
+    /// `UNSUPPORTED_OPERATION` error.
     pub fn pivot(
         &self,
         pivot_col: Column,
@@ -135,7 +173,7 @@ impl GroupedData {
             .unwrap_or_default()
             .into_iter()
             .map(value_to_lit_expr)
-            .collect();
+            .collect::<Result<_>>()?;
         Ok(GroupedData {
             dataframe: self.dataframe.clone(),
             group_cols: self.group_cols.clone(),
@@ -1048,6 +1086,101 @@ mod tests {
         }
     }
 
+    #[test]
+    fn pivot_values_are_typed_literals() {
+        use crate::row::Value;
+        use spark_connect_proto::{expression::literal::LiteralType, 
relation::RelType};
+        let values = vec![
+            Value::Binary(vec![1, 2]),
+            Value::Date(19723),
+            Value::Timestamp(1_704_067_200_000_000),
+            Value::TimestampNtz(1_704_067_200_000_000),
+            Value::Time(3_600_000_000_000),
+            Value::Decimal {
+                value: "1.50".to_string(),
+                precision: Some(5),
+                scale: Some(2),
+            },
+        ];
+        let expected = vec![
+            LiteralType::Binary(vec![1, 2].into()),
+            LiteralType::Date(19723),
+            LiteralType::Timestamp(1_704_067_200_000_000),
+            LiteralType::TimestampNtz(1_704_067_200_000_000),
+            LiteralType::Time(spark_connect_proto::expression::literal::Time {
+                nano: 3_600_000_000_000,
+                precision: Some(6),
+            }),
+            
LiteralType::Decimal(spark_connect_proto::expression::literal::Decimal {
+                value: "1.50".to_string(),
+                precision: Some(5),
+                scale: Some(2),
+            }),
+        ];
+        let frame = session().range(1).unwrap();
+        let pivot = frame
+            .group_by(vec![] as Vec<Column>)
+            .pivot(crate::column::col("value"), Some(values))
+            .unwrap()
+            .count();
+        let Some(RelType::Aggregate(aggregate)) = 
pivot.plan.to_proto().rel_type else {
+            panic!("expected Aggregate");
+        };
+        let literal_types: Vec<_> = aggregate
+            .pivot
+            .unwrap()
+            .values
+            .into_iter()
+            .map(|literal| literal.literal_type)
+            .collect();
+        assert_eq!(
+            literal_types,
+            expected.into_iter().map(Some).collect::<Vec<_>>()
+        );
+    }
+
+    #[test]
+    fn pivot_values_without_a_literal_are_unsupported() {
+        use crate::row::Value;
+        let frame = session().range(1).unwrap();
+        let cases = [
+            (Value::Null, "Pivot on a null value"),
+            (Value::List(vec![]), "Pivot on an array value"),
+            (Value::Map(vec![]), "Pivot on a map value"),
+            (
+                Value::Variant {
+                    value: vec![],
+                    metadata: vec![],
+                },
+                "Pivot on a variant value",
+            ),
+            (
+                Value::Decimal {
+                    value: "1.5".to_string(),
+                    precision: None,
+                    scale: Some(1),
+                },
+                "Pivot on a decimal without precision or scale",
+            ),
+        ];
+        for (value, operation) in cases {
+            let error = frame
+                .group_by(vec![] as Vec<Column>)
+                .pivot(crate::column::col("value"), Some(vec![value]))
+                .err()
+                .expect("an error");
+            assert_eq!(error.kind, SparkErrorKind::NotImplementedError);
+            assert_eq!(
+                error.get_condition().as_deref(),
+                Some("UNSUPPORTED_OPERATION")
+            );
+            assert_eq!(
+                error.get_message_parameters().unwrap()["operation"],
+                operation
+            );
+        }
+    }
+
     #[test]
     fn stat_crosstab_plan() {
         let spark = session();
diff --git a/crates/spark-connect/tests/e2e_dataframe.rs 
b/crates/spark-connect/tests/e2e_dataframe.rs
index 1f359d42..b94ec112 100644
--- a/crates/spark-connect/tests/e2e_dataframe.rs
+++ b/crates/spark-connect/tests/e2e_dataframe.rs
@@ -252,6 +252,70 @@ fn group_numeric_aggregates_follow_pyspark() {
     );
 }
 
+/// A pivot on a date, timestamp or decimal column takes typed values. The 
counts match those
+/// of PySpark 4.3.0 pivoting the same column on the same values as strings, 
which the server
+/// casts to the column's type.
+#[test]
+fn pivot_on_typed_values_matches_pyspark() {
+    use spark_connect::row::Value;
+    if !should_run() {
+        return;
+    }
+    let s = session();
+    let names = |names: &[&str]| names.iter().map(|n| 
n.to_string()).collect::<Vec<String>>();
+    let rows = |rows: &[&[&str]]| {
+        rows.iter()
+            .map(|r| r.iter().map(|v| v.to_string()).collect::<Vec<String>>())
+            .collect::<Vec<Vec<String>>>()
+    };
+    let counted = |df: &DataFrame, column: &str, value: Value| {
+        named_rows(
+            &df.group_by(vec![col("k")])
+                .pivot(col(column), Some(vec![value]))
+                .unwrap()
+                .count(),
+        )
+    };
+
+    let dates = s
+        .sql(
+            "SELECT * FROM VALUES (1, DATE'2024-01-01'), (1, 
DATE'2024-01-02'), \
+             (2, DATE'2024-01-01') AS t(k, d)",
+        )
+        .unwrap();
+    let (cols, got) = counted(&dates, "d", Value::Date(19723));
+    assert_eq!(cols, names(&["k", "2024-01-01"]));
+    assert_eq!(got, rows(&[&["1", "1"], &["2", "1"]]));
+
+    // Epoch seconds, so that the instants do not depend on the session time 
zone.
+    let stamps = s
+        .sql(
+            "SELECT * FROM VALUES (1, CAST(1704067200 AS TIMESTAMP)), \
+             (1, CAST(1704153600 AS TIMESTAMP)), (2, CAST(1704067200 AS 
TIMESTAMP)) AS t(k, ts)",
+        )
+        .unwrap();
+    let (_, got) = counted(&stamps, "ts", 
Value::Timestamp(1_704_067_200_000_000));
+    assert_eq!(got, rows(&[&["1", "1"], &["2", "1"]]));
+
+    let decimals = s
+        .sql(
+            "SELECT * FROM VALUES (1, CAST(1.50 AS DECIMAL(5,2))), \
+             (1, CAST(2.25 AS DECIMAL(5,2))), (2, CAST(1.50 AS DECIMAL(5,2))) 
AS t(k, dec)",
+        )
+        .unwrap();
+    let (cols, got) = counted(
+        &decimals,
+        "dec",
+        Value::Decimal {
+            value: "1.50".to_string(),
+            precision: Some(5),
+            scale: Some(2),
+        },
+    );
+    assert_eq!(cols, names(&["k", "1.50"]));
+    assert_eq!(got, rows(&[&["1", "1"], &["2", "1"]]));
+}
+
 #[test]
 fn dataframe_metadata_json_semantics() {
     if !should_run() {


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

Reply via email to