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 ef2ddf5f [SPARK-61473][CONNECT][PYTHON] Raise PySpark's errors for the
operands that Column operators and methods do not take, in the Python client
ef2ddf5f is described below
commit ef2ddf5f13691998dd85a0ee87f3db463d363097
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Thu Nov 12 09:46:52 2026 +0900
[SPARK-61473][CONNECT][PYTHON] Raise PySpark's errors for the operands that
Column operators and methods do not take, in the Python client
### What changes were proposed in this pull request?
The Column operators and methods of the Python client now take their
operand as PySpark's `_bin_op` does, and raise PySpark's errors for the rest:
- An operand of `+ - * / %`, their reverse forms, `**` (both ways), the
comparisons, `&`, `|`, `between`, `eqNullSafe`, `bitwiseAND`/`OR`/`XOR`,
`contains`, `startswith`, `endswith`, `like`, `rlike` and `ilike` is a Column,
or a literal of the types `_bin_op` takes after `enum_to_value`: None, bool,
int, float, str, date, time, datetime, timedelta or Decimal (`__eq__` takes no
timedelta, as PySpark's `Column.__eq__`). For any other operand, the client
looks up its `_expr`, as PySpark [...]
- `Column.otherwise`, `Column.when`, `isin`, `getItem` and `__getitem__`
raise `PySparkTypeError [UNSUPPORTED_DATA_TYPE]` for a NumPy array, as
PySpark's `LiteralExpression._from_value` does. `lit` and `functions.when`
still take one, as PySpark's do.
### Why are the changes needed?
The drop-in turned operands that PySpark rejects into literals, or raised a
different error. A probe of 14 operator families against 16 kinds of operand
gave these differences with PySpark 4.3.0:
```python
F.col("a") + [2] # before: +(a, array(2)), which the server
rejects later
F.col("a") == b"x" # before: a binary literal
F.col("a") == np.int64(2) # before: a literal (np.int64 is not an int, so
PySpark rejects it)
F.col("a") + (2,) # before: PySparkTypeError
[UNSUPPORTED_DATA_TYPE] `tuple`
# PySpark 4.3.0, each: AttributeError: '<type>' object has no attribute
'_expr'
F.col("id").isin(np.array([0, 1])) # before: an AnalysisException from
the server
F.when(c, 1).otherwise(np.array([1, 2])) # before: an array literal
# PySpark 4.3.0: PySparkTypeError [UNSUPPORTED_DATA_TYPE] Unsupported
DataType `ndarray`.
```
A program that worked on the drop-in failed on PySpark. After this change,
the probe gives no difference.
### Does this PR introduce _any_ user-facing change?
Yes. These operands are now rejected with PySpark's error, as above. The
operands that PySpark takes, including `np.float64`, which is a float, and Enum
members, build the same expressions as before.
### How was this patch tested?
- Three new offline tests in `python/tests/test_dropin_offline.py`:
`test_column_operators_take_their_operands_as_pyspark` (each rejected kind for
every operator family),
`test_column_operators_take_the_literals_that_pyspark_takes` (each accepted
kind, including the `==`/`!=` timedelta difference), and
`test_column_value_methods_take_no_numpy_array_as_pyspark`. They fail without
this change and pass with it.
- The operator probe (224 cases) and the literal probe match PySpark 4.3.0.
- The offline suites (`test_dropin_offline.py`, `test_ml_offline.py` and
`test_arrow_handoff.py`, 3137 passed), the e2e suites against a Spark 4.3.0
server (`test_dropin_e2e.py`, `test_arrow_e2e.py` and `test_ml_e2e.py`, 291
passed), the Rust library tests, the `--no-run` builds (with and without
`wasm-udf`), `cargo fmt --check`, `scripts/audit_no_stubs.sh` and the ruff
gates.
### 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 #534 from HyukjinKwon/SPARK-61473-column-operands.
Authored-by: Hyukjin Kwon <[email protected]>
Signed-off-by: Hyukjin Kwon <[email protected]>
---
crates/pyspark-rs/src/column.rs | 126 ++++++++++++++++++++++++++----------
crates/pyspark-rs/src/functions.rs | 9 +++
python/tests/test_dropin_offline.py | 115 ++++++++++++++++++++++++++++++++
3 files changed, 215 insertions(+), 35 deletions(-)
diff --git a/crates/pyspark-rs/src/column.rs b/crates/pyspark-rs/src/column.rs
index fe22b0f5..49f2fc7c 100644
--- a/crates/pyspark-rs/src/column.rs
+++ b/crates/pyspark-rs/src/column.rs
@@ -8,12 +8,12 @@ use spark_connect::expression::{Alias, ExpressionNode,
NullOrdering};
use crate::errors::{not_expected_type, ResultExt};
// Re-exported for the modules that raise through
`crate::column::raise_pyspark`.
pub(crate) use crate::errors::raise_pyspark;
-use crate::functions::{to_column, to_value_column};
+use crate::functions::{enum_to_value, to_column, to_value_column};
/// The function `name` of `column` and `other`, a Column or a literal value,
as PySpark's
/// `_bin_op`.
fn binary_function(name: &str, column: &Column, other: &Bound<'_, PyAny>) ->
PyResult<PyColumn> {
- let other = to_column(other)?;
+ let other = operand_column(other)?;
Ok(PyColumn::new(Column::new(
spark_connect::expression::Expression::function(
name,
@@ -59,6 +59,62 @@ fn py_obj_to_column(obj: &Bound<'_, PyAny>) ->
PyResult<Column> {
to_column(obj)
}
+/// The Column of an operand of a binary operator, as PySpark's `_bin_op`
takes it: a Column, or
+/// a literal (see `is_literal_operand`). Another object is looked up for its
`_expr`, as PySpark
+/// does, so that its AttributeError, or a Row's PySparkAttributeError, is the
one it raises.
+fn operand_column(obj: &Bound<'_, PyAny>) -> PyResult<Column> {
+ operand(obj, true)
+}
+
+/// The Column of the operand of `__eq__`, as PySpark's `Column.__eq__` takes
it: as `_bin_op`,
+/// but without timedelta, which `__eq__` does not take as a literal.
+fn equality_operand_column(obj: &Bound<'_, PyAny>) -> PyResult<Column> {
+ operand(obj, false)
+}
+
+fn operand(obj: &Bound<'_, PyAny>, with_timedelta: bool) -> PyResult<Column> {
+ // The literal is converted from the object itself, as `to_column` takes
an Enum's value.
+ let value = enum_to_value(obj)?;
+ if obj.is_instance_of::<PyColumn>() || is_literal_operand(&value,
with_timedelta)? {
+ return to_column(obj);
+ }
+ // The `_expr` of PySpark's operand: an object that has none raises its
lookup's error here.
+ value.getattr("_expr")?;
+ // An object with an `_expr` is an expression of PySpark's, which this
client does not take.
+ let type_name = value.get_type().name()?.to_string();
+ Err(raise_pyspark(
+ value.py(),
+ "PySparkTypeError",
+ "UNSUPPORTED_DATA_TYPE",
+ &[("data_type", &type_name)],
+ ))
+}
+
+/// Whether `value` is a literal of PySpark's `_bin_op`, by isinstance: None,
or an instance of
+/// int (a bool too), float (a NumPy float64 too), str, date, time, datetime,
timedelta (unless
+/// `with_timedelta` is false) or Decimal. A NumPy int64 or bool_ is not one.
+fn is_literal_operand(value: &Bound<'_, PyAny>, with_timedelta: bool) ->
PyResult<bool> {
+ if value.is_none()
+ || value.is_instance_of::<pyo3::types::PyInt>()
+ || value.is_instance_of::<pyo3::types::PyFloat>()
+ || value.is_instance_of::<pyo3::types::PyString>()
+ {
+ return Ok(true);
+ }
+ let py = value.py();
+ let datetime = py.import("datetime")?;
+ let mut types = vec![
+ datetime.getattr("date")?,
+ datetime.getattr("time")?,
+ datetime.getattr("datetime")?,
+ ];
+ if with_timedelta {
+ types.push(datetime.getattr("timedelta")?);
+ }
+ types.push(py.import("decimal")?.getattr("Decimal")?);
+ value.is_instance(pyo3::types::PyTuple::new(py, types)?.as_any())
+}
+
/// The expression of a Column, as PySpark Connect's `Column._expr`: its `str`
and `repr` are
/// its rendering, as `Column<'...'>` shows it, and its `to_plan` its
`spark.connect.Expression`.
/// The expressions of PySpark Connect are those of
`pyspark.sql.connect.expressions`, of which
@@ -327,21 +383,21 @@ impl PyColumn {
/// Check if contains another column value.
fn contains(&self, other: &Bound<'_, PyAny>) -> PyResult<PyColumn> {
let _origin = crate::origin::with_origin("contains");
- let other_col = py_obj_to_column(other)?;
+ let other_col = operand_column(other)?;
Ok(PyColumn::new(self.column.clone().contains(other_col)))
}
/// Check if starts with another column value.
fn startswith(&self, other: &Bound<'_, PyAny>) -> PyResult<PyColumn> {
let _origin = crate::origin::with_origin("startswith");
- let other_col = py_obj_to_column(other)?;
+ let other_col = operand_column(other)?;
Ok(PyColumn::new(self.column.clone().startswith(other_col)))
}
/// Check if ends with another column value.
fn endswith(&self, other: &Bound<'_, PyAny>) -> PyResult<PyColumn> {
let _origin = crate::origin::with_origin("endswith");
- let other_col = py_obj_to_column(other)?;
+ let other_col = operand_column(other)?;
Ok(PyColumn::new(self.column.clone().endswith(other_col)))
}
@@ -485,42 +541,42 @@ impl PyColumn {
/// Equality (==) - returns a Column condition
fn __eq__(&self, py: Python<'_>, other: Py<PyAny>) -> PyResult<PyColumn> {
let _origin = crate::origin::with_origin("__eq__");
- let other_col = to_column(&other.bind(py))?;
+ let other_col = equality_operand_column(other.bind(py))?;
Ok(PyColumn::new(self.column.clone().eq(other_col)))
}
/// Inequality (!=) - returns a Column condition
fn __ne__(&self, py: Python<'_>, other: Py<PyAny>) -> PyResult<PyColumn> {
let _origin = crate::origin::with_origin("__ne__");
- let other_col = to_column(&other.bind(py))?;
+ let other_col = operand_column(other.bind(py))?;
Ok(PyColumn::new(self.column.clone().ne(other_col)))
}
/// Greater than (>) - returns a Column condition
fn __gt__(&self, py: Python<'_>, other: Py<PyAny>) -> PyResult<PyColumn> {
let _origin = crate::origin::with_origin("__gt__");
- let other_col = to_column(&other.bind(py))?;
+ let other_col = operand_column(other.bind(py))?;
Ok(PyColumn::new(self.column.clone().gt(other_col)))
}
/// Less than (<) - returns a Column condition
fn __lt__(&self, py: Python<'_>, other: Py<PyAny>) -> PyResult<PyColumn> {
let _origin = crate::origin::with_origin("__lt__");
- let other_col = to_column(&other.bind(py))?;
+ let other_col = operand_column(other.bind(py))?;
Ok(PyColumn::new(self.column.clone().lt(other_col)))
}
/// Greater than or equal (>=) - returns a Column condition
fn __ge__(&self, py: Python<'_>, other: Py<PyAny>) -> PyResult<PyColumn> {
let _origin = crate::origin::with_origin("__ge__");
- let other_col = to_column(&other.bind(py))?;
+ let other_col = operand_column(other.bind(py))?;
Ok(PyColumn::new(self.column.clone().ge(other_col)))
}
/// Less than or equal (<=) - returns a Column condition
fn __le__(&self, py: Python<'_>, other: Py<PyAny>) -> PyResult<PyColumn> {
let _origin = crate::origin::with_origin("__le__");
- let other_col = to_column(&other.bind(py))?;
+ let other_col = operand_column(other.bind(py))?;
Ok(PyColumn::new(self.column.clone().le(other_col)))
}
@@ -528,49 +584,49 @@ impl PyColumn {
/// Addition (+)
fn __add__(&self, py: Python<'_>, other: Py<PyAny>) -> PyResult<PyColumn> {
let _origin = crate::origin::with_origin("__add__");
- let other_col = to_column(&other.bind(py))?;
+ let other_col = operand_column(other.bind(py))?;
Ok(PyColumn::new(self.column.clone().add(other_col)))
}
/// Right addition (for reverse operations)
fn __radd__(&self, py: Python<'_>, other: Py<PyAny>) -> PyResult<PyColumn>
{
let _origin = crate::origin::with_origin("__radd__");
- let other_col = to_column(&other.bind(py))?;
+ let other_col = operand_column(other.bind(py))?;
Ok(PyColumn::new(other_col.add(self.column.clone())))
}
/// Subtraction (-)
fn __sub__(&self, py: Python<'_>, other: Py<PyAny>) -> PyResult<PyColumn> {
let _origin = crate::origin::with_origin("__sub__");
- let other_col = to_column(&other.bind(py))?;
+ let other_col = operand_column(other.bind(py))?;
Ok(PyColumn::new(self.column.clone().sub(other_col)))
}
/// Right subtraction (for reverse operations)
fn __rsub__(&self, py: Python<'_>, other: Py<PyAny>) -> PyResult<PyColumn>
{
let _origin = crate::origin::with_origin("__rsub__");
- let other_col = to_column(&other.bind(py))?;
+ let other_col = operand_column(other.bind(py))?;
Ok(PyColumn::new(other_col.sub(self.column.clone())))
}
/// Multiplication (*)
fn __mul__(&self, py: Python<'_>, other: Py<PyAny>) -> PyResult<PyColumn> {
let _origin = crate::origin::with_origin("__mul__");
- let other_col = to_column(&other.bind(py))?;
+ let other_col = operand_column(other.bind(py))?;
Ok(PyColumn::new(self.column.clone().mul(other_col)))
}
/// Right multiplication (for reverse operations)
fn __rmul__(&self, py: Python<'_>, other: Py<PyAny>) -> PyResult<PyColumn>
{
let _origin = crate::origin::with_origin("__rmul__");
- let other_col = to_column(&other.bind(py))?;
+ let other_col = operand_column(other.bind(py))?;
Ok(PyColumn::new(other_col.mul(self.column.clone())))
}
/// Division (/)
fn __truediv__(&self, py: Python<'_>, other: Py<PyAny>) ->
PyResult<PyColumn> {
let _origin = crate::origin::with_origin("__truediv__");
- let other_col = to_column(&other.bind(py))?;
+ let other_col = operand_column(other.bind(py))?;
Ok(PyColumn::new(self.column.clone().div(other_col)))
}
@@ -578,14 +634,14 @@ impl PyColumn {
/// calls: as `__truediv__`.
fn __div__(&self, py: Python<'_>, other: Py<PyAny>) -> PyResult<PyColumn> {
let _origin = crate::origin::with_origin("__div__");
- let other_col = to_column(&other.bind(py))?;
+ let other_col = operand_column(other.bind(py))?;
Ok(PyColumn::new(self.column.clone().div(other_col)))
}
/// Modulo (%)
fn __mod__(&self, py: Python<'_>, other: Py<PyAny>) -> PyResult<PyColumn> {
let _origin = crate::origin::with_origin("__mod__");
- let other_col = to_column(&other.bind(py))?;
+ let other_col = operand_column(other.bind(py))?;
Ok(PyColumn::new(self.column.clone().modulo(other_col)))
}
@@ -593,14 +649,14 @@ impl PyColumn {
/// Bitwise AND (&) - logical AND in Spark
fn __and__(&self, py: Python<'_>, other: Py<PyAny>) -> PyResult<PyColumn> {
let _origin = crate::origin::with_origin("__and__");
- let other_col = to_column(&other.bind(py))?;
+ let other_col = operand_column(other.bind(py))?;
Ok(PyColumn::new(self.column.clone().and(other_col)))
}
/// Bitwise OR (|) - logical OR in Spark
fn __or__(&self, py: Python<'_>, other: Py<PyAny>) -> PyResult<PyColumn> {
let _origin = crate::origin::with_origin("__or__");
- let other_col = to_column(&other.bind(py))?;
+ let other_col = operand_column(other.bind(py))?;
Ok(PyColumn::new(self.column.clone().or(other_col)))
}
@@ -779,28 +835,28 @@ impl PyColumn {
// --- reverse arithmetic/logical dunders (operand order swapped) ---
fn __rtruediv__(&self, py: Python<'_>, other: Py<PyAny>) ->
PyResult<PyColumn> {
let _origin = crate::origin::with_origin("__rtruediv__");
- let o = to_column(&other.bind(py))?;
+ let o = operand_column(other.bind(py))?;
Ok(PyColumn::new(o.div(self.column.clone())))
}
/// Reverse division, of the name of Python 2, as PySpark's Column has it:
as `__rtruediv__`.
fn __rdiv__(&self, py: Python<'_>, other: Py<PyAny>) -> PyResult<PyColumn>
{
let _origin = crate::origin::with_origin("__rdiv__");
- let o = to_column(&other.bind(py))?;
+ let o = operand_column(other.bind(py))?;
Ok(PyColumn::new(o.div(self.column.clone())))
}
fn __rmod__(&self, py: Python<'_>, other: Py<PyAny>) -> PyResult<PyColumn>
{
let _origin = crate::origin::with_origin("__rmod__");
- let o = to_column(&other.bind(py))?;
+ let o = operand_column(other.bind(py))?;
Ok(PyColumn::new(o.modulo(self.column.clone())))
}
fn __rand__(&self, py: Python<'_>, other: Py<PyAny>) -> PyResult<PyColumn>
{
let _origin = crate::origin::with_origin("__rand__");
- let o = to_column(&other.bind(py))?;
+ let o = operand_column(other.bind(py))?;
Ok(PyColumn::new(self.column.clone().and(o)))
}
fn __ror__(&self, py: Python<'_>, other: Py<PyAny>) -> PyResult<PyColumn> {
let _origin = crate::origin::with_origin("__ror__");
- let o = to_column(&other.bind(py))?;
+ let o = operand_column(other.bind(py))?;
Ok(PyColumn::new(self.column.clone().or(o)))
}
@@ -813,7 +869,7 @@ impl PyColumn {
"Column.__pow__() takes 2 positional arguments but 3 were
given",
));
}
- let o = to_column(&other.bind(py))?;
+ let o = operand_column(other.bind(py))?;
Ok(PyColumn::new(spark_connect::functions::pow(
self.column.clone(),
o,
@@ -828,7 +884,7 @@ impl PyColumn {
if !modulo.is_none(py) {
return Ok(py.NotImplemented());
}
- let o = to_column(&other.bind(py))?;
+ let o = operand_column(other.bind(py))?;
let column = PyColumn::new(spark_connect::functions::pow(o,
self.column.clone()));
Ok(Py::new(py, column)?.into_any())
}
@@ -886,26 +942,26 @@ impl PyColumn {
upperBound: Py<PyAny>,
) -> PyResult<PyColumn> {
let _origin = crate::origin::with_origin("between");
- let l = to_column(&lowerBound.bind(py))?;
- let u = to_column(&upperBound.bind(py))?;
+ let l = operand_column(lowerBound.bind(py))?;
+ let u = operand_column(upperBound.bind(py))?;
Ok(PyColumn::new(self.column.clone().between(l, u)))
}
#[pyo3(name = "bitwiseAND")]
fn bitwise_and(&self, py: Python<'_>, other: Py<PyAny>) ->
PyResult<PyColumn> {
let _origin = crate::origin::with_origin("bitwiseAND");
- let o = to_column(&other.bind(py))?;
+ let o = operand_column(other.bind(py))?;
Ok(PyColumn::new(self.column.clone().bitwise_and(o)))
}
#[pyo3(name = "bitwiseOR")]
fn bitwise_or(&self, py: Python<'_>, other: Py<PyAny>) ->
PyResult<PyColumn> {
let _origin = crate::origin::with_origin("bitwiseOR");
- let o = to_column(&other.bind(py))?;
+ let o = operand_column(other.bind(py))?;
Ok(PyColumn::new(self.column.clone().bitwise_or(o)))
}
#[pyo3(name = "bitwiseXOR")]
fn bitwise_xor(&self, py: Python<'_>, other: Py<PyAny>) ->
PyResult<PyColumn> {
let _origin = crate::origin::with_origin("bitwiseXOR");
- let o = to_column(&other.bind(py))?;
+ let o = operand_column(other.bind(py))?;
Ok(PyColumn::new(self.column.clone().bitwise_xor(o)))
}
fn ilike(&self, other: &Bound<'_, PyAny>) -> PyResult<PyColumn> {
@@ -920,7 +976,7 @@ impl PyColumn {
#[pyo3(name = "eqNullSafe")]
fn eq_null_safe(&self, py: Python<'_>, other: Py<PyAny>) ->
PyResult<PyColumn> {
let _origin = crate::origin::with_origin("eqNullSafe");
- let o = to_column(&other.bind(py))?;
+ let o = operand_column(other.bind(py))?;
Ok(PyColumn::new(self.column.clone().eq_null_safe(o)))
}
#[pyo3(signature = (*cols))]
diff --git a/crates/pyspark-rs/src/functions.rs
b/crates/pyspark-rs/src/functions.rs
index 41646db7..a3b31967 100644
--- a/crates/pyspark-rs/src/functions.rs
+++ b/crates/pyspark-rs/src/functions.rs
@@ -352,11 +352,20 @@ pub fn to_column(obj: &Bound<'_, PyAny>) ->
PyResult<Column> {
/// or `getItem`, to a Column. A list is a typed array literal, as PySpark's
/// `LiteralExpression._from_value` makes it, so an empty list or one that
starts with None is
/// CANNOT_INFER_ARRAY_ELEMENT_TYPE. `to_column` builds a list as `lit` does,
for the functions.
+/// A NumPy array is not a value, as PySpark's `_from_value` does not take it,
though `lit` does.
pub(crate) fn to_value_column(obj: &Bound<'_, PyAny>) -> PyResult<Column> {
let obj = &enum_to_value(obj)?;
if let Ok(list) = obj.cast::<pyo3::types::PyList>() {
return
Ok(Column::new(Expression::literal(typed_array_literal(list)?)));
}
+ if numpy_ndarray_ndim(obj)?.is_some() {
+ return Err(crate::column::raise_pyspark(
+ obj.py(),
+ "PySparkTypeError",
+ "UNSUPPORTED_DATA_TYPE",
+ &[("data_type", "ndarray")],
+ ));
+ }
to_column(obj)
}
diff --git a/python/tests/test_dropin_offline.py
b/python/tests/test_dropin_offline.py
index 60c474e1..0f1afd35 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -2254,6 +2254,121 @@ def
test_try_cast_and_isin_take_their_arguments_as_pyspark():
assert e.value.getMessageParameters() == {"data_type": "tuple"}
+def _column_operators(c):
+ # Each operator of a Column that takes an operand, by name, as a function
of the operand.
+ # The reverse dunders are called directly, as NumPy takes `value + column`
before a Column.
+ return {
+ "add": lambda v: c + v,
+ "radd": lambda v: c.__radd__(v),
+ "sub": lambda v: c - v,
+ "rsub": lambda v: c.__rsub__(v),
+ "mul": lambda v: c * v,
+ "rmul": lambda v: c.__rmul__(v),
+ "truediv": lambda v: c / v,
+ "rtruediv": lambda v: c.__rtruediv__(v),
+ "mod": lambda v: c % v,
+ "rmod": lambda v: c.__rmod__(v),
+ "pow": lambda v: c ** v,
+ "rpow": lambda v: c.__rpow__(v, None),
+ "eq": lambda v: c == v,
+ "ne": lambda v: c != v,
+ "lt": lambda v: c < v,
+ "le": lambda v: c <= v,
+ "gt": lambda v: c > v,
+ "ge": lambda v: c >= v,
+ "and": lambda v: c & v,
+ "rand": lambda v: c.__rand__(v),
+ "or": lambda v: c | v,
+ "ror": lambda v: c.__ror__(v),
+ "bitwiseAND": lambda v: c.bitwiseAND(v),
+ "bitwiseOR": lambda v: c.bitwiseOR(v),
+ "bitwiseXOR": lambda v: c.bitwiseXOR(v),
+ "eqNullSafe": lambda v: c.eqNullSafe(v),
+ "contains": lambda v: c.contains(v),
+ "startswith": lambda v: c.startswith(v),
+ "endswith": lambda v: c.endswith(v),
+ "like": lambda v: c.like(v),
+ "rlike": lambda v: c.rlike(v),
+ "ilike": lambda v: c.ilike(v),
+ "between": lambda v: c.between(v, 1),
+ "between_upper": lambda v: c.between(1, v),
+ }
+
+
+def test_column_operators_take_their_operands_as_pyspark():
+ # As PySpark's _bin_op: an operand that is neither a Column nor a literal
value has its
+ # `_expr` looked up, so the error of that lookup is the one raised, a
PySparkAttributeError
+ # for a Row. NumPy's int64 and bool_ are not literals, though a float64 is.
+ from pyspark.sql import functions as F
+
+ def expr_error(value):
+ with pytest.raises(AttributeError) as expected:
+ value._expr
+ return expected.value
+
+ rejected = [[2], (2,), {1: 2}, {1}, np.array([2]), np.int64(2),
np.bool_(True),
+ b"x", bytearray(b"x"), Row(a=1), object()]
+ operators = _column_operators(F.col("a"))
+ for name, build in operators.items():
+ for value in rejected:
+ expected = expr_error(value)
+ with pytest.raises(type(expected)) as error:
+ build(value)
+ assert str(error.value) == str(expected), (name, type(value))
+
+
+def test_column_operators_take_the_literals_that_pyspark_takes():
+ import datetime
+ import decimal
+ import enum
+
+ from pyspark.sql import functions as F
+ from pyspark.sql.connect.column import Column
+
+ class Code(enum.IntEnum):
+ A = 2
+
+ c = F.col("a")
+ literals = [None, True, 2, 2.5, np.float64(2.5), decimal.Decimal("1.5"),
+ datetime.date(2020, 1, 2), datetime.time(1, 2),
+ datetime.datetime(2020, 1, 2, 3), datetime.timedelta(1), "x",
np.str_("x"),
+ Code.A, F.col("b")]
+ for name, build in _column_operators(c).items():
+ for value in literals:
+ if name == "eq" and isinstance(value, datetime.timedelta):
+ # PySpark's `__eq__` takes no timedelta as a literal, though
`__ne__` does.
+ with pytest.raises(AttributeError, match="has no attribute
'_expr'"):
+ build(value)
+ continue
+ assert isinstance(build(value), Column), (name, value)
+ assert repr(c + np.float64(2.5)) == "Column<'+(a, 2.5)'>"
+ assert repr(c == Code.A) == "Column<'==(a, 2)'>"
+ assert repr(c != datetime.timedelta(1)) == "Column<'not(==(a,
P1DT0H0M0S))'>"
+
+
+def test_column_value_methods_take_no_numpy_array_as_pyspark():
+ # As PySpark's LiteralExpression._from_value, which takes a list as an
array, but not a NumPy
+ # array, as UNSUPPORTED_DATA_TYPE; the functions take one with lit, as
F.when does.
+ from pyspark.errors import PySparkTypeError
+ from pyspark.sql import functions as F
+
+ c = F.col("a")
+ array = np.array([1, 2])
+ for build in (
+ lambda: F.when(c == 1, 1).otherwise(array),
+ lambda: F.when(c == 1, 1).when(c == 2, array),
+ lambda: c.isin(array),
+ lambda: c.isin(np.array([[0], [1]])),
+ lambda: c.getItem(np.array([0])),
+ lambda: c[np.array([0])],
+ ):
+ with pytest.raises(PySparkTypeError) as error:
+ build()
+ assert error.value.getCondition() == "UNSUPPORTED_DATA_TYPE"
+ assert error.value.getMessageParameters() == {"data_type": "ndarray"}
+ assert repr(F.when(F.lit(True), array)) == repr(F.when(F.lit(True),
F.lit(array)))
+
+
@pytest.mark.parametrize("value", [[], [None, 2], [[], [1]]])
def
test_column_methods_cannot_infer_the_element_type_of_a_list_as_pyspark(value):
# As PySpark's LiteralExpression of a list: its element type is that of
its first element,
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]