This is an automated email from the ASF dual-hosted git repository.
viirya 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 f7fed015 [SPARK-61429][CONNECT][PYTHON] Share the argument-error and
option helpers of the PyO3 wrappers
f7fed015 is described below
commit f7fed0152ffd7658319f982d2a5578b5e018d4ee
Author: Liang-Chi Hsieh <[email protected]>
AuthorDate: Tue Nov 10 20:25:27 2026 -0800
[SPARK-61429][CONNECT][PYTHON] Share the argument-error and option helpers
of the PyO3 wrappers
### What changes were proposed in this pull request?
This removes the copy-pasted argument-error and option helpers of the PyO3
wrapper crate (`crates/pyspark-rs`). It is three commits, each reviewable on
its own:
1. **Share `raise_pyspark` and `not_expected_type` from `errors.rs`.**
`raise_pyspark` moves out of `column.rs`, and one `not_expected_type(value,
arg_name, expected)` replaces the byte-identical copies in `column.rs`
(`not_expected`), `readwriter.rs` and `stat_arguments.rs`. `column.rs` and
`stat_arguments.rs` re-export the functions, so the existing
`crate::column::raise_pyspark` and `crate::stat_arguments::not_expected_type`
call sites are untouched.
2. **Use the shared `not_expected_type` in `dataframe.rs` and
`catalog.rs`.** These copies were not identical to the shared one, which is why
they are a separate commit:
- the three in `dataframe.rs` listed the message parameters as
`expected_type, arg_name, arg_type`; the shared helper lists them as `arg_name,
expected_type, arg_type`;
- the one in `catalog.rs` propagated the error of reading the name of
the type (`get_type().name()?`); the shared helper falls back to an empty
`arg_type`, as the other copies did.
3. **Give the option helpers one module, `options.rs`.** PySpark treats an
option of `None` in two ways, and each helper is now named after the one it
implements:
- *skip* (the `None` is left out, as `OptionUtils._set_opts` does):
`set_option_skip_none`, generic over an `OptionBuilder` trait implemented for
`DataFrameReader`, `DataFrameWriter` and `DataStreamReader`, which replaces
`set_opt`, `set_ropt` and `wset_opt`; `set_options_skip_none` for a slice of
`(name, value)` pairs; `kwargs_skip_none` for `**options`, which replaces seven
written-out loops; and `str_kwargs_skip_none`, the former `table_options` of
`Catalog.createTable`, which d [...]
- *unset* (the `None` removes the key, as `DataFrameReader.option`,
`options` and `load` do): `set_reader_option_unset_none` and
`set_reader_kwargs_unset_none`. They replace `apply_options`, whose `unset_none
= false` branch had no caller.
`coerce_option_value` and `set_opts` move there unchanged, and `lib.rs`
re-exports `coerce_option_value` so its callers are untouched. The 209
statements of the form `r = set_opt(r, "name", name)?;` become 21
`set_options_skip_none` calls. That rewrite was done by a script and keeps the
order of the options and the conversion of each value, so the first value that
fails to convert still raises.
No `#[pyo3(signature = ...)]` changes, and `dispatch_generated.rs` is not
touched.
### Why are the changes needed?
The same `NOT_EXPECTED_TYPE` helper existed in five places besides the
inline ones, and `raise_pyspark` lived in `column.rs` although some sixteen
modules raise through it. The option plumbing had the same function over three
builder types, the same loop seven times, and nothing that said which of the
two `None` treatments a helper implemented, which is easy to get wrong when
adding a reader or writer method.
### Does this PR introduce _any_ user-facing change?
No change to any error class, error message or option. Two details differ,
both from the second commit:
- for the `NOT_EXPECTED_TYPE` errors raised from `dataframe.rs`,
`getMessageParameters()` now iterates as `arg_name, expected_type, arg_type`
rather than `expected_type, arg_name, arg_type`. The dict compares equal to the
previous one;
- `Catalog.createTable` with a `schema` whose type has no readable
`__name__` raises `NOT_EXPECTED_TYPE` with an empty `arg_type` rather than the
error of reading the name.
The order of the options is not observable in a plan: they are a `HashMap`
in the core client and a `map<string, string>` in the proto.
### How was this patch tested?
`python/tests/test_dropin_offline.py` against a release build of the
extension, before and after, at the commit the change was written on: 1810
passed, 2 failed, 8 skipped in both, with the same outcome for every test.
Rebased on the current master it is 1817 passed, 2 failed, 8 skipped: the same
two failures, which are on master without this change, and the seven tests
added since.
In addition, a script without a server recorded, for both builds, the
`_options`, `_format`, `_schema` and relation proto of `spark.read` and
`spark.readStream` after `json`, `csv`, `orc`, `text`, `xml`, `parquet` and
`jdbc` with every keyword argument set to a bool, an int, a float, a str,
`None` and an object whose `str()` raises, the same for `option`, `options`,
`load` and `_set_opts`, and some 170 argument errors of `DataFrame`, `Column`,
the writers, the catalog and the conf. Th [...]
`cargo build -p pyspark-rs --release` is warning-free (the crate denies
warnings) and `cargo fmt --all --check` is clean.
This pull request and its description were written by Isaac.
Closes #504 from viirya/SPARK-61429.
Authored-by: Liang-Chi Hsieh <[email protected]>
Signed-off-by: Liang-Chi Hsieh <[email protected]>
---
crates/pyspark-rs/src/catalog.rs | 38 +---
crates/pyspark-rs/src/column.rs | 58 +-----
crates/pyspark-rs/src/dataframe.rs | 204 +++++++--------------
crates/pyspark-rs/src/errors.rs | 43 +++++
crates/pyspark-rs/src/lib.rs | 18 +-
crates/pyspark-rs/src/options.rs | 173 ++++++++++++++++++
crates/pyspark-rs/src/readwriter.rs | 309 +++++++++++++-------------------
crates/pyspark-rs/src/stat_arguments.rs | 22 +--
crates/pyspark-rs/src/streaming.rs | 249 ++++++++++++-------------
9 files changed, 545 insertions(+), 569 deletions(-)
diff --git a/crates/pyspark-rs/src/catalog.rs b/crates/pyspark-rs/src/catalog.rs
index 7911a7e0..7d012f21 100644
--- a/crates/pyspark-rs/src/catalog.rs
+++ b/crates/pyspark-rs/src/catalog.rs
@@ -41,41 +41,13 @@ fn table_schema(
fields: st.current_fields(schema.py())?,
}));
}
- let type_name = schema.get_type().name()?.to_string();
- Err(crate::column::raise_pyspark(
- schema.py(),
- "PySparkTypeError",
- "NOT_EXPECTED_TYPE",
- &[
- ("arg_name", "schema"),
- ("expected_type", "struct type"),
- ("arg_type", &type_name),
- ],
+ Err(crate::errors::not_expected_type(
+ schema,
+ "schema",
+ "struct type",
))
}
-/// The `**options` of `createTable`, as PySpark's: strings, where a `None` is
left out.
-fn table_options(
- options: Option<&Bound<'_, pyo3::types::PyDict>>,
-) -> PyResult<std::collections::HashMap<String, String>> {
- let mut map = std::collections::HashMap::new();
- for (key, value) in options.into_iter().flat_map(|options| options.iter())
{
- if value.is_none() {
- continue;
- }
- if !value.is_instance_of::<pyo3::types::PyString>() {
- // As the protobuf map of strings that PySpark sets the options in.
- return Err(pyo3::exceptions::PyTypeError::new_err(format!(
- "{} has type {}, but expected one of: (<class 'bytes'>, <class
'str'>)",
- value.repr()?,
- value.get_type().str()?
- )));
- }
- map.insert(key.extract()?, value.extract()?);
- }
- Ok(map)
-}
-
/// The NamedTuple of `pyspark.sql.catalog` of a result of the catalog, as
PySpark's `Catalog`
/// returns: `CatalogMetadata`, `Database`, `Table`, `Column`, `Function` or
`TablePartition`.
trait NamedTuple {
@@ -435,7 +407,7 @@ impl PyCatalog {
options: Option<&Bound<'_, pyo3::types::PyDict>>,
) -> PyResult<PyDataFrame> {
let schema = table_schema(schema)?;
- let options = table_options(options)?;
+ let options = crate::options::str_kwargs_skip_none(options)?;
py.detach(|| {
self.catalog
.create_table_with(
diff --git a/crates/pyspark-rs/src/column.rs b/crates/pyspark-rs/src/column.rs
index cd7f12c9..d18ec4cf 100644
--- a/crates/pyspark-rs/src/column.rs
+++ b/crates/pyspark-rs/src/column.rs
@@ -5,53 +5,11 @@ use pyo3::types::PyDict;
use spark_connect::column::Column;
use spark_connect::expression::{Alias, ExpressionNode, NullOrdering};
-use crate::errors::ResultExt;
+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};
-/// Raise a `pyspark.errors` exception (`class_name`) carrying the given
`error_class`
-/// condition and message parameters, mirroring the reference Column
guard-rails.
-pub(crate) fn raise_pyspark(
- py: Python<'_>,
- class_name: &str,
- error_class: &str,
- params: &[(&str, &str)],
-) -> PyErr {
- use pyo3::types::PyDict;
- let build = || -> PyResult<PyErr> {
- let cls = py.import("pyspark.errors")?.getattr(class_name)?;
- let kwargs = PyDict::new(py);
- kwargs.set_item("errorClass", error_class)?;
- let mp = PyDict::new(py);
- for (k, v) in params {
- mp.set_item(*k, *v)?;
- }
- kwargs.set_item("messageParameters", mp)?;
- let exc = cls.call((), Some(&kwargs))?;
- Ok(PyErr::from_value(exc))
- };
- build().unwrap_or_else(|e| e)
-}
-
-/// PySpark's `NOT_EXPECTED_TYPE` error of the argument `name`, `value`, which
should be of
-/// the type `expected`.
-fn not_expected(value: &Bound<'_, PyAny>, name: &str, expected: &str) -> PyErr
{
- let type_name = value
- .get_type()
- .name()
- .map(|name| name.to_string())
- .unwrap_or_default();
- raise_pyspark(
- value.py(),
- "PySparkTypeError",
- "NOT_EXPECTED_TYPE",
- &[
- ("arg_name", name),
- ("expected_type", expected),
- ("arg_type", &type_name),
- ],
- )
-}
-
/// 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> {
@@ -223,7 +181,7 @@ impl PyColumn {
if !(dataType.is_instance_of::<pyo3::types::PyString>()
|| dataType.is_instance_of::<crate::types::PyDataType>())
{
- return Err(not_expected(dataType, "dataType", "DataType or str"));
+ return Err(not_expected_type(dataType, "dataType", "DataType or
str"));
}
// A DDL string keeps the unparsed type_str form (reference
cast("int"));
// any DataType object is converted to a typed cast.
@@ -679,7 +637,7 @@ impl PyColumn {
fn over(&self, window: &Bound<'_, PyAny>) -> PyResult<PyColumn> {
let _origin = crate::origin::with_origin("over");
let Ok(window) = window.extract::<PyRef<'_,
crate::window::PyWindowSpec>>() else {
- return Err(not_expected(window, "window", "WindowSpec"));
+ return Err(not_expected_type(window, "window", "WindowSpec"));
};
Ok(PyColumn::new(self.column.clone().over(window.spec.clone())))
}
@@ -1004,10 +962,10 @@ impl PyColumn {
let _origin = crate::origin::with_origin("withField");
// As PySpark's, of a str and a Column.
if !fieldName.is_instance_of::<pyo3::types::PyString>() {
- return Err(not_expected(fieldName, "fieldName", "str"));
+ return Err(not_expected_type(fieldName, "fieldName", "str"));
}
let Ok(value) = col.extract::<PyRef<'_, PyColumn>>() else {
- return Err(not_expected(col, "col", "Column"));
+ return Err(not_expected_type(col, "col", "Column"));
};
let field_name: String = fieldName.extract()?;
Ok(PyColumn::new(
@@ -1023,7 +981,7 @@ impl PyColumn {
let mut names = Vec::with_capacity(fieldNames.len());
for name in &fieldNames {
if !name.is_instance_of::<pyo3::types::PyString>() {
- return Err(not_expected(name, "fieldName", "str"));
+ return Err(not_expected_type(name, "fieldName", "str"));
}
names.push(name.extract::<String>()?);
}
diff --git a/crates/pyspark-rs/src/dataframe.rs
b/crates/pyspark-rs/src/dataframe.rs
index b6a0d753..cb6b906b 100644
--- a/crates/pyspark-rs/src/dataframe.rs
+++ b/crates/pyspark-rs/src/dataframe.rs
@@ -7,28 +7,14 @@ use spark_connect::plan::JoinType;
use spark_connect::udf::{eval_type, CommonInlineUserDefinedFunctionExpression,
PythonUDFPayload};
use crate::column::PyColumn;
-use crate::errors::ResultExt;
+use crate::errors::{not_expected_type, ResultExt};
use crate::group::PyGroupedData;
use crate::interrupt::interruptible;
+use crate::options::{set_option_skip_none, set_options_skip_none};
use crate::row::{FieldConverters, NestedFieldNames};
use crate::streaming::PyDataStreamWriter;
use crate::types::PyDataType;
-/// Apply a single writer option (skipping None; bool->"true"/"false").
-fn wset_opt(
- w: spark_connect::readwriter::DataFrameWriter,
- name: &str,
- v: Option<&Bound<'_, PyAny>>,
-) -> PyResult<spark_connect::readwriter::DataFrameWriter> {
- match v {
- Some(x) => match crate::coerce_option_value(x)? {
- Some(sv) => Ok(w.option(name, &sv)),
- None => Ok(w),
- },
- None => Ok(w),
- }
-}
-
/// Flatten `*cols` args that are each a str or a list of str (pyspark
/// partitionBy/bucketBy/sortBy accept both forms).
fn flatten_str_cols(cols: Vec<Bound<'_, PyAny>>) -> PyResult<Vec<String>> {
@@ -187,28 +173,11 @@ impl PyDataFrame {
pyo3::types::PyBool::new(py, false).to_owned().into_any(),
],
)?;
- let not_expected = |expected: &str, name: &str, value: &Bound<'_,
PyAny>| -> PyErr {
- let type_name = value
- .get_type()
- .name()
- .map(|name| name.to_string())
- .unwrap_or_default();
- crate::column::raise_pyspark(
- py,
- "PySparkTypeError",
- "NOT_EXPECTED_TYPE",
- &[
- ("expected_type", expected),
- ("arg_name", name),
- ("arg_type", &type_name),
- ],
- )
- };
if n.is_instance_of::<pyo3::types::PyBool>() ||
!n.is_instance_of::<pyo3::types::PyInt>() {
- return Err(not_expected("int", "n", &n));
+ return Err(not_expected_type(&n, "n", "int"));
}
if !vertical.is_instance_of::<pyo3::types::PyBool>() {
- return Err(not_expected("bool", "vertical", &vertical));
+ return Err(not_expected_type(&vertical, "vertical", "bool"));
}
let truncate =
if truncate.is_instance_of::<pyo3::types::PyBool>() &&
truncate.is_truthy()? {
@@ -218,7 +187,7 @@ impl PyDataFrame {
match
py.import("builtins")?.getattr("int")?.call1((&truncate,)) {
Ok(value) => value.extract::<i32>()?,
Err(err) if
err.is_instance_of::<pyo3::exceptions::PyValueError>(py) => {
- return Err(not_expected("bool", "truncate",
&truncate));
+ return Err(not_expected_type(&truncate, "truncate",
"bool"));
}
Err(err) => return Err(err),
}
@@ -409,26 +378,6 @@ fn unwrap_sequence(cols: Vec<Bound<'_, PyAny>>) ->
PyResult<Vec<Bound<'_, PyAny>
}
}
-/// PySpark's `NOT_EXPECTED_TYPE` error of the argument `name`, `value`, which
should be of
-/// the type `expected`.
-fn not_expected_type(value: &Bound<'_, PyAny>, name: &str, expected: &str) ->
PyErr {
- let type_name = value
- .get_type()
- .name()
- .map(|name| name.to_string())
- .unwrap_or_default();
- crate::column::raise_pyspark(
- value.py(),
- "PySparkTypeError",
- "NOT_EXPECTED_TYPE",
- &[
- ("expected_type", expected),
- ("arg_name", name),
- ("arg_type", &type_name),
- ],
- )
-}
-
/// PySpark's `VALUE_NOT_POSITIVE` error of `numPartitions`, unless it is
positive.
fn positive_partitions(py: Python<'_>, num_partitions: i64) -> PyResult<i32> {
if num_partitions > 0 {
@@ -673,7 +622,7 @@ fn watermark_argument(value: &Bound<'_, PyAny>, name: &str)
-> PyResult<String>
.get_type()
.is(value.py().get_type::<pyo3::types::PyString>())
{
- return Err(crate::stat_arguments::not_expected_type(value, name,
"str"));
+ return Err(not_expected_type(value, name, "str"));
}
value.extract()
}
@@ -1966,9 +1915,7 @@ impl PyDataFrame {
metadata: &Bound<'_, PyAny>,
) -> PyResult<PyDataFrame> {
if !metadata.is_instance_of::<PyDict>() {
- return Err(crate::stat_arguments::not_expected_type(
- metadata, "metadata", "dict",
- ));
+ return Err(not_expected_type(metadata, "metadata", "dict"));
}
let json: String = py
.import("json")?
@@ -3299,21 +3246,7 @@ pub(crate) fn column_or_name(col: &Bound<'_, PyAny>) ->
PyResult<spark_connect::
let _origin = crate::origin::with_origin("col");
return Ok(spark_connect::functions::col(&col.extract::<String>()?));
}
- let type_name = col
- .get_type()
- .name()
- .map(|name| name.to_string())
- .unwrap_or_default();
- Err(crate::column::raise_pyspark(
- col.py(),
- "PySparkTypeError",
- "NOT_EXPECTED_TYPE",
- &[
- ("expected_type", "Column or str"),
- ("arg_name", "col"),
- ("arg_type", &type_name),
- ],
- ))
+ Err(not_expected_type(col, "col", "Column or str"))
}
/// Python wrapper for `MergeIntoWriter` (`df.mergeInto(...)`).
@@ -3569,13 +3502,8 @@ fn apply_write_common(
};
w = w.partition_by(cols);
}
- if let Some(opts) = options {
- let mut map = std::collections::HashMap::new();
- for (k, v) in opts.iter() {
- if let Some(val) = crate::coerce_option_value(&v)? {
- map.insert(k.str()?.to_string(), val);
- }
- }
+ if options.is_some() {
+ let map = crate::options::kwargs_skip_none(options)?;
w = w.options(map);
}
Ok(w)
@@ -3591,7 +3519,7 @@ impl PyDataFrameWriter {
schema: Option<Bound<'_, PyAny>>,
options: Option<Bound<'_, pyo3::types::PyDict>>,
) -> PyResult<()> {
- crate::readwriter::set_opts(slf.as_any(), schema.as_ref(),
options.as_ref())
+ crate::options::set_opts(slf.as_any(), schema.as_ref(),
options.as_ref())
}
/// The save mode, as PySpark's: `None` keeps the default, "error".
@@ -3634,14 +3562,7 @@ impl PyDataFrameWriter {
slf: &Bound<'py, Self>,
options: Option<&Bound<'_, PyDict>>,
) -> PyResult<Bound<'py, Self>> {
- let mut map = std::collections::HashMap::new();
- if let Some(options) = options {
- for (k, v) in options.iter() {
- if let Some(val) = crate::coerce_option_value(&v)? {
- map.insert(k.str()?.to_string(), val);
- }
- }
- }
+ let map = crate::options::kwargs_skip_none(options)?;
slf.borrow().inner.update(|w| w.options(map));
Ok(slf.clone())
}
@@ -3814,7 +3735,7 @@ impl PyDataFrameWriter {
};
w = w.partition_by(cols);
}
- w = wset_opt(w, "compression", compression)?;
+ w = set_option_skip_none(w, "compression", compression)?;
// PySpark sets the mode/options/format on the writer itself, then
saves.
self.inner.set(w.clone().format("parquet"));
interruptible(py, &w.spark_session(), ||
w.parquet(path).map_err(Box::new))
@@ -3840,12 +3761,17 @@ impl PyDataFrameWriter {
if let Some(m) = mode {
w = w.mode(&m.str()?.to_string());
}
- w = wset_opt(w, "compression", compression)?;
- w = wset_opt(w, "dateFormat", dateFormat)?;
- w = wset_opt(w, "timestampFormat", timestampFormat)?;
- w = wset_opt(w, "lineSep", lineSep)?;
- w = wset_opt(w, "encoding", encoding)?;
- w = wset_opt(w, "ignoreNullFields", ignoreNullFields)?;
+ w = set_options_skip_none(
+ w,
+ &[
+ ("compression", compression),
+ ("dateFormat", dateFormat),
+ ("timestampFormat", timestampFormat),
+ ("lineSep", lineSep),
+ ("encoding", encoding),
+ ("ignoreNullFields", ignoreNullFields),
+ ],
+ )?;
// PySpark sets the mode/options/format on the writer itself, then
saves.
self.inner.set(w.clone().format("json"));
interruptible(py, &w.spark_session(), ||
w.json(path).map_err(Box::new))
@@ -3881,22 +3807,27 @@ impl PyDataFrameWriter {
if let Some(m) = mode {
w = w.mode(&m.str()?.to_string());
}
- w = wset_opt(w, "compression", compression)?;
- w = wset_opt(w, "sep", sep)?;
- w = wset_opt(w, "quote", quote)?;
- w = wset_opt(w, "escape", escape)?;
- w = wset_opt(w, "header", header)?;
- w = wset_opt(w, "nullValue", nullValue)?;
- w = wset_opt(w, "escapeQuotes", escapeQuotes)?;
- w = wset_opt(w, "quoteAll", quoteAll)?;
- w = wset_opt(w, "dateFormat", dateFormat)?;
- w = wset_opt(w, "timestampFormat", timestampFormat)?;
- w = wset_opt(w, "ignoreLeadingWhiteSpace", ignoreLeadingWhiteSpace)?;
- w = wset_opt(w, "ignoreTrailingWhiteSpace", ignoreTrailingWhiteSpace)?;
- w = wset_opt(w, "charToEscapeQuoteEscaping",
charToEscapeQuoteEscaping)?;
- w = wset_opt(w, "encoding", encoding)?;
- w = wset_opt(w, "emptyValue", emptyValue)?;
- w = wset_opt(w, "lineSep", lineSep)?;
+ w = set_options_skip_none(
+ w,
+ &[
+ ("compression", compression),
+ ("sep", sep),
+ ("quote", quote),
+ ("escape", escape),
+ ("header", header),
+ ("nullValue", nullValue),
+ ("escapeQuotes", escapeQuotes),
+ ("quoteAll", quoteAll),
+ ("dateFormat", dateFormat),
+ ("timestampFormat", timestampFormat),
+ ("ignoreLeadingWhiteSpace", ignoreLeadingWhiteSpace),
+ ("ignoreTrailingWhiteSpace", ignoreTrailingWhiteSpace),
+ ("charToEscapeQuoteEscaping", charToEscapeQuoteEscaping),
+ ("encoding", encoding),
+ ("emptyValue", emptyValue),
+ ("lineSep", lineSep),
+ ],
+ )?;
// PySpark sets the mode/options/format on the writer itself, then
saves.
self.inner.set(w.clone().format("csv"));
interruptible(py, &w.spark_session(), || w.csv(path).map_err(Box::new))
@@ -3926,7 +3857,7 @@ impl PyDataFrameWriter {
};
w = w.partition_by(cols);
}
- w = wset_opt(w, "compression", compression)?;
+ w = set_option_skip_none(w, "compression", compression)?;
// PySpark sets the mode/options/format on the writer itself, then
saves.
self.inner.set(w.clone().format("orc"));
interruptible(py, &w.spark_session(), || w.orc(path).map_err(Box::new))
@@ -3944,8 +3875,7 @@ impl PyDataFrameWriter {
lineSep: Option<&Bound<'_, PyAny>>,
) -> PyResult<()> {
let mut w = self.inner.get();
- w = wset_opt(w, "compression", compression)?;
- w = wset_opt(w, "lineSep", lineSep)?;
+ w = set_options_skip_none(w, &[("compression", compression),
("lineSep", lineSep)])?;
// PySpark sets the mode/options/format on the writer itself, then
saves.
self.inner.set(w.clone().format("text"));
interruptible(py, &w.spark_session(), ||
w.text(path).map_err(Box::new))
@@ -3974,21 +3904,26 @@ impl PyDataFrameWriter {
validateName: Option<&Bound<'_, PyAny>>,
) -> PyResult<()> {
let mut w = self.inner.get();
- w = wset_opt(w, "rowTag", rowTag)?;
+ w = set_option_skip_none(w, "rowTag", rowTag)?;
if let Some(m) = mode {
w = w.mode(&m.str()?.to_string());
}
- w = wset_opt(w, "attributePrefix", attributePrefix)?;
- w = wset_opt(w, "valueTag", valueTag)?;
- w = wset_opt(w, "rootTag", rootTag)?;
- w = wset_opt(w, "declaration", declaration)?;
- w = wset_opt(w, "arrayElementName", arrayElementName)?;
- w = wset_opt(w, "nullValue", nullValue)?;
- w = wset_opt(w, "dateFormat", dateFormat)?;
- w = wset_opt(w, "timestampFormat", timestampFormat)?;
- w = wset_opt(w, "compression", compression)?;
- w = wset_opt(w, "encoding", encoding)?;
- w = wset_opt(w, "validateName", validateName)?;
+ w = set_options_skip_none(
+ w,
+ &[
+ ("attributePrefix", attributePrefix),
+ ("valueTag", valueTag),
+ ("rootTag", rootTag),
+ ("declaration", declaration),
+ ("arrayElementName", arrayElementName),
+ ("nullValue", nullValue),
+ ("dateFormat", dateFormat),
+ ("timestampFormat", timestampFormat),
+ ("compression", compression),
+ ("encoding", encoding),
+ ("validateName", validateName),
+ ],
+ )?;
// PySpark sets the mode/options/format on the writer itself, then
saves.
self.inner.set(w.clone().format("xml"));
interruptible(py, &w.spark_session(), || w.xml(path).map_err(Box::new))
@@ -4018,7 +3953,7 @@ impl PyDataFrameWriterV2 {
schema: Option<Bound<'_, PyAny>>,
options: Option<Bound<'_, pyo3::types::PyDict>>,
) -> PyResult<()> {
- crate::readwriter::set_opts(slf.as_any(), schema.as_ref(),
options.as_ref())
+ crate::options::set_opts(slf.as_any(), schema.as_ref(),
options.as_ref())
}
fn using<'py>(slf: &Bound<'py, Self>, provider: &str) ->
PyResult<Bound<'py, Self>> {
@@ -4048,14 +3983,7 @@ impl PyDataFrameWriterV2 {
slf: &Bound<'py, Self>,
options: Option<&Bound<'_, PyDict>>,
) -> PyResult<Bound<'py, Self>> {
- let mut map = std::collections::HashMap::new();
- if let Some(options) = options {
- for (k, v) in options.iter() {
- if let Some(val) = crate::coerce_option_value(&v)? {
- map.insert(k.str()?.to_string(), val);
- }
- }
- }
+ let map = crate::options::kwargs_skip_none(options)?;
slf.borrow().inner.update(|w| w.options(map));
Ok(slf.clone())
}
diff --git a/crates/pyspark-rs/src/errors.rs b/crates/pyspark-rs/src/errors.rs
index a4d6a395..1584f936 100644
--- a/crates/pyspark-rs/src/errors.rs
+++ b/crates/pyspark-rs/src/errors.rs
@@ -5,6 +5,49 @@ use pyo3::prelude::*;
use pyo3::types::{PyBytes, PyDict, PyList};
use spark_connect_core::error::{ServerErrorInfo, SparkError, SparkErrorKind};
+/// Raise a `pyspark.errors` exception (`class_name`) carrying the given
`error_class`
+/// condition and message parameters, mirroring the reference Column
guard-rails.
+pub(crate) fn raise_pyspark(
+ py: Python<'_>,
+ class_name: &str,
+ error_class: &str,
+ params: &[(&str, &str)],
+) -> PyErr {
+ let build = || -> PyResult<PyErr> {
+ let cls = py.import("pyspark.errors")?.getattr(class_name)?;
+ let kwargs = PyDict::new(py);
+ kwargs.set_item("errorClass", error_class)?;
+ let mp = PyDict::new(py);
+ for (k, v) in params {
+ mp.set_item(*k, *v)?;
+ }
+ kwargs.set_item("messageParameters", mp)?;
+ let exc = cls.call((), Some(&kwargs))?;
+ Ok(PyErr::from_value(exc))
+ };
+ build().unwrap_or_else(|e| e)
+}
+
+/// PySpark's `NOT_EXPECTED_TYPE` error of the argument `name`, `value`, which
should be of
+/// the type `expected`.
+pub(crate) fn not_expected_type(value: &Bound<'_, PyAny>, name: &str,
expected: &str) -> PyErr {
+ let type_name = value
+ .get_type()
+ .name()
+ .map(|name| name.to_string())
+ .unwrap_or_default();
+ raise_pyspark(
+ value.py(),
+ "PySparkTypeError",
+ "NOT_EXPECTED_TYPE",
+ &[
+ ("arg_name", name),
+ ("expected_type", expected),
+ ("arg_type", &type_name),
+ ],
+ )
+}
+
/// Maps a SparkErrorKind to the corresponding pyspark.errors exception class
name.
/// Returns a string that can be used to retrieve the class from the
pyspark.errors module.
fn kind_to_pyspark_class_name(kind: SparkErrorKind) -> &'static str {
diff --git a/crates/pyspark-rs/src/lib.rs b/crates/pyspark-rs/src/lib.rs
index 47520fb8..ec22760a 100644
--- a/crates/pyspark-rs/src/lib.rs
+++ b/crates/pyspark-rs/src/lib.rs
@@ -7,22 +7,6 @@
#![allow(non_snake_case)]
use pyo3::prelude::*;
-use pyo3::types::PyBool;
-
-/// Coerce a Python option value the way reference pyspark's `to_str` does:
-/// `None` -> `None` (the option is left unset, NOT the literal string
"None"), a
-/// bool -> lowercase `"true"`/`"false"` (not Python's `"True"`/`"False"`), and
-/// everything else -> its `str()`. Used by every reader/writer/conf
`option(s)`
-/// binding so option handling matches the reference client.
-pub(crate) fn coerce_option_value(v: &Bound<'_, PyAny>) ->
PyResult<Option<String>> {
- if v.is_none() {
- return Ok(None);
- }
- if let Ok(b) = v.cast::<PyBool>() {
- return Ok(Some(if b.is_true() { "true" } else { "false"
}.to_string()));
- }
- Ok(Some(v.str()?.to_string()))
-}
mod catalog;
mod column;
@@ -38,6 +22,7 @@ mod infer;
mod interrupt;
mod ml;
mod observation;
+mod options;
mod origin;
mod pandas_input;
mod pipelines;
@@ -71,6 +56,7 @@ use dataframe::{
};
use datasource::PyDataSourceRegistration;
use group::{PyCoGroupedData, PyGroupedData};
+pub(crate) use options::coerce_option_value;
use readwriter::PyDataFrameReader;
use resource::{
PyExecutorResourceRequests, PyResourceProfile, PyResourceProfileBuilder,
PyTaskResourceRequests,
diff --git a/crates/pyspark-rs/src/options.rs b/crates/pyspark-rs/src/options.rs
new file mode 100644
index 00000000..90028c4a
--- /dev/null
+++ b/crates/pyspark-rs/src/options.rs
@@ -0,0 +1,173 @@
+//! The options of the readers, the writers and the catalog, as PySpark
converts them.
+//!
+//! PySpark treats an option of `None` in two ways, and each helper here is
named after the one
+//! it implements:
+//!
+//! - **skip**: the `None` is left out, and whatever the builder already holds
under that key
+//! stays. This is `OptionUtils._set_opts`, which the format methods (`csv`,
`json`, ...) pass
+//! their keyword arguments to, and the `option` and `options` of the
writers and of the
+//! stream reader.
+//! - **unset**: the `None` removes the key from the builder. This is
`DataFrameReader.option`,
+//! `options` and `load`.
+//!
+//! Every other value goes through [`coerce_option_value`].
+
+use std::collections::HashMap;
+
+use pyo3::prelude::*;
+use pyo3::types::{PyBool, PyDict, PyString};
+use spark_connect::readwriter::{DataFrameReader, DataFrameWriter};
+use spark_connect::streaming::DataStreamReader;
+
+/// Coerce a Python option value the way reference pyspark's `to_str` does:
+/// `None` -> `None` (the option is left unset, NOT the literal string
"None"), a
+/// bool -> lowercase `"true"`/`"false"` (not Python's `"True"`/`"False"`), and
+/// everything else -> its `str()`. Used by every reader/writer/conf
`option(s)`
+/// binding so option handling matches the reference client.
+pub(crate) fn coerce_option_value(v: &Bound<'_, PyAny>) ->
PyResult<Option<String>> {
+ if v.is_none() {
+ return Ok(None);
+ }
+ if let Ok(b) = v.cast::<PyBool>() {
+ return Ok(Some(if b.is_true() { "true" } else { "false"
}.to_string()));
+ }
+ Ok(Some(v.str()?.to_string()))
+}
+
+/// A reader or writer that takes string options one at a time.
+pub(crate) trait OptionBuilder: Sized {
+ fn with_option(self, key: &str, value: &str) -> Self;
+}
+
+impl OptionBuilder for DataFrameReader {
+ fn with_option(self, key: &str, value: &str) -> Self {
+ self.option(key, value)
+ }
+}
+
+impl OptionBuilder for DataFrameWriter {
+ fn with_option(self, key: &str, value: &str) -> Self {
+ self.option(key, value)
+ }
+}
+
+impl OptionBuilder for DataStreamReader {
+ fn with_option(self, key: &str, value: &str) -> Self {
+ self.option(key, value)
+ }
+}
+
+/// `builder` with the option `name` of `value`, **skipping** a `value` that
is absent or None.
+pub(crate) fn set_option_skip_none<B: OptionBuilder>(
+ builder: B,
+ name: &str,
+ value: Option<&Bound<'_, PyAny>>,
+) -> PyResult<B> {
+ match value {
+ Some(value) => match coerce_option_value(value)? {
+ Some(value) => Ok(builder.with_option(name, &value)),
+ None => Ok(builder),
+ },
+ None => Ok(builder),
+ }
+}
+
+/// `builder` with each of `options` in order, **skipping** those that are
absent or None, as
+/// [`set_option_skip_none`] one after the other: the first value that fails
to convert raises.
+pub(crate) fn set_options_skip_none<B: OptionBuilder>(
+ mut builder: B,
+ options: &[(&str, Option<&Bound<'_, PyAny>>)],
+) -> PyResult<B> {
+ for (name, value) in options {
+ builder = set_option_skip_none(builder, name, *value)?;
+ }
+ Ok(builder)
+}
+
+/// The `**options` of a call as a map of strings, **skipping** those that are
None.
+pub(crate) fn kwargs_skip_none(
+ options: Option<&Bound<'_, PyDict>>,
+) -> PyResult<HashMap<String, String>> {
+ let mut map = HashMap::new();
+ if let Some(options) = options {
+ for (key, value) in options.iter() {
+ if let Some(value) = coerce_option_value(&value)? {
+ map.insert(key.str()?.to_string(), value);
+ }
+ }
+ }
+ Ok(map)
+}
+
+/// `reader` with the option `key` of `value`, **unsetting** the key of a
`value` of None, as
+/// PySpark's `DataFrameReader.option`.
+pub(crate) fn set_reader_option_unset_none(
+ reader: DataFrameReader,
+ key: &str,
+ value: &Bound<'_, PyAny>,
+) -> PyResult<DataFrameReader> {
+ Ok(match coerce_option_value(value)? {
+ Some(value) => reader.option(key, &value),
+ None => reader.unset_option(key),
+ })
+}
+
+/// `reader` with the `**options` of a call, **unsetting** the keys of those
that are None, as
+/// PySpark's `DataFrameReader.options` and `load`.
+pub(crate) fn set_reader_kwargs_unset_none(
+ mut reader: DataFrameReader,
+ options: Option<&Bound<'_, PyDict>>,
+) -> PyResult<DataFrameReader> {
+ if let Some(options) = options {
+ for (key, value) in options.iter() {
+ let key = key.str()?.to_string();
+ reader = set_reader_option_unset_none(reader, &key, &value)?;
+ }
+ }
+ Ok(reader)
+}
+
+/// The `**options` of `Catalog.createTable`, **skipping** those that are
None. Unlike the
+/// options of the readers and writers these are not converted: PySpark sets
them in a protobuf
+/// map of strings as they are, which takes a str and raises a `TypeError` for
anything else.
+pub(crate) fn str_kwargs_skip_none(
+ options: Option<&Bound<'_, PyDict>>,
+) -> PyResult<HashMap<String, String>> {
+ let mut map = HashMap::new();
+ for (key, value) in options.into_iter().flat_map(|options| options.iter())
{
+ if value.is_none() {
+ continue;
+ }
+ if !value.is_instance_of::<PyString>() {
+ // As the protobuf map of strings that PySpark sets the options in.
+ return Err(pyo3::exceptions::PyTypeError::new_err(format!(
+ "{} has type {}, but expected one of: (<class 'bytes'>, <class
'str'>)",
+ value.repr()?,
+ value.get_type().str()?
+ )));
+ }
+ map.insert(key.extract()?, value.extract()?);
+ }
+ Ok(map)
+}
+
+/// The `_set_opts` of the readers and writers, as PySpark's
`OptionUtils._set_opts`: the schema of
+/// `slf`, if any, and its options of `options`, **skipping** those that are
None, through its own
+/// Python `schema` and `option`, which convert them and raise their errors.
+pub(crate) fn set_opts(
+ slf: &Bound<'_, PyAny>,
+ schema: Option<&Bound<'_, PyAny>>,
+ options: Option<&Bound<'_, PyDict>>,
+) -> PyResult<()> {
+ if let Some(schema) = schema.filter(|schema| !schema.is_none()) {
+ slf.call_method1("schema", (schema,))?;
+ }
+ if let Some(options) = options {
+ for (key, value) in options.iter() {
+ if !value.is_none() {
+ slf.call_method1("option", (key, value))?;
+ }
+ }
+ }
+ Ok(())
+}
diff --git a/crates/pyspark-rs/src/readwriter.rs
b/crates/pyspark-rs/src/readwriter.rs
index a61d1893..6d74200d 100644
--- a/crates/pyspark-rs/src/readwriter.rs
+++ b/crates/pyspark-rs/src/readwriter.rs
@@ -7,7 +7,11 @@ use pyo3::types::PyDict;
use spark_connect::readwriter::DataFrameReader;
use crate::dataframe::PyDataFrame;
-use crate::errors::ResultExt;
+use crate::errors::{not_expected_type, ResultExt};
+use crate::options::{
+ set_option_skip_none, set_options_skip_none, set_reader_kwargs_unset_none,
+ set_reader_option_unset_none,
+};
/// Python wrapper for the batch DataFrameReader.
///
@@ -100,26 +104,6 @@ fn path_list(paths: &[Bound<'_, PyAny>]) ->
PyResult<Vec<String>> {
.collect()
}
-/// PySpark's `NOT_EXPECTED_TYPE` error of the argument `name`, `value`, which
should be of
-/// the type `expected`.
-fn not_expected_type(value: &Bound<'_, PyAny>, name: &str, expected: &str) ->
PyErr {
- let type_name = value
- .get_type()
- .name()
- .map(|name| name.to_string())
- .unwrap_or_default();
- crate::column::raise_pyspark(
- value.py(),
- "PySparkTypeError",
- "NOT_EXPECTED_TYPE",
- &[
- ("arg_name", name),
- ("expected_type", expected),
- ("arg_type", &type_name),
- ],
- )
-}
-
/// The columns of `df.write.bucketBy(numBuckets, col, *cols)` and
`sortBy(col, *cols)`, as
/// PySpark's: column names, or a list or tuple of them alone.
pub(crate) fn writer_columns(
@@ -169,42 +153,6 @@ pub(crate) fn bucket_count(num_buckets: &Bound<'_, PyAny>)
-> PyResult<i32> {
}
}
-/// The reader `r` with the `options` of a call, lowercasing bools. A None
value unsets its
-/// option when `unset_none`, as PySpark's `DataFrameReader.option`, `options`
and `load` do,
-/// and is skipped otherwise, as the `_set_opts` of its format methods does.
-fn apply_options(
- mut r: DataFrameReader,
- options: Option<&Bound<'_, PyDict>>,
- unset_none: bool,
-) -> PyResult<DataFrameReader> {
- if let Some(opts) = options {
- for (k, v) in opts.iter() {
- let key = k.str()?.to_string();
- match crate::coerce_option_value(&v)? {
- Some(val) => r = r.option(&key, &val),
- None if unset_none => r = r.unset_option(&key),
- None => {}
- }
- }
- }
- Ok(r)
-}
-
-/// Apply a single reader option (skipping None; bool->"true"/"false").
-fn set_opt(
- r: DataFrameReader,
- name: &str,
- v: Option<&Bound<'_, PyAny>>,
-) -> PyResult<DataFrameReader> {
- match v {
- Some(x) => match crate::coerce_option_value(x)? {
- Some(sv) => Ok(r.option(name, &sv)),
- None => Ok(r),
- },
- None => Ok(r),
- }
-}
-
/// A reader `schema` as pyspark's `DataFrameReader.schema` and
`DataStreamReader.schema`
/// send it: a StructType as its JSON, which keeps field metadata, and a
string as is, for
/// the server to parse. Anything else raises `NOT_EXPECTED_TYPE`.
@@ -259,27 +207,6 @@ fn apply_reader_schema(r: DataFrameReader, v: &Bound<'_,
PyAny>) -> PyResult<Dat
Ok(r.schema(reader_schema(v)?))
}
-/// The `_set_opts` of the readers and writers, as PySpark's
`OptionUtils._set_opts`: the schema of
-/// `slf`, if any, and its options of `options` that are not None, through its
own `schema` and
-/// `option`, which convert them and raise their errors.
-pub(crate) fn set_opts(
- slf: &Bound<'_, PyAny>,
- schema: Option<&Bound<'_, PyAny>>,
- options: Option<&Bound<'_, pyo3::types::PyDict>>,
-) -> PyResult<()> {
- if let Some(schema) = schema.filter(|schema| !schema.is_none()) {
- slf.call_method1("schema", (schema,))?;
- }
- if let Some(options) = options {
- for (key, value) in options.iter() {
- if !value.is_none() {
- slf.call_method1("option", (key, value))?;
- }
- }
- }
- Ok(())
-}
-
#[pymethods]
impl PyDataFrameReader {
/// Set the schema, if any, and the options of `options` that are not
None, through its own
@@ -290,7 +217,7 @@ impl PyDataFrameReader {
schema: Option<Bound<'_, PyAny>>,
options: Option<Bound<'_, pyo3::types::PyDict>>,
) -> PyResult<()> {
- crate::readwriter::set_opts(slf.as_any(), schema.as_ref(),
options.as_ref())
+ crate::options::set_opts(slf.as_any(), schema.as_ref(),
options.as_ref())
}
/// Set the source format (e.g. "parquet", "json", "csv"). As PySpark's,
None unsets it, so
@@ -320,10 +247,7 @@ impl PyDataFrameReader {
key: &str,
value: &Bound<'_, PyAny>,
) -> PyResult<PyRefMut<'py, Self>> {
- slf.inner = match crate::coerce_option_value(value)? {
- Some(v) => slf.inner.clone().option(key, &v),
- None => slf.inner.clone().unset_option(key),
- };
+ slf.inner = set_reader_option_unset_none(slf.inner.clone(), key,
value)?;
Ok(slf)
}
@@ -334,7 +258,7 @@ impl PyDataFrameReader {
mut slf: PyRefMut<'py, Self>,
options: Option<&Bound<'_, PyDict>>,
) -> PyResult<PyRefMut<'py, Self>> {
- slf.inner = apply_options(slf.inner.clone(), options, true)?;
+ slf.inner = set_reader_kwargs_unset_none(slf.inner.clone(), options)?;
Ok(slf)
}
@@ -380,7 +304,7 @@ impl PyDataFrameReader {
schema: Option<&Bound<'_, PyAny>>,
options: Option<&Bound<'_, PyDict>>,
) -> PyResult<PyDataFrame> {
- let mut r = apply_options(self.inner.clone(), options, true)?;
+ let mut r = set_reader_kwargs_unset_none(self.inner.clone(), options)?;
if let Some(f) = format {
r = r.format(f);
}
@@ -445,34 +369,38 @@ impl PyDataFrameReader {
if let Some(v) = schema {
r = apply_reader_schema(r, v)?;
}
- r = set_opt(r, "primitivesAsString", primitivesAsString)?;
- r = set_opt(r, "prefersDecimal", prefersDecimal)?;
- r = set_opt(r, "allowComments", allowComments)?;
- r = set_opt(r, "allowUnquotedFieldNames", allowUnquotedFieldNames)?;
- r = set_opt(r, "allowSingleQuotes", allowSingleQuotes)?;
- r = set_opt(r, "allowNumericLeadingZero", allowNumericLeadingZero)?;
- r = set_opt(
+ r = set_options_skip_none(
r,
- "allowBackslashEscapingAnyCharacter",
- allowBackslashEscapingAnyCharacter,
+ &[
+ ("primitivesAsString", primitivesAsString),
+ ("prefersDecimal", prefersDecimal),
+ ("allowComments", allowComments),
+ ("allowUnquotedFieldNames", allowUnquotedFieldNames),
+ ("allowSingleQuotes", allowSingleQuotes),
+ ("allowNumericLeadingZero", allowNumericLeadingZero),
+ (
+ "allowBackslashEscapingAnyCharacter",
+ allowBackslashEscapingAnyCharacter,
+ ),
+ ("mode", mode),
+ ("columnNameOfCorruptRecord", columnNameOfCorruptRecord),
+ ("dateFormat", dateFormat),
+ ("timestampFormat", timestampFormat),
+ ("multiLine", multiLine),
+ ("allowUnquotedControlChars", allowUnquotedControlChars),
+ ("lineSep", lineSep),
+ ("samplingRatio", samplingRatio),
+ ("dropFieldIfAllNull", dropFieldIfAllNull),
+ ("encoding", encoding),
+ ("locale", locale),
+ ("pathGlobFilter", pathGlobFilter),
+ ("recursiveFileLookup", recursiveFileLookup),
+ ("modifiedBefore", modifiedBefore),
+ ("modifiedAfter", modifiedAfter),
+ ("allowNonNumericNumbers", allowNonNumericNumbers),
+ ("useUnsafeRow", useUnsafeRow),
+ ],
)?;
- r = set_opt(r, "mode", mode)?;
- r = set_opt(r, "columnNameOfCorruptRecord",
columnNameOfCorruptRecord)?;
- r = set_opt(r, "dateFormat", dateFormat)?;
- r = set_opt(r, "timestampFormat", timestampFormat)?;
- r = set_opt(r, "multiLine", multiLine)?;
- r = set_opt(r, "allowUnquotedControlChars",
allowUnquotedControlChars)?;
- r = set_opt(r, "lineSep", lineSep)?;
- r = set_opt(r, "samplingRatio", samplingRatio)?;
- r = set_opt(r, "dropFieldIfAllNull", dropFieldIfAllNull)?;
- r = set_opt(r, "encoding", encoding)?;
- r = set_opt(r, "locale", locale)?;
- r = set_opt(r, "pathGlobFilter", pathGlobFilter)?;
- r = set_opt(r, "recursiveFileLookup", recursiveFileLookup)?;
- r = set_opt(r, "modifiedBefore", modifiedBefore)?;
- r = set_opt(r, "modifiedAfter", modifiedAfter)?;
- r = set_opt(r, "allowNonNumericNumbers", allowNonNumericNumbers)?;
- r = set_opt(r, "useUnsafeRow", useUnsafeRow)?;
self.read_or_parse(r, "json", spark_connect::plan::ParseFormat::Json,
path)
}
@@ -497,7 +425,7 @@ impl PyDataFrameReader {
"int96RebaseMode",
] {
let value = options.map(|o|
o.get_item(name)).transpose()?.flatten();
- r = set_opt(r, name, value.as_ref())?;
+ r = set_option_skip_none(r, name, value.as_ref())?;
}
let paths = path_list(&paths)?;
self.commit(&r, "parquet");
@@ -549,42 +477,43 @@ impl PyDataFrameReader {
if let Some(v) = schema {
r = apply_reader_schema(r, v)?;
}
- r = set_opt(r, "sep", sep)?;
- r = set_opt(r, "encoding", encoding)?;
- r = set_opt(r, "quote", quote)?;
- r = set_opt(r, "escape", escape)?;
- r = set_opt(r, "comment", comment)?;
- r = set_opt(r, "header", header)?;
- r = set_opt(r, "inferSchema", inferSchema)?;
- r = set_opt(r, "ignoreLeadingWhiteSpace", ignoreLeadingWhiteSpace)?;
- r = set_opt(r, "ignoreTrailingWhiteSpace", ignoreTrailingWhiteSpace)?;
- r = set_opt(r, "nullValue", nullValue)?;
- r = set_opt(r, "nanValue", nanValue)?;
- r = set_opt(r, "positiveInf", positiveInf)?;
- r = set_opt(r, "negativeInf", negativeInf)?;
- r = set_opt(r, "dateFormat", dateFormat)?;
- r = set_opt(r, "timestampFormat", timestampFormat)?;
- r = set_opt(r, "maxColumns", maxColumns)?;
- r = set_opt(r, "maxCharsPerColumn", maxCharsPerColumn)?;
- r = set_opt(
+ r = set_options_skip_none(
r,
- "maxMalformedLogPerPartition",
- maxMalformedLogPerPartition,
+ &[
+ ("sep", sep),
+ ("encoding", encoding),
+ ("quote", quote),
+ ("escape", escape),
+ ("comment", comment),
+ ("header", header),
+ ("inferSchema", inferSchema),
+ ("ignoreLeadingWhiteSpace", ignoreLeadingWhiteSpace),
+ ("ignoreTrailingWhiteSpace", ignoreTrailingWhiteSpace),
+ ("nullValue", nullValue),
+ ("nanValue", nanValue),
+ ("positiveInf", positiveInf),
+ ("negativeInf", negativeInf),
+ ("dateFormat", dateFormat),
+ ("timestampFormat", timestampFormat),
+ ("maxColumns", maxColumns),
+ ("maxCharsPerColumn", maxCharsPerColumn),
+ ("maxMalformedLogPerPartition", maxMalformedLogPerPartition),
+ ("mode", mode),
+ ("columnNameOfCorruptRecord", columnNameOfCorruptRecord),
+ ("multiLine", multiLine),
+ ("charToEscapeQuoteEscaping", charToEscapeQuoteEscaping),
+ ("samplingRatio", samplingRatio),
+ ("enforceSchema", enforceSchema),
+ ("emptyValue", emptyValue),
+ ("locale", locale),
+ ("lineSep", lineSep),
+ ("pathGlobFilter", pathGlobFilter),
+ ("recursiveFileLookup", recursiveFileLookup),
+ ("modifiedBefore", modifiedBefore),
+ ("modifiedAfter", modifiedAfter),
+ ("unescapedQuoteHandling", unescapedQuoteHandling),
+ ],
)?;
- r = set_opt(r, "mode", mode)?;
- r = set_opt(r, "columnNameOfCorruptRecord",
columnNameOfCorruptRecord)?;
- r = set_opt(r, "multiLine", multiLine)?;
- r = set_opt(r, "charToEscapeQuoteEscaping",
charToEscapeQuoteEscaping)?;
- r = set_opt(r, "samplingRatio", samplingRatio)?;
- r = set_opt(r, "enforceSchema", enforceSchema)?;
- r = set_opt(r, "emptyValue", emptyValue)?;
- r = set_opt(r, "locale", locale)?;
- r = set_opt(r, "lineSep", lineSep)?;
- r = set_opt(r, "pathGlobFilter", pathGlobFilter)?;
- r = set_opt(r, "recursiveFileLookup", recursiveFileLookup)?;
- r = set_opt(r, "modifiedBefore", modifiedBefore)?;
- r = set_opt(r, "modifiedAfter", modifiedAfter)?;
- r = set_opt(r, "unescapedQuoteHandling", unescapedQuoteHandling)?;
self.read_or_parse(r, "csv", spark_connect::plan::ParseFormat::Csv,
path)
}
@@ -602,11 +531,16 @@ impl PyDataFrameReader {
modifiedAfter: Option<&Bound<'_, PyAny>>,
) -> PyResult<PyDataFrame> {
let mut r = self.inner.clone();
- r = set_opt(r, "mergeSchema", mergeSchema)?;
- r = set_opt(r, "pathGlobFilter", pathGlobFilter)?;
- r = set_opt(r, "recursiveFileLookup", recursiveFileLookup)?;
- r = set_opt(r, "modifiedBefore", modifiedBefore)?;
- r = set_opt(r, "modifiedAfter", modifiedAfter)?;
+ r = set_options_skip_none(
+ r,
+ &[
+ ("mergeSchema", mergeSchema),
+ ("pathGlobFilter", pathGlobFilter),
+ ("recursiveFileLookup", recursiveFileLookup),
+ ("modifiedBefore", modifiedBefore),
+ ("modifiedAfter", modifiedAfter),
+ ],
+ )?;
let paths = paths_of(path)?;
self.commit(&r, "orc");
Ok(PyDataFrame::new(r.format("orc").load_paths(paths)))
@@ -627,12 +561,17 @@ impl PyDataFrameReader {
modifiedAfter: Option<&Bound<'_, PyAny>>,
) -> PyResult<PyDataFrame> {
let mut r = self.inner.clone();
- r = set_opt(r, "wholetext", wholetext)?;
- r = set_opt(r, "lineSep", lineSep)?;
- r = set_opt(r, "pathGlobFilter", pathGlobFilter)?;
- r = set_opt(r, "recursiveFileLookup", recursiveFileLookup)?;
- r = set_opt(r, "modifiedBefore", modifiedBefore)?;
- r = set_opt(r, "modifiedAfter", modifiedAfter)?;
+ r = set_options_skip_none(
+ r,
+ &[
+ ("wholetext", wholetext),
+ ("lineSep", lineSep),
+ ("pathGlobFilter", pathGlobFilter),
+ ("recursiveFileLookup", recursiveFileLookup),
+ ("modifiedBefore", modifiedBefore),
+ ("modifiedAfter", modifiedAfter),
+ ],
+ )?;
let paths = paths_of(paths)?;
self.commit(&r, "text");
Ok(PyDataFrame::new(r.format("text").load_paths(paths)))
@@ -666,27 +605,32 @@ impl PyDataFrameReader {
locale: Option<&Bound<'_, PyAny>>,
) -> PyResult<PyDataFrame> {
let mut r = self.inner.clone();
- r = set_opt(r, "rowTag", rowTag)?;
+ r = set_option_skip_none(r, "rowTag", rowTag)?;
if let Some(v) = schema {
r = apply_reader_schema(r, v)?;
}
- r = set_opt(r, "excludeAttribute", excludeAttribute)?;
- r = set_opt(r, "attributePrefix", attributePrefix)?;
- r = set_opt(r, "valueTag", valueTag)?;
- r = set_opt(r, "ignoreSurroundingSpaces", ignoreSurroundingSpaces)?;
- r = set_opt(r, "rowValidationXSDPath", rowValidationXSDPath)?;
- r = set_opt(r, "ignoreNamespace", ignoreNamespace)?;
- r = set_opt(r, "wildcardColName", wildcardColName)?;
- r = set_opt(r, "encoding", encoding)?;
- r = set_opt(r, "inferSchema", inferSchema)?;
- r = set_opt(r, "nullValue", nullValue)?;
- r = set_opt(r, "dateFormat", dateFormat)?;
- r = set_opt(r, "timestampFormat", timestampFormat)?;
- r = set_opt(r, "mode", mode)?;
- r = set_opt(r, "columnNameOfCorruptRecord",
columnNameOfCorruptRecord)?;
- r = set_opt(r, "multiLine", multiLine)?;
- r = set_opt(r, "samplingRatio", samplingRatio)?;
- r = set_opt(r, "locale", locale)?;
+ r = set_options_skip_none(
+ r,
+ &[
+ ("excludeAttribute", excludeAttribute),
+ ("attributePrefix", attributePrefix),
+ ("valueTag", valueTag),
+ ("ignoreSurroundingSpaces", ignoreSurroundingSpaces),
+ ("rowValidationXSDPath", rowValidationXSDPath),
+ ("ignoreNamespace", ignoreNamespace),
+ ("wildcardColName", wildcardColName),
+ ("encoding", encoding),
+ ("inferSchema", inferSchema),
+ ("nullValue", nullValue),
+ ("dateFormat", dateFormat),
+ ("timestampFormat", timestampFormat),
+ ("mode", mode),
+ ("columnNameOfCorruptRecord", columnNameOfCorruptRecord),
+ ("multiLine", multiLine),
+ ("samplingRatio", samplingRatio),
+ ("locale", locale),
+ ],
+ )?;
self.read_or_parse(r, "xml", spark_connect::plan::ParseFormat::Xml,
path)
}
@@ -727,17 +671,22 @@ impl PyDataFrameReader {
)));
}
}
- r = set_opt(r, "partitionColumn", Some(column))?;
- r = set_opt(r, "lowerBound", lowerBound)?;
- r = set_opt(r, "upperBound", upperBound)?;
- r = set_opt(r, "numPartitions", numPartitions)?;
+ r = set_options_skip_none(
+ r,
+ &[
+ ("partitionColumn", Some(column)),
+ ("lowerBound", lowerBound),
+ ("upperBound", upperBound),
+ ("numPartitions", numPartitions),
+ ],
+ )?;
None
}
None => predicates,
};
if let Some(properties) = properties {
for (key, value) in properties.iter() {
- r = set_opt(r, &key.str()?.to_cow()?, Some(&value))?;
+ r = set_option_skip_none(r, &key.str()?.to_cow()?,
Some(&value))?;
}
}
// PySpark's jdbc also leaves url/dbtable on the reader.
diff --git a/crates/pyspark-rs/src/stat_arguments.rs
b/crates/pyspark-rs/src/stat_arguments.rs
index 734c5115..feee6081 100644
--- a/crates/pyspark-rs/src/stat_arguments.rs
+++ b/crates/pyspark-rs/src/stat_arguments.rs
@@ -8,29 +8,11 @@ use spark_connect::group::StatFunctions;
use crate::column::raise_pyspark;
use crate::dataframe::PyDataFrame;
+// Re-exported for the modules that raise through
`crate::stat_arguments::not_expected_type`.
+pub(crate) use crate::errors::not_expected_type;
use crate::errors::ResultExt;
use crate::interrupt::interruptible;
-/// PySpark's `NOT_EXPECTED_TYPE` error of the argument `name`, `value`, which
should be of
-/// the type `expected`.
-pub(crate) fn not_expected_type(value: &Bound<'_, PyAny>, name: &str,
expected: &str) -> PyErr {
- let type_name = value
- .get_type()
- .name()
- .map(|name| name.to_string())
- .unwrap_or_default();
- raise_pyspark(
- value.py(),
- "PySparkTypeError",
- "NOT_EXPECTED_TYPE",
- &[
- ("arg_name", name),
- ("expected_type", expected),
- ("arg_type", &type_name),
- ],
- )
-}
-
fn is_sequence(value: &Bound<'_, PyAny>) -> bool {
value.is_instance_of::<PyList>() || value.is_instance_of::<PyTuple>()
}
diff --git a/crates/pyspark-rs/src/streaming.rs
b/crates/pyspark-rs/src/streaming.rs
index 2cc39103..935c3c03 100644
--- a/crates/pyspark-rs/src/streaming.rs
+++ b/crates/pyspark-rs/src/streaming.rs
@@ -14,6 +14,7 @@ use std::sync::Arc;
use crate::dataframe::{PyDataFrame, WriterState};
use crate::errors::spark_error_to_py_exception;
use crate::interrupt::{interruptible, interruptible_outcome};
+use crate::options::{set_option_skip_none, set_options_skip_none};
/// Adapts Python listeners to the native bus: deserialize one typed event for
the whole
/// snapshot, then dispatch it through Python's callback-exception isolation
helper. Decode
@@ -173,23 +174,6 @@ fn post_started_event(
.map_err(|error| *error)
}
-/// Apply a named read option to a streaming reader when supplied (mirrors the
batch
-/// `set_opt` in readwriter.rs): `None` leaves the option unset (not the
string "None");
-/// booleans lowercase to "true"/"false" via `coerce_option_value`.
-fn set_ropt(
- r: DataStreamReader,
- name: &str,
- v: Option<&Bound<'_, PyAny>>,
-) -> PyResult<DataStreamReader> {
- match v {
- Some(x) => match crate::coerce_option_value(x)? {
- Some(sv) => Ok(r.option(name, &sv)),
- None => Ok(r),
- },
- None => Ok(r),
- }
-}
-
/// Apply a `schema` argument (a StructType or a DDL string) to a streaming
reader, as the
/// batch reader does.
fn apply_stream_schema(r: DataStreamReader, v: &Bound<'_, PyAny>) ->
PyResult<DataStreamReader> {
@@ -295,7 +279,7 @@ impl PyDataStreamReader {
schema: Option<Bound<'_, PyAny>>,
options: Option<Bound<'_, pyo3::types::PyDict>>,
) -> PyResult<()> {
- crate::readwriter::set_opts(slf.as_any(), schema.as_ref(),
options.as_ref())
+ crate::options::set_opts(slf.as_any(), schema.as_ref(),
options.as_ref())
}
/// Set the source format. As PySpark's, None unsets it, so that the
server reads its
@@ -343,14 +327,7 @@ impl PyDataStreamReader {
mut slf: PyRefMut<'py, Self>,
options: Option<&Bound<'_, PyDict>>,
) -> PyResult<PyRefMut<'py, Self>> {
- let mut opts = HashMap::new();
- if let Some(options) = options {
- for (k, v) in options.iter() {
- if let Some(val) = crate::coerce_option_value(&v)? {
- opts.insert(k.str()?.to_string(), val);
- }
- }
- }
+ let opts = crate::options::kwargs_skip_none(options)?;
slf.inner = slf.inner.clone().options(opts);
Ok(slf)
}
@@ -388,13 +365,8 @@ impl PyDataStreamReader {
if let Some(v) = schema {
r = apply_stream_schema(r, v)?;
}
- if let Some(options) = options {
- let mut opts = HashMap::new();
- for (k, v) in options.iter() {
- if let Some(val) = crate::coerce_option_value(&v)? {
- opts.insert(k.str()?.to_string(), val);
- }
- }
+ if options.is_some() {
+ let opts = crate::options::kwargs_skip_none(options)?;
r = r.options(opts);
}
// PySpark's one-shot load sets format/schema/options on the reader
itself.
@@ -469,27 +441,32 @@ impl PyDataStreamReader {
locale: Option<&Bound<'_, PyAny>>,
) -> PyResult<PyDataFrame> {
let mut r = self.inner.clone().format("xml");
- r = set_ropt(r, "rowTag", rowTag)?;
+ r = set_option_skip_none(r, "rowTag", rowTag)?;
if let Some(v) = schema {
r = apply_stream_schema(r, v)?;
}
- r = set_ropt(r, "excludeAttribute", excludeAttribute)?;
- r = set_ropt(r, "attributePrefix", attributePrefix)?;
- r = set_ropt(r, "valueTag", valueTag)?;
- r = set_ropt(r, "ignoreSurroundingSpaces", ignoreSurroundingSpaces)?;
- r = set_ropt(r, "rowValidationXSDPath", rowValidationXSDPath)?;
- r = set_ropt(r, "ignoreNamespace", ignoreNamespace)?;
- r = set_ropt(r, "wildcardColName", wildcardColName)?;
- r = set_ropt(r, "encoding", encoding)?;
- r = set_ropt(r, "inferSchema", inferSchema)?;
- r = set_ropt(r, "nullValue", nullValue)?;
- r = set_ropt(r, "dateFormat", dateFormat)?;
- r = set_ropt(r, "timestampFormat", timestampFormat)?;
- r = set_ropt(r, "mode", mode)?;
- r = set_ropt(r, "columnNameOfCorruptRecord",
columnNameOfCorruptRecord)?;
- r = set_ropt(r, "multiLine", multiLine)?;
- r = set_ropt(r, "samplingRatio", samplingRatio)?;
- r = set_ropt(r, "locale", locale)?;
+ r = set_options_skip_none(
+ r,
+ &[
+ ("excludeAttribute", excludeAttribute),
+ ("attributePrefix", attributePrefix),
+ ("valueTag", valueTag),
+ ("ignoreSurroundingSpaces", ignoreSurroundingSpaces),
+ ("rowValidationXSDPath", rowValidationXSDPath),
+ ("ignoreNamespace", ignoreNamespace),
+ ("wildcardColName", wildcardColName),
+ ("encoding", encoding),
+ ("inferSchema", inferSchema),
+ ("nullValue", nullValue),
+ ("dateFormat", dateFormat),
+ ("timestampFormat", timestampFormat),
+ ("mode", mode),
+ ("columnNameOfCorruptRecord", columnNameOfCorruptRecord),
+ ("multiLine", multiLine),
+ ("samplingRatio", samplingRatio),
+ ("locale", locale),
+ ],
+ )?;
// Like PySpark, the options and the xml format stay on the reader.
self.inner = r.clone();
let path = format_path(path)?;
@@ -533,31 +510,35 @@ impl PyDataStreamReader {
if let Some(v) = schema {
r = apply_stream_schema(r, v)?;
}
- r = set_ropt(r, "primitivesAsString", primitivesAsString)?;
- r = set_ropt(r, "prefersDecimal", prefersDecimal)?;
- r = set_ropt(r, "allowComments", allowComments)?;
- r = set_ropt(r, "allowUnquotedFieldNames", allowUnquotedFieldNames)?;
- r = set_ropt(r, "allowSingleQuotes", allowSingleQuotes)?;
- r = set_ropt(r, "allowNumericLeadingZero", allowNumericLeadingZero)?;
- r = set_ropt(
+ r = set_options_skip_none(
r,
- "allowBackslashEscapingAnyCharacter",
- allowBackslashEscapingAnyCharacter,
+ &[
+ ("primitivesAsString", primitivesAsString),
+ ("prefersDecimal", prefersDecimal),
+ ("allowComments", allowComments),
+ ("allowUnquotedFieldNames", allowUnquotedFieldNames),
+ ("allowSingleQuotes", allowSingleQuotes),
+ ("allowNumericLeadingZero", allowNumericLeadingZero),
+ (
+ "allowBackslashEscapingAnyCharacter",
+ allowBackslashEscapingAnyCharacter,
+ ),
+ ("mode", mode),
+ ("columnNameOfCorruptRecord", columnNameOfCorruptRecord),
+ ("dateFormat", dateFormat),
+ ("timestampFormat", timestampFormat),
+ ("multiLine", multiLine),
+ ("allowUnquotedControlChars", allowUnquotedControlChars),
+ ("lineSep", lineSep),
+ ("locale", locale),
+ ("dropFieldIfAllNull", dropFieldIfAllNull),
+ ("encoding", encoding),
+ ("pathGlobFilter", pathGlobFilter),
+ ("recursiveFileLookup", recursiveFileLookup),
+ ("allowNonNumericNumbers", allowNonNumericNumbers),
+ ("useUnsafeRow", useUnsafeRow),
+ ],
)?;
- r = set_ropt(r, "mode", mode)?;
- r = set_ropt(r, "columnNameOfCorruptRecord",
columnNameOfCorruptRecord)?;
- r = set_ropt(r, "dateFormat", dateFormat)?;
- r = set_ropt(r, "timestampFormat", timestampFormat)?;
- r = set_ropt(r, "multiLine", multiLine)?;
- r = set_ropt(r, "allowUnquotedControlChars",
allowUnquotedControlChars)?;
- r = set_ropt(r, "lineSep", lineSep)?;
- r = set_ropt(r, "locale", locale)?;
- r = set_ropt(r, "dropFieldIfAllNull", dropFieldIfAllNull)?;
- r = set_ropt(r, "encoding", encoding)?;
- r = set_ropt(r, "pathGlobFilter", pathGlobFilter)?;
- r = set_ropt(r, "recursiveFileLookup", recursiveFileLookup)?;
- r = set_ropt(r, "allowNonNumericNumbers", allowNonNumericNumbers)?;
- r = set_ropt(r, "useUnsafeRow", useUnsafeRow)?;
// Like PySpark, the options and the format stay on the reader.
self.inner = r.clone().format("json");
let path = format_path(path)?;
@@ -576,11 +557,16 @@ impl PyDataStreamReader {
int96RebaseMode: Option<&Bound<'_, PyAny>>,
) -> PyResult<PyDataFrame> {
let mut r = self.inner.clone();
- r = set_ropt(r, "mergeSchema", mergeSchema)?;
- r = set_ropt(r, "pathGlobFilter", pathGlobFilter)?;
- r = set_ropt(r, "recursiveFileLookup", recursiveFileLookup)?;
- r = set_ropt(r, "datetimeRebaseMode", datetimeRebaseMode)?;
- r = set_ropt(r, "int96RebaseMode", int96RebaseMode)?;
+ r = set_options_skip_none(
+ r,
+ &[
+ ("mergeSchema", mergeSchema),
+ ("pathGlobFilter", pathGlobFilter),
+ ("recursiveFileLookup", recursiveFileLookup),
+ ("datetimeRebaseMode", datetimeRebaseMode),
+ ("int96RebaseMode", int96RebaseMode),
+ ],
+ )?;
// Like PySpark, the options and the format stay on the reader.
self.inner = r.clone().format("parquet");
let path = format_path(path)?;
@@ -627,39 +613,40 @@ impl PyDataStreamReader {
if let Some(v) = schema {
r = apply_stream_schema(r, v)?;
}
- r = set_ropt(r, "sep", sep)?;
- r = set_ropt(r, "encoding", encoding)?;
- r = set_ropt(r, "quote", quote)?;
- r = set_ropt(r, "escape", escape)?;
- r = set_ropt(r, "comment", comment)?;
- r = set_ropt(r, "header", header)?;
- r = set_ropt(r, "inferSchema", inferSchema)?;
- r = set_ropt(r, "ignoreLeadingWhiteSpace", ignoreLeadingWhiteSpace)?;
- r = set_ropt(r, "ignoreTrailingWhiteSpace", ignoreTrailingWhiteSpace)?;
- r = set_ropt(r, "nullValue", nullValue)?;
- r = set_ropt(r, "nanValue", nanValue)?;
- r = set_ropt(r, "positiveInf", positiveInf)?;
- r = set_ropt(r, "negativeInf", negativeInf)?;
- r = set_ropt(r, "dateFormat", dateFormat)?;
- r = set_ropt(r, "timestampFormat", timestampFormat)?;
- r = set_ropt(r, "maxColumns", maxColumns)?;
- r = set_ropt(r, "maxCharsPerColumn", maxCharsPerColumn)?;
- r = set_ropt(
+ r = set_options_skip_none(
r,
- "maxMalformedLogPerPartition",
- maxMalformedLogPerPartition,
+ &[
+ ("sep", sep),
+ ("encoding", encoding),
+ ("quote", quote),
+ ("escape", escape),
+ ("comment", comment),
+ ("header", header),
+ ("inferSchema", inferSchema),
+ ("ignoreLeadingWhiteSpace", ignoreLeadingWhiteSpace),
+ ("ignoreTrailingWhiteSpace", ignoreTrailingWhiteSpace),
+ ("nullValue", nullValue),
+ ("nanValue", nanValue),
+ ("positiveInf", positiveInf),
+ ("negativeInf", negativeInf),
+ ("dateFormat", dateFormat),
+ ("timestampFormat", timestampFormat),
+ ("maxColumns", maxColumns),
+ ("maxCharsPerColumn", maxCharsPerColumn),
+ ("maxMalformedLogPerPartition", maxMalformedLogPerPartition),
+ ("mode", mode),
+ ("columnNameOfCorruptRecord", columnNameOfCorruptRecord),
+ ("multiLine", multiLine),
+ ("charToEscapeQuoteEscaping", charToEscapeQuoteEscaping),
+ ("enforceSchema", enforceSchema),
+ ("emptyValue", emptyValue),
+ ("locale", locale),
+ ("lineSep", lineSep),
+ ("pathGlobFilter", pathGlobFilter),
+ ("recursiveFileLookup", recursiveFileLookup),
+ ("unescapedQuoteHandling", unescapedQuoteHandling),
+ ],
)?;
- r = set_ropt(r, "mode", mode)?;
- r = set_ropt(r, "columnNameOfCorruptRecord",
columnNameOfCorruptRecord)?;
- r = set_ropt(r, "multiLine", multiLine)?;
- r = set_ropt(r, "charToEscapeQuoteEscaping",
charToEscapeQuoteEscaping)?;
- r = set_ropt(r, "enforceSchema", enforceSchema)?;
- r = set_ropt(r, "emptyValue", emptyValue)?;
- r = set_ropt(r, "locale", locale)?;
- r = set_ropt(r, "lineSep", lineSep)?;
- r = set_ropt(r, "pathGlobFilter", pathGlobFilter)?;
- r = set_ropt(r, "recursiveFileLookup", recursiveFileLookup)?;
- r = set_ropt(r, "unescapedQuoteHandling", unescapedQuoteHandling)?;
// Like PySpark, the options and the format stay on the reader.
self.inner = r.clone().format("csv");
let path = format_path(path)?;
@@ -676,9 +663,14 @@ impl PyDataStreamReader {
recursiveFileLookup: Option<&Bound<'_, PyAny>>,
) -> PyResult<PyDataFrame> {
let mut r = self.inner.clone();
- r = set_ropt(r, "mergeSchema", mergeSchema)?;
- r = set_ropt(r, "pathGlobFilter", pathGlobFilter)?;
- r = set_ropt(r, "recursiveFileLookup", recursiveFileLookup)?;
+ r = set_options_skip_none(
+ r,
+ &[
+ ("mergeSchema", mergeSchema),
+ ("pathGlobFilter", pathGlobFilter),
+ ("recursiveFileLookup", recursiveFileLookup),
+ ],
+ )?;
// Like PySpark, the options and the format stay on the reader.
self.inner = r.clone().format("orc");
let path = format_path(path)?;
@@ -696,10 +688,15 @@ impl PyDataStreamReader {
recursiveFileLookup: Option<&Bound<'_, PyAny>>,
) -> PyResult<PyDataFrame> {
let mut r = self.inner.clone();
- r = set_ropt(r, "wholetext", wholetext)?;
- r = set_ropt(r, "lineSep", lineSep)?;
- r = set_ropt(r, "pathGlobFilter", pathGlobFilter)?;
- r = set_ropt(r, "recursiveFileLookup", recursiveFileLookup)?;
+ r = set_options_skip_none(
+ r,
+ &[
+ ("wholetext", wholetext),
+ ("lineSep", lineSep),
+ ("pathGlobFilter", pathGlobFilter),
+ ("recursiveFileLookup", recursiveFileLookup),
+ ],
+ )?;
// Like PySpark, the options and the format stay on the reader.
self.inner = r.clone().format("text");
let path = format_path(path)?;
@@ -795,13 +792,8 @@ impl PyDataStreamWriter {
if let Some(qn) = query_name {
w = w.query_name(&query_name_of(qn)?);
}
- if let Some(options) = options {
- let mut opts = HashMap::new();
- for (k, v) in options.iter() {
- if let Some(val) = crate::coerce_option_value(&v)? {
- opts.insert(k.str()?.to_string(), val);
- }
- }
+ if options.is_some() {
+ let opts = crate::options::kwargs_skip_none(options)?;
w = w.options(opts);
}
// PySpark's start/toTable set these on the writer itself before
starting.
@@ -844,14 +836,7 @@ impl PyDataStreamWriter {
slf: &Bound<'py, Self>,
options: Option<&Bound<'_, PyDict>>,
) -> PyResult<Bound<'py, Self>> {
- let mut opts = HashMap::new();
- if let Some(options) = options {
- for (k, v) in options.iter() {
- if let Some(val) = crate::coerce_option_value(&v)? {
- opts.insert(k.str()?.to_string(), val);
- }
- }
- }
+ let opts = crate::options::kwargs_skip_none(options)?;
slf.borrow().inner.update(|w| w.options(opts));
Ok(slf.clone())
}
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]