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 66b982c6 [SPARK-61613][FOLLOWUP][CONNECT][PYTHON] Take bytes in the
formats, modes, partitioning and clustering columns and JDBC url and table of
the readers and writers, as PySpark does
66b982c6 is described below
commit 66b982c64dd9bf1c99e3eab8d7701bcaa9d25a0c
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Fri Nov 13 22:14:59 2026 +0900
[SPARK-61613][FOLLOWUP][CONNECT][PYTHON] Take bytes in the formats, modes,
partitioning and clustering columns and JDBC url and table of the readers and
writers, as PySpark does
### What changes were proposed in this pull request?
A follow-up to #608. The Python client's readers and writers now take these
arguments as PySpark 4.3.0 does: the formats, the save mode,
`DataFrameWriterV2.using`, the partitioning and clustering columns, and the
JDBC `url` and `table`. Bytes are sent as text, and any other object fails
where PySpark fails, with PySpark's error: at the call, the load or the write.
`start`, `toTable` and the readers' `load` also apply their arguments in
PySpark's order, so a failing argument leaves the [...]
### Why are the changes needed?
A post-merge review of #608 found that these arguments raised a `TypeError`
at the call. PySpark instead takes bytes, or fails later.
### Does this PR introduce _any_ user-facing change?
Yes, these arguments now behave as in PySpark 4.3.0. Two narrow differences
remain:
- A str with a lone surrogate fails earlier than in PySpark: as a reader's
format at `load`, and as a JDBC url or table at the call.
- A JDBC read with predicates and a None `url` or `table` sends an empty
string.
### How was this patch tested?
- New offline tests check the sent protobuf fields, the errors and when
they are raised. A new live test writes with a bytes format.
- `test_dropin_offline.py`: 2011 passed, 8 skipped. The reader and writer
subset of `test_dropin_e2e.py`: 31 passed.
- The 79 reader and writer signatures are unchanged.
- Probes give the same results as the official `pyspark-client` 4.3.0.
### 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 #629 from HyukjinKwon/SPARK-61613-followup-bytes.
Authored-by: Hyukjin Kwon <[email protected]>
Signed-off-by: Hyukjin Kwon <[email protected]>
---
crates/pyspark-rs/src/dataframe.rs | 541 ++++++++++++++++++++++-------
crates/pyspark-rs/src/readwriter.rs | 185 ++++++++--
crates/pyspark-rs/src/streaming.rs | 233 +++++++++----
crates/spark-connect/src/readwriter.rs | 6 +
python/tests/test_dropin_e2e.py | 7 +
python/tests/test_dropin_offline.py | 615 +++++++++++++++++++++++++++++++++
6 files changed, 1372 insertions(+), 215 deletions(-)
diff --git a/crates/pyspark-rs/src/dataframe.rs
b/crates/pyspark-rs/src/dataframe.rs
index 88a3bb1f..bea1db51 100644
--- a/crates/pyspark-rs/src/dataframe.rs
+++ b/crates/pyspark-rs/src/dataframe.rs
@@ -16,20 +16,6 @@ use crate::stat_arguments::proto_int;
use crate::streaming::{proto_bool, ProtoBool, PyDataStreamWriter};
use crate::types::PyDataType;
-/// 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>> {
- let mut out = Vec::new();
- for c in cols {
- if let Ok(one) = c.extract::<String>() {
- out.push(one);
- } else {
- out.extend(c.extract::<Vec<String>>()?);
- }
- }
- Ok(out)
-}
-
/// Python wrapper for a Spark DataFrame.
#[pyclass(
name = "DataFrame",
@@ -2865,6 +2851,8 @@ impl PyDataFrame {
inner:
std::sync::Arc::new(WriterState::new(slf.borrow().dataframe.write_to(&name))),
unsent_table,
frame: slf.clone().unbind(),
+ unsent_provider: std::sync::Arc::new(std::sync::Mutex::new(None)),
+ unsent_clustering:
std::sync::Arc::new(std::sync::Mutex::new(None)),
}
}
@@ -3817,6 +3805,25 @@ pub struct PyDataFrameWriter {
/// 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::Arc<std::sync::Mutex<Option<Py<PyAny>>>>,
+ /// The format, the partitioning columns and the save mode that PySpark
keeps as they are,
+ /// and whose `WriteOperation.command` converts, or resolves, at each
write ([`UnsentArgs`]).
+ unsent: std::sync::Arc<std::sync::Mutex<UnsentArgs>>,
+}
+
+/// The arguments of a writer that PySpark keeps as they are, and that its
`WriteOperation.command`
+/// converts at the write, which fails with the first one that does not
convert. Each one is
+/// replaced by the next call that sets the same argument, as PySpark's
attribute is.
+#[derive(Default)]
+pub(crate) struct UnsentArgs {
+ /// The format, when it is not a str of UTF-8 (`format`, and the `format`
of a write).
+ format: Option<Py<PyAny>>,
+ /// The first partitioning column that is not a str of UTF-8.
+ partition: Option<Py<PyAny>>,
+ /// The first clustering column that is not a str of UTF-8, which
PySpark's command extends
+ /// after the partitioning columns.
+ clustering: Option<Py<PyAny>>,
+ /// The save mode, when it is not a str.
+ mode: Option<Py<PyAny>>,
}
impl PyDataFrameWriter {
@@ -3827,10 +3834,129 @@ impl PyDataFrameWriter {
PyDataFrameWriter {
inner: std::sync::Arc::new(WriterState::new(writer)),
refused_bucket_count:
std::sync::Arc::new(std::sync::Mutex::new(None)),
+ unsent:
std::sync::Arc::new(std::sync::Mutex::new(UnsentArgs::default())),
frame,
}
}
+ fn unsent(&self) -> std::sync::MutexGuard<'_, UnsentArgs> {
+ self.unsent
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ }
+
+ /// The writer `w` with the format `source` of PySpark's `format`, which
sets it at once when it
+ /// is a str of UTF-8 (bytes too), and else keeps the object for the
write. None unsets it.
+ fn with_format(
+ &self,
+ w: spark_connect::readwriter::DataFrameWriter,
+ source: Option<&Bound<'_, PyAny>>,
+ ) -> spark_connect::readwriter::DataFrameWriter {
+ let mut unsent = self.unsent();
+ match source.map(crate::str_argument) {
+ Some(Ok(text)) => {
+ unsent.format = None;
+ w.format(&text)
+ }
+ Some(Err(_)) => {
+ unsent.format = source.map(|source| source.clone().unbind());
+ w.clear_format()
+ }
+ None => {
+ unsent.format = None;
+ w.clear_format()
+ }
+ }
+ }
+
+ /// The writer `w` of a format method of PySpark, which sets the format
`format` at once, over
+ /// a format that was kept.
+ fn with_fixed_format(
+ &self,
+ w: spark_connect::readwriter::DataFrameWriter,
+ format: &str,
+ ) -> spark_connect::readwriter::DataFrameWriter {
+ self.unsent().format = None;
+ w.format(format)
+ }
+
+ /// The writer `w` with the save mode `mode` of PySpark's `mode`: a str
sets it at once, and any
+ /// other object is kept for the write, which resolves it
([`crate::readwriter::unsent_save_mode`]).
+ /// None leaves the mode as it is.
+ fn with_mode(
+ &self,
+ w: spark_connect::readwriter::DataFrameWriter,
+ mode: Option<&Bound<'_, PyAny>>,
+ ) -> spark_connect::readwriter::DataFrameWriter {
+ let Some(mode) = mode else {
+ return w;
+ };
+ match mode.extract::<String>() {
+ Ok(text) => {
+ self.unsent().mode = None;
+ w.mode(&text)
+ }
+ Err(_) => {
+ self.unsent().mode = Some(mode.clone().unbind());
+ w
+ }
+ }
+ }
+
+ /// The writer `w` with the partitioning columns `cols` of PySpark's
`partitionBy`, which replace
+ /// those of an earlier call. A column that is not a str of UTF-8 is kept
for the write.
+ fn with_partition_by(
+ &self,
+ w: spark_connect::readwriter::DataFrameWriter,
+ cols: &[Bound<'_, PyAny>],
+ ) -> PyResult<spark_connect::readwriter::DataFrameWriter> {
+ let (names, unsent) =
crate::readwriter::writer_partition_columns(cols)?;
+ self.unsent().partition = unsent;
+ Ok(w.partition_by(names))
+ }
+
+ /// Fail a write whose format or partitioning columns were kept, as
PySpark's
+ /// `WriteOperation.command` does after its input plan and before its
bucketing. Each one fails
+ /// again at each write, as it does not convert.
+ fn check_unsent_source_and_partition(
+ &self,
+ py: Python<'_>,
+ w: spark_connect::readwriter::DataFrameWriter,
+ ) -> PyResult<spark_connect::readwriter::DataFrameWriter> {
+ let (format, partition, clustering) = {
+ let unsent = self.unsent();
+ (
+ unsent.format.as_ref().map(|f| f.clone_ref(py)),
+ unsent.partition.as_ref().map(|p| p.clone_ref(py)),
+ unsent.clustering.as_ref().map(|c| c.clone_ref(py)),
+ )
+ };
+ if let Some(format) = format {
+ crate::str_argument(format.bind(py))?;
+ }
+ if let Some(column) = partition {
+ crate::str_argument(column.bind(py))?;
+ }
+ if let Some(column) = clustering {
+ crate::str_argument(column.bind(py))?;
+ }
+ Ok(w)
+ }
+
+ /// The writer `w` with the kept save mode resolved, after its path, as
PySpark's
+ /// `WriteOperation.command` does last
([`crate::readwriter::unsent_save_mode`]).
+ fn check_unsent_mode(
+ &self,
+ py: Python<'_>,
+ w: spark_connect::readwriter::DataFrameWriter,
+ ) -> PyResult<spark_connect::readwriter::DataFrameWriter> {
+ let mode = self.unsent().mode.as_ref().map(|m| m.clone_ref(py));
+ match mode {
+ Some(mode) =>
Ok(w.mode(&crate::readwriter::unsent_save_mode(mode.bind(py))?)),
+ None => Ok(w),
+ }
+ }
+
fn refused_bucket_count(&self) -> std::sync::MutexGuard<'_,
Option<Py<PyAny>>> {
self.refused_bucket_count
.lock()
@@ -3854,36 +3980,33 @@ impl PyDataFrameWriter {
}
}
-/// Apply the shared `format` / `mode` / `partitionBy` / `**options` arguments
that
-/// reference `DataFrameWriter.save` and `.saveAsTable` accept inline,
mirroring
-/// `.format().mode().partitionBy().options()` chaining.
-fn apply_write_common(
- mut w: spark_connect::readwriter::DataFrameWriter,
- format: Option<&str>,
- mode: Option<&str>,
- partitionBy: Option<&Bound<'_, PyAny>>,
- options: Option<&Bound<'_, PyDict>>,
-) -> PyResult<spark_connect::readwriter::DataFrameWriter> {
- crate::options::check_keyword_keys(options)?;
- if let Some(f) = format {
- w = w.format(f);
- }
- if let Some(m) = mode {
- w = w.mode(m);
- }
- if let Some(pb) = partitionBy {
- let cols: Vec<String> = if let Ok(one) = pb.extract::<String>() {
- vec![one]
- } else {
- pb.extract::<Vec<String>>()?
- };
- w = w.partition_by(cols);
- }
- if options.is_some() {
- let map = crate::options::kwargs_skip_none(options)?;
- w = w.options(map);
+impl PyDataFrameWriter {
+ /// Apply the shared `format` / `mode` / `partitionBy` / `**options`
arguments that reference
+ /// `DataFrameWriter.save` and `.saveAsTable` accept inline, mirroring
+ /// `.format().mode().partitionBy().options()` chaining. None of them
fails here, as PySpark
+ /// sets each as it is and its command fails with it at the write.
+ fn apply_write_common(
+ &self,
+ mut w: spark_connect::readwriter::DataFrameWriter,
+ format: Option<&Bound<'_, PyAny>>,
+ mode: Option<&Bound<'_, PyAny>>,
+ partitionBy: Option<&Bound<'_, PyAny>>,
+ options: Option<&Bound<'_, PyDict>>,
+ ) -> PyResult<spark_connect::readwriter::DataFrameWriter> {
+ crate::options::check_keyword_keys(options)?;
+ if let Some(f) = format {
+ w = self.with_format(w, Some(f));
+ }
+ w = self.with_mode(w, mode);
+ if let Some(pb) = partitionBy {
+ w = self.with_partition_by(w, std::slice::from_ref(pb))?;
+ }
+ if options.is_some() {
+ let map = crate::options::kwargs_skip_none(options)?;
+ w = w.options(map);
+ }
+ Ok(w)
}
- Ok(w)
}
#[pymethods]
@@ -3895,6 +4018,7 @@ impl PyDataFrameWriter {
PyDataFrameWriter {
inner: std::sync::Arc::clone(&self.inner),
refused_bucket_count:
std::sync::Arc::clone(&self.refused_bucket_count),
+ unsent: std::sync::Arc::clone(&self.unsent),
frame: self.frame.clone_ref(py),
}
}
@@ -3913,6 +4037,16 @@ impl PyDataFrameWriter {
.refused_bucket_count()
.as_ref()
.map(|n| n.clone_ref(py));
+ let (kept_format, kept_partition, kept_clustering, kept_mode) = {
+ let unsent = self.unsent();
+ let kept = |object: &Option<Py<PyAny>>| object.as_ref().map(|o|
o.clone_ref(py));
+ (
+ kept(&unsent.format),
+ kept(&unsent.partition),
+ kept(&unsent.clustering),
+ kept(&unsent.mode),
+ )
+ };
let args = PyTuple::new(
py,
[
@@ -3926,6 +4060,10 @@ impl PyDataFrameWriter {
PyList::new(py, writer.get_sort_cols())?.into_any(),
PyList::new(py, writer.get_cluster_cols())?.into_any(),
optional_object(py, refused.as_ref()),
+ optional_object(py, kept_format.as_ref()),
+ optional_object(py, kept_partition.as_ref()),
+ optional_object(py, kept_clustering.as_ref()),
+ optional_object(py, kept_mode.as_ref()),
],
)?;
of_state_reduce::<PyDataFrameWriter>(py, args)
@@ -3947,7 +4085,11 @@ impl PyDataFrameWriter {
bucket_cols,
sort_cols,
cluster_cols,
- refused
+ refused,
+ kept_format,
+ kept_partition,
+ kept_clustering,
+ kept_mode
)
)]
fn _of_state(
@@ -3962,6 +4104,10 @@ impl PyDataFrameWriter {
sort_cols: Vec<String>,
cluster_cols: Vec<String>,
refused: Option<Py<PyAny>>,
+ kept_format: Option<Py<PyAny>>,
+ kept_partition: Option<Py<PyAny>>,
+ kept_clustering: Option<Py<PyAny>>,
+ kept_mode: Option<Py<PyAny>>,
) -> PyResult<PyDataFrameWriter> {
let mut writer = frame.borrow(py).dataframe.write();
if let Some(format) = format {
@@ -3982,6 +4128,12 @@ impl PyDataFrameWriter {
}
let restored = PyDataFrameWriter::new(writer, frame);
*restored.refused_bucket_count() = refused;
+ *restored.unsent() = UnsentArgs {
+ format: kept_format,
+ partition: kept_partition,
+ clustering: kept_clustering,
+ mode: kept_mode,
+ };
Ok(restored)
}
@@ -3997,20 +4149,23 @@ impl PyDataFrameWriter {
}
/// The save mode, as PySpark's: `None` keeps the default, "error".
- fn mode<'py>(slf: &Bound<'py, Self>, saveMode: Option<&str>) ->
PyResult<Bound<'py, Self>> {
- if let Some(save_mode) = saveMode {
- slf.borrow().inner.update(|w| w.mode(save_mode));
- }
+ fn mode<'py>(
+ slf: &Bound<'py, Self>,
+ saveMode: Option<&Bound<'_, PyAny>>,
+ ) -> PyResult<Bound<'py, Self>> {
+ let writer = slf.borrow();
+ writer.inner.update(|w| writer.with_mode(w, saveMode));
Ok(slf.clone())
}
/// The format of the write. As PySpark's, None unsets it, so that the
server writes its
/// default source.
- fn format<'py>(slf: &Bound<'py, Self>, source: Option<&str>) ->
PyResult<Bound<'py, Self>> {
- match source {
- Some(source) => slf.borrow().inner.update(|w| w.format(source)),
- None => slf.borrow().inner.update(|w| w.clear_format()),
- }
+ fn format<'py>(
+ slf: &Bound<'py, Self>,
+ source: Option<&Bound<'_, PyAny>>,
+ ) -> PyResult<Bound<'py, Self>> {
+ let writer = slf.borrow();
+ writer.inner.update(|w| writer.with_format(w, source));
Ok(slf.clone())
}
@@ -4048,8 +4203,10 @@ impl PyDataFrameWriter {
slf: &Bound<'py, Self>,
cols: Vec<Bound<'_, PyAny>>,
) -> PyResult<Bound<'py, Self>> {
- let cols = flatten_str_cols(cols)?;
- slf.borrow().inner.update(|w| w.partition_by(cols));
+ let writer = slf.borrow();
+ let (cols, unsent) =
crate::readwriter::writer_partition_columns(&cols)?;
+ writer.unsent().partition = unsent;
+ writer.inner.update(|w| w.partition_by(cols));
Ok(slf.clone())
}
@@ -4103,18 +4260,18 @@ impl PyDataFrameWriter {
slf: &Bound<'py, Self>,
cols: Vec<Bound<'_, PyAny>>,
) -> PyResult<Bound<'py, Self>> {
- let cols: Vec<String> = match cols.as_slice() {
- [only] if only.is_instance_of::<PyList>() ||
only.is_instance_of::<PyTuple>() => {
- only.extract()?
- }
- _ => cols.iter().map(|c| c.extract()).collect::<PyResult<_>>()?,
- };
- if cols.is_empty() {
+ // As PySpark's, which asserts the count after unpacking, and keeps
the columns as they are:
+ // a column that does not convert fails each write, after the
partitioning columns.
+ let items = crate::readwriter::writer_column_items(&cols)?;
+ if items.is_empty() {
return Err(pyo3::exceptions::PyAssertionError::new_err(
"clusterBy needs one or more clustering columns.",
));
}
- slf.borrow().inner.update(|w| w.cluster_by(cols));
+ let (names, unsent) = crate::readwriter::writer_columns_kept(&items);
+ let writer = slf.borrow();
+ writer.unsent().clustering = unsent;
+ writer.inner.update(|w| w.cluster_by(names));
Ok(slf.clone())
}
@@ -4124,17 +4281,15 @@ impl PyDataFrameWriter {
fn jdbc(
&self,
py: Python<'_>,
- url: &str,
- table: &str,
- mode: Option<&str>,
+ url: &Bound<'_, PyAny>,
+ table: &Bound<'_, PyAny>,
+ mode: Option<&Bound<'_, PyAny>>,
properties: Option<&Bound<'_, PyDict>>,
) -> PyResult<()> {
// Same order as PySpark: format, mode, properties, then url/dbtable
(which
// win over same-named properties), all kept on the writer, then save.
- let mut w = self.inner.get().format("jdbc");
- if let Some(m) = mode {
- w = w.mode(m);
- }
+ let mut w = self.with_fixed_format(self.inner.get(), "jdbc");
+ w = self.with_mode(w, mode);
if let Some(props) = properties {
// As PySpark's `options(**properties)`, whose unpacking raises
for a key that is not
// a str before any property is set, with the format and the mode
kept on the writer.
@@ -4154,9 +4309,13 @@ impl PyDataFrameWriter {
}
}
}
- w = w.option("url", url).option("dbtable", table);
+ // As PySpark's `options(url=url, dbtable=table)`, which skips a None.
+ w = set_option_skip_none(w, "url", Some(url))?;
+ w = set_option_skip_none(w, "dbtable", Some(table))?;
self.inner.set(w.clone());
+ let w = self.check_unsent_source_and_partition(py, w)?;
self.check_bucket_count(py)?;
+ let w = self.check_unsent_mode(py, w)?;
interruptible(py, &w.spark_session(), ||
w.save(None).map_err(Box::new))
}
@@ -4166,17 +4325,20 @@ impl PyDataFrameWriter {
&self,
py: Python<'_>,
path: Option<&Bound<'_, PyAny>>,
- format: Option<&str>,
- mode: Option<&str>,
+ format: Option<&Bound<'_, PyAny>>,
+ mode: Option<&Bound<'_, PyAny>>,
partitionBy: Option<&Bound<'_, PyAny>>,
options: Option<&Bound<'_, PyDict>>,
) -> PyResult<()> {
- let w = apply_write_common(self.inner.get(), format, mode,
partitionBy, options)?;
- // PySpark sets the inline format/mode/partitionBy/options on the
writer itself, before
- // its command sets the bucket count and then the path.
+ let w = self.apply_write_common(self.inner.get(), format, mode,
partitionBy, options)?;
+ // PySpark sets the inline format/mode/partitionBy/options on the
writer itself, before its
+ // command sets the source and the partitioning columns, the bucket
count, the path, and
+ // last the save mode.
self.inner.set(w.clone());
+ let w = self.check_unsent_source_and_partition(py, w)?;
self.check_bucket_count(py)?;
let path = path.map(crate::readwriter::writer_path).transpose()?;
+ let w = self.check_unsent_mode(py, w)?;
interruptible(py, &w.spark_session(), || {
w.save(path.as_deref()).map_err(Box::new)
})
@@ -4188,15 +4350,17 @@ impl PyDataFrameWriter {
&self,
py: Python<'_>,
name: &Bound<'_, PyAny>,
- format: Option<&str>,
- mode: Option<&str>,
+ format: Option<&Bound<'_, PyAny>>,
+ mode: Option<&Bound<'_, PyAny>>,
partitionBy: Option<&Bound<'_, PyAny>>,
options: Option<&Bound<'_, PyDict>>,
) -> PyResult<()> {
- let w = apply_write_common(self.inner.get(), format, mode,
partitionBy, options)?;
+ let w = self.apply_write_common(self.inner.get(), format, mode,
partitionBy, options)?;
self.inner.set(w.clone());
+ let w = self.check_unsent_source_and_partition(py, w)?;
self.check_bucket_count(py)?;
let name = crate::readwriter::writer_table_name(name)?;
+ let w = self.check_unsent_mode(py, w)?;
interruptible(py, &w.spark_session(), || {
match &name {
Some(name) => w.save_as_table(name),
@@ -4219,12 +4383,15 @@ impl PyDataFrameWriter {
let mut w = self.inner.get();
if let Some(ow) = overwrite {
let ow = ow.is_truthy()?;
+ self.unsent().mode = None;
w = w.mode(if ow { "overwrite" } else { "append" });
}
// PySpark sets the overwrite/append mode on the writer itself.
self.inner.set(w.clone());
+ let w = self.check_unsent_source_and_partition(py, w)?;
self.check_bucket_count(py)?;
let tableName = crate::readwriter::writer_table_name(tableName)?;
+ let w = self.check_unsent_mode(py, w)?;
interruptible(py, &w.spark_session(), || {
match &tableName {
Some(name) => w.insert_into(name),
@@ -4249,22 +4416,17 @@ impl PyDataFrameWriter {
) -> PyResult<()> {
crate::options::check_unexpected_keywords("DataFrameWriter.parquet",
unexpected)?;
let mut w = self.inner.get();
- if let Some(m) = mode {
- w = w.mode(&m.str()?.to_string());
- }
+ w = self.with_mode(w, mode);
if let Some(pb) = partitionBy {
- let cols: Vec<String> = if let Ok(one) = pb.extract::<String>() {
- vec![one]
- } else {
- pb.extract::<Vec<String>>()?
- };
- w = w.partition_by(cols);
+ w = self.with_partition_by(w, std::slice::from_ref(pb))?;
}
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"));
+ self.inner.set(self.with_fixed_format(w.clone(), "parquet"));
+ let w = self.check_unsent_source_and_partition(py, w)?;
self.check_bucket_count(py)?;
let path = crate::readwriter::writer_path(path)?;
+ let w = self.check_unsent_mode(py, w)?;
interruptible(py, &w.spark_session(), || {
w.parquet(&path).map_err(Box::new)
})
@@ -4289,9 +4451,7 @@ impl PyDataFrameWriter {
) -> PyResult<()> {
crate::options::check_unexpected_keywords("DataFrameWriter.json",
unexpected)?;
let mut w = self.inner.get();
- if let Some(m) = mode {
- w = w.mode(&m.str()?.to_string());
- }
+ w = self.with_mode(w, mode);
w = set_options_skip_none(
w,
&[
@@ -4304,9 +4464,11 @@ impl PyDataFrameWriter {
],
)?;
// PySpark sets the mode/options/format on the writer itself, then
saves.
- self.inner.set(w.clone().format("json"));
+ self.inner.set(self.with_fixed_format(w.clone(), "json"));
+ let w = self.check_unsent_source_and_partition(py, w)?;
self.check_bucket_count(py)?;
let path = crate::readwriter::writer_path(path)?;
+ let w = self.check_unsent_mode(py, w)?;
interruptible(py, &w.spark_session(), ||
w.json(&path).map_err(Box::new))
}
@@ -4339,9 +4501,7 @@ impl PyDataFrameWriter {
) -> PyResult<()> {
crate::options::check_unexpected_keywords("DataFrameWriter.csv",
unexpected)?;
let mut w = self.inner.get();
- if let Some(m) = mode {
- w = w.mode(&m.str()?.to_string());
- }
+ w = self.with_mode(w, mode);
w = set_options_skip_none(
w,
&[
@@ -4364,9 +4524,11 @@ impl PyDataFrameWriter {
],
)?;
// PySpark sets the mode/options/format on the writer itself, then
saves.
- self.inner.set(w.clone().format("csv"));
+ self.inner.set(self.with_fixed_format(w.clone(), "csv"));
+ let w = self.check_unsent_source_and_partition(py, w)?;
self.check_bucket_count(py)?;
let path = crate::readwriter::writer_path(path)?;
+ let w = self.check_unsent_mode(py, w)?;
interruptible(py, &w.spark_session(), ||
w.csv(&path).map_err(Box::new))
}
@@ -4385,22 +4547,17 @@ impl PyDataFrameWriter {
) -> PyResult<()> {
crate::options::check_unexpected_keywords("DataFrameWriter.orc",
unexpected)?;
let mut w = self.inner.get();
- if let Some(m) = mode {
- w = w.mode(&m.str()?.to_string());
- }
+ w = self.with_mode(w, mode);
if let Some(pb) = partitionBy {
- let cols: Vec<String> = if let Ok(one) = pb.extract::<String>() {
- vec![one]
- } else {
- pb.extract::<Vec<String>>()?
- };
- w = w.partition_by(cols);
+ w = self.with_partition_by(w, std::slice::from_ref(pb))?;
}
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"));
+ self.inner.set(self.with_fixed_format(w.clone(), "orc"));
+ let w = self.check_unsent_source_and_partition(py, w)?;
self.check_bucket_count(py)?;
let path = crate::readwriter::writer_path(path)?;
+ let w = self.check_unsent_mode(py, w)?;
interruptible(py, &w.spark_session(), ||
w.orc(&path).map_err(Box::new))
}
@@ -4420,9 +4577,11 @@ impl PyDataFrameWriter {
let mut w = self.inner.get();
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"));
+ self.inner.set(self.with_fixed_format(w.clone(), "text"));
+ let w = self.check_unsent_source_and_partition(py, w)?;
self.check_bucket_count(py)?;
let path = crate::readwriter::writer_path(path)?;
+ let w = self.check_unsent_mode(py, w)?;
interruptible(py, &w.spark_session(), ||
w.text(&path).map_err(Box::new))
}
@@ -4452,9 +4611,7 @@ impl PyDataFrameWriter {
crate::options::check_unexpected_keywords("DataFrameWriter.xml",
unexpected)?;
let mut w = self.inner.get();
w = set_option_skip_none(w, "rowTag", rowTag)?;
- if let Some(m) = mode {
- w = w.mode(&m.str()?.to_string());
- }
+ w = self.with_mode(w, mode);
w = set_options_skip_none(
w,
&[
@@ -4472,11 +4629,41 @@ impl PyDataFrameWriter {
],
)?;
// PySpark sets the mode/options/format on the writer itself, then
saves.
- self.inner.set(w.clone().format("xml"));
+ self.inner.set(self.with_fixed_format(w.clone(), "xml"));
+ let w = self.check_unsent_source_and_partition(py, w)?;
self.check_bucket_count(py)?;
let path = crate::readwriter::writer_path(path)?;
+ let w = self.check_unsent_mode(py, w)?;
interruptible(py, &w.spark_session(), ||
w.xml(&path).map_err(Box::new))
}
+
+ fn __traverse__(&self, visit: pyo3::PyVisit<'_>) -> Result<(),
pyo3::PyTraverseError> {
+ // The kept arguments, which Python's garbage collector sees, as
`exclusive_relation_owners`
+ // reports a DataFrame's owners: only when this writer holds them
alone, so that a copy that
+ // shares them does not count one reference twice. A lock held
elsewhere is skipped.
+ if std::sync::Arc::strong_count(&self.unsent) != 1 {
+ return Ok(());
+ }
+ if let Ok(unsent) = self.unsent.try_lock() {
+ for object in [
+ &unsent.format,
+ &unsent.partition,
+ &unsent.clustering,
+ &unsent.mode,
+ ]
+ .into_iter()
+ .flatten()
+ {
+ visit.call(object)?;
+ }
+ }
+ Ok(())
+ }
+
+ /// Drop this writer's reference to the kept arguments; a copy's are kept.
+ fn __clear__(&mut self) {
+ self.unsent =
std::sync::Arc::new(std::sync::Mutex::new(UnsentArgs::default()));
+ }
}
/// Python wrapper for the V2 `DataFrameWriter` (`df.writeTo`).
@@ -4494,9 +4681,48 @@ pub struct PyDataFrameWriterV2 {
/// The table of `writeTo` that its string field does not take, which
Python's garbage
/// collector sees ([`written_table`]).
unsent_table: Option<Py<PyAny>>,
+ /// The provider of `using` when it is not a str of UTF-8, which each
write fails with after
+ /// its table, as PySpark's command sets it there. A lock, as the state of
the writer, since
+ /// the writer's methods run on several threads ([`WriterState`]).
+ unsent_provider: std::sync::Arc<std::sync::Mutex<Option<Py<PyAny>>>>,
+ /// The first clustering column of `clusterBy` that is not a str of UTF-8,
which each write
+ /// fails with after its provider, as PySpark's command extends the
clustering columns there.
+ unsent_clustering: std::sync::Arc<std::sync::Mutex<Option<Py<PyAny>>>>,
}
-impl PyDataFrameWriterV2 {}
+impl PyDataFrameWriterV2 {
+ fn unsent_provider(&self) -> std::sync::MutexGuard<'_, Option<Py<PyAny>>> {
+ self.unsent_provider
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ }
+
+ fn unsent_clustering(&self) -> std::sync::MutexGuard<'_,
Option<Py<PyAny>>> {
+ self.unsent_clustering
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ }
+
+ /// The error of a write whose clustering column is not text, which
PySpark's command extends
+ /// after the provider and the partitioning columns.
+ fn check_unsent_clustering(&self, py: Python<'_>) -> PyResult<()> {
+ let column = self.unsent_clustering().as_ref().map(|c|
c.clone_ref(py));
+ match column {
+ Some(column) => crate::str_argument(column.bind(py)).map(drop),
+ None => Ok(()),
+ }
+ }
+
+ /// The error of a write whose provider is not text, which PySpark's
command sets after the
+ /// table ([`check_written_table`]).
+ fn check_unsent_provider(&self, py: Python<'_>) -> PyResult<()> {
+ let provider = self.unsent_provider().as_ref().map(|p|
p.clone_ref(py));
+ match provider {
+ Some(provider) => crate::str_argument(provider.bind(py)).map(drop),
+ None => Ok(()),
+ }
+ }
+}
#[pymethods]
impl PyDataFrameWriterV2 {
@@ -4506,6 +4732,8 @@ impl PyDataFrameWriterV2 {
PyDataFrameWriterV2 {
inner: std::sync::Arc::clone(&self.inner),
unsent_table: self.unsent_table.as_ref().map(|table|
table.clone_ref(py)),
+ unsent_provider: std::sync::Arc::clone(&self.unsent_provider),
+ unsent_clustering: std::sync::Arc::clone(&self.unsent_clustering),
frame: self.frame.clone_ref(py),
}
}
@@ -4513,9 +4741,19 @@ impl PyDataFrameWriterV2 {
/// 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};
+ use crate::reduce::{column_list, of_state_reduce, optional_object,
str_dict};
let writer = self.inner.get();
+ let (kept_provider, kept_clustering) = {
+ let kept = |object: &std::sync::Mutex<Option<Py<PyAny>>>| {
+ object
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .as_ref()
+ .map(|o| o.clone_ref(py))
+ };
+ (kept(&self.unsent_provider), kept(&self.unsent_clustering))
+ };
let args = PyTuple::new(
py,
[
@@ -4526,6 +4764,9 @@ impl PyDataFrameWriterV2 {
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(),
+ optional_object(py, self.unsent_table.as_ref()),
+ optional_object(py, kept_provider.as_ref()),
+ optional_object(py, kept_clustering.as_ref()),
],
)?;
of_state_reduce::<PyDataFrameWriterV2>(py, args)
@@ -4543,6 +4784,9 @@ impl PyDataFrameWriterV2 {
table_properties: std::collections::HashMap<String, String>,
partition_cols: &Bound<'_, PyAny>,
cluster_cols: Vec<String>,
+ unsent_table: Option<Py<PyAny>>,
+ kept_provider: Option<Py<PyAny>>,
+ kept_clustering: Option<Py<PyAny>>,
) -> PyResult<PyDataFrameWriterV2> {
let mut writer = frame.borrow(py).dataframe.write_to(table);
if let Some(provider) = provider {
@@ -4561,7 +4805,9 @@ impl PyDataFrameWriterV2 {
}
Ok(PyDataFrameWriterV2 {
inner: std::sync::Arc::new(WriterState::new(writer)),
- unsent_table: None,
+ unsent_table,
+ unsent_provider:
std::sync::Arc::new(std::sync::Mutex::new(kept_provider)),
+ unsent_clustering:
std::sync::Arc::new(std::sync::Mutex::new(kept_clustering)),
frame,
})
}
@@ -4577,8 +4823,27 @@ impl PyDataFrameWriterV2 {
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>> {
- slf.borrow().inner.update(|w| w.using(provider));
+ /// Set the provider of the write, as PySpark's `using`: a str of UTF-8
(bytes too) at once, else
+ /// kept for each write to fail with. None unsets it.
+ fn using<'py>(
+ slf: &Bound<'py, Self>,
+ provider: Option<&Bound<'_, PyAny>>,
+ ) -> PyResult<Bound<'py, Self>> {
+ let writer = slf.borrow();
+ match provider.map(crate::str_argument) {
+ Some(Ok(text)) => {
+ *writer.unsent_provider() = None;
+ writer.inner.update(|w| w.using(&text));
+ }
+ Some(Err(_)) => {
+ *writer.unsent_provider() = provider.map(|p|
p.clone().unbind());
+ writer.inner.update(|w| w.clear_provider());
+ }
+ None => {
+ *writer.unsent_provider() = None;
+ writer.inner.update(|w| w.clear_provider());
+ }
+ }
Ok(slf.clone())
}
@@ -4646,20 +4911,27 @@ impl PyDataFrameWriterV2 {
Ok(slf.clone())
}
+ /// The clustering columns of `clusterBy(col, *cols)`, which PySpark keeps
as `[col, *cols]`:
+ /// each column is set in the string field of the command at each write, as
+ /// [`crate::str_argument`] converts it.
#[pyo3(name = "clusterBy", signature = (col, *cols))]
fn cluster_by<'py>(
slf: &Bound<'py, Self>,
- col: String,
- cols: Vec<String>,
+ col: &Bound<'_, PyAny>,
+ cols: Vec<Bound<'_, PyAny>>,
) -> PyResult<Bound<'py, Self>> {
- let mut all = vec![col];
- all.extend(cols);
- slf.borrow().inner.update(|w| w.cluster_by(all));
+ let items: Vec<Bound<'_, PyAny>> =
std::iter::once(col.clone()).chain(cols).collect();
+ let (names, unsent) = crate::readwriter::writer_columns_kept(&items);
+ let writer = slf.borrow();
+ *writer.unsent_clustering() = unsent;
+ writer.inner.update(|w| w.cluster_by(names));
Ok(slf.clone())
}
fn create(&self, py: Python<'_>) -> PyResult<()> {
check_written_table(py, &self.unsent_table)?;
+ self.check_unsent_provider(py)?;
+ self.check_unsent_clustering(py)?;
let writer = self.inner.get();
interruptible(py, &writer.spark_session(), || {
writer.create().map_err(Box::new)
@@ -4668,6 +4940,8 @@ impl PyDataFrameWriterV2 {
fn replace(&self, py: Python<'_>) -> PyResult<()> {
check_written_table(py, &self.unsent_table)?;
+ self.check_unsent_provider(py)?;
+ self.check_unsent_clustering(py)?;
let writer = self.inner.get();
interruptible(py, &writer.spark_session(), || {
writer.replace().map_err(Box::new)
@@ -4677,6 +4951,8 @@ impl PyDataFrameWriterV2 {
#[pyo3(name = "createOrReplace")]
fn create_or_replace(&self, py: Python<'_>) -> PyResult<()> {
check_written_table(py, &self.unsent_table)?;
+ self.check_unsent_provider(py)?;
+ self.check_unsent_clustering(py)?;
let writer = self.inner.get();
interruptible(py, &writer.spark_session(), || {
writer.create_or_replace().map_err(Box::new)
@@ -4685,6 +4961,8 @@ impl PyDataFrameWriterV2 {
fn append(&self, py: Python<'_>) -> PyResult<()> {
check_written_table(py, &self.unsent_table)?;
+ self.check_unsent_provider(py)?;
+ self.check_unsent_clustering(py)?;
let writer = self.inner.get();
interruptible(py, &writer.spark_session(), || {
writer.append().map_err(Box::new)
@@ -4696,6 +4974,8 @@ impl PyDataFrameWriterV2 {
fn overwrite(&self, py: Python<'_>, condition: &Bound<'_, PyAny>) ->
PyResult<()> {
let (writer, condition) = (self.inner.get(),
column_or_name(condition)?);
check_written_table(py, &self.unsent_table)?;
+ self.check_unsent_provider(py)?;
+ self.check_unsent_clustering(py)?;
interruptible(py, &writer.spark_session(), || {
writer.overwrite(condition).map_err(Box::new)
})
@@ -4704,6 +4984,8 @@ impl PyDataFrameWriterV2 {
#[pyo3(name = "overwritePartitions")]
fn overwrite_partitions(&self, py: Python<'_>) -> PyResult<()> {
check_written_table(py, &self.unsent_table)?;
+ self.check_unsent_provider(py)?;
+ self.check_unsent_clustering(py)?;
let writer = self.inner.get();
interruptible(py, &writer.spark_session(), || {
writer.overwrite_partitions().map_err(Box::new)
@@ -4714,11 +4996,26 @@ impl PyDataFrameWriterV2 {
if let Some(table) = &self.unsent_table {
visit.call(table)?;
}
+ // The kept arguments that a copy shares are reported by no owner, as
the writer's are, and a
+ // lock held elsewhere is skipped.
+ for kept in [&self.unsent_provider, &self.unsent_clustering] {
+ if std::sync::Arc::strong_count(kept) != 1 {
+ continue;
+ }
+ if let Ok(kept) = kept.try_lock() {
+ if let Some(object) = &*kept {
+ visit.call(object)?;
+ }
+ }
+ }
Ok(())
}
+ /// Drop this writer's references to the kept arguments; a copy's are kept.
fn __clear__(&mut self) {
self.unsent_table = None;
+ self.unsent_provider =
std::sync::Arc::new(std::sync::Mutex::new(None));
+ self.unsent_clustering =
std::sync::Arc::new(std::sync::Mutex::new(None));
}
}
diff --git a/crates/pyspark-rs/src/readwriter.rs
b/crates/pyspark-rs/src/readwriter.rs
index be9c9f32..2a8ce4dc 100644
--- a/crates/pyspark-rs/src/readwriter.rs
+++ b/crates/pyspark-rs/src/readwriter.rs
@@ -9,8 +9,8 @@ use spark_connect::readwriter::DataFrameReader;
use crate::dataframe::PyDataFrame;
use crate::errors::{not_expected_type, ResultExt};
use crate::options::{
- check_keyword_keys, set_option_skip_none, set_options_skip_none,
set_reader_kwargs_unset_none,
- set_reader_option_unset_none, DefaultedOption,
+ check_keyword_keys, coerce_option_value, set_option_skip_none,
set_options_skip_none,
+ set_reader_kwargs_unset_none, set_reader_option_unset_none,
DefaultedOption,
};
/// Python wrapper for the batch DataFrameReader.
@@ -30,6 +30,9 @@ pub struct PyDataFrameReader {
/// 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>>>,
+ /// The format of `format` when it is not a str, which PySpark keeps as it
is and whose
+ /// `DataSource` asserts at `load` ([`reader_format`]). Any other format
replaces it.
+ unsent_format: Option<Py<PyAny>>,
}
impl PyDataFrameReader {
@@ -38,6 +41,7 @@ impl PyDataFrameReader {
PyDataFrameReader {
inner: without_options(reader, &options),
options:
std::sync::Arc::new(crate::dataframe::WriterState::new(options)),
+ unsent_format: None,
}
}
@@ -59,6 +63,7 @@ impl PyDataFrameReader {
/// Called before the path is checked, as PySpark's `load` sets the format
first.
fn commit(&mut self, r: &DataFrameReader, format: &str) {
self.set_state(r.clone().format(format));
+ self.unsent_format = None;
}
/// The DataFrame of `r`, this reader with the options of a call of
`json`, `csv` or `xml`
@@ -75,6 +80,8 @@ impl PyDataFrameReader {
parse_format: spark_connect::plan::ParseFormat,
path: &Bound<'_, PyAny>,
) -> PyResult<PyDataFrame> {
+ // As PySpark's, this sets the format of the reader, which replaces an
unsent one.
+ self.unsent_format = None;
if let Ok(df) = path.extract::<PyRef<'_, PyDataFrame>>() {
let r = apply_optional_schema(r, schema)?;
let parsed = r
@@ -107,6 +114,22 @@ fn without_options(reader: DataFrameReader, options:
&HashMap<String, String>) -
.fold(reader, |reader, key| reader.unset_option(key))
}
+/// The reader with the format `source` of PySpark's `format`, and the unsent
format that it keeps.
+/// None unsets the format. A str sets it. Any other object is kept as it is,
and `load` fails its
+/// `DataSource` assertion with it, as PySpark's `DataSource` takes only a str.
+fn reader_format(
+ reader: DataFrameReader,
+ source: Option<&Bound<'_, PyAny>>,
+) -> (DataFrameReader, Option<Py<PyAny>>) {
+ match source {
+ None => (reader.clear_format(), None),
+ Some(source) => match source.extract::<String>() {
+ Ok(text) => (reader.format(&text), None),
+ Err(_) => (reader.clear_format(), Some(source.clone().unbind())),
+ },
+ }
+}
+
/// 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>> {
@@ -171,6 +194,70 @@ pub(crate) fn writer_table_name(name: &Bound<'_, PyAny>)
-> PyResult<Option<Stri
crate::str_argument(name).map(Some)
}
+/// The column items of `partitionBy(*cols)` and `clusterBy(*cols)` of a
writer, as PySpark's take
+/// them: a list or tuple alone stands for its items, else the arguments are
the items.
+pub(crate) fn writer_column_items<'py>(
+ cols: &[Bound<'py, PyAny>],
+) -> PyResult<Vec<Bound<'py, PyAny>>> {
+ match cols {
+ [only]
+ if only.is_instance_of::<pyo3::types::PyList>()
+ || only.is_instance_of::<pyo3::types::PyTuple>() =>
+ {
+ only.try_iter()?.collect::<PyResult<_>>()
+ }
+ _ => Ok(cols.to_vec()),
+ }
+}
+
+/// The column names of the items of a writer column argument, as
[`crate::str_argument`] converts
+/// each one, which PySpark sets in a string field of its command at the
write. The names that
+/// convert are returned with the first item that does not, which the write
fails with.
+pub(crate) fn writer_columns_kept(items: &[Bound<'_, PyAny>]) -> (Vec<String>,
Option<Py<PyAny>>) {
+ let mut names = Vec::new();
+ let mut unsent = None;
+ for item in items {
+ match crate::str_argument(item) {
+ Ok(name) => names.push(name),
+ Err(_) => {
+ unsent.get_or_insert_with(|| item.clone().unbind());
+ }
+ }
+ }
+ (names, unsent)
+}
+
+/// The partitioning columns of `partitionBy(*cols)` of a writer, as
[`writer_columns_kept`].
+pub(crate) fn writer_partition_columns(
+ cols: &[Bound<'_, PyAny>],
+) -> PyResult<(Vec<String>, Option<Py<PyAny>>)> {
+ Ok(writer_columns_kept(&writer_column_items(cols)?))
+}
+
+/// The save mode of a write whose `mode` is not a str, as PySpark's
`WriteOperation.command`
+/// resolves it: `mode.lower()` is one of the four modes, or else
UNSUPPORTED_OPERATION of the
+/// mode, as for the bytes of `b"append"`. An object without `lower` raises
its AttributeError.
+pub(crate) fn unsent_save_mode(mode: &Bound<'_, PyAny>) -> PyResult<String> {
+ let lowered = mode.call_method0("lower")?;
+ if let Ok(text) = lowered.extract::<String>() {
+ if ["append", "overwrite", "error", "ignore"].contains(&text.as_str())
{
+ return Ok(text);
+ }
+ }
+ // The operation is the mode object itself, which PySpark's message
formats as it is.
+ let py = mode.py();
+ let params = PyDict::new(py);
+ params.set_item("operation", mode)?;
+ let kwargs = PyDict::new(py);
+ kwargs.set_item("errorClass", "UNSUPPORTED_OPERATION")?;
+ kwargs.set_item("messageParameters", params)?;
+ let error = py
+ .import("pyspark.errors")?
+ .getattr("PySparkValueError")?
+ .call((), Some(&kwargs))?;
+ Err(PyErr::from_value(error))
+}
+
/// 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(
@@ -318,18 +405,23 @@ 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 {
+ /// The shallow copy of a reader, as PySpark's `copy.copy`: the copy
shares the options of
+ /// this reader, and has its own format, which is kept as it is.
+ fn __copy__(&self, py: Python<'_>) -> PyDataFrameReader {
PyDataFrameReader {
inner: self.state(),
options: std::sync::Arc::clone(&self.options),
+ unsent_format: self
+ .unsent_format
+ .as_ref()
+ .map(|format| format.clone_ref(py)),
}
}
/// 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};
+ use crate::reduce::{of_state_reduce, optional_object, str_dict};
let session = crate::session::session_object(py,
&self.inner.spark_session())?;
let args = pyo3::types::PyTuple::new(
@@ -339,13 +431,14 @@ impl PyDataFrameReader {
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(),
+ optional_object(py, self.unsent_format.as_ref()),
],
)?;
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.
+ /// the schema, the options and the format that is kept (`unsent`).
#[staticmethod]
fn _of_state(
py: Python<'_>,
@@ -353,6 +446,7 @@ impl PyDataFrameReader {
format: Option<String>,
schema: String,
options: HashMap<String, String>,
+ unsent: Option<Py<PyAny>>,
) -> PyDataFrameReader {
let mut reader = session.borrow(py).session.read();
if let Some(format) = format {
@@ -361,7 +455,10 @@ impl PyDataFrameReader {
if !schema.is_empty() {
reader = reader.schema(schema);
}
- PyDataFrameReader::new(reader.options(options))
+ PyDataFrameReader {
+ unsent_format: unsent,
+ ..PyDataFrameReader::new(reader.options(options))
+ }
}
/// Set the schema, if any, and the options of `options` that are not
None, through its own
@@ -376,13 +473,15 @@ 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> {
- let state = match source {
- Some(source) => slf.state().format(source),
- None => slf.state().clear_format(),
- };
- slf.set_state(state);
+ /// that the server reads its default source, and an object that is not a
str is kept until
+ /// `load` fails its assertion.
+ fn format<'py>(
+ mut slf: PyRefMut<'py, Self>,
+ source: Option<&Bound<'_, PyAny>>,
+ ) -> PyRefMut<'py, Self> {
+ let (reader, unsent) = reader_format(slf.state(), source);
+ slf.set_state(reader);
+ slf.unsent_format = unsent;
slf
}
@@ -433,6 +532,17 @@ impl PyDataFrameReader {
Ok(slf)
}
+ fn __traverse__(&self, visit: pyo3::PyVisit<'_>) -> Result<(),
pyo3::PyTraverseError> {
+ if let Some(format) = &self.unsent_format {
+ visit.call(format)?;
+ }
+ Ok(())
+ }
+
+ fn __clear__(&mut self) {
+ self.unsent_format = None;
+ }
+
/// The configured source format (PySpark Connect's
`DataFrameReader._format`).
#[getter]
fn _format(&self) -> Option<String> {
@@ -471,20 +581,30 @@ impl PyDataFrameReader {
fn load(
&mut self,
path: Option<&Bound<'_, PyAny>>,
- format: Option<&str>,
+ format: Option<&Bound<'_, PyAny>>,
schema: Option<&Bound<'_, PyAny>>,
options: Option<&Bound<'_, PyDict>>,
) -> PyResult<PyDataFrame> {
- let mut r = set_reader_kwargs_unset_none(self.state(), options)?;
+ // As PySpark's load, which sets the format, the schema and the
options on the reader in
+ // turn, each one kept when a later one fails. CPython checks the
keyword keys first.
+ check_keyword_keys(options)?;
+ let mut r = self.state();
if let Some(f) = format {
- r = r.format(f);
+ let (reader, unsent) = reader_format(r, Some(f));
+ r = reader;
+ self.unsent_format = unsent;
}
+ self.set_state(r.clone());
if let Some(s) = schema {
r = apply_reader_schema(r, s)?;
}
- // PySpark's one-shot load sets format/schema/options on the reader
itself, before it
- // checks the path.
self.set_state(r.clone());
+ r = set_reader_kwargs_unset_none(r, options)?;
+ // Then its `DataSource` asserts the format, which precedes the check
of the paths.
+ self.set_state(r.clone());
+ if self.unsent_format.is_some() {
+ return Err(pyo3::exceptions::PyAssertionError::new_err(()));
+ }
let paths = path.map(paths_of).transpose()?.unwrap_or_default();
Ok(PyDataFrame::new(r.load_paths(paths)))
}
@@ -845,8 +965,8 @@ impl PyDataFrameReader {
#[allow(non_snake_case, clippy::too_many_arguments)]
fn jdbc(
&mut self,
- url: &str,
- table: &str,
+ url: &Bound<'_, PyAny>,
+ table: &Bound<'_, PyAny>,
column: Option<&Bound<'_, PyAny>>,
lowerBound: Option<&Bound<'_, PyAny>>,
upperBound: Option<&Bound<'_, PyAny>>,
@@ -855,6 +975,7 @@ impl PyDataFrameReader {
properties: Option<&Bound<'_, PyDict>>,
) -> PyResult<PyDataFrame> {
self.set_state(self.state().format("jdbc"));
+ self.unsent_format = None;
let mut r = self.state();
let predicates = match column {
Some(column) => {
@@ -894,9 +1015,25 @@ impl PyDataFrameReader {
r = set_option_skip_none(r, &crate::str_argument(&key)?,
Some(&value))?;
}
}
- // PySpark's jdbc also leaves url/dbtable on the reader, before it
asserts the predicates.
- self.set_state(r.clone().option("url", url).option("dbtable", table));
+ // PySpark's jdbc also sets url and dbtable as options,
`options(url=url, dbtable=table)`,
+ // which leaves an option of None unset, before it asserts the
predicates.
+ r = set_reader_option_unset_none(r, "url", url)?;
+ r = set_reader_option_unset_none(r, "dbtable", table)?;
+ self.set_state(r.clone());
let predicates = predicates.map(jdbc_predicates).transpose()?;
- Ok(PyDataFrame::new(r.jdbc(url, table, predicates)))
+ let url = coerce_option_value(url)?;
+ let table = coerce_option_value(table)?;
+ Ok(PyDataFrame::new(match (url, table, predicates) {
+ (Some(url), Some(table), predicates) => r.jdbc(&url, &table,
predicates),
+ // Without predicates, the read is that of the options alone,
which leave a None url or
+ // dbtable unset, as the core's `jdbc` needs both as strs.
+ (_, _, None) => r.load_paths(Vec::<String>::new()),
+ // Known residual: with predicates, the core's `jdbc` sets a None
url or dbtable as "".
+ (url, table, predicates) => r.jdbc(
+ &url.unwrap_or_default(),
+ &table.unwrap_or_default(),
+ predicates,
+ ),
+ }))
}
}
diff --git a/crates/pyspark-rs/src/streaming.rs
b/crates/pyspark-rs/src/streaming.rs
index 1a10c0ae..72534eef 100644
--- a/crates/pyspark-rs/src/streaming.rs
+++ b/crates/pyspark-rs/src/streaming.rs
@@ -204,25 +204,15 @@ fn load_path(path: &Bound<'_, PyAny>) -> PyResult<String>
{
))
}
-/// Coerce a `partitionBy` argument (a single column name or a list of names)
to a
-/// column-name vector, mirroring PySpark's `str | list[str]` acceptance.
-fn extract_partition_cols(v: &Bound<'_, PyAny>) -> PyResult<Vec<String>> {
- if let Ok(s) = v.extract::<String>() {
- return Ok(vec![s]);
- }
- v.extract::<Vec<String>>()
-}
-
-/// The column names of `partitionBy(*cols)` and `clusterBy(*cols)`, as
PySpark's take them:
-/// the names, or a list or tuple of them alone.
-fn column_names(cols: &Bound<'_, PyTuple>) -> PyResult<Vec<String>> {
- if cols.len() == 1 {
- let only = cols.get_item(0)?;
- if only.is_instance_of::<pyo3::types::PyList>() ||
only.is_instance_of::<PyTuple>() {
- return only.extract();
- }
- }
- cols.extract()
+/// The column names of a stream writer's `partitionBy` or `clusterBy`, which
PySpark clears and then
+/// extends into its protobuf string field at the call, each one converted as
[`crate::str_argument`]
+/// does. A list or tuple alone stands for its items. The extension is atomic,
so a column that does
+/// not convert leaves none, and its error is raised.
+fn stream_column_names(cols: &[Bound<'_, PyAny>]) -> PyResult<Vec<String>> {
+ crate::readwriter::writer_column_items(cols)?
+ .iter()
+ .map(crate::str_argument)
+ .collect()
}
/// The name of a query, as PySpark's `queryName` checks it: a non-empty str,
else
@@ -259,6 +249,25 @@ pub struct PyDataStreamReader {
/// 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>>>,
+ /// The format of `format` when it is not a str, which PySpark keeps as it
is and whose
+ /// `DataSource` asserts at `load`, after the path
([`stream_reader_format`]).
+ unsent_format: Option<Py<PyAny>>,
+}
+
+/// The stream reader with the format `source` of PySpark's `format`, and the
unsent format that it
+/// keeps: None unsets the format, a str sets it, and any other object is kept
for `load`, as the
+/// batch reader keeps it.
+fn stream_reader_format(
+ reader: DataStreamReader,
+ source: Option<&Bound<'_, PyAny>>,
+) -> (DataStreamReader, Option<Py<PyAny>>) {
+ match source {
+ None => (reader.clear_format(), None),
+ Some(source) => match source.extract::<String>() {
+ Ok(text) => (reader.format(&text), None),
+ Err(_) => (reader.clear_format(), Some(source.clone().unbind())),
+ },
+ }
}
impl PyDataStreamReader {
@@ -267,6 +276,7 @@ impl PyDataStreamReader {
PyDataStreamReader {
inner: without_options(reader, &options),
options: Arc::new(WriterState::new(options)),
+ unsent_format: None,
}
}
@@ -301,6 +311,7 @@ impl PyDataStreamReader {
));
}
self.set_state(reader.clone().format(format));
+ self.unsent_format = None;
load_path(path)
}
}
@@ -308,18 +319,22 @@ impl PyDataStreamReader {
#[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 {
+ /// options of this reader, and has its own format, which is kept as it is.
+ fn __copy__(&self, py: Python<'_>) -> PyDataStreamReader {
PyDataStreamReader {
inner: self.state(),
options: Arc::clone(&self.options),
+ unsent_format: self
+ .unsent_format
+ .as_ref()
+ .map(|format| format.clone_ref(py)),
}
}
/// 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};
+ use crate::reduce::{of_state_reduce, optional_object, str_dict};
let session = crate::session::session_object(py,
&self.inner.spark_session())?;
let args = PyTuple::new(
@@ -330,13 +345,14 @@ impl PyDataStreamReader {
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(),
+ optional_object(py, self.unsent_format.as_ref()),
],
)?;
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.
+ /// format, the schema, the options, the source name and the format that
is kept (`unsent`).
#[staticmethod]
fn _of_state(
py: Python<'_>,
@@ -345,6 +361,7 @@ impl PyDataStreamReader {
schema: String,
options: HashMap<String, String>,
source_name: Option<String>,
+ unsent: Option<Py<PyAny>>,
) -> PyResult<PyDataStreamReader> {
let mut reader = session.borrow(py).session.read_stream();
if let Some(format) = format {
@@ -357,7 +374,10 @@ impl PyDataStreamReader {
if let Some(source_name) = source_name {
reader = reader.name(&source_name);
}
- Ok(PyDataStreamReader::new(reader))
+ Ok(PyDataStreamReader {
+ unsent_format: unsent,
+ ..PyDataStreamReader::new(reader)
+ })
}
/// Set the schema, if any, and the options of `options` that are not
None, through its own
@@ -375,13 +395,11 @@ impl PyDataStreamReader {
/// default source.
fn format<'py>(
mut slf: PyRefMut<'py, Self>,
- source: Option<&str>,
+ source: Option<&Bound<'_, PyAny>>,
) -> PyResult<PyRefMut<'py, Self>> {
- let state = match source {
- Some(source) => slf.state().format(source),
- None => slf.state().clear_format(),
- };
- slf.set_state(state);
+ let (reader, unsent) = stream_reader_format(slf.state(), source);
+ slf.set_state(reader);
+ slf.unsent_format = unsent;
Ok(slf)
}
@@ -431,6 +449,17 @@ impl PyDataStreamReader {
Ok(slf)
}
+ fn __traverse__(&self, visit: pyo3::PyVisit<'_>) -> Result<(),
pyo3::PyTraverseError> {
+ if let Some(format) = &self.unsent_format {
+ visit.call(format)?;
+ }
+ Ok(())
+ }
+
+ fn __clear__(&mut self) {
+ self.unsent_format = None;
+ }
+
/// The configured source format (PySpark Connect's
`DataStreamReader._format`).
#[getter]
fn _format(&self) -> Option<String> {
@@ -453,25 +482,34 @@ impl PyDataStreamReader {
fn load(
&mut self,
path: Option<&Bound<'_, PyAny>>,
- format: Option<&str>,
+ format: Option<&Bound<'_, PyAny>>,
schema: Option<&Bound<'_, PyAny>>,
options: Option<&Bound<'_, PyDict>>,
) -> PyResult<PyDataFrame> {
+ // As PySpark's load, which sets the format, the schema and the
options on the reader in
+ // turn, each one kept when a later one fails.
crate::options::check_keyword_keys(options)?;
let mut r = self.state();
if let Some(fmt) = format {
- r = r.format(fmt);
+ let (reader, unsent) = stream_reader_format(r, Some(fmt));
+ r = reader;
+ self.unsent_format = unsent;
}
+ self.set_state(r.clone());
if let Some(v) = schema {
r = apply_stream_schema(r, v)?;
}
+ self.set_state(r.clone());
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.
+ // Then the path is checked, and the `DataSource` of PySpark asserts
the format after that.
self.set_state(r.clone());
let path = path.map(load_path).transpose()?;
+ if self.unsent_format.is_some() {
+ return Err(pyo3::exceptions::PyAssertionError::new_err(()));
+ }
Ok(PyDataFrame::new(r.load(path.as_deref())))
}
@@ -941,39 +979,76 @@ impl PyDataStreamWriter {
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.
- fn apply_write_opts(
- &self,
- format: Option<&str>,
- output_mode: Option<&str>,
+ /// The steps of PySpark's `_start_internal` on the writer `w`, in its
order: the options, the output
+ /// mode, the partitioning columns, the format and the query name. Each
step sets its part of the
+ /// writer in place, so a step that fails keeps the steps before it, and
the writer is returned with
+ /// the error of that step. The clear of the columns precedes their
extension, which leaves none
+ /// when it fails.
+ fn start_steps(
+ mut w: DataStreamWriter,
+ format: Option<&Bound<'_, PyAny>>,
+ output_mode: Option<&Bound<'_, PyAny>>,
partition_by: Option<&Bound<'_, PyAny>>,
query_name: Option<&Bound<'_, PyAny>>,
options: Option<&Bound<'_, PyDict>>,
- ) -> PyResult<DataStreamWriter> {
- crate::options::check_keyword_keys(options)?;
- let mut w = self.inner.get();
- if let Some(fmt) = format {
- w = w.format(fmt);
+ ) -> (DataStreamWriter, PyResult<()>) {
+ if options.is_some() {
+ match crate::options::kwargs_skip_none(options) {
+ Ok(opts) => w = w.options(opts),
+ Err(error) => return (w, Err(error)),
+ }
}
if let Some(m) = output_mode {
- w = w.output_mode(m);
+ match crate::str_argument(m) {
+ Ok(mode) => w = w.output_mode(&mode),
+ Err(error) => return (w, Err(error)),
+ }
}
if let Some(pb) = partition_by {
- let cols = extract_partition_cols(pb)?;
- let refs: Vec<&str> = cols.iter().map(|s| s.as_str()).collect();
- w = w.partition_by(refs);
+ match stream_column_names(std::slice::from_ref(pb)) {
+ Ok(names) => w = w.partition_by(names),
+ Err(error) => return (w.partition_by(Vec::<String>::new()),
Err(error)),
+ }
}
- if let Some(qn) = query_name {
- w = w.query_name(&query_name_of(qn)?);
+ if let Some(fmt) = format {
+ match crate::str_argument(fmt) {
+ Ok(source) => w = w.format(&source),
+ Err(error) => return (w, Err(error)),
+ }
}
- if options.is_some() {
- let opts = crate::options::kwargs_skip_none(options)?;
- w = w.options(opts);
+ if let Some(qn) = query_name {
+ match query_name_of(qn) {
+ Ok(name) => w = w.query_name(&name),
+ Err(error) => return (w, Err(error)),
+ }
}
- // PySpark's start/toTable set these on the writer itself before
starting.
+ (w, Ok(()))
+ }
+
+ /// 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.
+ fn apply_write_opts(
+ &self,
+ format: Option<&Bound<'_, PyAny>>,
+ output_mode: Option<&Bound<'_, PyAny>>,
+ partition_by: Option<&Bound<'_, PyAny>>,
+ query_name: Option<&Bound<'_, PyAny>>,
+ options: Option<&Bound<'_, PyDict>>,
+ ) -> PyResult<DataStreamWriter> {
+ crate::options::check_keyword_keys(options)?;
+ let (w, applied) = Self::start_steps(
+ self.inner.get(),
+ format,
+ output_mode,
+ partition_by,
+ query_name,
+ options,
+ );
+ // PySpark's start/toTable set these on the writer itself before
starting, and keep each
+ // step before a failing one.
self.inner.set(w.clone());
+ applied?;
Ok(w)
}
}
@@ -1095,13 +1170,25 @@ impl PyDataStreamWriter {
Ok(restored)
}
- fn outputMode<'py>(slf: &Bound<'py, Self>, outputMode: &str) ->
PyResult<Bound<'py, Self>> {
- slf.borrow().inner.update(|w| w.output_mode(outputMode));
+ /// The output mode, which PySpark sets in its protobuf string field at
once, as
+ /// [`crate::str_argument`] converts it.
+ fn outputMode<'py>(
+ slf: &Bound<'py, Self>,
+ outputMode: &Bound<'_, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ let outputMode = crate::str_argument(outputMode)?;
+ slf.borrow().inner.update(|w| w.output_mode(&outputMode));
Ok(slf.clone())
}
- fn format<'py>(slf: &Bound<'py, Self>, source: &str) ->
PyResult<Bound<'py, Self>> {
- slf.borrow().inner.update(|w| w.format(source));
+ /// The format, which PySpark sets in its protobuf string field at once, as
+ /// [`crate::str_argument`] converts it.
+ fn format<'py>(
+ slf: &Bound<'py, Self>,
+ source: &Bound<'_, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ let source = crate::str_argument(source)?;
+ slf.borrow().inner.update(|w| w.format(&source));
Ok(slf.clone())
}
@@ -1141,9 +1228,13 @@ impl PyDataStreamWriter {
slf: &Bound<'py, Self>,
cols: &Bound<'_, PyTuple>,
) -> PyResult<Bound<'py, Self>> {
- let cols = column_names(cols)?;
- let col_refs: Vec<&str> = cols.iter().map(|s| s.as_str()).collect();
- slf.borrow().inner.update(|w| w.partition_by(col_refs));
+ let items: Vec<Bound<'_, PyAny>> = cols.iter().collect();
+ let writer = slf.borrow();
+ let names = stream_column_names(&items);
+ writer
+ .inner
+ .update(|w| w.partition_by(names.as_deref().unwrap_or_default()));
+ names?;
Ok(slf.clone())
}
@@ -1153,9 +1244,13 @@ impl PyDataStreamWriter {
slf: &Bound<'py, Self>,
cols: &Bound<'_, PyTuple>,
) -> PyResult<Bound<'py, Self>> {
- let cols = column_names(cols)?;
- let col_refs: Vec<&str> = cols.iter().map(|s| s.as_str()).collect();
- slf.borrow().inner.update(|w| w.cluster_by(col_refs));
+ let items: Vec<Bound<'_, PyAny>> = cols.iter().collect();
+ let writer = slf.borrow();
+ let names = stream_column_names(&items);
+ writer
+ .inner
+ .update(|w| w.cluster_by(names.as_deref().unwrap_or_default()));
+ names?;
Ok(slf.clone())
}
@@ -1256,8 +1351,8 @@ impl PyDataStreamWriter {
&self,
py: Python<'_>,
path: Option<&Bound<'_, PyAny>>,
- format: Option<&str>,
- outputMode: Option<&str>,
+ format: Option<&Bound<'_, PyAny>>,
+ outputMode: Option<&Bound<'_, PyAny>>,
partitionBy: Option<&Bound<'_, PyAny>>,
queryName: Option<&Bound<'_, PyAny>>,
options: Option<&Bound<'_, PyDict>>,
@@ -1284,8 +1379,8 @@ impl PyDataStreamWriter {
&self,
py: Python<'_>,
tableName: &Bound<'_, PyAny>,
- format: Option<&str>,
- outputMode: Option<&str>,
+ format: Option<&Bound<'_, PyAny>>,
+ outputMode: Option<&Bound<'_, PyAny>>,
partitionBy: Option<&Bound<'_, PyAny>>,
queryName: Option<&Bound<'_, PyAny>>,
options: Option<&Bound<'_, PyDict>>,
diff --git a/crates/spark-connect/src/readwriter.rs
b/crates/spark-connect/src/readwriter.rs
index 4f8c1a95..20ab6721 100644
--- a/crates/spark-connect/src/readwriter.rs
+++ b/crates/spark-connect/src/readwriter.rs
@@ -693,6 +693,12 @@ impl DataFrameWriterV2 {
self
}
+ /// Unset the provider, as PySpark's `using(None)`.
+ pub fn clear_provider(mut self) -> Self {
+ self.provider = None;
+ self
+ }
+
/// Add a write option.
pub fn option(mut self, key: &str, value: &str) -> Self {
self.options.insert(key.to_string(), value.to_string());
diff --git a/python/tests/test_dropin_e2e.py b/python/tests/test_dropin_e2e.py
index 6dfa86eb..09fb2713 100644
--- a/python/tests/test_dropin_e2e.py
+++ b/python/tests/test_dropin_e2e.py
@@ -1931,6 +1931,13 @@ def
test_bool_stream_options_and_bytes_table_options_are_read_by_the_server(sess
session.sql("DROP TABLE IF EXISTS e2e_bytes_table_option")
+def test_writer_format_takes_bytes_and_writes_as_its_str(session):
+ # As PySpark's WriteOperation, which sends the source as its UTF-8 text,
so that the noop
+ # source of bytes is written by the server as that of a str.
+ session.range(1).write.format(b"noop").mode("overwrite").save()
+ session.range(1).write.format("noop").mode("overwrite").save()
+
+
def
test_reader_none_unsets_an_option_and_external_description_is_the_comment(session,
tmp_path):
# As PySpark's: DataFrameReader.option, options and load unset an option
given None, while
# the format methods skip None and keep it. createExternalTable's
description is the
diff --git a/python/tests/test_dropin_offline.py
b/python/tests/test_dropin_offline.py
index accd641e..c7a32666 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -8081,6 +8081,477 @@ def
test_write_to_and_merge_into_set_their_table_at_each_write_as_pyspark(mock_c
assert ref() is None
+def test_writer_formats_take_bytes_and_fail_the_write_as_pyspark(mock_connect):
+ # As PySpark's WriteOperation, which sets the source as it is given and
converts it at the
+ # command: bytes are sent decoded, and another object raises at each
write, the TypeError of
+ # the field, or the error of its decoding, while the call of format keeps
it. A format method
+ # of PySpark sets its own format over the kept one.
+ spark, service = mock_connect
+ df = spark.range(1)
+
+ def sent_operation():
+ # 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])
+
+ # WriteOperation.source=2, and WriteOperation.mode=5
(SAVE_MODE_OVERWRITE=2).
+ df.write.format(b"noop").mode("overwrite").save()
+ assert sent_operation()[2] == [b"noop"] and sent_operation()[5] == [2]
+ df.write.save(format=b"noop", mode="overwrite")
+ assert sent_operation()[2] == [b"noop"]
+ df.write.format(5).format("noop").mode("overwrite").save()
+ assert sent_operation()[2] == [b"noop"]
+ df.write.format(5).json("p")
+ assert sent_operation()[2] == [b"json"]
+
+ # None unsets the format, so that no source is sent.
+ df.write.format(None).mode("overwrite").save()
+ assert 2 not in sent_operation()
+ requests = len(service.execute_requests)
+ for source in [5, bytearray(b"noop")]:
+ writer = df.write.format(source)
+ assert len(service.execute_requests) == requests
+ with pytest.raises(TypeError) as error:
+ writer.mode("overwrite").save()
+ assert str(error.value) == "bad argument type for built-in operation"
+ for source, error, message in [
+ (b"\xff", UnicodeDecodeError, "'utf-8' codec can't decode byte 0xff in
position 0: invalid start byte"),
+ ("\ud800", UnicodeEncodeError, "'utf-8' codec can't encode character
'\\ud800' in position 0: surrogates not allowed"),
+ ]:
+ with pytest.raises(error) as raised:
+ df.write.format(source).save()
+ assert str(raised.value) == message
+ with pytest.raises(TypeError, match="^bad argument type for built-in
operation$"):
+ df.write.save(format=5)
+ assert len(service.execute_requests) == requests
+
+
+def
test_writer_modes_take_any_object_and_fail_the_write_as_pyspark(mock_connect):
+ # As PySpark's WriteOperation, which resolves a mode that is not a str at
the write, after its
+ # path: `lower()` of it is one of the four modes, else
UNSUPPORTED_OPERATION of the mode, and
+ # an object without `lower` raises its AttributeError. None leaves the
mode as it is, and a
+ # later mode, or insertInto's overwrite, replaces the kept one.
+ from pyspark.errors import PySparkValueError
+
+ spark, service = mock_connect
+ df = spark.range(1)
+ requests = len(service.execute_requests)
+ writer = df.write.format("noop").mode(b"append").mode(None)
+ assert len(service.execute_requests) == requests
+ with pytest.raises(PySparkValueError) as error:
+ writer.save()
+ assert error.value.getCondition() == "UNSUPPORTED_OPERATION"
+ assert error.value.getMessageParameters() == {"operation": b"append"}
+ assert str(error.value) == "[UNSUPPORTED_OPERATION] b'append' is not
supported."
+ with pytest.raises(PySparkValueError) as error:
+ df.write.format("noop").mode(bytearray(b"append")).save()
+ assert error.value.getMessageParameters() == {"operation":
bytearray(b"append")}
+ with pytest.raises(AttributeError, match="^'int' object has no attribute
'lower'$"):
+ df.write.format("noop").mode(5).save()
+ with pytest.raises(PySparkValueError):
+ df.write.save(format="noop", mode=b"append")
+ with pytest.raises(PySparkValueError):
+ df.write.parquet("p", mode=b"append")
+ assert len(service.execute_requests) == requests
+ # The later mode replaces the kept one, and insertInto's overwrite too.
+ df.write.format("noop").mode(5).mode("overwrite").save()
+ df.write.mode(b"append").insertInto(b"t", True)
+ assert len(service.execute_requests) == requests + 2
+
+
+def
test_stream_writer_formats_and_output_modes_take_bytes_at_the_call_as_pyspark(mock_connect):
+ # As PySpark's DataStreamWriter, which sets the format and the output mode
in their protobuf
+ # string fields at the call: bytes are sent decoded, and another object
raises the TypeError of
+ # the field at the call, and so does start with it, before any request.
+ spark, service = mock_connect
+ stream = spark.readStream.format("rate").load().writeStream
+ stream.format(b"noop").outputMode(b"append")
+ requests = len(service.execute_requests)
+ for call in [
+ lambda: stream.format(5),
+ lambda: stream.format(None),
+ lambda: stream.outputMode(bytearray(b"append")),
+ lambda: stream.outputMode(None),
+ ]:
+ with pytest.raises(TypeError, match="^bad argument type for built-in
operation$"):
+ call()
+ assert len(service.execute_requests) == requests
+ # ExecutePlanResponse.write_stream_operation_start_result=8: query_id=1
(id=1, run_id=2).
+ service.execute_payload = message_field(
+ 8, message_field(1, message_field(1, "q") + message_field(2, "r")))
+ stream.start(format=b"noop", outputMode=b"append")
+ # Command.write_stream_operation_start=6 ->
WriteStreamOperationStart.format=2, output_mode=9.
+ plan = parse_message(parse_message(service.execute_requests[-1])[3][0])
+ start = parse_message(parse_message(plan[2][0])[6][0])
+ assert start[2] == [b"noop"] and start[9] == [b"append"]
+ with pytest.raises(TypeError, match="^bad argument type for built-in
operation$"):
+ stream.start(format=5)
+ assert len(service.execute_requests) == requests + 1
+
+
+def test_reader_formats_are_kept_until_load_as_pyspark(mock_connect):
+ # As PySpark's DataFrameReader, whose DataSource asserts the format at
load, and whose format
+ # methods of a path set their own. The assertion has no message.
+ spark, service = mock_connect
+ for call in [
+ lambda: spark.read.format(b"noop").load(),
+ lambda: spark.read.format(5).load("p"),
+ lambda: spark.read.load(format=bytearray(b"noop")),
+ ]:
+ with pytest.raises(AssertionError) as error:
+ call()
+ assert str(error.value) == ""
+ assert service.analyze_requests == [] and service.execute_requests == []
+ spark.read.format(b"noop").format("noop").load()
+ df = spark.read.format(5).parquet("p")
+ assert df.schema is not None
+ # Read.data_source=2 -> DataSource.format=1.
+ data_source = parse_message(_sent_relation(service.analyze_requests[-1],
2)[2][0])
+ assert data_source[1] == [b"parquet"]
+
+
+def test_stream_reader_formats_are_kept_until_load_as_pyspark(mock_connect):
+ # As PySpark's DataStreamReader.load, which checks the path before its
DataSource asserts the
+ # format, and whose format methods of a path set their own.
+ from pyspark.errors import PySparkValueError
+
+ spark, service = mock_connect
+ with pytest.raises(PySparkValueError) as error:
+ spark.readStream.format(5).load("")
+ assert error.value.getCondition() == "VALUE_NOT_NON_EMPTY_STR"
+ for call in [
+ lambda: spark.readStream.format(b"rate").load(),
+ lambda: spark.readStream.load(format=b"rate"),
+ ]:
+ with pytest.raises(AssertionError) as error:
+ call()
+ assert str(error.value) == ""
+ stream = spark.readStream.format(b"rate").format("rate").load()
+ assert stream.schema is not None
+ # Read.data_source=2 -> DataSource.format=1.
+ data_source = parse_message(_sent_relation(service.analyze_requests[-1],
2)[2][0])
+ assert data_source[1] == [b"rate"]
+ spark.readStream.format(5).json("p")
+
+
+def
test_reader_jdbc_sends_url_and_dbtable_as_options_of_to_str_as_pyspark(mock_connect):
+ # As PySpark's DataFrameReader.jdbc, which sets url and dbtable as the
options of to_str: a
+ # bool is "true" or "false", another object its str(), and None leaves the
option out.
+ spark, service = mock_connect
+
+ def options(df):
+ assert df.schema is not None
+ # Read.data_source=2 -> DataSource.options=3, the entries of which
have key=1, value=2.
+ data_source =
parse_message(_sent_relation(service.analyze_requests[-1], 2)[2][0])
+ return {parse_message(e)[1][0]: parse_message(e)[2][0] for e in
data_source.get(3, [])}
+
+ assert options(spark.read.jdbc("jdbc:zz:nx", b"t")) == {
+ b"url": b"jdbc:zz:nx", b"dbtable": b"b't'"}
+ assert options(spark.read.jdbc("jdbc:zz:nx", 7))[b"dbtable"] == b"7"
+ assert options(spark.read.jdbc(True, "t"))[b"url"] == b"true"
+ unset = options(spark.read.jdbc("jdbc:zz:nx", None))
+ assert b"dbtable" not in unset and unset[b"url"] == b"jdbc:zz:nx"
+
+
+def
test_writer_jdbc_sends_url_and_dbtable_as_options_of_to_str_as_pyspark(mock_connect):
+ # As PySpark's DataFrameWriter.jdbc, which sets url and dbtable as
options, which skip a None,
+ # of to_str, and writes with the format "jdbc".
+ spark, service = mock_connect
+ df = spark.range(1)
+ df.write.jdbc("jdbc:zz:nx", b"t")
+ # Command.write_operation=2 -> WriteOperation.source=2, options=9 (key=1,
value=2).
+ plan = parse_message(parse_message(service.execute_requests[-1])[3][0])
+ operation = parse_message(parse_message(plan[2][0])[2][0])
+ assert operation[2] == [b"jdbc"]
+ assert {parse_message(e)[1][0]: parse_message(e)[2][0] for e in
operation[9]} == {
+ b"url": b"jdbc:zz:nx", b"dbtable": b"b't'"}
+ df.write.jdbc(None, 7)
+ plan = parse_message(parse_message(service.execute_requests[-1])[3][0])
+ operation = parse_message(parse_message(plan[2][0])[2][0])
+ assert {parse_message(e)[1][0]: parse_message(e)[2][0] for e in
operation[9]} == {
+ b"dbtable": b"7"}
+
+
+def test_partition_columns_take_bytes_at_each_write_as_pyspark(mock_connect):
+ # As PySpark's WriteOperation, which sets each partitioning column in its
string field at the
+ # write: bytes are sent decoded, a list or tuple alone stands for its
items, a later call
+ # replaces the columns, and a column that is not a str of UTF-8 fails each
write, not the call.
+ spark, service = mock_connect
+ df = spark.range(1)
+
+ def sent_operation():
+ # 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])
+
+ # WriteOperation.partitioning_columns=7.
+ df.write.partitionBy(b"k").format("noop").save()
+ assert sent_operation()[7] == [b"k"]
+ df.write.save(format="noop", partitionBy=[b"a", "b"])
+ assert sent_operation()[7] == [b"a", b"b"]
+ requests = len(service.execute_requests)
+ writer = df.write.partitionBy(5)
+ assert len(service.execute_requests) == requests
+ with pytest.raises(TypeError, match="^bad argument type for built-in
operation$"):
+ writer.format("noop").save()
+ with pytest.raises(TypeError, match="^bad argument type for built-in
operation$"):
+ df.write.partitionBy("a", ["b"]).format("noop").save()
+ df.write.partitionBy(5).partitionBy(b"k").format("noop").save()
+ assert sent_operation()[7] == [b"k"]
+ with pytest.raises(TypeError, match="^bad argument type for built-in
operation$"):
+ df.write.parquet("p", partitionBy=5)
+ assert len(service.execute_requests) == requests + 1
+
+
+def test_v2_using_takes_bytes_and_fails_each_write_as_pyspark(mock_connect):
+ # As PySpark's WriteOperationV2, which sets the provider after the table
at each write: bytes
+ # are sent decoded, and another object fails each write after the table,
while using keeps it.
+ from pyspark.sql import functions as F
+
+ spark, service = mock_connect
+ df = spark.range(1)
+
+ def sent_operation():
+ # ExecutePlanRequest.plan=3 -> Plan.command=2 ->
Command.write_operation_v2=4.
+ plan = parse_message(parse_message(service.execute_requests[-1])[3][0])
+ return parse_message(parse_message(plan[2][0])[4][0])
+
+ # WriteOperationV2.table_name=2, provider=3.
+ df.writeTo("t").using(b"noop").append()
+ assert sent_operation()[3] == [b"noop"]
+ df.writeTo("t").using(5).using("noop").append()
+ assert sent_operation()[3] == [b"noop"]
+ df.writeTo("t").using(5).using(None).append()
+ assert 3 not in sent_operation()
+ requests = len(service.execute_requests)
+ writer = df.writeTo("t").using(5)
+ assert len(service.execute_requests) == requests
+ for write in [writer.create, writer.replace, writer.createOrReplace,
writer.append,
+ writer.overwritePartitions, lambda:
writer.overwrite(F.lit(True))]:
+ with pytest.raises(TypeError, match="^bad argument type for built-in
operation$"):
+ write()
+ with pytest.raises(UnicodeDecodeError):
+ df.writeTo(b"\xff").using(5).append()
+ assert len(service.execute_requests) == requests
+
+
+def
test_kept_arguments_of_the_writers_and_readers_are_seen_by_the_collector_as_pyspark(
+ mock_connect):
+ # The kept arguments of the writers and readers are visited by Python's
garbage collector, which
+ # frees a reference cycle through them.
+ import gc
+ import weakref
+
+ spark, _ = mock_connect
+ df = spark.range(1)
+
+ class Holder:
+ pass
+
+ for keep in [
+ lambda h: df.write.format(h),
+ lambda h: df.write.mode(h),
+ lambda h: df.write.partitionBy(h),
+ lambda h: df.write.clusterBy(h),
+ lambda h: df.writeTo("t").using(h),
+ lambda h: df.writeTo("t").clusterBy(h),
+ lambda h: spark.read.format(h),
+ lambda h: spark.readStream.format(h),
+ ]:
+ holder = Holder()
+ holder.kept = keep(holder)
+ ref = weakref.ref(holder.kept)
+ del holder
+ gc.collect()
+ assert ref() is None
+
+
+def test_stream_writer_columns_take_bytes_at_the_call_as_pyspark(mock_connect):
+ # As PySpark's DataStreamWriter, which clears and then extends the
partitioning and clustering
+ # columns in their protobuf string fields at the call: bytes are sent
decoded, a list or tuple
+ # alone stands for its items, and a column that does not convert raises at
the call, leaving
+ # none.
+ spark, service = mock_connect
+ stream = spark.readStream.format("rate").load().writeStream
+
+ def sent_start():
+ # ExecutePlanRequest.plan=3 -> Plan.command=2 ->
Command.write_stream_operation_start=6.
+ plan = parse_message(parse_message(service.execute_requests[-1])[3][0])
+ return parse_message(parse_message(plan[2][0])[6][0])
+
+ stream.partitionBy(b"k", "j").clusterBy([b"c"])
+ # ExecutePlanResponse.write_stream_operation_start_result=8: query_id=1
(id=1, run_id=2).
+ service.execute_payload = message_field(
+ 8, message_field(1, message_field(1, "q") + message_field(2, "r")))
+ stream.start(format="noop")
+ # WriteStreamOperationStart.partitioning_column_names=4,
clustering_column_names=15.
+ assert sent_start()[15] == [b"c"]
+ stream.start(partitionBy=[b"p", "q"], format="noop")
+ assert sent_start()[4] == [b"p", b"q"]
+ requests = len(service.execute_requests)
+ message = "^bad argument type for built-in operation$"
+ with pytest.raises(TypeError, match=message):
+ stream.partitionBy(b"a", 5)
+ with pytest.raises(TypeError, match=message):
+ stream.clusterBy(None)
+ with pytest.raises(UnicodeDecodeError):
+ stream.start(partitionBy=b"\xff")
+ assert len(service.execute_requests) == requests
+ stream.start(format="noop")
+ assert 4 not in sent_start()
+
+
+def
test_writer_clusters_take_bytes_and_fail_each_write_as_pyspark(mock_connect):
+ # As PySpark's DataFrameWriter.clusterBy, which asserts the count after a
list or tuple alone is
+ # unpacked, and keeps the columns for each write: bytes are sent decoded,
another object fails
+ # each write after the partitioning columns, and not the call.
+ spark, service = mock_connect
+ df = spark.range(1)
+
+ def sent_operation():
+ # 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])
+
+ # WriteOperation.clustering_columns=10.
+ df.write.clusterBy(b"k").format("noop").mode("overwrite").save()
+ assert sent_operation()[10] == [b"k"]
+ df.write.clusterBy([b"a", "b"]).format("noop").mode("overwrite").save()
+ assert sent_operation()[10] == [b"a", b"b"]
+ with pytest.raises(AssertionError, match="^clusterBy needs one or more
clustering columns.$"):
+ df.write.clusterBy([])
+ requests = len(service.execute_requests)
+ writer = df.write.clusterBy(5)
+ assert len(service.execute_requests) == requests
+ with pytest.raises(TypeError, match="^bad argument type for built-in
operation$"):
+ writer.format("noop").mode("overwrite").save()
+ # The partitioning columns are converted first.
+ with pytest.raises(TypeError, match="^bad argument type for built-in
operation$"):
+ df.write.partitionBy(5).clusterBy(b"\xff").format("noop").save()
+ with pytest.raises(UnicodeDecodeError):
+ df.write.clusterBy(b"\xff").format("noop").save()
+ assert len(service.execute_requests) == requests
+
+
+def
test_v2_cluster_by_takes_bytes_and_fails_each_write_as_pyspark(mock_connect):
+ # As PySpark's DataFrameWriterV2.clusterBy, which keeps `[col, *cols]` as
it is given and extends
+ # the clustering columns of each write after its provider: bytes are sent
decoded, and another
+ # object fails each write, after the table and the provider.
+ from pyspark.sql import functions as F
+
+ spark, service = mock_connect
+ df = spark.range(1)
+
+ def sent_operation():
+ # ExecutePlanRequest.plan=3 -> Plan.command=2 ->
Command.write_operation_v2=4.
+ plan = parse_message(parse_message(service.execute_requests[-1])[3][0])
+ return parse_message(parse_message(plan[2][0])[4][0])
+
+ # WriteOperationV2.clustering_columns=9.
+ df.writeTo("t").clusterBy(b"k").append()
+ assert sent_operation()[9] == [b"k"]
+ df.writeTo("t").clusterBy(b"a", "b").append()
+ assert sent_operation()[9] == [b"a", b"b"]
+ requests = len(service.execute_requests)
+ writer = df.writeTo("t").clusterBy(5)
+ assert len(service.execute_requests) == requests
+ for write in [writer.create, writer.replace, writer.createOrReplace,
writer.append,
+ writer.overwritePartitions, lambda:
writer.overwrite(F.lit(True))]:
+ with pytest.raises(TypeError, match="^bad argument type for built-in
operation$"):
+ write()
+ with pytest.raises(TypeError, match="^bad argument type for built-in
operation$"):
+ df.writeTo("t").using(5).clusterBy(5).append()
+ with pytest.raises(UnicodeDecodeError):
+ df.writeTo(b"\xff").clusterBy(5).append()
+ assert len(service.execute_requests) == requests
+
+
+def
test_stream_writer_keeps_the_steps_before_a_failing_one_as_pyspark(mock_connect):
+ # As PySpark's _start_internal, which sets the options, the output mode,
the partitioning
+ # columns, the format and the query name on the writer in turn, each in
place: a step that
+ # fails keeps the steps before it, and a failing partitioning clears its
columns.
+ from pyspark.errors import PySparkValueError
+
+ spark, service = mock_connect
+ # ExecutePlanResponse.write_stream_operation_start_result=8: query_id=1
(id=1, run_id=2).
+ service.execute_payload = message_field(
+ 8, message_field(1, message_field(1, "q") + message_field(2, "r")))
+ message = "^bad argument type for built-in operation$"
+
+ def started(stream):
+ # Command.write_stream_operation_start=6 -> WriteStreamOperationStart;
its options=3 map
+ # has key=1 and value=2, partitioning_column_names=4, output_mode=9.
+ stream.start(format="noop")
+ plan = parse_message(parse_message(service.execute_requests[-1])[3][0])
+ start = parse_message(parse_message(plan[2][0])[6][0])
+ options = {parse_message(e)[1][0]: parse_message(e)[2][0] for e in
start.get(3, [])}
+ return start, options
+
+ rate = spark.readStream.format("rate").load()
+ stream = rate.writeStream
+ with pytest.raises(TypeError, match=message):
+ stream.start(outputMode=5, foo="1")
+ start, options = started(stream)
+ assert options == {b"foo": b"1"} and 9 not in start
+
+ stream = rate.writeStream
+ with pytest.raises(TypeError, match=message):
+ stream.start(outputMode=b"append", format=5)
+ start, _ = started(stream)
+ assert start[9] == [b"append"]
+
+ stream = rate.writeStream
+ with pytest.raises(TypeError, match=message):
+ stream.start(partitionBy=5, bar="1")
+ start, options = started(stream)
+ assert options == {b"bar": b"1"} and 4 not in start
+
+ stream = rate.writeStream
+ stream.partitionBy(b"k")
+ with pytest.raises(TypeError, match=message):
+ stream.start(partitionBy=5)
+ start, _ = started(stream)
+ assert 4 not in start
+
+ stream = rate.writeStream
+ with pytest.raises(TypeError, match=message):
+ stream.toTable("t", format=5, qux="1")
+ start, options = started(stream)
+ assert options == {b"qux": b"1"}
+
+ stream = rate.writeStream
+ with pytest.raises(PySparkValueError) as error:
+ stream.start(queryName="", quux="1")
+ assert error.value.getCondition() == "VALUE_NOT_NON_EMPTY_STR"
+ start, options = started(stream)
+ assert options == {b"quux": b"1"}
+
+
+def
test_readers_keep_the_format_of_a_load_whose_schema_fails_as_pyspark(mock_connect):
+ # As PySpark's load, which sets the format, then the schema, then the
options on the reader in
+ # turn: a schema that is not a str or a struct fails after the format,
which the reader keeps,
+ # and before the options, which are not applied.
+ from pyspark.errors import PySparkTypeError
+
+ spark, service = mock_connect
+ reader = spark.read
+ with pytest.raises(PySparkTypeError) as error:
+ reader.load(format="csv", schema=5, foo="1")
+ assert error.value.getCondition() == "NOT_EXPECTED_TYPE"
+ assert reader.load().schema is not None
+ # Read.data_source=2 -> DataSource.format=1, and options=3 (key=1).
+ data_source = parse_message(_sent_relation(service.analyze_requests[-1],
2)[2][0])
+ assert data_source[1] == [b"csv"]
+ assert b"foo" not in {parse_message(e)[1][0] for e in data_source.get(3,
[])}
+
+ stream_reader = spark.readStream
+ with pytest.raises(PySparkTypeError):
+ stream_reader.load(format="rate", schema=5, foo="1")
+ assert stream_reader.load().schema is not None
+ data_source = parse_message(_sent_relation(service.analyze_requests[-1],
2)[2][0])
+ assert data_source[1] == [b"rate"]
+
+
def test_stream_writer_skips_a_false_path_and_table_as_pyspark(mock_connect):
# As PySpark's `_start_internal`, which sets the path of start and the
table of toTable in
# the string fields of its command only `if path:` and `if tableName:`: a
false one, such as
@@ -25882,3 +26353,147 @@ def
test_a_shallow_copy_of_a_merge_builder_keeps_its_schema_evolution_as_pyspark
copied.merge()
assert sent_schema_evolution() is True
assert len(service.execute_requests) >= 2
+
+
+class _NotAMode:
+ # An object that is not a save mode, whose `lower()` names none of them.
+ def lower(self):
+ return "bogus"
+
+
+def
test_copies_of_the_writers_share_their_kept_arguments_as_pyspark(mock_connect):
+ # As PySpark's copy.copy of a writer, which shares its `_write`: an
argument that the copy keeps
+ # for the write (a format, a save mode, a partitioning or clustering
column, or a provider) is in
+ # the write of the original too, as an attribute set on the shared object
is.
+ import copy
+
+ from pyspark.errors import PySparkValueError
+
+ spark, _ = mock_connect
+ df = spark.range(1)
+ writer = df.write
+ copied = copy.copy(writer)
+ copied.format(5)
+ with pytest.raises(TypeError, match="^bad argument type for built-in
operation$"):
+ writer.mode("overwrite").save()
+ writer.format("noop")
+ copied.mode(b"append")
+ with pytest.raises(PySparkValueError) as error:
+ writer.save()
+ assert error.value.getCondition() == "UNSUPPORTED_OPERATION"
+ writer.mode("overwrite")
+ copied.partitionBy(5)
+ with pytest.raises(TypeError, match="^bad argument type for built-in
operation$"):
+ writer.save()
+ writer.partitionBy("id")
+ copied.clusterBy(5)
+ with pytest.raises(TypeError, match="^bad argument type for built-in
operation$"):
+ writer.save()
+ writer.clusterBy("id")
+ copied.format(5)
+ with pytest.raises(TypeError, match="^bad argument type for built-in
operation$"):
+ writer.save()
+
+ v2 = df.writeTo("forked_copy_table")
+ copied_v2 = copy.copy(v2)
+ copied_v2.using(5)
+ with pytest.raises(TypeError, match="^bad argument type for built-in
operation$"):
+ v2.append()
+ v2.using("noop")
+ copied_v2.clusterBy(5)
+ with pytest.raises(TypeError, match="^bad argument type for built-in
operation$"):
+ v2.append()
+
+
+def
test_deep_copies_keep_the_kept_arguments_through_the_memo_as_pyspark(mock_connect):
+ # As PySpark's copy.deepcopy, which copies the state of a writer, and the
objects that it keeps,
+ # through the memo: the copied save mode of the copied writer is the copy
of the object.
+ import copy
+
+ from pyspark.errors import PySparkValueError
+
+ spark, _ = mock_connect
+ mode = _NotAMode()
+ copied = copy.deepcopy({"writer": spark.range(1).write.mode(mode), "mode":
mode})
+ with pytest.raises(PySparkValueError) as error:
+ copied["writer"].format("noop").save()
+ assert error.value.getMessageParameters()["operation"] is copied["mode"]
+ assert copied["mode"] is not mode
+
+
+def
test_reader_copies_keep_their_format_and_share_their_options_as_pyspark(mock_connect):
+ # As PySpark's copy.copy of a reader: the copy shares the options, and its
format and schema
+ # stay its own, so a format on the copy does not reach the original.
+ import copy
+
+ spark, _ = mock_connect
+ reader = spark.read.format("noop")
+ copied = copy.copy(reader)
+ copied.format(5).option("k", "v")
+ assert reader.load() is not None
+ assert reader._options == {"k": "v"}
+ with pytest.raises(AssertionError):
+ copied.load()
+ deep = copy.deepcopy(copied)
+ with pytest.raises(AssertionError):
+ deep.load()
+
+
+def
test_unpickled_kept_arguments_fail_as_the_originals_do_as_pyspark(mock_connect):
+ # As PySpark's cloudpickle of the writers and readers: the kept arguments
unpickle with them, so
+ # that the write or the load fails as the original's does, and an object
that does not pickle
+ # makes the pickle fail with its TypeError.
+ import copy
+ import threading
+
+ import cloudpickle
+
+ spark, _ = mock_connect
+ df = spark.range(1)
+
+ def unpickled(obj):
+ return cloudpickle.loads(cloudpickle.dumps(obj))
+
+ with pytest.raises(TypeError, match="^bad argument type for built-in
operation$"):
+ unpickled(df.write.format(5)).mode("overwrite").save()
+ with pytest.raises(TypeError, match="^bad argument type for built-in
operation$"):
+ unpickled(df.writeTo("forked_pickle_table").using(5)).append()
+ with pytest.raises(TypeError, match="^bad argument type for built-in
operation$"):
+ unpickled(df.writeTo("forked_pickle_table").clusterBy(5)).append()
+ with pytest.raises(AssertionError):
+ unpickled(spark.read.format(5)).load()
+ with pytest.raises(AssertionError):
+ unpickled(spark.readStream.format(5)).load()
+ with pytest.raises(TypeError, match="^cannot pickle '_thread.lock'
object$"):
+ cloudpickle.dumps(df.write.format(threading.Lock()))
+ with pytest.raises(TypeError, match="^cannot pickle '_thread.lock'
object$"):
+ copy.deepcopy(df.write.format(threading.Lock()))
+
+
+def
test_kept_arguments_shared_by_copies_are_not_counted_twice_by_the_collector_as_pyspark(
+ mock_connect):
+ # The kept objects of a writer and of its copy are shared: Python's
garbage collector reports
+ # them from no owner, as the owners of a DataFrame that another plan
shares, so a collection
+ # that runs while they are shared frees nothing that the copy still uses.
+ import gc
+
+ spark, _ = mock_connect
+ df = spark.range(1)
+
+ class Holder:
+ pass
+
+ holder = Holder()
+ writer = df.write.format(holder)
+ copied = copy_module_copy(writer)
+ holder.writer = writer
+ del holder
+ gc.collect()
+ with pytest.raises(TypeError, match="^bad argument type for built-in
operation$"):
+ copied.mode("overwrite").save()
+
+
+def copy_module_copy(obj):
+ import copy
+
+ return copy.copy(obj)
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]