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 fbd1af84 [SPARK-61320][CONNECT] Keep the type of pivot values as their 
Spark literals, reject a NULL one, and reject a bad dropna how as PySpark does
fbd1af84 is described below

commit fbd1af8445e478d0cb36ab2af6aff40082047868
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Tue Nov 10 10:20:55 2026 +0900

    [SPARK-61320][CONNECT] Keep the type of pivot values as their Spark 
literals, reject a NULL one, and reject a bad dropna how as PySpark does
    
    ### What changes were proposed in this pull request?
    
    [SPARK-61320](https://issues.apache.org/jira/browse/SPARK-61320): Keep the 
type of pivot values as their Spark literals, reject a NULL pivot value, and 
reject a bad `how` in `DataFrame::dropna`, as PySpark does.
    
    - `GroupedData::pivot`: an explicit pivot value keeps its type. Date, 
timestamp, timestamp without time zone, time, binary and decimal values become 
the matching literals (a decimal without a precision or scale takes those of 
its text, as `BigDecimal` has them). Before, every such value other than a 
bool, number, string or interval was sent as the text of its Debug form 
("Date(18262)", "Null"). A NULL, list, map, struct or variant value is now 
`NOT_EXPECTED_TYPE` with the Python type  [...]
    - `DataFrame::dropna` and `NaFunctions::drop` now return 
`Result<DataFrame>`. `how` must be `"any"` or `"all"` (or `None`, which is 
`"any"`), else `VALUE_NOT_ALLOWED` with `['any', 'all']`, as PySpark's `dropna` 
raises. Before, any other value silently meant `"any"`. The drop-in now takes 
the core's check instead of its own copy of it; its results and errors are the 
same (checked against official 4.3.0 with `how` values of several types and 
with `thresh` and `subset` set). Callers in  [...]
    - The other string arguments of the core were checked against official 
4.3.0 and need no change: `corr` and `cov` take no method (only "pearson" 
exists), `explain_string` already checks its mode, and the join types, 
`nearestByJoin`, `asOfJoin`, `summary`, `outputMode` and the save mode are sent 
to the server as PySpark sends them.
    
    Official PySpark 4.3.0 rejects a date, timestamp or decimal pivot value on 
the client (`NOT_EXPECTED_TYPE`), so the Rust API can pivot on those values 
only through its own call; the server accepts them. The test compares that 
pivot with the one PySpark computes without values for the same data.
    
    ### Why are the changes needed?
    
    - A pivot on a date column with `Value::Date` values failed on the server 
with `CAST_INVALID_INPUT`, because the value was sent as the text 
`Date(18262)`. A NULL pivot value silently pivoted a string column on the text 
`Null`.
    - `dropna(Some("bogus"), None, None)` dropped every row with a NULL, as 
`"any"` does. PySpark raises `VALUE_NOT_ALLOWED` for it, and so does the 
drop-in.
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes, for the Rust API only. `DataFrame::dropna` and `NaFunctions::drop` 
return a `Result` (a call site needs `?` or `.unwrap()`). A pivot value of a 
date, timestamp, time, binary or decimal type pivots on that value, and a NULL 
pivot value is an error. The Python drop-in's results do not change.
    
    ### How was this patch tested?
    
    - Offline unit tests in `crates/spark-connect/src/group.rs` (`mod tests`, 
before `stat_crosstab_plan`): `pivot_values_keep_their_types_as_literals` 
checks the proto literal of each value type, including decimals with and 
without a precision and scale, and 
`a_null_or_a_nested_pivot_value_is_not_expected_type` checks the error of a 
NULL, list and map value.
    - Offline unit test in `crates/spark-connect/src/dataframe.rs` 
(`plan_construction_tests`, before `replace_literals_plan`): 
`dropna_takes_how_any_or_all_as_pyspark` checks that "any", "all" and no `how` 
are accepted and that `"ANY"`, `"all "`, `""` and `"some"` give 
`VALUE_NOT_ALLOWED` with and without `thresh`.
    - Live test in `crates/spark-connect/tests/e2e_dataframe.rs` (before 
`day_time_interval_input_roundtrips`): 
`pivot_values_of_dates_timestamps_and_decimals_match_discovered_pivots` checks 
that explicit date, timestamp and decimal pivot values give the same result as 
the discovered pivot of the same data, and that a NULL value and `how="bogus"` 
give the errors above. Official PySpark 4.3.0 on the same server and data: a 
NULL pivot value raises `NOT_EXPECTED_TYPE` with `arg_type` `NoneTy [...]
    - The existing live tests that call `dropna` and `na().drop` 
(`agg_na_stat_reshape_surface`, `na_reshape_execute`) pass with the new 
`Result`.
    - The lib tests (531 passed), the build of all tests, the offline Python 
suites (2927 passed, 8 skipped) with the rebuilt extension, and the live Rust 
tests `e2e_dataframe` (8 passed), `e2e_coverage -k agg_na_stat_reshape_surface` 
and `e2e_ops_breadth -k na_reshape_execute` against a local Spark 4.3.0 server. 
Clippy reports no new diagnostics in the changed lines.
    
    ### Was this patch authored or co-authored using generative AI tooling?
    
    Generated-by: Claude Opus 5.5
    
    This pull request and its description were written by Isaac.
    
    Closes #441 from HyukjinKwon/SPARK-61320-pivot-literals-dropna.
    
    Authored-by: Hyukjin Kwon <[email protected]>
    Signed-off-by: Hyukjin Kwon <[email protected]>
---
 crates/pyspark-rs/src/stat_arguments.rs       |  45 +++---
 crates/spark-connect/src/dataframe.rs         |  39 ++++-
 crates/spark-connect/src/group.rs             | 201 +++++++++++++++-----------
 crates/spark-connect/tests/e2e_coverage.rs    |   8 +-
 crates/spark-connect/tests/e2e_dataframe.rs   |  77 ++++++++++
 crates/spark-connect/tests/e2e_ops_breadth.rs |   6 +-
 6 files changed, 258 insertions(+), 118 deletions(-)

diff --git a/crates/pyspark-rs/src/stat_arguments.rs 
b/crates/pyspark-rs/src/stat_arguments.rs
index e3cd4210..8c6bdead 100644
--- a/crates/pyspark-rs/src/stat_arguments.rs
+++ b/crates/pyspark-rs/src/stat_arguments.rs
@@ -79,41 +79,38 @@ fn column_refs(columns: &[String]) -> Option<Vec<&str>> {
     (!columns.is_empty()).then(|| columns.iter().map(String::as_str).collect())
 }
 
-/// `df.dropna(how, thresh, subset)` and `df.na.drop`, as PySpark's: `how` is 
"any" or "all",
-/// else `VALUE_NOT_ALLOWED`, `thresh`, an int, overrides it, and `subset` is 
a column name,
-/// or a list or tuple of them.
+/// `df.dropna(how, thresh, subset)` and `df.na.drop`, as PySpark's: `how` is 
a str, which the core
+/// checks to be "any" or "all", else `VALUE_NOT_ALLOWED`, `thresh`, an int, 
overrides it, and
+/// `subset` is a column name, or a list or tuple of them.
 pub(crate) fn dropna(
     df: &DataFrame,
     how: Option<&Bound<'_, PyAny>>,
     thresh: Option<&Bound<'_, PyAny>>,
     subset: Option<&Bound<'_, PyAny>>,
 ) -> PyResult<PyDataFrame> {
-    let mut how_name = "any";
-    if let Some(how) = how {
-        match string_argument(how, "how")?.as_str() {
-            "all" => how_name = "all",
-            "any" => {}
-            _ => {
-                return Err(raise_pyspark(
-                    how.py(),
-                    "PySparkValueError",
-                    "VALUE_NOT_ALLOWED",
-                    &[("arg_name", "how"), ("allowed_values", "['any', 
'all']")],
-                ))
-            }
-        }
-    }
+    let how = how.map(|how| string_argument(how, "how")).transpose()?;
+    // PySpark checks `how` before `thresh` and `subset`, so the core's error 
of `how` comes first.
+    let parsed = dropna_thresh_and_subset(thresh, subset);
+    let (thresh, columns) = match &parsed {
+        Ok((thresh, columns)) => (*thresh, column_refs(columns)),
+        Err(_) => (None, None),
+    };
+    let dataframe = df.dropna(how.as_deref(), thresh, columns).to_pyerr()?;
+    parsed?;
+    Ok(PyDataFrame::new(dataframe))
+}
+
+/// The `thresh` and the `subset` of `dropna`, checked as PySpark's.
+fn dropna_thresh_and_subset(
+    thresh: Option<&Bound<'_, PyAny>>,
+    subset: Option<&Bound<'_, PyAny>>,
+) -> PyResult<(Option<i32>, Vec<String>)> {
     let thresh = match thresh {
         None => None,
         Some(thresh) if thresh.is_instance_of::<PyInt>() => 
Some(thresh.extract::<i32>()?),
         Some(thresh) => return Err(not_expected_type(thresh, "thresh", "int")),
     };
-    let columns = subset_columns(subset, "list, str or tuple")?;
-    Ok(PyDataFrame::new(df.dropna(
-        Some(how_name),
-        thresh,
-        column_refs(&columns),
-    )))
+    Ok((thresh, subset_columns(subset, "list, str or tuple")?))
 }
 
 /// `df.fillna(value, subset)` and `df.na.fill`, as PySpark's: `value` is a 
bool, an int, a
diff --git a/crates/spark-connect/src/dataframe.rs 
b/crates/spark-connect/src/dataframe.rs
index a232bba6..878ab9f3 100644
--- a/crates/spark-connect/src/dataframe.rs
+++ b/crates/spark-connect/src/dataframe.rs
@@ -1800,14 +1800,24 @@ impl DataFrame {
         DataFrame::new(self.session.clone(), plan)
     }
 
-    /// Drop NA values.
+    /// Drop NA values. Mirrors `DataFrame.dropna`: `how` is "any" (the 
default) or "all", else
+    /// a `VALUE_NOT_ALLOWED` error, as PySpark's; `thresh` overrides it.
     pub fn dropna(
         &self,
         how: Option<&str>,
         thresh: Option<i32>,
         subset: Option<Vec<&str>>,
-    ) -> DataFrame {
-        let how_str = how.unwrap_or("any").to_string();
+    ) -> Result<DataFrame> {
+        let how_str = match how {
+            None | Some("any") => "any",
+            Some("all") => "all",
+            Some(_) => {
+                return Err(SparkError::value(
+                    "VALUE_NOT_ALLOWED",
+                    &[("arg_name", "how"), ("allowed_values", "['any', 
'all']")],
+                ))
+            }
+        };
         let columns = subset
             .map(|v| v.iter().map(|s| s.to_string()).collect())
             .unwrap_or_default();
@@ -1815,11 +1825,11 @@ impl DataFrame {
         // and `thresh` in `NADrop::to_proto` (mirrors pyspark's translation).
         let plan = LogicalPlan::NADrop {
             input: Arc::clone(&self.plan),
-            how: how_str,
+            how: how_str.to_string(),
             min_non_null: thresh,
             columns,
         };
-        DataFrame::new(self.session.clone(), plan)
+        Ok(DataFrame::new(self.session.clone(), plan))
     }
 
     /// Replace values, each given as a string: a numeric-looking string is a 
double, otherwise
@@ -4837,6 +4847,25 @@ mod plan_construction_tests {
         }
     }
 
+    #[test]
+    fn dropna_takes_how_any_or_all_as_pyspark() {
+        let df = session().range(1).unwrap();
+        for how in [None, Some("any"), Some("all")] {
+            assert!(df.dropna(how, None, None).is_ok());
+            assert!(df.na().drop(how, Some(1), None).is_ok());
+        }
+        // A bad `how` is rejected even when `thresh` would override it, as 
PySpark's.
+        for how in ["ANY", "all ", "", "some"] {
+            for thresh in [None, Some(1)] {
+                let err = df.dropna(Some(how), thresh, None).err().expect("an 
error");
+                assert_eq!(err.get_condition().as_deref(), 
Some("VALUE_NOT_ALLOWED"));
+                let parameters = err.get_message_parameters().unwrap();
+                assert_eq!(parameters["arg_name"], "how");
+                assert_eq!(parameters["allowed_values"], "['any', 'all']");
+            }
+        }
+    }
+
     #[test]
     fn replace_literals_plan() {
         use crate::expression::LiteralExpression;
diff --git a/crates/spark-connect/src/group.rs 
b/crates/spark-connect/src/group.rs
index 506cdd28..4bd45706 100644
--- a/crates/spark-connect/src/group.rs
+++ b/crates/spark-connect/src/group.rs
@@ -13,14 +13,14 @@ use crate::plan::{AggregateGroupType, LogicalPlan};
 use crate::types::DataType;
 use crate::udf::CommonInlineUserDefinedFunctionExpression;
 
-/// 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.
+/// Convert a [`crate::row::Value`] into a literal [`Expression`] of a pivot 
value. Each value
+/// keeps its own type, as the literal of Spark's pivot, and a NULL is an 
error, as PySpark's
+/// `GroupedData.pivot` rejects a None.
 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 {
+        Value::Null => return Err(not_a_pivot_value("NoneType")),
         Value::Bool(b) => L::boolean(b),
         Value::Byte(x) => L::int(x as i32),
         Value::Short(x) => L::int(x as i32),
@@ -30,44 +30,72 @@ fn value_to_lit_expr(v: crate::row::Value) -> 
Result<Expression> {
         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::Date(d) => L::Date(d),
+        Value::Timestamp(t) => L::Timestamp(t),
+        Value::TimestampNtz(t) => L::TimestampNtz(t),
+        // `TimeType()` of PySpark has a precision of 6.
         Value::Time(nano) => L::Time { nano, precision: 6 },
         Value::DayTimeInterval(v) => L::DayTimeInterval(v),
         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",
-            ))
+        } => {
+            let (precision, scale) = match (precision, scale) {
+                (Some(precision), Some(scale)) => (precision, scale),
+                // As a decimal of the text: its digits and fraction, as 
`Decimal(text)` of Spark.
+                _ => decimal_type_of_text(&value),
+            };
+            L::Decimal {
+                value,
+                precision,
+                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")),
+        Value::List(_) => return Err(not_a_pivot_value("list")),
+        Value::Map(_) => return Err(not_a_pivot_value("dict")),
+        Value::Struct(_) => return Err(not_a_pivot_value("Row")),
+        Value::Variant { .. } => return Err(not_a_pivot_value("Variant")),
     };
     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 {
+/// The `NOT_EXPECTED_TYPE` error of a pivot value of the type `arg_type`, 
which PySpark's
+/// `GroupedData.pivot` rejects (its values are bools, floats, ints and strs), 
named as Python names it.
+fn not_a_pivot_value(arg_type: &str) -> SparkError {
     SparkError::classed(
-        SparkErrorKind::NotImplementedError,
-        "UNSUPPORTED_OPERATION",
-        &[("operation", &format!("Pivot on {kind}"))],
+        SparkErrorKind::TypeError,
+        "NOT_EXPECTED_TYPE",
+        &[
+            ("arg_name", "value"),
+            ("expected_type", "bool, float, int or str"),
+            ("arg_type", arg_type),
+        ],
     )
 }
 
+/// The precision and scale of a decimal text, such as `"1.50"` (3 and 2) or 
`"1E+3"` (1 and -3),
+/// as Java's `BigDecimal` of the text has them. Text that is not a decimal 
gives `(10, 0)`, and
+/// the server rejects it.
+fn decimal_type_of_text(text: &str) -> (i32, i32) {
+    let (mantissa, exponent) = match text.split_once(['e', 'E']) {
+        Some((mantissa, exponent)) => (mantissa, exponent.parse::<i32>().ok()),
+        None => (text, Some(0)),
+    };
+    let Some(exponent) = exponent else {
+        return (10, 0);
+    };
+    let unsigned = mantissa.trim_start_matches(['-', '+']);
+    let (int_part, frac_part) = unsigned.split_once('.').unwrap_or((unsigned, 
""));
+    let digits = format!("{int_part}{frac_part}");
+    if !digits.bytes().all(|b| b.is_ascii_digit()) || digits.is_empty() {
+        return (10, 0);
+    }
+    let unscaled = digits.trim_start_matches('0');
+    let precision = unscaled.len().max(1) as i32;
+    (precision, frac_part.len() as i32 - exponent)
+}
+
 /// Grouped data for performing aggregations.
 ///
 /// Mirrors `pyspark.sql.GroupedData`.
@@ -158,11 +186,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 typed
+    /// server computes the distinct values; when supplied they are serialized 
as
     /// 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.
+    /// A value of the explicit `values` keeps its type as a literal. A NULL, 
or a list, map or
+    /// struct, is `NOT_EXPECTED_TYPE`, as PySpark rejects it.
     pub fn pivot(
         &self,
         pivot_col: Column,
@@ -682,13 +710,14 @@ impl NaFunctions {
         NaFunctions { dataframe }
     }
 
-    /// Drop rows containing null values. Mirrors `DataFrameNaFunctions.drop`.
+    /// Drop rows containing null values. Mirrors `DataFrameNaFunctions.drop`; 
see
+    /// [`DataFrame::dropna`] for `how`.
     pub fn drop(
         &self,
         how: Option<&str>,
         thresh: Option<i32>,
         subset: Option<Vec<&str>>,
-    ) -> DataFrame {
+    ) -> Result<DataFrame> {
         self.dataframe.dropna(how, thresh, subset)
     }
 
@@ -1087,35 +1116,31 @@ mod tests {
     }
 
     #[test]
-    fn pivot_values_are_typed_literals() {
+    fn pivot_values_keep_their_types_as_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::Date(18262),
+            Value::Timestamp(1_577_836_800_000_000),
+            Value::TimestampNtz(1_577_836_800_000_000),
             Value::Time(3_600_000_000_000),
+            Value::Binary(vec![1, 2]),
             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),
-            }),
+            // Without a precision and a scale, those of the text: as 
`BigDecimal` has them.
+            Value::Decimal {
+                value: "-0.05".to_string(),
+                precision: None,
+                scale: None,
+            },
+            Value::Decimal {
+                value: "1E+3".to_string(),
+                precision: None,
+                scale: None,
+            },
         ];
         let frame = session().range(1).unwrap();
         let pivot = frame
@@ -1126,58 +1151,60 @@ mod tests {
         let Some(RelType::Aggregate(aggregate)) = 
pivot.plan.to_proto().rel_type else {
             panic!("expected Aggregate");
         };
-        let literal_types: Vec<_> = aggregate
+        let literals: Vec<_> = aggregate
             .pivot
             .unwrap()
             .values
             .into_iter()
             .map(|literal| literal.literal_type)
             .collect();
+        let decimal = |value: &str, precision, scale| {
+            Some(LiteralType::Decimal(
+                spark_connect_proto::expression::literal::Decimal {
+                    value: value.to_string(),
+                    precision: Some(precision),
+                    scale: Some(scale),
+                },
+            ))
+        };
+        assert_eq!(literals[0], Some(LiteralType::Date(18262)));
+        assert_eq!(
+            literals[1],
+            Some(LiteralType::Timestamp(1_577_836_800_000_000))
+        );
         assert_eq!(
-            literal_types,
-            expected.into_iter().map(Some).collect::<Vec<_>>()
+            literals[2],
+            Some(LiteralType::TimestampNtz(1_577_836_800_000_000))
         );
+        assert!(matches!(
+            literals[3],
+            Some(LiteralType::Time(ref time)) if time.nano == 
3_600_000_000_000 && time.precision == Some(6)
+        ));
+        assert_eq!(literals[4], Some(LiteralType::Binary(vec![1, 2].into())));
+        assert_eq!(literals[5], decimal("1.50", 5, 2));
+        assert_eq!(literals[6], decimal("-0.05", 1, 2));
+        assert_eq!(literals[7], decimal("1E+3", 1, -3));
     }
 
     #[test]
-    fn pivot_values_without_a_literal_are_unsupported() {
+    fn a_null_or_a_nested_pivot_value_is_not_expected_type() {
         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
+        for (value, arg_type) in [
+            (Value::Null, "NoneType"),
+            (Value::List(vec![]), "list"),
+            (Value::Map(vec![]), "dict"),
+        ] {
+            let err = 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
-            );
+            assert_eq!(err.kind, SparkErrorKind::TypeError);
+            assert_eq!(err.get_condition().as_deref(), 
Some("NOT_EXPECTED_TYPE"));
+            let parameters = err.get_message_parameters().unwrap();
+            assert_eq!(parameters["arg_name"], "value");
+            assert_eq!(parameters["arg_type"], arg_type);
         }
     }
 
diff --git a/crates/spark-connect/tests/e2e_coverage.rs 
b/crates/spark-connect/tests/e2e_coverage.rs
index 53c77e05..a5a059fa 100644
--- a/crates/spark-connect/tests/e2e_coverage.rs
+++ b/crates/spark-connect/tests/e2e_coverage.rs
@@ -490,7 +490,12 @@ fn agg_na_stat_reshape_surface() {
         .collect();
 
     // na
-    let _ = df.na().drop(Some("any"), None, None).collect().unwrap();
+    let _ = df
+        .na()
+        .drop(Some("any"), None, None)
+        .unwrap()
+        .collect()
+        .unwrap();
     let _ = df.na().fill(0, None).collect().unwrap();
     let _ = df
         .na()
@@ -500,6 +505,7 @@ fn agg_na_stat_reshape_surface() {
     let _ = df.fillna(0, Some(vec!["val"])).collect().unwrap();
     let _ = df
         .dropna(Some("all"), Some(1), Some(vec!["name"]))
+        .unwrap()
         .collect()
         .unwrap();
     let _ = df
diff --git a/crates/spark-connect/tests/e2e_dataframe.rs 
b/crates/spark-connect/tests/e2e_dataframe.rs
index 2e97489a..02b81252 100644
--- a/crates/spark-connect/tests/e2e_dataframe.rs
+++ b/crates/spark-connect/tests/e2e_dataframe.rs
@@ -368,6 +368,83 @@ fn dataframe_metadata_json_semantics() {
     assert_eq!(parts.len(), 2);
 }
 
+/// `GroupedData.pivot` takes explicit values of the types of the Spark 
literals, dates,
+/// timestamps and decimals too: they give the columns of the pivot without 
values, which PySpark
+/// computes for the same data. PySpark itself rejects those types as values 
(NOT_EXPECTED_TYPE),
+/// and a NULL value, as it does; `dropna` rejects a `how` other than "any" or 
"all"
+/// (VALUE_NOT_ALLOWED), as PySpark does.
+#[test]
+fn pivot_values_of_dates_timestamps_and_decimals_match_discovered_pivots() {
+    if !should_run() {
+        return;
+    }
+    use spark_connect::row::Value;
+    let s = session();
+    let df = s
+        .sql(
+            "SELECT * FROM VALUES (DATE'2020-01-01', TIMESTAMP'2020-01-01 
00:00:00', \
+             CAST(1.50 AS DECIMAL(5,2)), 'a', 1), \
+             (DATE'2020-01-02', TIMESTAMP'2020-01-02 00:00:00', CAST(2.00 AS 
DECIMAL(5,2)), 'b', 2) \
+             AS t(d, ts, dec, k, v)",
+        )
+        .unwrap();
+    let pivot = |column: &str, values: Option<Vec<Value>>| {
+        named_rows(
+            &df.group_by(vec![col("k")])
+                .pivot(col(column), values)
+                .unwrap()
+                .sum(vec!["v"])
+                .unwrap(),
+        )
+    };
+    let decimal = |value: &str| Value::Decimal {
+        value: value.to_string(),
+        precision: Some(5),
+        scale: Some(2),
+    };
+    // Days since the epoch of 2020-01-01 and 2020-01-02, and their micros in 
UTC.
+    assert_eq!(
+        pivot("d", Some(vec![Value::Date(18262), Value::Date(18263)])),
+        pivot("d", None)
+    );
+    assert_eq!(
+        pivot(
+            "ts",
+            Some(vec![
+                Value::Timestamp(1_577_836_800_000_000),
+                Value::Timestamp(1_577_923_200_000_000),
+            ])
+        ),
+        pivot("ts", None)
+    );
+    assert_eq!(
+        pivot("dec", Some(vec![decimal("1.50"), decimal("2.00")])),
+        pivot("dec", None)
+    );
+    let err = df
+        .group_by(vec![col("k")])
+        .pivot(col("k"), Some(vec![Value::Null]))
+        .err()
+        .expect("an error");
+    assert_eq!(err.get_condition().as_deref(), Some("NOT_EXPECTED_TYPE"));
+    assert_eq!(
+        err.get_message_parameters().unwrap()["arg_type"],
+        "NoneType"
+    );
+
+    // As PySpark's `dropna(how="bogus")`.
+    for how in ["bogus", "ANY"] {
+        let err = df.dropna(Some(how), None, None).err().expect("an error");
+        assert_eq!(err.get_condition().as_deref(), Some("VALUE_NOT_ALLOWED"));
+        assert_eq!(err.get_message_parameters().unwrap()["arg_name"], "how");
+        assert!(df.na().drop(Some(how), None, None).is_err());
+    }
+    assert_eq!(
+        df.dropna(Some("all"), None, None).unwrap().count().unwrap(),
+        2
+    );
+}
+
 #[test]
 fn day_time_interval_input_roundtrips() {
     if !should_run() {
diff --git a/crates/spark-connect/tests/e2e_ops_breadth.rs 
b/crates/spark-connect/tests/e2e_ops_breadth.rs
index 3af3d618..e6e8628b 100644
--- a/crates/spark-connect/tests/e2e_ops_breadth.rs
+++ b/crates/spark-connect/tests/e2e_ops_breadth.rs
@@ -213,7 +213,11 @@ fn na_reshape_execute() {
     let _ = df.fillna(0, Some(vec!["id"])).collect().unwrap();
     let _ = df.fillna_double(0.0, Some(vec!["v"])).collect().unwrap();
     let _ = df.fillna_string("x", Some(vec!["name"])).collect().unwrap();
-    let _ = df.dropna(Some("any"), None, None).collect().unwrap();
+    let _ = df
+        .dropna(Some("any"), None, None)
+        .unwrap()
+        .collect()
+        .unwrap();
     let _ = df
         .replace(vec![("a".to_string(), "A".to_string())], Some(vec!["name"]))
         .collect()


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

Reply via email to