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 bfbae38b [SPARK-61627][CONNECT][PYTHON] Let copy, deepcopy and pickle
copy GroupedData, the readers, the writers, the catalog and the other DataFrame
helpers as PySpark does in the Python client
bfbae38b is described below
commit bfbae38b17d6b4e89a7bd904af1bcffd05de3462
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Fri Nov 13 18:03:35 2026 +0900
[SPARK-61627][CONNECT][PYTHON] Let copy, deepcopy and pickle copy
GroupedData, the readers, the writers, the catalog and the other DataFrame
helpers as PySpark does in the Python client
### What changes were proposed in this pull request?
copy.copy, copy.deepcopy and pickle of the Python client's DataFrame
helpers raised `TypeError: cannot pickle '<class>' object`. PySpark 4.3.0
copies them as plain Python objects. A post-merge review of #610, which made
DataFrame copies match PySpark, found this sibling gap. The affected classes
were GroupedData (and the result of `pivot`), DataFrameNaFunctions,
DataFrameStatFunctions, DataFrameReader, DataFrameWriter, DataFrameWriterV2,
Catalog and RuntimeConf. A sweep of the other u [...]
- DataStreamReader, DataStreamWriter, StreamingQuery and
StreamingQueryManager;
- MergeIntoWriter and its WhenMatched, WhenNotMatched and
WhenNotMatchedBySource;
- PandasCogroupedOps;
- TableValuedFunction;
- DataSourceRegistration.
They now copy as PySpark's do:
- **copy.copy**: the copy holds the same DataFrame or session, as a shallow
copy of PySpark's `__dict__` does. Where it is observable, the copy shares
mutable state with the original, as PySpark's copies share their attributes:
- a writer's copy (batch, V2 and stream) shares the whole writer, so a
setting made on the copy is in the original's write;
- a reader's copy (batch and stream) shares its options, while the
format, schema and source name stay per object;
- a merge builder's copy shares its action lists, while
`withSchemaEvolution` stays per object.
- **copy.deepcopy**: deep-copies the DataFrame or session that the object
holds through the memo, with #610's machinery. So `copy.deepcopy({"df": df,
"g": df.groupBy("id")})` keeps the copied `g` on the copied `df`.
- **pickle**: works where PySpark's works, at every protocol. An unpickle
without an active session raises `NO_ACTIVE_SESSION`, as PySpark's does. A
stream writer's pickle keeps its `foreach`/`foreachBatch` functions.
- **Where PySpark's copies fail, these fail too:**
- deep copies and pickles of RuntimeConf, the merge builders and their
actions raise `TypeError: cannot pickle '_thread._local' object`;
- StreamingQueryManager's raise `cannot pickle '_thread.lock' object`.
The Rust core gets the accessors that the copies need: the parts of a
GroupedData, the settings of the readers and writers, and the parts of a
StreamingQuery. They are doc-hidden and not a stable API. The `spark_session()`
accessors of the readers are public, like the writer's existing one.
### Why are the changes needed?
For parity with PySpark 4.3.0: code that copies or deep-copies an object
holding a writer, a grouping or the catalog failed on the drop-in.
### Does this PR introduce _any_ user-facing change?
Yes. These objects can be copied, deep-copied and pickled, as in PySpark,
where they raised `TypeError`.
A drop-in pickle of these objects names the drop-in's own reconstructors.
So it unpickles only where the drop-in is installed, unlike a DataFrame's
pickle.
### How was this patch tested?
- New offline tests in `python/tests/test_dropin_offline.py`, with the
expected outcome of each case taken from the reference client:
- copy, deepcopy and pickle at every protocol of each object;
- unpickles without an active session;
- the memo identity of a deep copy of grouped data;
- the shared settings of the copies of the writers and readers;
- the per-object schema evolution of the merge builder.
Of the first 161 cases, 129 failed before the change; all pass after.
- StreamingQuery cannot be built offline. Its copy, deepcopy and pickle
were checked against the reference client on a live Spark 4.3.0 Connect server.
- Results:
- `tests/test_dropin_offline.py` and `tests/test_ml_offline.py`: 2337
passed, 8 skipped, after rebasing on master;
- the reader, writer, group, catalog, conf, stream, merge and TVF tests
of `tests/test_dropin_e2e.py`, against a live server: 98 passed;
- `cargo test -p apache-spark-connect -p apache-spark-connect-core
--lib`: 679 and 220 passed;
- `cargo clippy --workspace --all-targets -- -D warnings` and `cargo fmt
--check` pass, as do `scripts/audit_no_stubs.sh` and `ruff check`.
### 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 #632 from HyukjinKwon/SPARK-61627-copy-helpers.
Authored-by: Hyukjin Kwon <[email protected]>
Signed-off-by: Hyukjin Kwon <[email protected]>
---
crates/pyspark-rs/src/catalog.rs | 12 ++
crates/pyspark-rs/src/conf.rs | 14 ++
crates/pyspark-rs/src/dataframe.rs | 373 ++++++++++++++++++++++++++++++---
crates/pyspark-rs/src/datasource.rs | 13 ++
crates/pyspark-rs/src/group.rs | 153 +++++++++++++-
crates/pyspark-rs/src/lib.rs | 2 +
crates/pyspark-rs/src/readwriter.rs | 130 +++++++++---
crates/pyspark-rs/src/reduce.rs | 112 ++++++++++
crates/pyspark-rs/src/stat.rs | 15 ++
crates/pyspark-rs/src/streaming.rs | 363 +++++++++++++++++++++++++++++---
crates/pyspark-rs/src/tvf.rs | 13 ++
crates/spark-connect/src/group.rs | 46 ++++
crates/spark-connect/src/readwriter.rs | 97 +++++++++
crates/spark-connect/src/streaming.rs | 79 +++++++
crates/spark-connect/src/tvf.rs | 6 +
python/tests/test_dropin_offline.py | 241 +++++++++++++++++++++
16 files changed, 1581 insertions(+), 88 deletions(-)
diff --git a/crates/pyspark-rs/src/catalog.rs b/crates/pyspark-rs/src/catalog.rs
index 8c53c177..f6fd61d2 100644
--- a/crates/pyspark-rs/src/catalog.rs
+++ b/crates/pyspark-rs/src/catalog.rs
@@ -208,6 +208,18 @@ impl PyCatalog {
#[pymethods]
impl PyCatalog {
+ /// The shallow copy of the catalog, as PySpark's `copy.copy`: of the same
session.
+ fn __copy__(&self) -> PyCatalog {
+ PyCatalog::new(self.catalog.clone())
+ }
+
+ /// The reduce of the catalog, as PySpark's: `catalog` of its session,
which unpickles with
+ /// it.
+ fn __reduce__<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py,
pyo3::types::PyTuple>> {
+ let session = crate::session::session_object(py,
self.catalog.spark_session())?;
+ crate::reduce::getattr_reduce(py, session.into_bound(py).into_any(),
"catalog")
+ }
+
/// Get the current catalog.
fn currentCatalog(&self, py: Python<'_>) -> PyResult<String> {
self.detached(py, |catalog|
catalog.current_catalog().map_err(Box::new))
diff --git a/crates/pyspark-rs/src/conf.rs b/crates/pyspark-rs/src/conf.rs
index 442fa353..400d58a7 100644
--- a/crates/pyspark-rs/src/conf.rs
+++ b/crates/pyspark-rs/src/conf.rs
@@ -88,6 +88,20 @@ pub(crate) fn warn_all(py: Python<'_>, warnings: &[String])
-> PyResult<()> {
// whole call.
#[pymethods]
impl PyRuntimeConf {
+ /// The shallow copy of the runtime configuration, as PySpark's
`copy.copy`: of the same
+ /// session.
+ fn __copy__(&self) -> PyRuntimeConf {
+ PyRuntimeConf::new(self.session.clone())
+ }
+
+ /// The runtime configuration does not pickle, as PySpark's, whose client
holds a
+ /// thread-local state that pickle cannot copy.
+ fn __reduce__(&self) -> PyResult<()> {
+ Err(pyo3::exceptions::PyTypeError::new_err(
+ "cannot pickle '_thread._local' object",
+ ))
+ }
+
/// Set a configuration value, as PySpark's: a bool as "true" or "false",
an int as its
/// `str()`, a str as it is, and None as no value, which the server
rejects. Warns each
/// warning of the server.
diff --git a/crates/pyspark-rs/src/dataframe.rs
b/crates/pyspark-rs/src/dataframe.rs
index 24a14e57..88a3bb1f 100644
--- a/crates/pyspark-rs/src/dataframe.rs
+++ b/crates/pyspark-rs/src/dataframe.rs
@@ -1494,26 +1494,46 @@ impl PyDataFrame {
/// Group by columns for aggregation.
#[pyo3(signature = (*cols))]
- fn groupBy(&self, py: Python<'_>, cols: Vec<Bound<'_, PyAny>>) ->
PyResult<PyGroupedData> {
- let columns = self.grouping_columns(py, cols, "cols")?;
- Ok(PyGroupedData::new(self.dataframe.group_by(columns)))
+ fn groupBy(
+ slf: &Bound<'_, Self>,
+ py: Python<'_>,
+ cols: Vec<Bound<'_, PyAny>>,
+ ) -> PyResult<PyGroupedData> {
+ let this = slf.borrow();
+ let columns = this.grouping_columns(py, cols, "cols")?;
+ Ok(PyGroupedData::new(
+ this.dataframe.group_by(columns),
+ slf.clone().unbind(),
+ ))
}
/// Rollup multi-dimensional aggregation.
#[pyo3(signature = (*cols))]
- fn rollup(&self, py: Python<'_>, cols: Vec<Bound<'_, PyAny>>) ->
PyResult<PyGroupedData> {
+ fn rollup(
+ slf: &Bound<'_, Self>,
+ py: Python<'_>,
+ cols: Vec<Bound<'_, PyAny>>,
+ ) -> PyResult<PyGroupedData> {
+ let this = slf.borrow();
Ok(PyGroupedData::new(
- self.dataframe
- .rollup(self.grouping_columns(py, cols, "cols")?),
+ this.dataframe
+ .rollup(this.grouping_columns(py, cols, "cols")?),
+ slf.clone().unbind(),
))
}
/// Cube multi-dimensional aggregation.
#[pyo3(signature = (*cols))]
- fn cube(&self, py: Python<'_>, cols: Vec<Bound<'_, PyAny>>) ->
PyResult<PyGroupedData> {
+ fn cube(
+ slf: &Bound<'_, Self>,
+ py: Python<'_>,
+ cols: Vec<Bound<'_, PyAny>>,
+ ) -> PyResult<PyGroupedData> {
+ let this = slf.borrow();
Ok(PyGroupedData::new(
- self.dataframe
- .cube(self.grouping_columns(py, cols, "cols")?),
+ this.dataframe
+ .cube(this.grouping_columns(py, cols, "cols")?),
+ slf.clone().unbind(),
))
}
@@ -1523,11 +1543,13 @@ impl PyDataFrame {
/// aggregations, of Columns, names and ordinals, as are those of the sets.
#[pyo3(name = "groupingSets", signature = (groupingSets, *cols))]
fn grouping_sets(
- &self,
+ slf: &Bound<'_, Self>,
py: Python<'_>,
groupingSets: &Bound<'_, PyAny>,
cols: Vec<Bound<'_, PyAny>>,
) -> PyResult<PyGroupedData> {
+ let this = slf.borrow();
+
use pyo3::types::{PyInt, PyString};
// As PySpark's `_to_cols(grouping_set)`: a set is a sequence of
columns, or one column.
let mut sets = Vec::new();
@@ -1546,12 +1568,13 @@ impl PyDataFrame {
} else {
vec![set]
};
- sets.push(self.grouping_column_list(py, items, "groupingSets")?);
+ sets.push(this.grouping_column_list(py, items, "groupingSets")?);
}
// As PySpark's `_to_cols(cols)`, of the columns themselves, not a
list of them.
- let columns = self.grouping_column_list(py, cols, "cols")?;
+ let columns = this.grouping_column_list(py, cols, "cols")?;
Ok(PyGroupedData::new(
- self.dataframe.grouping_sets_with_columns(sets, columns),
+ this.dataframe.grouping_sets_with_columns(sets, columns),
+ slf.clone().unbind(),
))
}
@@ -2233,8 +2256,12 @@ impl PyDataFrame {
/// Alias for groupBy.
#[pyo3(signature = (*cols))]
- fn groupby(&self, py: Python<'_>, cols: Vec<Bound<'_, PyAny>>) ->
PyResult<PyGroupedData> {
- self.groupBy(py, cols)
+ fn groupby(
+ slf: &Bound<'_, Self>,
+ py: Python<'_>,
+ cols: Vec<Bound<'_, PyAny>>,
+ ) -> PyResult<PyGroupedData> {
+ Self::groupBy(slf, py, cols)
}
/// Apply a function to this DataFrame and return its result:
@@ -2824,27 +2851,29 @@ impl PyDataFrame {
/// The V1 writer interface (`df.write`).
#[getter]
- fn write(&self) -> PyDataFrameWriter {
- PyDataFrameWriter::new(self.dataframe.write())
+ fn write(slf: &Bound<'_, Self>) -> PyDataFrameWriter {
+ let this = slf.borrow();
+ PyDataFrameWriter::new(this.dataframe.write(), slf.clone().unbind())
}
/// The V2 writer interface (`df.writeTo("table")`), of the table as
[`written_table`] takes
/// it.
#[pyo3(name = "writeTo")]
- fn write_to(&self, table: &Bound<'_, PyAny>) -> PyDataFrameWriterV2 {
+ fn write_to(slf: &Bound<'_, Self>, table: &Bound<'_, PyAny>) ->
PyDataFrameWriterV2 {
let (name, unsent_table) = written_table(table);
PyDataFrameWriterV2 {
- inner: WriterState::new(self.dataframe.write_to(&name)),
+ inner:
std::sync::Arc::new(WriterState::new(slf.borrow().dataframe.write_to(&name))),
unsent_table,
+ frame: slf.clone().unbind(),
}
}
/// The streaming writer interface (`df.writeStream`).
#[getter]
#[pyo3(name = "writeStream")]
- fn write_stream(&self) -> PyDataStreamWriter {
- let writer = self.dataframe.write_stream();
- PyDataStreamWriter::new(writer)
+ fn write_stream(slf: &Bound<'_, Self>) -> PyDataStreamWriter {
+ let writer = slf.borrow().dataframe.write_stream();
+ PyDataStreamWriter::new(writer, slf.clone().unbind())
}
/// Null-handling functions (`df.na.drop()/fill()/replace()`), of this
DataFrame, their
@@ -2863,7 +2892,11 @@ impl PyDataFrame {
fn merge_into(&self, table: &Bound<'_, PyAny>, condition: &PyColumn) ->
PyMergeIntoWriter {
let (name, unsent_table) = written_table(table);
PyMergeIntoWriter {
- inner: WriterState::new(self.dataframe.merge_into(&name,
condition.column.clone())),
+ inner: std::sync::Arc::new(WriterState::new(
+ self.dataframe.merge_into(&name, condition.column.clone()),
+ )),
+ schema_evolution: std::sync::atomic::AtomicBool::new(false),
+
unsent_table,
}
}
@@ -3152,6 +3185,21 @@ pub struct PyDataFrameNaFunctions {
#[pymethods]
impl PyDataFrameNaFunctions {
+ /// The shallow copy of the null functions, as PySpark's `copy.copy`: of
the same DataFrame.
+ fn __copy__(&self, py: Python<'_>) -> PyDataFrameNaFunctions {
+ PyDataFrameNaFunctions {
+ df: self.df.clone(),
+ frame: self.frame.clone_ref(py),
+ }
+ }
+
+ /// The reduce of the null functions, as PySpark's: `na` of their
DataFrame, which unpickles
+ /// with it.
+ fn __reduce__<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py,
PyTuple>> {
+ let frame = self.frame.clone_ref(py).into_any().into_bound(py);
+ crate::reduce::getattr_reduce(py, frame, "na")
+ }
+
/// The DataFrame of these functions, as PySpark's
`DataFrameNaFunctions.df`: `df.na.df` is
/// `df`.
#[getter(df)]
@@ -3442,7 +3490,12 @@ fn check_written_table(py: Python<'_>, unsent_table:
&Option<Py<PyAny>>) -> PyRe
/// replaced in place and `merge` runs on a clone.
#[pyclass(name = "MergeIntoWriter", module = "pyspark.sql.merge", weakref,
dict)]
pub struct PyMergeIntoWriter {
- inner: WriterState<spark_connect::MergeIntoWriter>,
+ inner: std::sync::Arc<WriterState<spark_connect::MergeIntoWriter>>,
+ /// Whether `withSchemaEvolution` was called on this builder, as PySpark's
+ /// `_schema_evolution_enabled` attribute, which a shallow copy takes by
value and then
+ /// keeps apart from the copied builder.
+ schema_evolution: std::sync::atomic::AtomicBool,
+
/// The table of `mergeInto` that its string field does not take, which
Python's garbage
/// collector sees ([`written_table`]).
unsent_table: Option<Py<PyAny>>,
@@ -3478,6 +3531,29 @@ fn check_merge_clause(
#[pymethods]
impl PyMergeIntoWriter {
+ /// The shallow copy of a merge builder, as PySpark's `copy.copy`: the
copy shares the state
+ /// of this one, its table, its condition and its actions, as the copy of
PySpark's shares
+ /// its attributes.
+ fn __copy__(&self, py: Python<'_>) -> PyMergeIntoWriter {
+ PyMergeIntoWriter {
+ inner: std::sync::Arc::clone(&self.inner),
+ schema_evolution: std::sync::atomic::AtomicBool::new(
+ self.schema_evolution
+ .load(std::sync::atomic::Ordering::SeqCst),
+ ),
+
+ unsent_table: self.unsent_table.as_ref().map(|table|
table.clone_ref(py)),
+ }
+ }
+
+ /// A merge builder does not pickle, as PySpark's, whose client holds a
thread-local state
+ /// that pickle cannot copy.
+ fn __reduce__(&self) -> PyResult<()> {
+ Err(pyo3::exceptions::PyTypeError::new_err(
+ "cannot pickle '_thread._local' object",
+ ))
+ }
+
/// Nested builder-class references, mirroring pyspark's
`MergeIntoWriter.WhenMatched`
/// etc. (the objects returned by `whenMatched()` / `whenNotMatched()` /
/// `whenNotMatchedBySource()`).
@@ -3526,13 +3602,22 @@ impl PyMergeIntoWriter {
#[pyo3(name = "withSchemaEvolution")]
fn with_schema_evolution<'py>(slf: &Bound<'py, Self>) -> Bound<'py, Self> {
- slf.borrow().inner.update(|w| w.with_schema_evolution());
+ slf.borrow()
+ .schema_evolution
+ .store(true, std::sync::atomic::Ordering::SeqCst);
+
slf.clone()
}
fn merge(&self, py: Python<'_>) -> PyResult<()> {
check_written_table(py, &self.unsent_table)?;
- let writer = self.inner.get();
+ let mut writer = self.inner.get();
+ if self
+ .schema_evolution
+ .load(std::sync::atomic::Ordering::SeqCst)
+ {
+ writer = writer.with_schema_evolution();
+ }
interruptible(py, &writer.spark_session(), || {
writer.merge().map_err(Box::new)
})
@@ -3570,6 +3655,23 @@ pub struct PyWhenMatched {
#[pymethods]
impl PyWhenMatched {
+ /// The shallow copy of a merge action, as PySpark's `copy.copy`: of the
same merge builder
+ /// and condition.
+ fn __copy__(&self, py: Python<'_>) -> PyWhenMatched {
+ PyWhenMatched {
+ writer: self.writer.clone_ref(py),
+ condition: self.condition.clone(),
+ }
+ }
+
+ /// A merge action does not pickle, as PySpark's, whose merge builder
holds a client with a
+ /// thread-local state that pickle cannot copy.
+ fn __reduce__(&self) -> PyResult<()> {
+ Err(pyo3::exceptions::PyTypeError::new_err(
+ "cannot pickle '_thread._local' object",
+ ))
+ }
+
#[pyo3(name = "updateAll")]
fn update_all(&self, py: Python<'_>) -> PyResult<Py<PyMergeIntoWriter>> {
let cond = self.condition.clone();
@@ -3605,6 +3707,23 @@ pub struct PyWhenNotMatched {
#[pymethods]
impl PyWhenNotMatched {
+ /// The shallow copy of a merge action, as PySpark's `copy.copy`: of the
same merge builder
+ /// and condition.
+ fn __copy__(&self, py: Python<'_>) -> PyWhenNotMatched {
+ PyWhenNotMatched {
+ writer: self.writer.clone_ref(py),
+ condition: self.condition.clone(),
+ }
+ }
+
+ /// A merge action does not pickle, as PySpark's, whose merge builder
holds a client with a
+ /// thread-local state that pickle cannot copy.
+ fn __reduce__(&self) -> PyResult<()> {
+ Err(pyo3::exceptions::PyTypeError::new_err(
+ "cannot pickle '_thread._local' object",
+ ))
+ }
+
#[pyo3(name = "insertAll")]
fn insert_all(&self, py: Python<'_>) -> PyResult<Py<PyMergeIntoWriter>> {
let cond = self.condition.clone();
@@ -3634,6 +3753,23 @@ pub struct PyWhenNotMatchedBySource {
#[pymethods]
impl PyWhenNotMatchedBySource {
+ /// The shallow copy of a merge action, as PySpark's `copy.copy`: of the
same merge builder
+ /// and condition.
+ fn __copy__(&self, py: Python<'_>) -> PyWhenNotMatchedBySource {
+ PyWhenNotMatchedBySource {
+ writer: self.writer.clone_ref(py),
+ condition: self.condition.clone(),
+ }
+ }
+
+ /// A merge action does not pickle, as PySpark's, whose merge builder
holds a client with a
+ /// thread-local state that pickle cannot copy.
+ fn __reduce__(&self) -> PyResult<()> {
+ Err(pyo3::exceptions::PyTypeError::new_err(
+ "cannot pickle '_thread._local' object",
+ ))
+ }
+
#[pyo3(name = "updateAll")]
fn update_all(&self, py: Python<'_>) -> PyResult<Py<PyMergeIntoWriter>> {
let cond = self.condition.clone();
@@ -3673,18 +3809,25 @@ impl PyWhenNotMatchedBySource {
dict
)]
pub struct PyDataFrameWriter {
- inner: WriterState<spark_connect::readwriter::DataFrameWriter>,
+ inner:
std::sync::Arc<WriterState<spark_connect::readwriter::DataFrameWriter>>,
+ /// The DataFrame that is written, as the Python object of `df.write`, as
PySpark's `_df`.
+ frame: Py<PyDataFrame>,
+
/// The `numBuckets` of the last `bucketBy` when it is a positive count
that the proto
/// refuses, which PySpark keeps and fails each write with, as its
`WriteOperation.command`
/// sets it in the proto; the core writer then has no bucketing.
- refused_bucket_count: std::sync::Mutex<Option<Py<PyAny>>>,
+ refused_bucket_count: std::sync::Arc<std::sync::Mutex<Option<Py<PyAny>>>>,
}
impl PyDataFrameWriter {
- pub(crate) fn new(writer: spark_connect::readwriter::DataFrameWriter) ->
Self {
+ pub(crate) fn new(
+ writer: spark_connect::readwriter::DataFrameWriter,
+ frame: Py<PyDataFrame>,
+ ) -> Self {
PyDataFrameWriter {
- inner: WriterState::new(writer),
- refused_bucket_count: std::sync::Mutex::new(None),
+ inner: std::sync::Arc::new(WriterState::new(writer)),
+ refused_bucket_count:
std::sync::Arc::new(std::sync::Mutex::new(None)),
+ frame,
}
}
@@ -3745,6 +3888,103 @@ fn apply_write_common(
#[pymethods]
impl PyDataFrameWriter {
+ /// The shallow copy of a writer, as PySpark's `copy.copy`: the copy
shares the state of
+ /// this writer, as its `_write` is the same object, so that a setter of
either one is seen
+ /// by both, and the same DataFrame.
+ fn __copy__(&self, py: Python<'_>) -> PyDataFrameWriter {
+ PyDataFrameWriter {
+ inner: std::sync::Arc::clone(&self.inner),
+ refused_bucket_count:
std::sync::Arc::clone(&self.refused_bucket_count),
+ frame: self.frame.clone_ref(py),
+ }
+ }
+
+ /// The reduce of a writer, as PySpark's pickle of its DataFrame and its
state, which
+ /// `_of_state` gives back.
+ fn __reduce__<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py,
PyTuple>> {
+ use crate::reduce::{of_state_reduce, optional_object, save_mode_name,
str_dict};
+
+ let writer = self.inner.get();
+ let mode = match writer.get_unsupported_mode() {
+ Some(mode) => mode.to_string(),
+ None => save_mode_name(writer.get_save_mode()).to_string(),
+ };
+ let refused = self
+ .refused_bucket_count()
+ .as_ref()
+ .map(|n| n.clone_ref(py));
+ let args = PyTuple::new(
+ py,
+ [
+ self.frame.clone_ref(py).into_any().into_bound(py),
+ writer.get_format().into_pyobject(py)?.into_any(),
+ mode.into_pyobject(py)?.into_any(),
+ str_dict(py, writer.get_options())?.into_any(),
+ PyList::new(py, writer.get_partition_cols())?.into_any(),
+ writer.get_num_buckets().into_pyobject(py)?.into_any(),
+ PyList::new(py, writer.get_bucket_cols())?.into_any(),
+ PyList::new(py, writer.get_sort_cols())?.into_any(),
+ PyList::new(py, writer.get_cluster_cols())?.into_any(),
+ optional_object(py, refused.as_ref()),
+ ],
+ )?;
+ of_state_reduce::<PyDataFrameWriter>(py, args)
+ }
+
+ /// A writer of its state, as `__reduce__` gives it: of the DataFrame
`frame`, the format,
+ /// the save mode (or the last mode that is not one), the options, the
partitioning, the
+ /// buckets (their number, None if there is none, and their columns), the
sorting and the
+ /// clustering columns, and the number of buckets that the proto refuses.
+ #[staticmethod]
+ #[pyo3(
+ signature = (
+ frame,
+ format,
+ mode,
+ options,
+ partition_cols,
+ num_buckets,
+ bucket_cols,
+ sort_cols,
+ cluster_cols,
+ refused
+ )
+ )]
+ fn _of_state(
+ py: Python<'_>,
+ frame: Py<PyDataFrame>,
+ format: Option<String>,
+ mode: String,
+ options: std::collections::HashMap<String, String>,
+ partition_cols: Vec<String>,
+ num_buckets: Option<i32>,
+ bucket_cols: Vec<String>,
+ sort_cols: Vec<String>,
+ cluster_cols: Vec<String>,
+ refused: Option<Py<PyAny>>,
+ ) -> PyResult<PyDataFrameWriter> {
+ let mut writer = frame.borrow(py).dataframe.write();
+ if let Some(format) = format {
+ writer = writer.format(&format);
+ }
+ writer = writer.mode(&mode).options(options);
+ if !partition_cols.is_empty() {
+ writer = writer.partition_by(partition_cols);
+ }
+ if let Some(num_buckets) = num_buckets {
+ writer = writer.bucket_by(num_buckets, bucket_cols);
+ }
+ if !sort_cols.is_empty() {
+ writer = writer.sort_by(sort_cols);
+ }
+ if !cluster_cols.is_empty() {
+ writer = writer.cluster_by(cluster_cols);
+ }
+ let restored = PyDataFrameWriter::new(writer, frame);
+ *restored.refused_bucket_count() = refused;
+ Ok(restored)
+ }
+
/// Set the schema, if any, and the options of `options` that are not
None, through its own
/// `schema` and `option`, as PySpark's `OptionUtils._set_opts`, which
pandas-on-Spark calls.
#[pyo3(signature = (schema=None, **options))]
@@ -4247,7 +4487,10 @@ impl PyDataFrameWriter {
dict
)]
pub struct PyDataFrameWriterV2 {
- inner: WriterState<spark_connect::readwriter::DataFrameWriterV2>,
+ inner:
std::sync::Arc<WriterState<spark_connect::readwriter::DataFrameWriterV2>>,
+ /// The DataFrame that is written, as the Python object of `df.writeTo`,
as PySpark's `_df`.
+ frame: Py<PyDataFrame>,
+
/// The table of `writeTo` that its string field does not take, which
Python's garbage
/// collector sees ([`written_table`]).
unsent_table: Option<Py<PyAny>>,
@@ -4257,6 +4500,72 @@ impl PyDataFrameWriterV2 {}
#[pymethods]
impl PyDataFrameWriterV2 {
+ /// The shallow copy of a V2 writer, as PySpark's `copy.copy`: the copy
shares the state of
+ /// this writer, as its `_write` is the same object, and the same
DataFrame.
+ fn __copy__(&self, py: Python<'_>) -> PyDataFrameWriterV2 {
+ PyDataFrameWriterV2 {
+ inner: std::sync::Arc::clone(&self.inner),
+ unsent_table: self.unsent_table.as_ref().map(|table|
table.clone_ref(py)),
+ frame: self.frame.clone_ref(py),
+ }
+ }
+
+ /// The reduce of a V2 writer, as PySpark's pickle of its DataFrame and
its state, which
+ /// `_of_state` gives back.
+ fn __reduce__<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py,
PyTuple>> {
+ use crate::reduce::{column_list, of_state_reduce, str_dict};
+
+ let writer = self.inner.get();
+ let args = PyTuple::new(
+ py,
+ [
+ self.frame.clone_ref(py).into_any().into_bound(py),
+ writer.get_table_name().into_pyobject(py)?.into_any(),
+ writer.get_provider().into_pyobject(py)?.into_any(),
+ str_dict(py, writer.get_options())?.into_any(),
+ str_dict(py, writer.get_table_properties())?.into_any(),
+ column_list(py, writer.get_partition_cols())?.into_any(),
+ PyList::new(py, writer.get_cluster_cols())?.into_any(),
+ ],
+ )?;
+ of_state_reduce::<PyDataFrameWriterV2>(py, args)
+ }
+
+ /// A V2 writer of its state, as `__reduce__` gives it: of the DataFrame
`frame`, the table,
+ /// the provider, the options, the table properties, the partitioning and
the clustering.
+ #[staticmethod]
+ fn _of_state(
+ py: Python<'_>,
+ frame: Py<PyDataFrame>,
+ table: &str,
+ provider: Option<String>,
+ options: std::collections::HashMap<String, String>,
+ table_properties: std::collections::HashMap<String, String>,
+ partition_cols: &Bound<'_, PyAny>,
+ cluster_cols: Vec<String>,
+ ) -> PyResult<PyDataFrameWriterV2> {
+ let mut writer = frame.borrow(py).dataframe.write_to(table);
+ if let Some(provider) = provider {
+ writer = writer.using(&provider);
+ }
+ writer = writer.options(options);
+ for (property, value) in &table_properties {
+ writer = writer.table_property(property, value);
+ }
+ let partition_cols = crate::reduce::columns_of(partition_cols)?;
+ if !partition_cols.is_empty() {
+ writer = writer.partition_by(partition_cols);
+ }
+ if !cluster_cols.is_empty() {
+ writer = writer.cluster_by(cluster_cols);
+ }
+ Ok(PyDataFrameWriterV2 {
+ inner: std::sync::Arc::new(WriterState::new(writer)),
+ unsent_table: None,
+ frame,
+ })
+ }
+
/// Set the schema, if any, and the options of `options` that are not
None, through its own
/// `schema` and `option`, as PySpark's `OptionUtils._set_opts`, which
pandas-on-Spark calls.
#[pyo3(signature = (schema=None, **options))]
diff --git a/crates/pyspark-rs/src/datasource.rs
b/crates/pyspark-rs/src/datasource.rs
index 0b5dd2e1..b6519e19 100644
--- a/crates/pyspark-rs/src/datasource.rs
+++ b/crates/pyspark-rs/src/datasource.rs
@@ -30,6 +30,19 @@ impl PyDataSourceRegistration {
#[pymethods]
impl PyDataSourceRegistration {
+ /// The shallow copy of the data source registration, as PySpark's
`copy.copy`: of the same
+ /// session.
+ fn __copy__(&self, py: Python<'_>) -> PyDataSourceRegistration {
+ PyDataSourceRegistration::new(self.session.clone_ref(py))
+ }
+
+ /// The reduce of the data source registration, as PySpark's: `dataSource`
of its session,
+ /// which unpickles with it.
+ fn __reduce__<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py,
pyo3::types::PyTuple>> {
+ let session = self.session.clone_ref(py).into_bound(py).into_any();
+ crate::reduce::getattr_reduce(py, session, "dataSource")
+ }
+
/// The session of the registration, as PySpark's
`DataSourceRegistration.sparkSession`.
#[getter(sparkSession)]
fn spark_session(&self, py: Python<'_>) -> Py<PySparkSession> {
diff --git a/crates/pyspark-rs/src/group.rs b/crates/pyspark-rs/src/group.rs
index 44d23c48..de30c405 100644
--- a/crates/pyspark-rs/src/group.rs
+++ b/crates/pyspark-rs/src/group.rs
@@ -1,13 +1,17 @@
//! PyO3 wrapper for spark_connect::group::GroupedData.
use pyo3::prelude::*;
+use pyo3::types::{PyList, PyTuple};
+
use spark_connect::group::{CoGroupedData as RustCoGroupedData, GroupedData as
RustGroupedData};
use spark_connect::udf::eval_type;
+use crate::column::PyColumn;
use crate::dataframe::{
build_map_udf, infer_group_map_eval_type, validate_map_function,
PyDataFrame,
};
use crate::errors::ResultExt;
+
use crate::interrupt::interruptible;
/// As PySpark's `_check_same_session` of the DataFrames of grouped data:
`SESSION_NOT_SAME`
@@ -33,11 +37,17 @@ fn check_same_session(
#[pyclass(name = "GroupedData", module = "pyspark.sql.group", weakref, dict)]
pub struct PyGroupedData {
pub(crate) grouped_data: RustGroupedData,
+ /// The DataFrame that is grouped, as the Python object that `groupBy` was
called on, as
+ /// PySpark's `GroupedData._df` is.
+ frame: Py<PyDataFrame>,
}
impl PyGroupedData {
- pub fn new(grouped_data: RustGroupedData) -> Self {
- PyGroupedData { grouped_data }
+ pub fn new(grouped_data: RustGroupedData, frame: Py<PyDataFrame>) -> Self {
+ PyGroupedData {
+ grouped_data,
+ frame,
+ }
}
}
@@ -105,6 +115,89 @@ impl PyGroupedData {
#[pymethods]
impl PyGroupedData {
+ /// The DataFrame that is grouped, as PySpark's `GroupedData._df`.
+ #[getter(_df)]
+ fn df(&self, py: Python<'_>) -> Py<PyDataFrame> {
+ self.frame.clone_ref(py)
+ }
+
+ /// The shallow copy of grouped data, as PySpark's `copy.copy`: of the
DataFrame that it
+ /// groups, which the copy holds too, and of the same grouping.
+ fn __copy__(&self, py: Python<'_>) -> PyGroupedData {
+ PyGroupedData {
+ grouped_data: self.grouped_data.clone(),
+ frame: self.frame.clone_ref(py),
+ }
+ }
+
+ /// The reduce of grouped data, as PySpark's pickle of its state: its
DataFrame, the
+ /// grouping columns, the type of the grouping, the pivot column and
values, and the
+ /// grouping sets, which `_of_state` gives back.
+ fn __reduce__<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py,
PyTuple>> {
+ use crate::reduce::{column_list, group_type_name, of_state_reduce};
+
+ let group = &self.grouped_data;
+ let pivot_col = match group.pivot_column() {
+ Some(column) => Bound::new(py, PyColumn::new(column))?.into_any(),
+ None => py.None().into_bound(py),
+ };
+ let sets = group
+ .grouping_set_columns()
+ .iter()
+ .map(|set| column_list(py, set))
+ .collect::<PyResult<Vec<_>>>()?;
+ let args = PyTuple::new(
+ py,
+ [
+ self.frame.clone_ref(py).into_any().into_bound(py),
+ group_type_name(group.group_type())
+ .into_pyobject(py)?
+ .into_any(),
+ column_list(py, group.grouping_columns())?.into_any(),
+ pivot_col,
+ column_list(py, &group.pivot_value_columns())?.into_any(),
+ PyList::new(py, sets)?.into_any(),
+ ],
+ )?;
+ of_state_reduce::<PyGroupedData>(py, args)
+ }
+
+ /// Grouped data of its state, as `__reduce__` gives it: of the DataFrame
`frame`, the
+ /// grouping columns `cols`, the type of the grouping `group_type`, the
pivot column
+ /// `pivot_col` (None if there is none), the pivot values `pivot_values`,
and the grouping
+ /// sets `grouping_sets`, each a list of columns.
+ #[staticmethod]
+ fn _of_state(
+ py: Python<'_>,
+ frame: Py<PyDataFrame>,
+ group_type: &str,
+ cols: &Bound<'_, PyAny>,
+ pivot_col: &Bound<'_, PyAny>,
+ pivot_values: &Bound<'_, PyAny>,
+ grouping_sets: &Bound<'_, PyAny>,
+ ) -> PyResult<PyGroupedData> {
+ use crate::reduce::{columns_of, group_type_of};
+
+ let pivot_col = match pivot_col.is_none() {
+ true => None,
+ false => Some(pivot_col.extract::<PyRef<'_,
PyColumn>>()?.column.clone()),
+ };
+ let sets = grouping_sets
+ .try_iter()?
+ .map(|set| columns_of(&set?))
+ .collect::<PyResult<Vec<_>>>()?;
+ let dataframe = frame.borrow(py).dataframe.clone();
+ let grouped = RustGroupedData::from_parts(
+ dataframe,
+ columns_of(cols)?,
+ group_type_of(group_type)?,
+ pivot_col,
+ columns_of(pivot_values)?,
+ sets,
+ );
+ Ok(PyGroupedData::new(grouped, frame))
+ }
+
/// As PySpark Connect's: the grouping expressions, the columns of the
DataFrame and their
/// types, and the type of the grouping, such as
/// `GroupedData[grouping expressions: [k], value: [k: int, v: double],
type: GroupBy]`.
@@ -181,6 +274,7 @@ impl PyGroupedData {
#[pyo3(signature = (pivot_col, values=None))]
fn pivot(
&self,
+ py: Python<'_>,
pivot_col: &Bound<'_, PyAny>,
values: Option<&Bound<'_, PyAny>>,
) -> PyResult<PyGroupedData> {
@@ -219,6 +313,7 @@ impl PyGroupedData {
let pcol = self.grouped_data.dataframe().col(&name.to_cow()?);
Ok(PyGroupedData::new(
self.grouped_data.pivot(pcol, vals).to_pyerr()?,
+ self.frame.clone_ref(py),
))
}
@@ -337,10 +432,18 @@ impl PyGroupedData {
/// `GroupedData.cogroup`.
#[pyo3(name = "cogroup")]
- fn cogroup(&self, py: Python<'_>, other: &PyGroupedData) ->
PyResult<PyCoGroupedData> {
- check_same_session(py, &self.grouped_data, &other.grouped_data)?;
+ fn cogroup(
+ slf: &Bound<'_, Self>,
+ py: Python<'_>,
+ other: &Bound<'_, PyGroupedData>,
+ ) -> PyResult<PyCoGroupedData> {
+ let this = slf.borrow();
+ let that = other.borrow();
+ check_same_session(py, &this.grouped_data, &that.grouped_data)?;
Ok(PyCoGroupedData {
- inner: self.grouped_data.cogroup(&other.grouped_data),
+ inner: this.grouped_data.cogroup(&that.grouped_data),
+ left: slf.clone().unbind(),
+ right: other.clone().unbind(),
})
}
@@ -519,10 +622,50 @@ fn twus_func<'py>(
)]
pub struct PyCoGroupedData {
pub(crate) inner: RustCoGroupedData,
+ /// The grouped data on the left and on the right, as the Python objects
of `cogroup`.
+ left: Py<PyGroupedData>,
+ right: Py<PyGroupedData>,
}
#[pymethods]
impl PyCoGroupedData {
+ /// The shallow copy of cogrouped ops, as PySpark's `copy.copy`: of the
same two groups.
+ fn __copy__(&self, py: Python<'_>) -> PyCoGroupedData {
+ PyCoGroupedData {
+ inner: self.inner.clone(),
+ left: self.left.clone_ref(py),
+ right: self.right.clone_ref(py),
+ }
+ }
+
+ /// The reduce of cogrouped ops, as PySpark's pickle of its two grouped
data, which
+ /// `_of_state` gives back.
+ fn __reduce__<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py,
PyTuple>> {
+ let args = PyTuple::new(
+ py,
+ [
+ self.left.clone_ref(py).into_any().into_bound(py),
+ self.right.clone_ref(py).into_any().into_bound(py),
+ ],
+ )?;
+ crate::reduce::of_state_reduce::<PyCoGroupedData>(py, args)
+ }
+
+ /// The cogrouped ops of two grouped data, as `__reduce__` gives them back.
+ #[staticmethod]
+ fn _of_state(
+ py: Python<'_>,
+ left: Py<PyGroupedData>,
+ right: Py<PyGroupedData>,
+ ) -> PyResult<PyCoGroupedData> {
+ let inner = {
+ let this = left.borrow(py);
+ let that = right.borrow(py);
+ this.grouped_data.cogroup(&that.grouped_data)
+ };
+ Ok(PyCoGroupedData { inner, left, right })
+ }
+
/// `PandasCogroupedOps.applyInPandas`.
#[pyo3(name = "applyInPandas")]
fn apply_in_pandas(
diff --git a/crates/pyspark-rs/src/lib.rs b/crates/pyspark-rs/src/lib.rs
index 6dd9725f..e466d1be 100644
--- a/crates/pyspark-rs/src/lib.rs
+++ b/crates/pyspark-rs/src/lib.rs
@@ -35,6 +35,8 @@ mod progress;
mod pyarrow_export;
mod pyarrow_import;
mod readwriter;
+mod reduce;
+
mod resource;
mod row;
mod session;
diff --git a/crates/pyspark-rs/src/readwriter.rs
b/crates/pyspark-rs/src/readwriter.rs
index d8f0bca0..be9c9f32 100644
--- a/crates/pyspark-rs/src/readwriter.rs
+++ b/crates/pyspark-rs/src/readwriter.rs
@@ -27,18 +27,38 @@ use crate::options::{
)]
pub struct PyDataFrameReader {
inner: DataFrameReader,
+ /// The options of the reader, which a shallow copy of it shares, as
PySpark's `_options` dict
+ /// is shared by the copies of a reader. The core reader holds none of
them (see `state`).
+ options: std::sync::Arc<crate::dataframe::WriterState<HashMap<String,
String>>>,
}
impl PyDataFrameReader {
pub fn new(reader: DataFrameReader) -> Self {
- PyDataFrameReader { inner: reader }
+ let options = reader.get_options().clone();
+ PyDataFrameReader {
+ inner: without_options(reader, &options),
+ options:
std::sync::Arc::new(crate::dataframe::WriterState::new(options)),
+ }
+ }
+
+ /// The core reader of this reader, with its options, which the copies of
this reader share.
+ fn state(&self) -> DataFrameReader {
+ self.inner.clone().options(self.options.get())
+ }
+
+ /// Keep `reader` as the state of this reader: its options are shared by
the copies of this
+ /// reader, and its format and schema are this reader's own.
+ fn set_state(&mut self, reader: DataFrameReader) {
+ let options = reader.get_options().clone();
+ self.inner = without_options(reader, &options);
+ self.options.set(options);
}
/// Keep the options of a format-specific read on this reader, as PySpark
does
/// (its `json`/`csv`/... set the options and the format on `self`, then
`load`).
/// Called before the path is checked, as PySpark's `load` sets the format
first.
fn commit(&mut self, r: &DataFrameReader, format: &str) {
- self.inner = r.clone().format(format);
+ self.set_state(r.clone().format(format));
}
/// The DataFrame of `r`, this reader with the options of a call of
`json`, `csv` or `xml`
@@ -62,7 +82,7 @@ impl PyDataFrameReader {
.parse(parse_format, &df.dataframe)
.map(PyDataFrame::new)
.to_pyerr()?;
- self.inner = r;
+ self.set_state(r);
return Ok(parsed);
}
if path.is_instance_of::<pyo3::types::PyString>()
@@ -75,11 +95,18 @@ impl PyDataFrameReader {
return Ok(PyDataFrame::new(r.format(format).load_paths(paths)));
}
// PySpark's options are set before the path is checked, so they stay
on this reader.
- self.inner = r;
+ self.set_state(r);
Err(not_expected_type(path, "path", "str, list, or DataFrame"))
}
}
+/// The reader without the options of `options`, which the reader keeps apart
from its core state.
+fn without_options(reader: DataFrameReader, options: &HashMap<String, String>)
-> DataFrameReader {
+ options
+ .keys()
+ .fold(reader, |reader, key| reader.unset_option(key))
+}
+
/// The paths of `path`, a path or a list of them, or None for none, as
PySpark's `load` takes
/// them: anything else fails its assertion.
fn paths_of(path: &Bound<'_, PyAny>) -> PyResult<Vec<String>> {
@@ -291,6 +318,52 @@ fn apply_optional_schema(
#[pymethods]
impl PyDataFrameReader {
+ /// The shallow copy of a reader, as PySpark's `copy.copy`: the copy has
the same state.
+ fn __copy__(&self) -> PyDataFrameReader {
+ PyDataFrameReader {
+ inner: self.state(),
+ options: std::sync::Arc::clone(&self.options),
+ }
+ }
+
+ /// The reduce of a reader, as PySpark's pickle of its session and its
state, which
+ /// `_of_state` gives back.
+ fn __reduce__<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py,
pyo3::types::PyTuple>> {
+ use crate::reduce::{of_state_reduce, str_dict};
+
+ let session = crate::session::session_object(py,
&self.inner.spark_session())?;
+ let args = pyo3::types::PyTuple::new(
+ py,
+ [
+ session.into_bound(py).into_any(),
+ self.inner.get_format().into_pyobject(py)?.into_any(),
+ self.inner.get_schema().into_pyobject(py)?.into_any(),
+ str_dict(py, &self.options.get())?.into_any(),
+ ],
+ )?;
+ of_state_reduce::<PyDataFrameReader>(py, args)
+ }
+
+ /// A reader of its state, as `__reduce__` gives it: of the session
`session`, the format,
+ /// the schema and the options.
+ #[staticmethod]
+ fn _of_state(
+ py: Python<'_>,
+ session: Py<crate::session::PySparkSession>,
+ format: Option<String>,
+ schema: String,
+ options: HashMap<String, String>,
+ ) -> PyDataFrameReader {
+ let mut reader = session.borrow(py).session.read();
+ if let Some(format) = format {
+ reader = reader.format(&format);
+ }
+ if !schema.is_empty() {
+ reader = reader.schema(schema);
+ }
+ PyDataFrameReader::new(reader.options(options))
+ }
+
/// Set the schema, if any, and the options of `options` that are not
None, through its own
/// `schema` and `option`, as PySpark's `OptionUtils._set_opts`, which
pandas-on-Spark calls.
#[pyo3(signature = (schema=None, **options))]
@@ -305,10 +378,11 @@ impl PyDataFrameReader {
/// Set the source format (e.g. "parquet", "json", "csv"). As PySpark's,
None unsets it, so
/// that the server reads its default source.
fn format<'py>(mut slf: PyRefMut<'py, Self>, source: Option<&str>) ->
PyRefMut<'py, Self> {
- slf.inner = match source {
- Some(source) => slf.inner.clone().format(source),
- None => slf.inner.clone().clear_format(),
+ let state = match source {
+ Some(source) => slf.state().format(source),
+ None => slf.state().clear_format(),
};
+ slf.set_state(state);
slf
}
@@ -318,7 +392,8 @@ impl PyDataFrameReader {
schema: &Bound<'_, PyAny>,
) -> PyResult<PyRefMut<'py, Self>> {
let schema = reader_schema(schema)?;
- slf.inner = slf.inner.clone().schema(schema);
+ let state = slf.state().schema(schema);
+ slf.set_state(state);
Ok(slf)
}
@@ -335,12 +410,14 @@ impl PyDataFrameReader {
key.hash()?;
// Only a str that UTF-8 encodes is the key of an option that is
set.
if let Ok(key) = key.extract::<String>() {
- slf.inner = slf.inner.clone().unset_option(&key);
+ let state = slf.state().unset_option(&key);
+ slf.set_state(state);
}
return Ok(slf);
}
let key = crate::options::reader_option_key(key)?;
- slf.inner = set_reader_option_unset_none(slf.inner.clone(), &key,
value)?;
+ let state = set_reader_option_unset_none(slf.state(), &key, value)?;
+ slf.set_state(state);
Ok(slf)
}
@@ -351,7 +428,8 @@ impl PyDataFrameReader {
mut slf: PyRefMut<'py, Self>,
options: Option<&Bound<'_, PyDict>>,
) -> PyResult<PyRefMut<'py, Self>> {
- slf.inner = set_reader_kwargs_unset_none(slf.inner.clone(), options)?;
+ let state = set_reader_kwargs_unset_none(slf.state(), options)?;
+ slf.set_state(state);
Ok(slf)
}
@@ -370,7 +448,7 @@ impl PyDataFrameReader {
/// The configured read options (`DataFrameReader._options`); a copy.
#[getter]
fn _options(&self) -> HashMap<String, String> {
- self.inner.get_options().clone()
+ self.options.get()
}
/// The JVM reader of classic PySpark, which PySpark Connect's raises
@@ -397,7 +475,7 @@ impl PyDataFrameReader {
schema: Option<&Bound<'_, PyAny>>,
options: Option<&Bound<'_, PyDict>>,
) -> PyResult<PyDataFrame> {
- let mut r = set_reader_kwargs_unset_none(self.inner.clone(), options)?;
+ let mut r = set_reader_kwargs_unset_none(self.state(), options)?;
if let Some(f) = format {
r = r.format(f);
}
@@ -406,7 +484,7 @@ impl PyDataFrameReader {
}
// PySpark's one-shot load sets format/schema/options on the reader
itself, before it
// checks the path.
- self.inner = r.clone();
+ self.set_state(r.clone());
let paths = path.map(paths_of).transpose()?.unwrap_or_default();
Ok(PyDataFrame::new(r.load_paths(paths)))
}
@@ -415,7 +493,7 @@ impl PyDataFrameReader {
/// [`crate::str_argument`] converts it, as `changes` and those of the
stream reader do.
fn table(&self, tableName: &Bound<'_, PyAny>) -> PyResult<PyDataFrame> {
let tableName = crate::str_argument(tableName)?;
- Ok(PyDataFrame::new(self.inner.clone().table(&tableName)))
+ Ok(PyDataFrame::new(self.state().table(&tableName)))
}
/// Read the CDC changes of a named table. Mirrors
`DataFrameReader.changes`, which raises an
@@ -426,7 +504,7 @@ impl PyDataFrameReader {
return Err(changes_of_schema_error(py));
}
let tableName = crate::str_argument(tableName)?;
- Ok(PyDataFrame::new(self.inner.clone().changes(&tableName)))
+ Ok(PyDataFrame::new(self.state().changes(&tableName)))
}
/// Read JSON file(s) - full pyspark signature; each named option is
@@ -464,7 +542,7 @@ impl PyDataFrameReader {
unexpected: Option<&Bound<'_, PyDict>>,
) -> PyResult<PyDataFrame> {
crate::options::check_unexpected_keywords("DataFrameReader.json",
unexpected)?;
- let mut r = self.inner.clone();
+ let mut r = self.state();
r = set_options_skip_none(
r,
&[
@@ -517,7 +595,7 @@ impl PyDataFrameReader {
options: Option<&Bound<'_, PyDict>>,
) -> PyResult<PyDataFrame> {
check_keyword_keys(options)?;
- let mut r = self.inner.clone();
+ let mut r = self.state();
for name in [
"mergeSchema",
"pathGlobFilter",
@@ -578,7 +656,7 @@ impl PyDataFrameReader {
unexpected: Option<&Bound<'_, PyDict>>,
) -> PyResult<PyDataFrame> {
crate::options::check_unexpected_keywords("DataFrameReader.csv",
unexpected)?;
- let mut r = self.inner.clone();
+ let mut r = self.state();
r = set_options_skip_none(
r,
&[
@@ -640,7 +718,7 @@ impl PyDataFrameReader {
unexpected: Option<&Bound<'_, PyDict>>,
) -> PyResult<PyDataFrame> {
crate::options::check_unexpected_keywords("DataFrameReader.orc",
unexpected)?;
- let mut r = self.inner.clone();
+ let mut r = self.state();
r = set_options_skip_none(
r,
&[
@@ -678,7 +756,7 @@ impl PyDataFrameReader {
) -> PyResult<PyDataFrame> {
crate::options::check_unexpected_keywords("DataFrameReader.text",
unexpected)?;
let wholetext = wholetext.or_bool(py, false);
- let mut r = self.inner.clone();
+ let mut r = self.state();
r = set_options_skip_none(
r,
&[
@@ -724,7 +802,7 @@ impl PyDataFrameReader {
unexpected: Option<&Bound<'_, PyDict>>,
) -> PyResult<PyDataFrame> {
crate::options::check_unexpected_keywords("DataFrameReader.xml",
unexpected)?;
- let mut r = self.inner.clone();
+ let mut r = self.state();
r = set_option_skip_none(r, "rowTag", rowTag)?;
if let Some(v) = schema {
r = apply_reader_schema(r, v)?;
@@ -776,8 +854,8 @@ impl PyDataFrameReader {
predicates: Option<&Bound<'_, PyAny>>,
properties: Option<&Bound<'_, PyDict>>,
) -> PyResult<PyDataFrame> {
- self.inner = self.inner.clone().format("jdbc");
- let mut r = self.inner.clone();
+ self.set_state(self.state().format("jdbc"));
+ let mut r = self.state();
let predicates = match column {
Some(column) => {
for (bound, name) in [
@@ -809,7 +887,7 @@ impl PyDataFrameReader {
// a str before any property is set, with the format and the
options of a column kept
// on the reader.
if let Err(err) = check_keyword_keys(Some(properties)) {
- self.inner = r;
+ self.set_state(r);
return Err(err);
}
for (key, value) in properties.iter() {
@@ -817,7 +895,7 @@ impl PyDataFrameReader {
}
}
// PySpark's jdbc also leaves url/dbtable on the reader, before it
asserts the predicates.
- self.inner = r.clone().option("url", url).option("dbtable", table);
+ self.set_state(r.clone().option("url", url).option("dbtable", table));
let predicates = predicates.map(jdbc_predicates).transpose()?;
Ok(PyDataFrame::new(r.jdbc(url, table, predicates)))
}
diff --git a/crates/pyspark-rs/src/reduce.rs b/crates/pyspark-rs/src/reduce.rs
new file mode 100644
index 00000000..3e6347cd
--- /dev/null
+++ b/crates/pyspark-rs/src/reduce.rs
@@ -0,0 +1,112 @@
+//! The copies and pickles of the wrappers of PySpark's plain objects
(readers, writers, groups,
+//! catalogs and the like). As PySpark's, a copy of one shares the state that
PySpark's shallow
+//! copy shares, and a pickle keeps the session or DataFrame that the object
holds, which
+//! unpickles first, with the state of the object.
+
+use pyo3::prelude::*;
+use pyo3::types::{PyList, PyTuple};
+use spark_connect::column::Column;
+use spark_connect::plan::AggregateGroupType;
+
+use crate::column::PyColumn;
+
+/// The reduce of an object that pickles as `getattr(holder, name)`, such as a
catalog as the
+/// attribute of its session.
+pub(crate) fn getattr_reduce<'py>(
+ py: Python<'py>,
+ holder: Bound<'py, PyAny>,
+ name: &str,
+) -> PyResult<Bound<'py, PyTuple>> {
+ let getattr = py.import("builtins")?.getattr("getattr")?;
+ let args = PyTuple::new(py, [holder, name.into_pyobject(py)?.into_any()])?;
+ PyTuple::new(py, [getattr, args.into_any()])
+}
+
+/// The reduce of an object of the class `T`, which pickles by the `_of_state`
of `T` called
+/// with `args`, the state of the object.
+pub(crate) fn of_state_reduce<'py, T: pyo3::PyTypeInfo>(
+ py: Python<'py>,
+ args: Bound<'py, PyTuple>,
+) -> PyResult<Bound<'py, PyTuple>> {
+ let of_state = py.get_type::<T>().getattr("_of_state")?;
+ PyTuple::new(py, [of_state, args.into_any()])
+}
+
+/// The Python list of the columns, each a Column of the wrapper of `Column`.
+pub(crate) fn column_list<'py>(
+ py: Python<'py>,
+ columns: &[Column],
+) -> PyResult<Bound<'py, PyList>> {
+ let items = columns
+ .iter()
+ .map(|column| Bound::new(py, PyColumn::new(column.clone())))
+ .collect::<PyResult<Vec<_>>>()?;
+ PyList::new(py, items)
+}
+
+/// The columns of the Python iterable `items`, each a Column, as
`column_list` makes them.
+pub(crate) fn columns_of(items: &Bound<'_, PyAny>) -> PyResult<Vec<Column>> {
+ items
+ .try_iter()?
+ .map(|item| Ok(item?.extract::<PyRef<'_, PyColumn>>()?.column.clone()))
+ .collect()
+}
+
+/// The name of the type of a grouping, which `_of_state` of grouped data
takes back.
+pub(crate) fn group_type_name(group_type: AggregateGroupType) -> &'static str {
+ match group_type {
+ AggregateGroupType::GroupBy => "groupBy",
+ AggregateGroupType::Rollup => "rollup",
+ AggregateGroupType::Cube => "cube",
+ AggregateGroupType::Pivot => "pivot",
+ AggregateGroupType::GroupingSets => "groupingSets",
+ }
+}
+
+/// The type of a grouping of its name, as `group_type_name` gives it.
+pub(crate) fn group_type_of(name: &str) -> PyResult<AggregateGroupType> {
+ match name {
+ "groupBy" => Ok(AggregateGroupType::GroupBy),
+ "rollup" => Ok(AggregateGroupType::Rollup),
+ "cube" => Ok(AggregateGroupType::Cube),
+ "pivot" => Ok(AggregateGroupType::Pivot),
+ "groupingSets" => Ok(AggregateGroupType::GroupingSets),
+ _ => Err(pyo3::exceptions::PyValueError::new_err(format!(
+ "unknown grouping type: {name}"
+ ))),
+ }
+}
+
+/// The Python dict of the string pairs of `map`.
+pub(crate) fn str_dict<'py>(
+ py: Python<'py>,
+ map: &std::collections::HashMap<String, String>,
+) -> PyResult<Bound<'py, pyo3::types::PyDict>> {
+ let dict = pyo3::types::PyDict::new(py);
+ for (key, value) in map {
+ dict.set_item(key, value)?;
+ }
+ Ok(dict)
+}
+
+/// The name of a save mode, which `DataFrameWriter.mode` takes back.
+pub(crate) fn save_mode_name(mode: spark_connect::readwriter::SaveMode) ->
&'static str {
+ use spark_connect::readwriter::SaveMode;
+ match mode {
+ SaveMode::Append => "append",
+ SaveMode::Overwrite => "overwrite",
+ SaveMode::ErrorIfExists => "error",
+ SaveMode::Ignore => "ignore",
+ }
+}
+
+/// The Python object of an optional Python object, None if there is none.
+pub(crate) fn optional_object<'py>(
+ py: Python<'py>,
+ object: Option<&Py<PyAny>>,
+) -> Bound<'py, PyAny> {
+ match object {
+ Some(object) => object.clone_ref(py).into_bound(py),
+ None => py.None().into_bound(py),
+ }
+}
diff --git a/crates/pyspark-rs/src/stat.rs b/crates/pyspark-rs/src/stat.rs
index 01692559..2f31fada 100644
--- a/crates/pyspark-rs/src/stat.rs
+++ b/crates/pyspark-rs/src/stat.rs
@@ -27,6 +27,21 @@ impl PyStatFunctions {
#[pymethods]
impl PyStatFunctions {
+ /// The shallow copy of the statistics functions, as PySpark's
`copy.copy`: of the same
+ /// DataFrame.
+ fn __copy__(&self, py: Python<'_>) -> PyStatFunctions {
+ let frame = self.frame.clone_ref(py);
+ let stat = frame.borrow(py).dataframe.stat();
+ PyStatFunctions::new(stat, frame)
+ }
+
+ /// The reduce of the statistics functions, as PySpark's: `stat` of their
DataFrame, which
+ /// unpickles with it.
+ fn __reduce__<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py,
pyo3::types::PyTuple>> {
+ let frame = self.frame.clone_ref(py).into_any().into_bound(py);
+ crate::reduce::getattr_reduce(py, frame, "stat")
+ }
+
/// The DataFrame of these functions, as PySpark's
`DataFrameStatFunctions.df`: `df.stat.df`
/// is `df`.
#[getter(df)]
diff --git a/crates/pyspark-rs/src/streaming.rs
b/crates/pyspark-rs/src/streaming.rs
index 455d7b27..1a10c0ae 100644
--- a/crates/pyspark-rs/src/streaming.rs
+++ b/crates/pyspark-rs/src/streaming.rs
@@ -1,7 +1,8 @@
//! PyO3 wrappers for Structured Streaming.
use pyo3::prelude::*;
-use pyo3::types::{PyDict, PyTuple};
+use pyo3::types::{PyDict, PyList, PyTuple};
+
use spark_connect::streaming::{
DataStreamReader, DataStreamWriter, ListenerEventStream, StreamingQuery,
StreamingQueryListener, StreamingQueryListenerEvent,
StreamingQueryManager, Trigger,
@@ -255,11 +256,31 @@ fn query_name_of(name: &Bound<'_, PyAny>) ->
PyResult<String> {
)]
pub struct PyDataStreamReader {
inner: DataStreamReader,
+ /// The options of the reader, which a shallow copy of it shares, as
PySpark's `_options` dict
+ /// is shared by the copies of a reader. The core reader holds none of
them (see `state`).
+ options: Arc<WriterState<HashMap<String, String>>>,
}
impl PyDataStreamReader {
pub fn new(reader: DataStreamReader) -> Self {
- PyDataStreamReader { inner: reader }
+ let options = reader.get_options().clone();
+ PyDataStreamReader {
+ inner: without_options(reader, &options),
+ options: Arc::new(WriterState::new(options)),
+ }
+ }
+
+ /// The core reader of this reader, with its options, which the copies of
this reader share.
+ fn state(&self) -> DataStreamReader {
+ self.inner.clone().options(self.options.get())
+ }
+
+ /// Keep `reader` as the state of this reader: its options are shared by
the copies of this
+ /// reader, and its format, schema and source name are this reader's own.
+ fn set_state(&mut self, reader: DataStreamReader) {
+ let options = reader.get_options().clone();
+ self.inner = without_options(reader, &options);
+ self.options.set(options);
}
/// The path of a format reader, such as `json`, as PySpark's takes it,
and the state that
@@ -273,19 +294,72 @@ impl PyDataStreamReader {
format: &str,
path: &Bound<'_, PyAny>,
) -> PyResult<String> {
- self.inner = reader.clone();
+ self.set_state(reader.clone());
if !path.is_instance_of::<pyo3::types::PyString>() {
return Err(crate::stat_arguments::not_expected_type(
path, "path", "str",
));
}
- self.inner = reader.clone().format(format);
+ self.set_state(reader.clone().format(format));
load_path(path)
}
}
#[pymethods]
impl PyDataStreamReader {
+ /// The shallow copy of a stream reader, as PySpark's `copy.copy`: the
copy shares the
+ /// options of this reader.
+ fn __copy__(&self) -> PyDataStreamReader {
+ PyDataStreamReader {
+ inner: self.state(),
+ options: Arc::clone(&self.options),
+ }
+ }
+
+ /// The reduce of a stream reader, as PySpark's pickle of its session and
its state, which
+ /// `_of_state` gives back.
+ fn __reduce__<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py,
PyTuple>> {
+ use crate::reduce::{of_state_reduce, str_dict};
+
+ let session = crate::session::session_object(py,
&self.inner.spark_session())?;
+ let args = PyTuple::new(
+ py,
+ [
+ session.into_bound(py).into_any(),
+ self.inner.get_format().into_pyobject(py)?.into_any(),
+ self.inner.get_schema().into_pyobject(py)?.into_any(),
+ str_dict(py, &self.options.get())?.into_any(),
+ self.inner.get_source_name().into_pyobject(py)?.into_any(),
+ ],
+ )?;
+ of_state_reduce::<PyDataStreamReader>(py, args)
+ }
+
+ /// A stream reader of its state, as `__reduce__` gives it: of the session
`session`, the
+ /// format, the schema, the options and the source name.
+ #[staticmethod]
+ fn _of_state(
+ py: Python<'_>,
+ session: Py<crate::session::PySparkSession>,
+ format: Option<String>,
+ schema: String,
+ options: HashMap<String, String>,
+ source_name: Option<String>,
+ ) -> PyResult<PyDataStreamReader> {
+ let mut reader = session.borrow(py).session.read_stream();
+ if let Some(format) = format {
+ reader = reader.format(&format);
+ }
+ if !schema.is_empty() {
+ reader = reader.schema(schema);
+ }
+ reader = reader.options(options);
+ if let Some(source_name) = source_name {
+ reader = reader.name(&source_name);
+ }
+ Ok(PyDataStreamReader::new(reader))
+ }
+
/// Set the schema, if any, and the options of `options` that are not
None, through its own
/// `schema` and `option`, as PySpark's `OptionUtils._set_opts`, which
pandas-on-Spark calls.
#[pyo3(signature = (schema=None, **options))]
@@ -303,10 +377,11 @@ impl PyDataStreamReader {
mut slf: PyRefMut<'py, Self>,
source: Option<&str>,
) -> PyResult<PyRefMut<'py, Self>> {
- slf.inner = match source {
- Some(source) => slf.inner.clone().format(source),
- None => slf.inner.clone().clear_format(),
+ let state = match source {
+ Some(source) => slf.state().format(source),
+ None => slf.state().clear_format(),
};
+ slf.set_state(state);
Ok(slf)
}
@@ -316,7 +391,8 @@ impl PyDataStreamReader {
schema: &Bound<'_, PyAny>,
) -> PyResult<PyRefMut<'py, Self>> {
let schema = crate::readwriter::reader_schema(schema)?;
- slf.inner = slf.inner.clone().schema(&schema);
+ let state = slf.state().schema(&schema);
+ slf.set_state(state);
Ok(slf)
}
@@ -334,7 +410,8 @@ impl PyDataStreamReader {
let key = crate::options::reader_option_key(key)?;
match crate::options::stream_option_value(value)? {
Some(v) => {
- slf.inner = slf.inner.clone().option(&key, &v);
+ let state = slf.state().option(&key, &v);
+ slf.set_state(state);
Ok(slf)
}
None => Ok(slf),
@@ -349,7 +426,8 @@ impl PyDataStreamReader {
options: Option<&Bound<'_, PyDict>>,
) -> PyResult<PyRefMut<'py, Self>> {
let opts = crate::options::kwargs_skip_none(options)?;
- slf.inner = slf.inner.clone().options(opts);
+ let state = slf.state().options(opts);
+ slf.set_state(state);
Ok(slf)
}
@@ -368,7 +446,7 @@ impl PyDataStreamReader {
/// The configured read options (`DataStreamReader._options`); a copy.
#[getter]
fn _options(&self) -> HashMap<String, String> {
- self.inner.get_options().clone()
+ self.options.get()
}
#[pyo3(signature = (path=None, format=None, schema=None, **options))]
@@ -380,7 +458,7 @@ impl PyDataStreamReader {
options: Option<&Bound<'_, PyDict>>,
) -> PyResult<PyDataFrame> {
crate::options::check_keyword_keys(options)?;
- let mut r = self.inner.clone();
+ let mut r = self.state();
if let Some(fmt) = format {
r = r.format(fmt);
}
@@ -392,7 +470,7 @@ impl PyDataStreamReader {
r = r.options(opts);
}
// PySpark's one-shot load sets format/schema/options on the reader
itself.
- self.inner = r.clone();
+ self.set_state(r.clone());
let path = path.map(load_path).transpose()?;
Ok(PyDataFrame::new(r.load(path.as_deref())))
}
@@ -421,7 +499,8 @@ impl PyDataStreamReader {
&[("source_name", &name)],
));
}
- slf.inner = slf.inner.clone().name(&name);
+ let state = slf.state().name(&name);
+ slf.set_state(state);
Ok(slf)
}
@@ -433,7 +512,7 @@ impl PyDataStreamReader {
return Err(crate::readwriter::changes_of_schema_error(py));
}
let tableName = crate::str_argument(tableName)?;
- Ok(PyDataFrame::new(self.inner.clone().changes(&tableName)))
+ Ok(PyDataFrame::new(self.state().changes(&tableName)))
}
/// Load an XML streaming source. Mirrors `DataStreamReader.xml(...)`: set
each named
@@ -465,7 +544,7 @@ impl PyDataStreamReader {
unexpected: Option<&Bound<'_, PyDict>>,
) -> PyResult<PyDataFrame> {
crate::options::check_unexpected_keywords("DataStreamReader.xml",
unexpected)?;
- let mut r = self.inner.clone();
+ let mut r = self.state();
r = set_stream_option_skip_none(r, "rowTag", rowTag)?;
if let Some(v) = schema {
r = apply_stream_schema(r, v)?;
@@ -500,7 +579,7 @@ impl PyDataStreamReader {
/// Read a table by name, which PySpark's `Read` plan sets in its string
field as it is, as
/// [`crate::str_argument`] converts it.
fn table(&self, tableName: &Bound<'_, PyAny>) -> PyResult<PyDataFrame> {
- let df = self.inner.clone().table(&crate::str_argument(tableName)?);
+ let df = self.state().table(&crate::str_argument(tableName)?);
Ok(PyDataFrame::new(df))
}
@@ -534,7 +613,7 @@ impl PyDataStreamReader {
unexpected: Option<&Bound<'_, PyDict>>,
) -> PyResult<PyDataFrame> {
crate::options::check_unexpected_keywords("DataStreamReader.json",
unexpected)?;
- let mut r = self.inner.clone();
+ let mut r = self.state();
if let Some(v) = schema {
r = apply_stream_schema(r, v)?;
}
@@ -585,7 +664,7 @@ impl PyDataStreamReader {
unexpected: Option<&Bound<'_, PyDict>>,
) -> PyResult<PyDataFrame> {
crate::options::check_unexpected_keywords("DataStreamReader.parquet",
unexpected)?;
- let mut r = self.inner.clone();
+ let mut r = self.state();
r = set_stream_options_skip_none(
r,
&[
@@ -639,7 +718,7 @@ impl PyDataStreamReader {
unexpected: Option<&Bound<'_, PyDict>>,
) -> PyResult<PyDataFrame> {
crate::options::check_unexpected_keywords("DataStreamReader.csv",
unexpected)?;
- let mut r = self.inner.clone();
+ let mut r = self.state();
if let Some(v) = schema {
r = apply_stream_schema(r, v)?;
}
@@ -693,7 +772,7 @@ impl PyDataStreamReader {
unexpected: Option<&Bound<'_, PyDict>>,
) -> PyResult<PyDataFrame> {
crate::options::check_unexpected_keywords("DataStreamReader.orc",
unexpected)?;
- let mut r = self.inner.clone();
+ let mut r = self.state();
r = set_stream_options_skip_none(
r,
&[
@@ -726,7 +805,7 @@ impl PyDataStreamReader {
) -> PyResult<PyDataFrame> {
crate::options::check_unexpected_keywords("DataStreamReader.text",
unexpected)?;
let wholetext = wholetext.or_bool(py, false);
- let mut r = self.inner.clone();
+ let mut r = self.state();
r = set_stream_options_skip_none(
r,
&[
@@ -786,6 +865,42 @@ impl PyTrigger {
}
}
+/// The reader without the options of `options`, which the reader keeps apart
from its core state.
+fn without_options(
+ reader: DataStreamReader,
+ options: &HashMap<String, String>,
+) -> DataStreamReader {
+ options
+ .keys()
+ .fold(reader, |reader, key| reader.unset_option(key))
+}
+
+/// The kind and the value of a trigger, which a pickle keeps as a pair of
Python values.
+fn trigger_pair(trigger: &Trigger) -> (&'static str, Option<String>) {
+ match trigger {
+ Trigger::ProcessingTime(interval) => ("processingTime",
Some(interval.clone())),
+ Trigger::Once => ("once", None),
+ Trigger::AvailableNow => ("availableNow", None),
+ Trigger::Continuous(interval) => ("continuous",
Some(interval.clone())),
+ Trigger::RealTime(interval) => ("realTime", Some(interval.clone())),
+ }
+}
+
+/// The trigger of a kind and a value, as `trigger_pair` gives them.
+fn trigger_of(kind: &str, value: Option<String>) -> PyResult<Trigger> {
+ let value = value.unwrap_or_default();
+ match kind {
+ "processingTime" => Ok(Trigger::ProcessingTime(value)),
+ "once" => Ok(Trigger::Once),
+ "availableNow" => Ok(Trigger::AvailableNow),
+ "continuous" => Ok(Trigger::Continuous(value)),
+ "realTime" => Ok(Trigger::RealTime(value)),
+ _ => Err(pyo3::exceptions::PyValueError::new_err(format!(
+ "unknown trigger: {kind}"
+ ))),
+ }
+}
+
/// Python wrapper for DataStreamWriter.
#[pyclass(
name = "DataStreamWriter",
@@ -794,16 +909,38 @@ impl PyTrigger {
dict
)]
pub struct PyDataStreamWriter {
- inner: WriterState<DataStreamWriter>,
+ /// The state of the writer, which a shallow copy of it shares, as
PySpark's `_write_stream`.
+ inner: Arc<WriterState<DataStreamWriter>>,
+ /// The DataFrame that is streamed, as the Python object of
`df.writeStream`, as PySpark's
+ /// plan of its writer.
+ frame: Py<PyDataFrame>,
+ /// The functions of `foreachBatch` and `foreach` that the writer applied,
in order, with
+ /// the kind of each, which a pickle keeps, as PySpark's pickle keeps the
functions.
+ functions: AppliedFunctions,
}
+/// The functions of `foreachBatch` and `foreach` that a stream writer
applied, in order, each with
+/// its kind, shared by the shallow copies of the writer.
+type AppliedFunctions = Arc<std::sync::Mutex<Vec<(String, Py<PyAny>)>>>;
+
impl PyDataStreamWriter {
- pub fn new(writer: DataStreamWriter) -> Self {
+ pub fn new(writer: DataStreamWriter, frame: Py<PyDataFrame>) -> Self {
PyDataStreamWriter {
- inner: WriterState::new(writer),
+ inner: Arc::new(WriterState::new(writer)),
+ frame,
+ functions: Arc::new(std::sync::Mutex::new(Vec::new())),
}
}
+ /// Keep a function that the writer applied, as `kind` of `foreachBatch`
or `foreach`.
+ fn record(&self, kind: &str, function: &Bound<'_, PyAny>) {
+ let mut functions = self
+ .functions
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ functions.push((kind.to_string(), function.clone().unbind()));
+ }
+
/// Apply the one-shot writer options accepted by `start`/`toTable`
/// (`format`, `outputMode`, `partitionBy`, `queryName`, `**options`)
before
/// terminating the stream. Mirrors the reference, where these are keyword
args.
@@ -843,6 +980,121 @@ impl PyDataStreamWriter {
#[pymethods]
impl PyDataStreamWriter {
+ /// The shallow copy of a stream writer, as PySpark's `copy.copy`: the
copy shares the state
+ /// of this writer, as its `_write_stream` is the same object, and its
functions.
+ fn __copy__(&self, py: Python<'_>) -> PyDataStreamWriter {
+ PyDataStreamWriter {
+ inner: Arc::clone(&self.inner),
+ frame: self.frame.clone_ref(py),
+ functions: Arc::clone(&self.functions),
+ }
+ }
+
+ /// The reduce of a stream writer, as PySpark's pickle of its DataFrame
and its state, which
+ /// `_of_state` gives back, with the functions that it applied.
+ fn __reduce__<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py,
PyTuple>> {
+ use crate::reduce::{of_state_reduce, str_dict};
+
+ let writer = self.inner.get();
+
+ let trigger = match writer.get_trigger() {
+ Some(trigger) => {
+ let (kind, value) = trigger_pair(trigger);
+ PyTuple::new(
+ py,
+ [
+ kind.into_pyobject(py)?.into_any(),
+ value.into_pyobject(py)?.into_any(),
+ ],
+ )?
+ .into_any()
+ }
+ None => py.None().into_bound(py),
+ };
+ let functions = {
+ let functions = self
+ .functions
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ let pairs = functions
+ .iter()
+ .map(|(kind, function)| {
+ PyTuple::new(
+ py,
+ [
+ kind.into_pyobject(py)?.into_any(),
+ function.clone_ref(py).into_bound(py),
+ ],
+ )
+ })
+ .collect::<PyResult<Vec<_>>>()?;
+ PyList::new(py, pairs)?
+ };
+ let args = PyTuple::new(
+ py,
+ [
+ self.frame.clone_ref(py).into_any().into_bound(py),
+ writer.get_format().into_pyobject(py)?.into_any(),
+ writer.get_output_mode().into_pyobject(py)?.into_any(),
+ str_dict(py, writer.get_options())?.into_any(),
+ PyList::new(py, writer.get_partition_cols())?.into_any(),
+ PyList::new(py, writer.get_cluster_cols())?.into_any(),
+ writer.get_query_name().into_pyobject(py)?.into_any(),
+ trigger,
+ functions.into_any(),
+ ],
+ )?;
+ of_state_reduce::<PyDataStreamWriter>(py, args)
+ }
+
+ /// A stream writer of its state, as `__reduce__` gives it: of the
DataFrame `frame`, the
+ /// format, the output mode, the options, the partitioning and clustering
columns, the query
+ /// name, the trigger (a kind and its value, or None), and the functions
that were applied,
+ /// which are applied again, in order, to the writer.
+ #[staticmethod]
+ fn _of_state<'py>(
+ py: Python<'py>,
+ frame: Py<PyDataFrame>,
+ format: Option<String>,
+ output_mode: Option<String>,
+ options: HashMap<String, String>,
+ partition_cols: Vec<String>,
+ cluster_cols: Vec<String>,
+ query_name: Option<String>,
+ trigger: Option<(String, Option<String>)>,
+ functions: Vec<(String, Py<PyAny>)>,
+ ) -> PyResult<Bound<'py, PyDataStreamWriter>> {
+ let mut writer = frame.borrow(py).dataframe.write_stream();
+ if let Some(format) = format {
+ writer = writer.format(&format);
+ }
+ if let Some(output_mode) = output_mode {
+ writer = writer.output_mode(&output_mode);
+ }
+ writer = writer.options(options);
+ if !partition_cols.is_empty() {
+ writer = writer.partition_by(partition_cols);
+ }
+ if !cluster_cols.is_empty() {
+ writer = writer.cluster_by(cluster_cols);
+ }
+ if let Some(query_name) = query_name {
+ writer = writer.query_name(&query_name);
+ }
+ if let Some((kind, value)) = trigger {
+ writer = writer.trigger(trigger_of(&kind, value)?);
+ }
+ let restored = Bound::new(py, PyDataStreamWriter::new(writer, frame))?;
+ for (kind, function) in functions {
+ let function = function.into_bound(py);
+ match kind.as_str() {
+ "foreachBatch" => PyDataStreamWriter::foreachBatch(&restored,
py, &function)?,
+ _ => PyDataStreamWriter::foreach(&restored, py, &function)?,
+ };
+ }
+ Ok(restored)
+ }
+
fn outputMode<'py>(slf: &Bound<'py, Self>, outputMode: &str) ->
PyResult<Bound<'py, Self>> {
slf.borrow().inner.update(|w| w.output_mode(outputMode));
Ok(slf.clone())
@@ -1072,7 +1324,10 @@ impl PyDataStreamWriter {
command,
crate::dataframe::py_version(py),
);
+ slf.borrow().record("foreachBatch", func);
+
slf.borrow().inner.update(|w| w.foreach_batch(payload));
+
Ok(slf.clone())
}
@@ -1114,7 +1369,10 @@ impl PyDataStreamWriter {
command,
crate::dataframe::py_version(py),
);
+ slf.borrow().record("foreach", f);
+
slf.borrow().inner.update(|w| w.foreach(payload));
+
Ok(slf.clone())
}
}
@@ -1245,6 +1503,44 @@ impl PyStreamingQuery {
#[pymethods]
impl PyStreamingQuery {
+ /// The shallow copy of a streaming query, as PySpark's `copy.copy`: of
the same query.
+ fn __copy__(&self) -> PyStreamingQuery {
+ PyStreamingQuery::new(self.inner.clone())
+ }
+
+ /// The reduce of a streaming query, as PySpark's pickle of its session
and its state, which
+ /// `_of_state` gives back.
+ fn __reduce__<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py,
PyTuple>> {
+ use crate::reduce::of_state_reduce;
+
+ let session = crate::session::session_object(py,
&self.inner.spark_session())?;
+
+ let args = PyTuple::new(
+ py,
+ [
+ session.into_bound(py).into_any(),
+ self.inner.id().into_pyobject(py)?.into_any(),
+ self.inner.run_id().into_pyobject(py)?.into_any(),
+ self.inner.name().into_pyobject(py)?.into_any(),
+ ],
+ )?;
+ of_state_reduce::<PyStreamingQuery>(py, args)
+ }
+
+ /// A streaming query of its state, as `__reduce__` gives it: of the
session `session`, the
+ /// query ID, the run ID and the name.
+ #[staticmethod]
+ fn _of_state(
+ py: Python<'_>,
+ session: Py<crate::session::PySparkSession>,
+ query_id: String,
+ run_id: String,
+ name: Option<String>,
+ ) -> PyStreamingQuery {
+ let session = session.borrow(py).session.clone();
+ PyStreamingQuery::new(StreamingQuery::from_parts(session, query_id,
run_id, name))
+ }
+
#[getter]
fn id(&self) -> String {
self.inner.id().to_string()
@@ -1426,6 +1722,23 @@ impl PyStreamingQueryListenerBus {
#[pymethods]
impl PyStreamingQueryManager {
+ /// The shallow copy of a streaming query manager, as PySpark's
`copy.copy`: of the same
+ /// session and listener bus.
+ fn __copy__(&self) -> PyStreamingQueryManager {
+ PyStreamingQueryManager {
+ inner: self.inner.clone(),
+ session: self.session.clone(),
+ }
+ }
+
+ /// A streaming query manager does not pickle, as PySpark's, whose
listener bus holds a lock
+ /// that pickle cannot copy.
+ fn __reduce__(&self) -> PyResult<()> {
+ Err(pyo3::exceptions::PyTypeError::new_err(
+ "cannot pickle '_thread.lock' object",
+ ))
+ }
+
#[getter]
fn active(&self, py: Python<'_>) -> PyResult<Vec<PyStreamingQuery>> {
let queries = interruptible(py, &self.inner.spark_session(), || {
diff --git a/crates/pyspark-rs/src/tvf.rs b/crates/pyspark-rs/src/tvf.rs
index 85c3b420..2f9aae31 100644
--- a/crates/pyspark-rs/src/tvf.rs
+++ b/crates/pyspark-rs/src/tvf.rs
@@ -32,6 +32,19 @@ fn cols(items: Vec<Bound<'_, PyAny>>) ->
PyResult<Vec<spark_connect::column::Col
#[pymethods]
impl PyTableValuedFunction {
+ /// The shallow copy of the table-valued functions, as PySpark's
`copy.copy`: of the same
+ /// session.
+ fn __copy__(&self) -> PyTableValuedFunction {
+ PyTableValuedFunction::new(self.inner.clone())
+ }
+
+ /// The reduce of the table-valued functions, as PySpark's: `tvf` of their
session, which
+ /// unpickles with it.
+ fn __reduce__<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py,
pyo3::types::PyTuple>> {
+ let session = crate::session::session_object(py,
self.inner.spark_session())?;
+ crate::reduce::getattr_reduce(py, session.into_bound(py).into_any(),
"tvf")
+ }
+
/// Each argument is taken by its `int()`, as PySpark's `spark.tvf.range`
takes them, which
/// is `spark.range`.
#[pyo3(signature = (start, end=None,
step=crate::session::RangeStep::Omitted, numPartitions=None))]
diff --git a/crates/spark-connect/src/group.rs
b/crates/spark-connect/src/group.rs
index 1c278d3b..e42bab65 100644
--- a/crates/spark-connect/src/group.rs
+++ b/crates/spark-connect/src/group.rs
@@ -139,9 +139,55 @@ impl GroupedData {
&self.dataframe
}
+ /// The pivot column, as PySpark Connect's `GroupedData._pivot_col`, or
None. Not a stable API.
+ #[doc(hidden)]
+ pub fn pivot_column(&self) -> Option<Column> {
+ self.pivot_col.clone().map(Column::new)
+ }
+
+ /// The pivot values, as PySpark Connect's `GroupedData._pivot_values`:
literal columns.
+ /// Not a stable API.
+ #[doc(hidden)]
+ pub fn pivot_value_columns(&self) -> Vec<Column> {
+ self.pivot_values.iter().cloned().map(Column::new).collect()
+ }
+
+ /// The explicit grouping sets, as PySpark Connect's
`GroupedData._grouping_sets`.
+ /// Not a stable API.
+ #[doc(hidden)]
+ pub fn grouping_set_columns(&self) -> &[Vec<Column>] {
+ &self.grouping_sets
+ }
+
+ /// A GroupedData of its parts, as a pickled GroupedData gives them back:
the DataFrame, the
+ /// grouping columns, the type of the grouping, the pivot column and
values, and the grouping
+ /// sets, as they are. Not a stable API.
+ #[doc(hidden)]
+ pub fn from_parts(
+ dataframe: DataFrame,
+ group_cols: Vec<Column>,
+ group_type: AggregateGroupType,
+ pivot_col: Option<Column>,
+ pivot_values: Vec<Column>,
+ grouping_sets: Vec<Vec<Column>>,
+ ) -> Self {
+ GroupedData {
+ dataframe,
+ group_cols,
+ group_type,
+ pivot_col: pivot_col.map(|column| column.expression().clone()),
+ pivot_values: pivot_values
+ .iter()
+ .map(|column| column.expression().clone())
+ .collect(),
+ grouping_sets,
+ }
+ }
+
/// Create a new GroupedData.
pub(crate) fn new(
dataframe: DataFrame,
+
group_cols: Vec<Column>,
group_type: AggregateGroupType,
) -> Self {
diff --git a/crates/spark-connect/src/readwriter.rs
b/crates/spark-connect/src/readwriter.rs
index 20e7ab27..4f8c1a95 100644
--- a/crates/spark-connect/src/readwriter.rs
+++ b/crates/spark-connect/src/readwriter.rs
@@ -25,6 +25,11 @@ pub struct DataFrameReader {
}
impl DataFrameReader {
+ /// The session of this reader, whose reads it runs.
+ pub fn spark_session(&self) -> SparkSession {
+ self.session.clone()
+ }
+
/// Create a new DataFrameReader.
pub(crate) fn new(session: SparkSession) -> Self {
DataFrameReader {
@@ -305,6 +310,61 @@ impl DataFrameWriter {
pub fn spark_session(&self) -> SparkSession {
self.session.clone()
}
+
+ /// The format of this writer, as set by `format`, if any. Not a stable
API.
+ #[doc(hidden)]
+ pub fn get_format(&self) -> Option<&str> {
+ self.format.as_deref()
+ }
+
+ /// The save mode of this writer. Not a stable API.
+ #[doc(hidden)]
+ pub fn get_save_mode(&self) -> SaveMode {
+ self.mode
+ }
+
+ /// The last mode set when it is not a save mode, if any. Not a stable API.
+ #[doc(hidden)]
+ pub fn get_unsupported_mode(&self) -> Option<&str> {
+ self.unsupported_mode.as_deref()
+ }
+
+ /// The options of this writer. Not a stable API.
+ #[doc(hidden)]
+ pub fn get_options(&self) -> &HashMap<String, String> {
+ &self.options
+ }
+
+ /// The partitioning columns of this writer. Not a stable API.
+ #[doc(hidden)]
+ pub fn get_partition_cols(&self) -> &[String] {
+ &self.partition_cols
+ }
+
+ /// The bucketing columns of this writer. Not a stable API.
+ #[doc(hidden)]
+ pub fn get_bucket_cols(&self) -> &[String] {
+ &self.bucket_cols
+ }
+
+ /// The number of buckets of this writer, if it buckets. Not a stable API.
+ #[doc(hidden)]
+ pub fn get_num_buckets(&self) -> Option<i32> {
+ self.num_buckets
+ }
+
+ /// The sorting columns of this writer. Not a stable API.
+ #[doc(hidden)]
+ pub fn get_sort_cols(&self) -> &[String] {
+ &self.sort_cols
+ }
+
+ /// The clustering columns of this writer. Not a stable API.
+ #[doc(hidden)]
+ pub fn get_cluster_cols(&self) -> &[String] {
+ &self.cluster_cols
+ }
+
#[cfg(test)]
pub(crate) fn plan(&self) -> &LogicalPlan {
self.input_plan.as_ref()
@@ -539,6 +599,43 @@ impl DataFrameWriterV2 {
pub fn spark_session(&self) -> SparkSession {
self.session.clone()
}
+
+ /// The table of this writer, as `writeTo` gives it. Not a stable API.
+ #[doc(hidden)]
+ pub fn get_table_name(&self) -> &str {
+ &self.table_name
+ }
+
+ /// The provider of this writer, as set by `using`, if any. Not a stable
API.
+ #[doc(hidden)]
+ pub fn get_provider(&self) -> Option<&str> {
+ self.provider.as_deref()
+ }
+
+ /// The options of this writer. Not a stable API.
+ #[doc(hidden)]
+ pub fn get_options(&self) -> &HashMap<String, String> {
+ &self.options
+ }
+
+ /// The table properties of this writer. Not a stable API.
+ #[doc(hidden)]
+ pub fn get_table_properties(&self) -> &HashMap<String, String> {
+ &self.table_properties
+ }
+
+ /// The partitioning columns of this writer. Not a stable API.
+ #[doc(hidden)]
+ pub fn get_partition_cols(&self) -> &[Column] {
+ &self.partition_cols
+ }
+
+ /// The clustering columns of this writer. Not a stable API.
+ #[doc(hidden)]
+ pub fn get_cluster_cols(&self) -> &[String] {
+ &self.cluster_cols
+ }
+
#[cfg(test)]
pub(crate) fn plan(&self) -> &LogicalPlan {
self.input_plan.as_ref()
diff --git a/crates/spark-connect/src/streaming.rs
b/crates/spark-connect/src/streaming.rs
index 39ba9a5a..d2a1336f 100644
--- a/crates/spark-connect/src/streaming.rs
+++ b/crates/spark-connect/src/streaming.rs
@@ -30,6 +30,24 @@ pub struct DataStreamReader {
}
impl DataStreamReader {
+ /// The session of this reader, whose reads it runs.
+ pub fn spark_session(&self) -> SparkSession {
+ self.session.clone()
+ }
+
+ /// Remove an option of this reader, as `DataFrameReader::unset_option`
does. Not a stable API.
+ #[doc(hidden)]
+ pub fn unset_option(mut self, key: &str) -> Self {
+ self.options.remove(key);
+ self
+ }
+
+ /// The source name of this reader, as set by `name`, if any. Not a stable
API.
+ #[doc(hidden)]
+ pub fn get_source_name(&self) -> Option<&str> {
+ self.source_name.as_deref()
+ }
+
/// Create a new DataStreamReader.
pub(crate) fn new(session: SparkSession) -> Self {
DataStreamReader {
@@ -303,6 +321,49 @@ impl DataStreamWriter {
pub fn spark_session(&self) -> SparkSession {
self.session.clone()
}
+
+ /// The format of this writer, as set by `format`, if any. Not a stable
API.
+ #[doc(hidden)]
+ pub fn get_format(&self) -> Option<&str> {
+ self.format.as_deref()
+ }
+
+ /// The output mode of this writer, as set by `output_mode`, if any. Not a
stable API.
+ #[doc(hidden)]
+ pub fn get_output_mode(&self) -> Option<&str> {
+ self.output_mode.as_deref()
+ }
+
+ /// The options of this writer. Not a stable API.
+ #[doc(hidden)]
+ pub fn get_options(&self) -> &HashMap<String, String> {
+ &self.options
+ }
+
+ /// The partitioning columns of this writer. Not a stable API.
+ #[doc(hidden)]
+ pub fn get_partition_cols(&self) -> &[String] {
+ &self.partitioning_columns
+ }
+
+ /// The clustering columns of this writer. Not a stable API.
+ #[doc(hidden)]
+ pub fn get_cluster_cols(&self) -> &[String] {
+ &self.clustering_columns
+ }
+
+ /// The query name of this writer, if any. Not a stable API.
+ #[doc(hidden)]
+ pub fn get_query_name(&self) -> Option<&str> {
+ self.query_name.as_deref()
+ }
+
+ /// The trigger of this writer, if any. Not a stable API.
+ #[doc(hidden)]
+ pub fn get_trigger(&self) -> Option<&Trigger> {
+ self.trigger.as_ref()
+ }
+
#[cfg(test)]
pub(crate) fn plan(&self) -> &LogicalPlan {
self.plan.as_ref()
@@ -558,10 +619,27 @@ pub struct StreamingQuery {
}
impl StreamingQuery {
+ /// A query of its parts, as a pickled StreamingQuery gives them back. Not
a stable API.
+ #[doc(hidden)]
+ pub fn from_parts(
+ session: SparkSession,
+ query_id: String,
+ run_id: String,
+ name: Option<String>,
+ ) -> Self {
+ StreamingQuery {
+ session,
+ query_id,
+ run_id,
+ name,
+ }
+ }
+
/// The session of this query, whose executions it runs.
pub fn spark_session(&self) -> SparkSession {
self.session.clone()
}
+
/// Get the query ID.
pub fn id(&self) -> &str {
&self.query_id
@@ -1369,6 +1447,7 @@ fn run_listener_event_loop(
/// Mirrors `pyspark.sql.connect.streaming.StreamingQueryManager`, including a
native
/// client-side listener bus (so Rust clients get the listener feature too),
which is that of
/// its session.
+#[derive(Clone)]
pub struct StreamingQueryManager {
session: SparkSession,
bus: Arc<ListenerBus>,
diff --git a/crates/spark-connect/src/tvf.rs b/crates/spark-connect/src/tvf.rs
index 66acf04c..544ba163 100644
--- a/crates/spark-connect/src/tvf.rs
+++ b/crates/spark-connect/src/tvf.rs
@@ -14,12 +14,18 @@ use spark_connect_core::error::Result;
/// Table-valued functions for Spark SQL.
///
/// Mirrors `pyspark.sql.connect.tvf.TableValuedFunction`.
+#[derive(Clone)]
pub struct TableValuedFunction {
/// The session this TVF is bound to
session: SparkSession,
}
impl TableValuedFunction {
+ /// The session this TVF is bound to, as PySpark's `_sparkSession`.
+ pub fn spark_session(&self) -> &SparkSession {
+ &self.session
+ }
+
/// Create a new TableValuedFunction instance.
pub(crate) fn new(session: SparkSession) -> Self {
TableValuedFunction { session }
diff --git a/python/tests/test_dropin_offline.py
b/python/tests/test_dropin_offline.py
index d643be54..4bcb1822 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -25619,3 +25619,244 @@ def
test_a_non_nullable_column_with_nulls_is_read_with_its_nulls_as_pyarrow_read
)
assert spark.range(3).collect() == [Row(id=None), Row(id=None),
Row(id=None)]
assert list(spark.range(3).toLocalIterator()) == [Row(id=None),
Row(id=None), Row(id=None)]
+
+
+# The objects of PySpark's plain classes that a copy or a pickle keeps: as
PySpark's, a copy of
+# each works, and a deep copy and a pickle work for each except those below,
which hold a client
+# or a lock that cannot be copied; the merge actions hold their merge builder,
and so its client.
+_COPYABLE_OBJECTS = (
+ "reader",
+ "readStream",
+ "writer",
+ "writerV2",
+ "writeStream",
+ "groupBy",
+ "pivot",
+ "cogroup",
+ "na",
+ "stat",
+ "catalog",
+ "tvf",
+ "dataSource",
+ "udf",
+ "udtf",
+ "df",
+ "session",
+)
+_UNCOPYABLE_MESSAGES = {
+ "conf": "cannot pickle '_thread._local' object",
+ "merge": "cannot pickle '_thread._local' object",
+ "streams": "cannot pickle '_thread.lock' object",
+ "whenMatched": "cannot pickle '_thread._local' object",
+ "whenNotMatched": "cannot pickle '_thread._local' object",
+ "whenNotMatchedBySource": "cannot pickle '_thread._local' object",
+}
+
+
+def _copy_objects(spark):
+ # Each object of the classes, built afresh, from a DataFrame of the
session.
+ df = spark.range(3)
+ return {
+ "reader": lambda: spark.read.format("json").option("a", "1"),
+ "readStream": lambda: spark.readStream.format("rate").option("b", "2"),
+ "writer": lambda: df.write.format("parquet").option("c", "3"),
+ "writerV2": lambda: df.writeTo("t").using("parquet").option("d", "4"),
+ "writeStream": lambda: df.writeStream.format("memory").queryName("q"),
+ "groupBy": lambda: df.groupBy("id"),
+ "pivot": lambda: df.groupBy("id").pivot("id"),
+ "cogroup": lambda: df.groupby("id").cogroup(df.groupby("id")),
+ "na": lambda: df.na,
+ "stat": lambda: df.stat,
+ "conf": lambda: spark.conf,
+ "catalog": lambda: spark.catalog,
+ "merge": lambda: df.mergeInto("t", df.id == df.id),
+ "whenMatched": lambda: df.mergeInto("t", df.id == df.id).whenMatched(),
+ "whenNotMatched": lambda: df.mergeInto("t", df.id ==
df.id).whenNotMatched(),
+ "whenNotMatchedBySource": lambda: (
+ df.mergeInto("t", df.id == df.id).whenNotMatchedBySource()
+ ),
+ "streams": lambda: spark.streams,
+ "tvf": lambda: spark.tvf,
+ "dataSource": lambda: spark.dataSource,
+ "udf": lambda: spark.udf,
+ "udtf": lambda: spark.udtf,
+ "df": lambda: df,
+ "session": lambda: spark,
+ }
+
+
[email protected]("name", _COPYABLE_OBJECTS +
tuple(_UNCOPYABLE_MESSAGES))
+def test_copies_of_the_objects_as_pyspark(mock_connect, name):
+ # As PySpark's copy.copy and copy.deepcopy of these plain objects: a copy
has the class of
+ # the object, and a deep copy does too, except the conf, merge builder and
stream manager,
+ # whose deep copy raises the TypeError of the client or lock that they
hold.
+ import copy
+
+ spark, _ = mock_connect
+ obj = _copy_objects(spark)[name]()
+ assert type(copy.copy(obj)) is type(obj)
+ if name in _UNCOPYABLE_MESSAGES:
+ with pytest.raises(TypeError,
match=re.escape(_UNCOPYABLE_MESSAGES[name])):
+ copy.deepcopy(obj)
+ else:
+ assert type(copy.deepcopy(obj)) is type(obj)
+
+
[email protected]("protocol", range(6))
[email protected]("name", _COPYABLE_OBJECTS +
tuple(_UNCOPYABLE_MESSAGES))
+def test_pickles_of_the_objects_at_every_protocol_as_pyspark(mock_connect,
name, protocol):
+ # As PySpark's cloudpickle of these objects at every protocol: each
pickles and unpickles
+ # with the active session, except the conf, merge builder and stream
manager, which raise
+ # the TypeError that their deep copy raises.
+ import cloudpickle
+
+ spark, _ = mock_connect
+ obj = _copy_objects(spark)[name]()
+ if name in _UNCOPYABLE_MESSAGES:
+ with pytest.raises(TypeError,
match=re.escape(_UNCOPYABLE_MESSAGES[name])):
+ cloudpickle.dumps(obj, protocol)
+ return
+ data = cloudpickle.dumps(obj, protocol)
+ assert type(pickle.loads(data)) is type(obj)
+
+
[email protected]("name", _COPYABLE_OBJECTS)
+def test_unpickled_objects_need_an_active_session_as_pyspark(mock_connect,
name):
+ # As PySpark: the session of an object unpickles first, so on a thread
without an active
+ # session, as on a Python worker, an unpickled object raises
NO_ACTIVE_SESSION.
+ import threading
+
+ import cloudpickle
+ from pyspark.errors import PySparkRuntimeError
+
+ spark, _ = mock_connect
+ data = cloudpickle.dumps(_copy_objects(spark)[name]())
+ seen = []
+
+ def on_a_thread():
+ try:
+ pickle.loads(data)
+ except PySparkRuntimeError as error:
+ seen.append(error.getCondition())
+
+ thread = threading.Thread(target=on_a_thread)
+ thread.start()
+ thread.join()
+ assert seen == ["NO_ACTIVE_SESSION"]
+
+
+def
test_a_deep_copy_keeps_grouped_data_on_the_copied_dataframe_as_pyspark(mock_connect):
+ # As PySpark, where the grouped data of a copied DataFrame is grouped by
the copy: a deep
+ # copy of a dict of both copies the DataFrame once, through the memo of
the call, and the
+ # grouped data of the copy holds that copy, as GroupedData._df does.
+ import copy
+
+ spark, _ = mock_connect
+ df = spark.range(3)
+ grouped = df.groupBy("id")
+ copied = copy.deepcopy({"df": df, "g": grouped})
+ assert copied["df"] is not df
+ assert copied["g"]._df is copied["df"]
+ assert copy.deepcopy(grouped, {id(df): copied["df"]})._df is copied["df"]
+ assert copy.copy(grouped)._df is df
+
+
+def
test_shallow_copies_of_writers_share_their_settings_as_pyspark(mock_connect):
+ # As PySpark, where the writer keeps its settings in one object that a
shallow copy shares,
+ # so a setter of the copy is seen by the writer, and a deep copy keeps its
own.
+ import copy
+
+ spark, service = mock_connect
+
+ def sent_write():
+ # ExecutePlanRequest.plan=3, Plan.command=2, Command.write_operation=2.
+ plan = parse_message(parse_message(service.execute_requests[-1])[3][0])
+ return parse_message(parse_message(plan[2][0])[2][0])
+
+ writer = spark.range(1).write
+ copied = copy.copy(writer)
+ copied.format("json").option("k", "v").mode("overwrite")
+ writer.save("p")
+ # WriteOperation.source=2, mode=5 (SAVE_MODE_OVERWRITE=2), and options=9.
+ assert sent_write()[2] == [b"json"] and sent_write()[5] == [2]
+ options = {parse_message(entry)[1][0]: parse_message(entry)[2][0] for
entry in sent_write()[9]}
+ assert options == {b"k": b"v"}
+
+ deep = copy.deepcopy(writer)
+ deep.format("orc")
+ writer.save("p")
+ assert sent_write()[2] == [b"json"]
+
+
+def
test_shallow_copies_of_readers_share_their_options_as_pyspark(mock_connect):
+ # As PySpark, where the options of a reader are one dict that a shallow
copy shares, while
+ # its format is set on the copy alone, and a deep copy shares nothing.
+ import copy
+
+ spark, _ = mock_connect
+ reader = spark.read
+ copied = copy.copy(reader)
+ copied.option("k", "v").format("json")
+ assert reader._options == {"k": "v"}
+ assert reader._format is None and copied._format == "json"
+
+ deep = copy.deepcopy(reader)
+ deep.option("z", "9")
+ assert reader._options == {"k": "v"} and deep._options == {"k": "v", "z":
"9"}
+
+ stream = spark.readStream
+ copied_stream = copy.copy(stream)
+ copied_stream.option("a", "1").format("rate")
+ assert stream._options == {"a": "1"} and stream._format is None
+
+
+def
test_unpickled_writers_and_readers_keep_their_settings_as_pyspark(mock_connect):
+ # As PySpark's pickle of a writer and a reader, which keeps the format,
the save mode, the
+ # options and the schema, and sends them with the session that unpickles
with it.
+ import cloudpickle
+
+ spark, service = mock_connect
+
+ def sent_write():
+ plan = parse_message(parse_message(service.execute_requests[-1])[3][0])
+ return parse_message(parse_message(plan[2][0])[2][0])
+
+ writer = spark.range(1).write.format("json").mode("overwrite").option("a",
"1")
+ copied = cloudpickle.loads(cloudpickle.dumps(writer))
+ copied.save("p")
+ assert sent_write()[2] == [b"json"] and sent_write()[5] == [2]
+ options = {parse_message(entry)[1][0]: parse_message(entry)[2][0] for
entry in sent_write()[9]}
+ assert options == {b"a": b"1"}
+
+ reader = spark.read.format("json").option("a", "1").schema("id LONG")
+ copied = cloudpickle.loads(cloudpickle.dumps(reader))
+ assert copied._format == "json"
+ assert copied._options == {"a": "1"}
+ assert copied._schema == reader._schema
+
+
+def
test_a_shallow_copy_of_a_merge_builder_keeps_its_schema_evolution_as_pyspark(mock_connect):
+ # As PySpark, where withSchemaEvolution sets the attribute of the builder
it is called on,
+ # so a copy that sets it sends it alone, while the clauses that the copy
adds are shared.
+ import copy
+
+ from pyspark.sql import functions as F
+
+ spark, service = mock_connect
+
+ def sent_schema_evolution():
+ # ExecutePlanRequest.plan=3, Plan.command=2,
Command.merge_into_table_command=16, and
+ # MergeIntoTableCommand.with_schema_evolution=7.
+ command =
parse_message(parse_message(service.execute_requests[-1])[3][0])
+ merge = parse_message(parse_message(command[2][0])[16][0])
+ return bool(merge.get(7))
+
+ builder = spark.range(1).mergeInto("t", F.col("id") ==
1).whenMatched().updateAll()
+ copied = copy.copy(builder)
+ copied.withSchemaEvolution()
+ copied.whenNotMatched().insertAll()
+ builder.merge()
+ assert sent_schema_evolution() is False
+ copied.merge()
+ assert sent_schema_evolution() is True
+ assert len(service.execute_requests) >= 2
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]