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 f94409c3 [SPARK-61613][CONNECT][PYTHON] Take bytes, as PySpark does,
in the table names and paths of the catalog, the readers and the writers, in
the Python client
f94409c3 is described below
commit f94409c3f282a2d3777963c276abb90de30471ff
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Fri Nov 13 13:44:44 2026 +0900
[SPARK-61613][CONNECT][PYTHON] Take bytes, as PySpark does, in the table
names and paths of the catalog, the readers and the writers, in the Python
client
### What changes were proposed in this pull request?
A follow-up of #566 (SPARK-61535), from a post-merge review. PySpark 4.3.0
puts the table names, view names, database names, patterns and paths of the
catalog, the readers and the writers straight into proto string fields.
protobuf's default (upb) backend takes those as a str or as UTF-8 bytes, raises
`UnicodeDecodeError` for other bytes, and `TypeError: bad argument type for
built-in operation` for another object. The Python client took most of them as
str only, and refused bytes wit [...]
These now convert with `str_argument`, upb's conversion, at PySpark's point
and in PySpark's order:
- `Catalog`:
- `createTable`/`createExternalTable` (`tableName`, `path`, `source`,
`description`, after the schema check) and every other method's names, patterns
and paths. The deprecated-`dbName` warning still comes first, and `cacheTable`
converts the table before the storage level.
- `None`: the methods whose message PySpark constructs with the name
(`cacheTable`, `dropTable`, `dropView`, `createDatabase`, `dropDatabase`) send
an empty name, as upb leaves a `None` unset. Elsewhere it raises the
`TypeError`.
- `DataFrameWriter.insertInto`/`saveAsTable`: after the bucket-count check
and before the save-mode check. `None` writes as `save()` does, as PySpark's
`if self.table_name is not None`.
- `DataFrame.writeTo`/`mergeInto`: a name that does not convert is kept,
and each write raises its error, as PySpark converts it at the write.
- The temp-view methods, `DataFrameReader.table`/`changes` and
`DataStreamReader.table`/`changes`.
- `DataStreamWriter.start(path)` and `toTable(tableName)` set the path or
table only if it is true, as PySpark's `if path:`. A false value such as `0`
raised a `TypeError` before.
`spark.table` keeps its `NOT_EXPECTED_TYPE`.
### Why are the changes needed?
To match PySpark 4.3.0. The review's probes of these call sites
(`bytes_path.py`, `bytes_table.py`) and a sweep of 146 cases over the catalog,
reader and writer names now give the same results on official pyspark-client
4.3.0 (protobuf 7.36 upb) and on this client. The exceptions are pre-existing
differences, to be followed up separately.
### Does this PR introduce _any_ user-facing change?
Yes, in the Python client. These methods take UTF-8 bytes as PySpark does,
and raise PySpark's errors for other values. `start` and `toTable` ignore a
false path or table name.
### How was this patch tested?
- 5 new offline tests, after `test_writers_take_a_bytes_path_as_pyspark`.
They fail without the change.
- The whole `test_dropin_offline.py` (1963 passed, 8 skipped), and 46
related e2e tests against a Spark 4.3.0 server.
- `cargo fmt --all --check`, and ruff 0.14.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 #608 from HyukjinKwon/SPARK-61613-bytes-names.
Authored-by: Hyukjin Kwon <[email protected]>
Signed-off-by: Hyukjin Kwon <[email protected]>
---
crates/pyspark-rs/src/catalog.rs | 263 ++++++++++++++++++++----------
crates/pyspark-rs/src/dataframe.rs | 128 ++++++++++++---
crates/pyspark-rs/src/readwriter.rs | 23 ++-
crates/pyspark-rs/src/streaming.rs | 38 +++--
python/tests/test_dropin_offline.py | 311 ++++++++++++++++++++++++++++++++++++
5 files changed, 641 insertions(+), 122 deletions(-)
diff --git a/crates/pyspark-rs/src/catalog.rs b/crates/pyspark-rs/src/catalog.rs
index 9d05718e..74555e8f 100644
--- a/crates/pyspark-rs/src/catalog.rs
+++ b/crates/pyspark-rs/src/catalog.rs
@@ -12,7 +12,7 @@ use crate::dataframe::PyDataFrame;
use crate::interrupt::interruptible;
/// PySpark's FutureWarning of the deprecated `dbName` of the catalog method
`method`.
-fn warn_db_name(py: Python<'_>, method: &str, db_name: Option<&str>) ->
PyResult<()> {
+fn warn_db_name(py: Python<'_>, method: &str, db_name: Option<&Bound<'_,
PyAny>>) -> PyResult<()> {
if db_name.is_some() {
py.import("warnings")?.call_method1(
"warn",
@@ -28,6 +28,20 @@ fn warn_db_name(py: Python<'_>, method: &str, db_name:
Option<&str>) -> PyResult
Ok(())
}
+// The names, patterns and paths of the catalog methods are set in the string
fields of their
+// plans as they are, which protobuf's default (upb) backend converts as
`crate::str_argument`
+// does: a str, or bytes decoded as UTF-8. An optional one is set only when it
is not None.
+
+/// The name of a catalog method that PySpark passes to the constructor of its
message, which
+/// leaves the string field unset for None, and converts any other value as
+/// [`crate::str_argument`] does.
+fn constructor_name(name: &Bound<'_, PyAny>) -> PyResult<String> {
+ if name.is_none() {
+ return Ok(String::new());
+ }
+ crate::str_argument(name)
+}
+
/// The schema of `createTable`, a StructType, as PySpark's, else
`NOT_EXPECTED_TYPE`.
fn table_schema(
schema: Option<&Bound<'_, PyAny>>,
@@ -169,19 +183,25 @@ impl PyCatalog {
}
/// Set the current catalog.
- fn setCurrentCatalog(&self, py: Python<'_>, catalogName: &str) ->
PyResult<()> {
+ fn setCurrentCatalog(&self, py: Python<'_>, catalogName: &Bound<'_,
PyAny>) -> PyResult<()> {
+ let catalogName = crate::str_argument(catalogName)?;
self.detached(py, |catalog| {
- catalog.set_current_catalog(catalogName).map_err(Box::new)
+ catalog.set_current_catalog(&catalogName).map_err(Box::new)
})
}
/// List catalogs. Mirrors `Catalog.listCatalogs(pattern=None) ->
List[CatalogMetadata]`.
#[pyo3(signature = (pattern=None))]
- fn listCatalogs(&self, py: Python<'_>, pattern: Option<&str>) ->
PyResult<Vec<Py<PyAny>>> {
+ fn listCatalogs(
+ &self,
+ py: Python<'_>,
+ pattern: Option<&Bound<'_, PyAny>>,
+ ) -> PyResult<Vec<Py<PyAny>>> {
+ let pattern = pattern.map(crate::str_argument).transpose()?;
named_tuples(
py,
self.detached(py, |catalog| {
- catalog.list_catalogs_typed(pattern).map_err(Box::new)
+ { catalog.list_catalogs_typed(pattern.as_deref())
}.map_err(Box::new)
})?,
)
}
@@ -192,34 +212,42 @@ impl PyCatalog {
}
/// Set current database.
- fn setCurrentDatabase(&self, py: Python<'_>, dbName: &str) -> PyResult<()>
{
+ fn setCurrentDatabase(&self, py: Python<'_>, dbName: &Bound<'_, PyAny>) ->
PyResult<()> {
+ let dbName = crate::str_argument(dbName)?;
self.detached(py, |catalog| {
- catalog.set_current_database(dbName).map_err(Box::new)
+ catalog.set_current_database(&dbName).map_err(Box::new)
})
}
/// List databases. Mirrors `Catalog.listDatabases(pattern=None) ->
List[Database]`.
#[pyo3(signature = (pattern=None))]
- fn listDatabases(&self, py: Python<'_>, pattern: Option<&str>) ->
PyResult<Vec<Py<PyAny>>> {
+ fn listDatabases(
+ &self,
+ py: Python<'_>,
+ pattern: Option<&Bound<'_, PyAny>>,
+ ) -> PyResult<Vec<Py<PyAny>>> {
+ let pattern = pattern.map(crate::str_argument).transpose()?;
named_tuples(
py,
self.detached(py, |catalog| {
- catalog.list_databases_typed(pattern).map_err(Box::new)
+ { catalog.list_databases_typed(pattern.as_deref())
}.map_err(Box::new)
})?,
)
}
/// Check if database exists.
- fn databaseExists(&self, py: Python<'_>, dbName: &str) -> PyResult<bool> {
+ fn databaseExists(&self, py: Python<'_>, dbName: &Bound<'_, PyAny>) ->
PyResult<bool> {
+ let dbName = crate::str_argument(dbName)?;
self.detached(py, |catalog| {
- catalog.database_exists(dbName).map_err(Box::new)
+ catalog.database_exists(&dbName).map_err(Box::new)
})
}
/// Get database info. Mirrors `Catalog.getDatabase(dbName) -> Database`.
- fn getDatabase(&self, py: Python<'_>, dbName: &str) -> PyResult<Py<PyAny>>
{
+ fn getDatabase(&self, py: Python<'_>, dbName: &Bound<'_, PyAny>) ->
PyResult<Py<PyAny>> {
+ let dbName = crate::str_argument(dbName)?;
self.detached(py, |catalog| {
- catalog.get_database_typed(dbName).map_err(Box::new)
+ catalog.get_database_typed(&dbName).map_err(Box::new)
})?
.named_tuple(py)
}
@@ -230,30 +258,41 @@ impl PyCatalog {
fn listTables(
&self,
py: Python<'_>,
- dbName: Option<&str>,
- pattern: Option<&str>,
+ dbName: Option<&Bound<'_, PyAny>>,
+ pattern: Option<&Bound<'_, PyAny>>,
) -> PyResult<Vec<Py<PyAny>>> {
+ let dbName = dbName.map(crate::str_argument).transpose()?;
+ let pattern = pattern.map(crate::str_argument).transpose()?;
named_tuples(
py,
self.detached(py, |catalog| {
- catalog.list_tables_typed(dbName, pattern).map_err(Box::new)
+ { catalog.list_tables_typed(dbName.as_deref(),
pattern.as_deref()) }
+ .map_err(Box::new)
})?,
)
}
/// Check if table exists. Mirrors `Catalog.tableExists(tableName,
dbName=None) -> bool`.
#[pyo3(signature = (tableName, dbName=None))]
- fn tableExists(&self, py: Python<'_>, tableName: &str, dbName:
Option<&str>) -> PyResult<bool> {
+ fn tableExists(
+ &self,
+ py: Python<'_>,
+ tableName: &Bound<'_, PyAny>,
+ dbName: Option<&Bound<'_, PyAny>>,
+ ) -> PyResult<bool> {
warn_db_name(py, "tableExists", dbName)?;
+ let tableName = crate::str_argument(tableName)?;
+ let dbName = dbName.map(crate::str_argument).transpose()?;
self.detached(py, |catalog| {
- { catalog.table_exists_with_database(tableName, dbName)
}.map_err(Box::new)
+ { catalog.table_exists_with_database(&tableName,
dbName.as_deref()) }.map_err(Box::new)
})
}
/// Get table info. Mirrors `Catalog.getTable(tableName) -> Table`.
- fn getTable(&self, py: Python<'_>, tableName: &str) -> PyResult<Py<PyAny>>
{
+ fn getTable(&self, py: Python<'_>, tableName: &Bound<'_, PyAny>) ->
PyResult<Py<PyAny>> {
+ let tableName = crate::str_argument(tableName)?;
self.detached(py, |catalog| {
- catalog.get_table_typed(tableName).map_err(Box::new)
+ catalog.get_table_typed(&tableName).map_err(Box::new)
})?
.named_tuple(py)
}
@@ -264,14 +303,16 @@ impl PyCatalog {
fn listFunctions(
&self,
py: Python<'_>,
- dbName: Option<&str>,
- pattern: Option<&str>,
+ dbName: Option<&Bound<'_, PyAny>>,
+ pattern: Option<&Bound<'_, PyAny>>,
) -> PyResult<Vec<Py<PyAny>>> {
+ let dbName = dbName.map(crate::str_argument).transpose()?;
+ let pattern = pattern.map(crate::str_argument).transpose()?;
named_tuples(
py,
self.detached(py, |catalog| {
catalog
- .list_functions_typed(dbName, pattern)
+ .list_functions_typed(dbName.as_deref(),
pattern.as_deref())
.map_err(Box::new)
})?,
)
@@ -282,19 +323,23 @@ impl PyCatalog {
fn functionExists(
&self,
py: Python<'_>,
- functionName: &str,
- dbName: Option<&str>,
+ functionName: &Bound<'_, PyAny>,
+ dbName: Option<&Bound<'_, PyAny>>,
) -> PyResult<bool> {
warn_db_name(py, "functionExists", dbName)?;
+ let functionName = crate::str_argument(functionName)?;
+ let dbName = dbName.map(crate::str_argument).transpose()?;
self.detached(py, |catalog| {
- { catalog.function_exists_with_database(functionName, dbName)
}.map_err(Box::new)
+ { catalog.function_exists_with_database(&functionName,
dbName.as_deref()) }
+ .map_err(Box::new)
})
}
/// Get function info. Mirrors `Catalog.getFunction(functionName) ->
Function`.
- fn getFunction(&self, py: Python<'_>, functionName: &str) ->
PyResult<Py<PyAny>> {
+ fn getFunction(&self, py: Python<'_>, functionName: &Bound<'_, PyAny>) ->
PyResult<Py<PyAny>> {
+ let functionName = crate::str_argument(functionName)?;
self.detached(py, |catalog| {
- catalog.get_function_typed(functionName).map_err(Box::new)
+ catalog.get_function_typed(&functionName).map_err(Box::new)
})?
.named_tuple(py)
}
@@ -305,15 +350,17 @@ impl PyCatalog {
fn listColumns(
&self,
py: Python<'_>,
- tableName: &str,
- dbName: Option<&str>,
+ tableName: &Bound<'_, PyAny>,
+ dbName: Option<&Bound<'_, PyAny>>,
) -> PyResult<Vec<Py<PyAny>>> {
warn_db_name(py, "listColumns", dbName)?;
+ let tableName = crate::str_argument(tableName)?;
+ let dbName = dbName.map(crate::str_argument).transpose()?;
named_tuples(
py,
self.detached(py, |catalog| {
catalog
- .list_columns_typed(tableName, dbName)
+ .list_columns_typed(&tableName, dbName.as_deref())
.map_err(Box::new)
})?,
)
@@ -325,14 +372,16 @@ impl PyCatalog {
/// `CacheTable.storage_level` field (the same field layout
`DataFrame.persist` uses);
/// `None` leaves it unset so the server default applies. As PySpark's
`CacheTable`, which
/// converts a storage level that is true (`if self._storage_level:`), any
false value, such
- /// as 0, leaves it unset too, and another true value fails the assertion
of the conversion.
+ /// as 0, leaves it unset too, and another true value fails the assertion
of the conversion,
+ /// after the table name.
#[pyo3(signature = (tableName, storageLevel=None))]
fn cacheTable(
&self,
py: Python<'_>,
- tableName: &str,
+ tableName: &Bound<'_, PyAny>,
storageLevel: Option<&Bound<'_, PyAny>>,
) -> PyResult<()> {
+ let tableName = constructor_name(tableName)?;
let level = match storageLevel {
Some(level) if level.is_truthy()? => {
Some(crate::storagelevel::storage_level_proto(level)?)
@@ -340,34 +389,40 @@ impl PyCatalog {
_ => None,
};
self.detached(py, |catalog| {
- { catalog.cache_table_with_storage_level(tableName, level)
}.map_err(Box::new)
+ { catalog.cache_table_with_storage_level(&tableName, level)
}.map_err(Box::new)
})
}
/// Uncache a table.
- fn uncacheTable(&self, py: Python<'_>, tableName: &str) -> PyResult<()> {
+ fn uncacheTable(&self, py: Python<'_>, tableName: &Bound<'_, PyAny>) ->
PyResult<()> {
+ let tableName = crate::str_argument(tableName)?;
self.detached(py, |catalog| {
- catalog.uncache_table(tableName).map_err(Box::new)
+ catalog.uncache_table(&tableName).map_err(Box::new)
})
}
/// Drop temporary view.
- fn dropTempView(&self, py: Python<'_>, viewName: &str) -> PyResult<bool> {
+ fn dropTempView(&self, py: Python<'_>, viewName: &Bound<'_, PyAny>) ->
PyResult<bool> {
+ let viewName = crate::str_argument(viewName)?;
self.detached(py, |catalog| {
- catalog.drop_temp_view(viewName).map_err(Box::new)
+ catalog.drop_temp_view(&viewName).map_err(Box::new)
})
}
/// Drop a global temporary view.
- fn dropGlobalTempView(&self, py: Python<'_>, viewName: &str) ->
PyResult<bool> {
+ fn dropGlobalTempView(&self, py: Python<'_>, viewName: &Bound<'_, PyAny>)
-> PyResult<bool> {
+ let viewName = crate::str_argument(viewName)?;
self.detached(py, |catalog| {
- catalog.drop_global_temp_view(viewName).map_err(Box::new)
+ catalog.drop_global_temp_view(&viewName).map_err(Box::new)
})
}
/// Whether a table/view is cached.
- fn isCached(&self, py: Python<'_>, tableName: &str) -> PyResult<bool> {
- self.detached(py, |catalog|
catalog.is_cached(tableName).map_err(Box::new))
+ fn isCached(&self, py: Python<'_>, tableName: &Bound<'_, PyAny>) ->
PyResult<bool> {
+ let tableName = crate::str_argument(tableName)?;
+ self.detached(py, |catalog| {
+ catalog.is_cached(&tableName).map_err(Box::new)
+ })
}
/// Remove all cached tables from the in-memory cache.
@@ -376,23 +431,26 @@ impl PyCatalog {
}
/// Invalidate and refresh cached metadata for a table.
- fn refreshTable(&self, py: Python<'_>, tableName: &str) -> PyResult<()> {
+ fn refreshTable(&self, py: Python<'_>, tableName: &Bound<'_, PyAny>) ->
PyResult<()> {
+ let tableName = crate::str_argument(tableName)?;
self.detached(py, |catalog| {
- catalog.refresh_table(tableName).map_err(Box::new)
+ catalog.refresh_table(&tableName).map_err(Box::new)
})
}
/// Invalidate and refresh cached data for any table at a path.
- fn refreshByPath(&self, py: Python<'_>, path: &str) -> PyResult<()> {
+ fn refreshByPath(&self, py: Python<'_>, path: &Bound<'_, PyAny>) ->
PyResult<()> {
+ let path = crate::str_argument(path)?;
self.detached(py, |catalog| {
- catalog.refresh_by_path(path).map_err(Box::new)
+ catalog.refresh_by_path(&path).map_err(Box::new)
})
}
/// Recover all the partitions of a table.
- fn recoverPartitions(&self, py: Python<'_>, tableName: &str) ->
PyResult<()> {
+ fn recoverPartitions(&self, py: Python<'_>, tableName: &Bound<'_, PyAny>)
-> PyResult<()> {
+ let tableName = crate::str_argument(tableName)?;
self.detached(py, |catalog| {
- catalog.recover_partitions(tableName).map_err(Box::new)
+ catalog.recover_partitions(&tableName).map_err(Box::new)
})
}
@@ -403,24 +461,30 @@ impl PyCatalog {
fn createTable(
&self,
py: Python<'_>,
- tableName: &str,
- path: Option<&str>,
- source: Option<&str>,
+ tableName: &Bound<'_, PyAny>,
+ path: Option<&Bound<'_, PyAny>>,
+ source: Option<&Bound<'_, PyAny>>,
schema: Option<&Bound<'_, PyAny>>,
- description: Option<&str>,
+ description: Option<&Bound<'_, PyAny>>,
options: Option<&Bound<'_, pyo3::types::PyDict>>,
) -> PyResult<PyDataFrame> {
crate::options::check_keyword_keys(options)?;
let schema = table_schema(schema)?;
+ // In the order of PySpark's `CreateTable` plan, after its check of
the schema, and
+ // before the options.
+ let tableName = crate::str_argument(tableName)?;
+ let path = path.map(crate::str_argument).transpose()?;
+ let source = source.map(crate::str_argument).transpose()?;
+ let description = description.map(crate::str_argument).transpose()?;
let options = crate::options::str_kwargs_skip_none(options)?;
interruptible(py, self.catalog.spark_session(), || {
self.catalog
.create_table_with(
- tableName,
- path,
- source,
+ &tableName,
+ path.as_deref(),
+ source.as_deref(),
schema.as_ref(),
- description,
+ description.as_deref(),
options,
)
.map_err(Box::new)
@@ -435,11 +499,11 @@ impl PyCatalog {
fn createExternalTable(
&self,
py: Python<'_>,
- tableName: &str,
- path: Option<&str>,
- source: Option<&str>,
+ tableName: &Bound<'_, PyAny>,
+ path: Option<&Bound<'_, PyAny>>,
+ source: Option<&Bound<'_, PyAny>>,
schema: Option<&Bound<'_, PyAny>>,
- description: Option<&str>,
+ description: Option<&Bound<'_, PyAny>>,
options: Option<&Bound<'_, pyo3::types::PyDict>>,
) -> PyResult<PyDataFrame> {
crate::options::check_keyword_keys(options)?;
@@ -481,24 +545,26 @@ impl PyCatalog {
.call_method1("register", (name, f, returnType))
}
- /// Create a database.
+ /// Create a database, with the `properties` of PySpark's protobuf map of
strings, whose keys
+ /// and values are converted as `crate::str_argument` converts them.
#[pyo3(signature = (dbName, ifNotExists=false, properties=None))]
#[allow(non_snake_case)]
fn createDatabase(
&self,
py: Python<'_>,
- dbName: &str,
+ dbName: &Bound<'_, PyAny>,
ifNotExists: bool,
properties: Option<&Bound<'_, pyo3::types::PyDict>>,
) -> PyResult<()> {
+ let dbName = constructor_name(dbName)?;
let mut props = std::collections::HashMap::new();
if let Some(dict) = properties {
for (k, v) in dict.iter() {
- props.insert(k.extract::<String>()?, v.extract::<String>()?);
+ props.insert(crate::str_argument(&k)?,
crate::str_argument(&v)?);
}
}
self.detached(py, |catalog| {
- { catalog.create_database(dbName, ifNotExists, props)
}.map_err(Box::new)
+ { catalog.create_database(&dbName, ifNotExists, props)
}.map_err(Box::new)
})
}
@@ -508,12 +574,13 @@ impl PyCatalog {
fn dropDatabase(
&self,
py: Python<'_>,
- dbName: &str,
+ dbName: &Bound<'_, PyAny>,
ifExists: bool,
cascade: bool,
) -> PyResult<()> {
+ let dbName = constructor_name(dbName)?;
self.detached(py, |catalog| {
- { catalog.drop_database(dbName, ifExists, cascade)
}.map_err(Box::new)
+ { catalog.drop_database(&dbName, ifExists, cascade)
}.map_err(Box::new)
})
}
@@ -523,13 +590,14 @@ impl PyCatalog {
fn dropTable(
&self,
py: Python<'_>,
- tableName: &str,
+ tableName: &Bound<'_, PyAny>,
ifExists: bool,
purge: bool,
) -> PyResult<()> {
+ let tableName = constructor_name(tableName)?;
self.detached(py, |catalog| {
catalog
- .drop_table(tableName, ifExists, purge)
+ .drop_table(&tableName, ifExists, purge)
.map_err(Box::new)
})
}
@@ -537,26 +605,39 @@ impl PyCatalog {
/// Drop a view.
#[pyo3(signature = (viewName, ifExists=false))]
#[allow(non_snake_case)]
- fn dropView(&self, py: Python<'_>, viewName: &str, ifExists: bool) ->
PyResult<()> {
+ fn dropView(
+ &self,
+ py: Python<'_>,
+ viewName: &Bound<'_, PyAny>,
+ ifExists: bool,
+ ) -> PyResult<()> {
+ let viewName = constructor_name(viewName)?;
self.detached(py, |catalog| {
- catalog.drop_view(viewName, ifExists).map_err(Box::new)
+ catalog.drop_view(&viewName, ifExists).map_err(Box::new)
})
}
/// Truncate a table.
#[allow(non_snake_case)]
- fn truncateTable(&self, py: Python<'_>, tableName: &str) -> PyResult<()> {
+ fn truncateTable(&self, py: Python<'_>, tableName: &Bound<'_, PyAny>) ->
PyResult<()> {
+ let tableName = crate::str_argument(tableName)?;
self.detached(py, |catalog| {
- catalog.truncate_table(tableName).map_err(Box::new)
+ catalog.truncate_table(&tableName).map_err(Box::new)
})
}
/// Recover the statistics of a table.
#[pyo3(signature = (tableName, noScan=false))]
#[allow(non_snake_case)]
- fn analyzeTable(&self, py: Python<'_>, tableName: &str, noScan: bool) ->
PyResult<()> {
+ fn analyzeTable(
+ &self,
+ py: Python<'_>,
+ tableName: &Bound<'_, PyAny>,
+ noScan: bool,
+ ) -> PyResult<()> {
+ let tableName = crate::str_argument(tableName)?;
self.detached(py, |catalog| {
- catalog.analyze_table(tableName, noScan).map_err(Box::new)
+ catalog.analyze_table(&tableName, noScan).map_err(Box::new)
})
}
@@ -566,11 +647,12 @@ impl PyCatalog {
fn getCreateTableString(
&self,
py: Python<'_>,
- tableName: &str,
+ tableName: &Bound<'_, PyAny>,
asSerde: bool,
) -> PyResult<String> {
+ let tableName = crate::str_argument(tableName)?;
self.detached(py, |catalog| {
- { catalog.get_create_table_string(tableName, asSerde)
}.map_err(Box::new)
+ { catalog.get_create_table_string(&tableName, asSerde)
}.map_err(Box::new)
})
}
@@ -579,10 +661,11 @@ impl PyCatalog {
fn getTableProperties<'py>(
&self,
py: Python<'py>,
- tableName: &str,
+ tableName: &Bound<'_, PyAny>,
) -> PyResult<Bound<'py, pyo3::types::PyDict>> {
+ let tableName = crate::str_argument(tableName)?;
let props = self.detached(py, |catalog| {
- catalog.get_table_properties(tableName).map_err(Box::new)
+ catalog.get_table_properties(&tableName).map_err(Box::new)
})?;
let dict = pyo3::types::PyDict::new(py);
for (k, v) in props {
@@ -593,28 +676,40 @@ impl PyCatalog {
/// List the partitions of a table. Mirrors `Catalog.listPartitions ->
List[TablePartition]`.
#[allow(non_snake_case)]
- fn listPartitions(&self, py: Python<'_>, tableName: &str) ->
PyResult<Vec<Py<PyAny>>> {
+ fn listPartitions(
+ &self,
+ py: Python<'_>,
+ tableName: &Bound<'_, PyAny>,
+ ) -> PyResult<Vec<Py<PyAny>>> {
+ let tableName = crate::str_argument(tableName)?;
named_tuples(
py,
self.detached(py, |catalog| {
- catalog.list_partitions_typed(tableName).map_err(Box::new)
+ catalog.list_partitions_typed(&tableName).map_err(Box::new)
})?,
)
}
- /// List the views in a database. Mirrors `Catalog.listViews ->
List[Table]`.
+ /// List the views in a database. Mirrors `Catalog.listViews ->
List[Table]`, which asks for
+ /// the current database of a pattern without a database, before its plan
sets either.
#[pyo3(signature = (dbName=None, pattern=None))]
#[allow(non_snake_case)]
fn listViews(
&self,
py: Python<'_>,
- dbName: Option<&str>,
- pattern: Option<&str>,
+ dbName: Option<&Bound<'_, PyAny>>,
+ pattern: Option<&Bound<'_, PyAny>>,
) -> PyResult<Vec<Py<PyAny>>> {
+ let dbName = match (dbName, pattern) {
+ (None, Some(_)) => Some(self.currentDatabase(py)?),
+ (dbName, _) => dbName.map(crate::str_argument).transpose()?,
+ };
+ let pattern = pattern.map(crate::str_argument).transpose()?;
named_tuples(
py,
self.detached(py, |catalog| {
- catalog.list_views_typed(dbName, pattern).map_err(Box::new)
+ { catalog.list_views_typed(dbName.as_deref(),
pattern.as_deref()) }
+ .map_err(Box::new)
})?,
)
}
diff --git a/crates/pyspark-rs/src/dataframe.rs
b/crates/pyspark-rs/src/dataframe.rs
index 395a0334..b31aac2b 100644
--- a/crates/pyspark-rs/src/dataframe.rs
+++ b/crates/pyspark-rs/src/dataframe.rs
@@ -1710,12 +1710,14 @@ impl PyDataFrame {
})
}
- /// Register this DataFrame as a temporary view.
+ /// Register this DataFrame as a temporary view, of a name that PySpark's
`CreateView` sets in
+ /// its string field as it is, as [`crate::str_argument`] converts it, as
the other views do.
#[pyo3(name = "createOrReplaceTempView")]
- fn create_or_replace_temp_view(&self, py: Python<'_>, name: &str) ->
PyResult<()> {
+ fn create_or_replace_temp_view(&self, py: Python<'_>, name: &Bound<'_,
PyAny>) -> PyResult<()> {
+ let name = crate::str_argument(name)?;
interruptible(py, &self.dataframe.spark_session(), || {
self.dataframe
- .create_or_replace_temp_view(name)
+ .create_or_replace_temp_view(&name)
.map_err(Box::new)
})
}
@@ -1844,37 +1846,45 @@ impl PyDataFrame {
/// Register as a temporary view (session-scoped).
#[pyo3(name = "createTempView")]
- fn create_temp_view(&self, py: Python<'_>, name: &str) -> PyResult<()> {
+ fn create_temp_view(&self, py: Python<'_>, name: &Bound<'_, PyAny>) ->
PyResult<()> {
+ let name = crate::str_argument(name)?;
interruptible(py, &self.dataframe.spark_session(), || {
- self.dataframe.create_temp_view(name).map_err(Box::new)
+ self.dataframe.create_temp_view(&name).map_err(Box::new)
})
}
/// Register as a global temporary view.
#[pyo3(name = "createGlobalTempView")]
- fn create_global_temp_view(&self, py: Python<'_>, name: &str) ->
PyResult<()> {
+ fn create_global_temp_view(&self, py: Python<'_>, name: &Bound<'_, PyAny>)
-> PyResult<()> {
+ let name = crate::str_argument(name)?;
interruptible(py, &self.dataframe.spark_session(), || {
self.dataframe
- .create_global_temp_view(name)
+ .create_global_temp_view(&name)
.map_err(Box::new)
})
}
/// Register as (or replace) a global temporary view.
#[pyo3(name = "createOrReplaceGlobalTempView")]
- fn create_or_replace_global_temp_view(&self, py: Python<'_>, name: &str)
-> PyResult<()> {
+ fn create_or_replace_global_temp_view(
+ &self,
+ py: Python<'_>,
+ name: &Bound<'_, PyAny>,
+ ) -> PyResult<()> {
+ let name = crate::str_argument(name)?;
interruptible(py, &self.dataframe.spark_session(), || {
self.dataframe
- .create_or_replace_global_temp_view(name)
+ .create_or_replace_global_temp_view(&name)
.map_err(Box::new)
})
}
/// Deprecated alias for createOrReplaceTempView.
#[pyo3(name = "registerTempTable")]
- fn register_temp_table(&self, py: Python<'_>, name: &str) -> PyResult<()> {
+ fn register_temp_table(&self, py: Python<'_>, name: &Bound<'_, PyAny>) ->
PyResult<()> {
+ let name = crate::str_argument(name)?;
interruptible(py, &self.dataframe.spark_session(), || {
- self.dataframe.register_temp_table(name).map_err(Box::new)
+ self.dataframe.register_temp_table(&name).map_err(Box::new)
})
}
@@ -2761,11 +2771,14 @@ impl PyDataFrame {
PyDataFrameWriter::new(self.dataframe.write())
}
- /// The V2 writer interface (`df.writeTo("table")`).
+ /// The V2 writer interface (`df.writeTo("table")`), of the table as
[`written_table`] takes
+ /// it.
#[pyo3(name = "writeTo")]
- fn write_to(&self, table: &str) -> PyDataFrameWriterV2 {
+ fn write_to(&self, table: &Bound<'_, PyAny>) -> PyDataFrameWriterV2 {
+ let (name, unsent_table) = written_table(table);
PyDataFrameWriterV2 {
- inner: WriterState::new(self.dataframe.write_to(table)),
+ inner: WriterState::new(self.dataframe.write_to(&name)),
+ unsent_table,
}
}
@@ -2787,11 +2800,14 @@ impl PyDataFrame {
}
}
- /// Merge-into (`df.mergeInto("table", cond)`), returning a V2 merge
builder.
+ /// Merge-into (`df.mergeInto("table", cond)`), returning a V2 merge
builder, of the table as
+ /// [`written_table`] takes it.
#[pyo3(name = "mergeInto")]
- fn merge_into(&self, table: &str, condition: &PyColumn) ->
PyMergeIntoWriter {
+ 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(table,
condition.column.clone())),
+ inner: WriterState::new(self.dataframe.merge_into(&name,
condition.column.clone())),
+ unsent_table,
}
}
@@ -3338,6 +3354,29 @@ pub(crate) fn column_or_name(col: &Bound<'_, PyAny>) ->
PyResult<spark_connect::
Err(not_expected_type(col, "col", "Column or str"))
}
+/// The table of `writeTo` and `mergeInto`, which PySpark keeps as it is given
and sets in the
+/// string field of the command of each write, which leaves the field unset
for None: its name,
+/// as [`crate::str_argument`] converts it, or "" with the table that the
field does not take,
+/// whose error each write raises again with [`check_written_table`], and not
the call.
+fn written_table(table: &Bound<'_, PyAny>) -> (String, Option<Py<PyAny>>) {
+ if table.is_none() {
+ return (String::new(), None);
+ }
+ match crate::str_argument(table) {
+ Ok(name) => (name, None),
+ Err(_) => (String::new(), Some(table.clone().unbind())),
+ }
+}
+
+/// The error of a write of a table that its string field does not take
([`written_table`]),
+/// which PySpark's command raises after its input plan, before it sets the
other fields.
+fn check_written_table(py: Python<'_>, unsent_table: &Option<Py<PyAny>>) ->
PyResult<()> {
+ match unsent_table {
+ Some(table) => crate::str_argument(table.bind(py)).map(drop),
+ None => Ok(()),
+ }
+}
+
/// Python wrapper for `MergeIntoWriter` (`df.mergeInto(...)`).
///
/// Mirrors PySpark's mutable writer: `withSchemaEvolution` and every clause
action
@@ -3347,6 +3386,9 @@ pub(crate) fn column_or_name(col: &Bound<'_, PyAny>) ->
PyResult<spark_connect::
#[pyclass(name = "MergeIntoWriter", module = "pyspark.sql.merge", weakref,
dict)]
pub struct PyMergeIntoWriter {
inner: WriterState<spark_connect::MergeIntoWriter>,
+ /// The table of `mergeInto` that its string field does not take, which
Python's garbage
+ /// collector sees ([`written_table`]).
+ unsent_table: Option<Py<PyAny>>,
}
/// Apply a clause action to the parent writer in place and return that same
writer
@@ -3432,11 +3474,23 @@ impl PyMergeIntoWriter {
}
fn merge(&self, py: Python<'_>) -> PyResult<()> {
+ check_written_table(py, &self.unsent_table)?;
let writer = self.inner.get();
interruptible(py, &writer.spark_session(), || {
writer.merge().map_err(Box::new)
})
}
+
+ fn __traverse__(&self, visit: pyo3::PyVisit<'_>) -> Result<(),
pyo3::PyTraverseError> {
+ if let Some(table) = &self.unsent_table {
+ visit.call(table)?;
+ }
+ Ok(())
+ }
+
+ fn __clear__(&mut self) {
+ self.unsent_table = None;
+ }
}
fn assignments_to_map(
@@ -3836,7 +3890,7 @@ impl PyDataFrameWriter {
fn save_as_table(
&self,
py: Python<'_>,
- name: &str,
+ name: &Bound<'_, PyAny>,
format: Option<&str>,
mode: Option<&str>,
partitionBy: Option<&Bound<'_, PyAny>>,
@@ -3845,8 +3899,13 @@ impl PyDataFrameWriter {
let w = apply_write_common(self.inner.get(), format, mode,
partitionBy, options)?;
self.inner.set(w.clone());
self.check_bucket_count(py)?;
+ let name = crate::readwriter::writer_table_name(name)?;
interruptible(py, &w.spark_session(), || {
- w.save_as_table(name).map_err(Box::new)
+ match &name {
+ Some(name) => w.save_as_table(name),
+ None => w.save(None),
+ }
+ .map_err(Box::new)
})
}
@@ -3856,7 +3915,7 @@ impl PyDataFrameWriter {
fn insert_into(
&self,
py: Python<'_>,
- tableName: &str,
+ tableName: &Bound<'_, PyAny>,
overwrite: Option<bool>,
) -> PyResult<()> {
let mut w = self.inner.get();
@@ -3866,8 +3925,13 @@ impl PyDataFrameWriter {
// PySpark sets the overwrite/append mode on the writer itself.
self.inner.set(w.clone());
self.check_bucket_count(py)?;
+ let tableName = crate::readwriter::writer_table_name(tableName)?;
interruptible(py, &w.spark_session(), || {
- w.insert_into(tableName).map_err(Box::new)
+ match &tableName {
+ Some(name) => w.insert_into(name),
+ None => w.save(None),
+ }
+ .map_err(Box::new)
})
}
@@ -4113,6 +4177,9 @@ impl PyDataFrameWriter {
)]
pub struct PyDataFrameWriterV2 {
inner: WriterState<spark_connect::readwriter::DataFrameWriterV2>,
+ /// The table of `writeTo` that its string field does not take, which
Python's garbage
+ /// collector sees ([`written_table`]).
+ unsent_table: Option<Py<PyAny>>,
}
impl PyDataFrameWriterV2 {}
@@ -4212,6 +4279,7 @@ impl PyDataFrameWriterV2 {
}
fn create(&self, py: Python<'_>) -> PyResult<()> {
+ check_written_table(py, &self.unsent_table)?;
let writer = self.inner.get();
interruptible(py, &writer.spark_session(), || {
writer.create().map_err(Box::new)
@@ -4219,6 +4287,7 @@ impl PyDataFrameWriterV2 {
}
fn replace(&self, py: Python<'_>) -> PyResult<()> {
+ check_written_table(py, &self.unsent_table)?;
let writer = self.inner.get();
interruptible(py, &writer.spark_session(), || {
writer.replace().map_err(Box::new)
@@ -4227,6 +4296,7 @@ impl PyDataFrameWriterV2 {
#[pyo3(name = "createOrReplace")]
fn create_or_replace(&self, py: Python<'_>) -> PyResult<()> {
+ check_written_table(py, &self.unsent_table)?;
let writer = self.inner.get();
interruptible(py, &writer.spark_session(), || {
writer.create_or_replace().map_err(Box::new)
@@ -4234,6 +4304,7 @@ impl PyDataFrameWriterV2 {
}
fn append(&self, py: Python<'_>) -> PyResult<()> {
+ check_written_table(py, &self.unsent_table)?;
let writer = self.inner.get();
interruptible(py, &writer.spark_session(), || {
writer.append().map_err(Box::new)
@@ -4241,9 +4312,10 @@ impl PyDataFrameWriterV2 {
}
/// Overwrite the rows of `condition`, a Column or a column name, as
PySpark's `F._to_col`,
- /// else `NOT_EXPECTED_TYPE` of `col`.
+ /// else `NOT_EXPECTED_TYPE` of `col`, before the command sets the table.
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)?;
interruptible(py, &writer.spark_session(), || {
writer.overwrite(condition).map_err(Box::new)
})
@@ -4251,11 +4323,23 @@ impl PyDataFrameWriterV2 {
#[pyo3(name = "overwritePartitions")]
fn overwrite_partitions(&self, py: Python<'_>) -> PyResult<()> {
+ check_written_table(py, &self.unsent_table)?;
let writer = self.inner.get();
interruptible(py, &writer.spark_session(), || {
writer.overwrite_partitions().map_err(Box::new)
})
}
+
+ fn __traverse__(&self, visit: pyo3::PyVisit<'_>) -> Result<(),
pyo3::PyTraverseError> {
+ if let Some(table) = &self.unsent_table {
+ visit.call(table)?;
+ }
+ Ok(())
+ }
+
+ fn __clear__(&mut self) {
+ self.unsent_table = None;
+ }
}
/// The state of a Python writer (`df.write`, `df.writeTo`, `df.mergeInto`,
`df.writeStream`).
diff --git a/crates/pyspark-rs/src/readwriter.rs
b/crates/pyspark-rs/src/readwriter.rs
index 39f89dda..2ad077d8 100644
--- a/crates/pyspark-rs/src/readwriter.rs
+++ b/crates/pyspark-rs/src/readwriter.rs
@@ -134,6 +134,16 @@ pub(crate) fn writer_path(path: &Bound<'_, PyAny>) ->
PyResult<String> {
crate::str_argument(path)
}
+/// The table of `saveAsTable` and `insertInto`, which PySpark's
`WriteOperation` sets in its
+/// string field after the bucket count and before it checks the save mode, as
[`writer_path`]
+/// converts a path. None sets no table, so that the write is that of `save()`
without a path.
+pub(crate) fn writer_table_name(name: &Bound<'_, PyAny>) ->
PyResult<Option<String>> {
+ if name.is_none() {
+ return Ok(None);
+ }
+ crate::str_argument(name).map(Some)
+}
+
/// 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(
@@ -401,19 +411,22 @@ impl PyDataFrameReader {
Ok(PyDataFrame::new(r.load_paths(paths)))
}
- /// Read a table by name.
- fn table(&self, tableName: &str) -> PyResult<PyDataFrame> {
- Ok(PyDataFrame::new(self.inner.clone().table(tableName)))
+ /// Read a table by name, which PySpark's `Read` plan sets in its string
field as it is, as
+ /// [`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)))
}
/// Read the CDC changes of a named table. Mirrors
`DataFrameReader.changes`, which raises an
/// `AnalysisException` of `_LEGACY_ERROR_TEMP_1189` for a reader of a
schema.
#[allow(non_snake_case)]
- fn changes(&self, py: Python<'_>, tableName: &str) ->
PyResult<PyDataFrame> {
+ fn changes(&self, py: Python<'_>, tableName: &Bound<'_, PyAny>) ->
PyResult<PyDataFrame> {
if !self.inner.get_schema().is_empty() {
return Err(changes_of_schema_error(py));
}
- Ok(PyDataFrame::new(self.inner.clone().changes(tableName)))
+ let tableName = crate::str_argument(tableName)?;
+ Ok(PyDataFrame::new(self.inner.clone().changes(&tableName)))
}
/// Read JSON file(s) - full pyspark signature; each named option is
diff --git a/crates/pyspark-rs/src/streaming.rs
b/crates/pyspark-rs/src/streaming.rs
index c6bce701..00057cb8 100644
--- a/crates/pyspark-rs/src/streaming.rs
+++ b/crates/pyspark-rs/src/streaming.rs
@@ -427,12 +427,13 @@ impl PyDataStreamReader {
/// Read the streaming CDC changes of a named table. Mirrors
`DataStreamReader.changes`,
/// which raises an `AnalysisException` of `_LEGACY_ERROR_TEMP_1189` for a
reader of a
- /// schema.
- fn changes(&self, py: Python<'_>, tableName: &str) ->
PyResult<PyDataFrame> {
+ /// schema, before it sets the name in its string field, as `table` does.
+ fn changes(&self, py: Python<'_>, tableName: &Bound<'_, PyAny>) ->
PyResult<PyDataFrame> {
if !self.inner.get_schema().is_empty() {
return Err(crate::readwriter::changes_of_schema_error(py));
}
- Ok(PyDataFrame::new(self.inner.clone().changes(tableName)))
+ let tableName = crate::str_argument(tableName)?;
+ Ok(PyDataFrame::new(self.inner.clone().changes(&tableName)))
}
/// Load an XML streaming source. Mirrors `DataStreamReader.xml(...)`: set
each named
@@ -494,8 +495,10 @@ impl PyDataStreamReader {
Ok(PyDataFrame::new(r.format("xml").load(Some(&path))))
}
- fn table(&self, tableName: &str) -> PyResult<PyDataFrame> {
- let df = self.inner.clone().table(tableName);
+ /// 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)?);
Ok(PyDataFrame::new(df))
}
@@ -996,8 +999,12 @@ impl PyDataStreamWriter {
options: Option<&Bound<'_, PyDict>>,
) -> PyResult<PyStreamingQuery> {
let writer = self.apply_write_opts(format, outputMode, partitionBy,
queryName, options)?;
- // PySpark's start sets these on the writer before it checks the path.
- let path = path.map(crate::readwriter::writer_path).transpose()?;
+ // PySpark's start sets these on the writer before it checks the path,
which it sets in
+ // its string field only `if path:`, so that a false one, such as 0,
is no path.
+ let path = match path {
+ Some(path) if path.is_truthy()? =>
Some(crate::readwriter::writer_path(path)?),
+ _ => None,
+ };
// Memory/console/foreach sinks take no path; the core treats "" as
unset.
let query = interruptible(py, &writer.spark_session(), || {
writer
@@ -1012,7 +1019,7 @@ impl PyDataStreamWriter {
fn toTable(
&self,
py: Python<'_>,
- tableName: &str,
+ tableName: &Bound<'_, PyAny>,
format: Option<&str>,
outputMode: Option<&str>,
partitionBy: Option<&Bound<'_, PyAny>>,
@@ -1020,10 +1027,19 @@ impl PyDataStreamWriter {
options: Option<&Bound<'_, PyDict>>,
) -> PyResult<PyStreamingQuery> {
let writer = self.apply_write_opts(format, outputMode, partitionBy,
queryName, options)?;
+ // As the path of `start`, PySpark sets the table in its string field
only `if
+ // tableName:`, so that a false one, such as "", starts the query as
`start()` does.
+ let table = if tableName.is_truthy()? {
+ Some(crate::str_argument(tableName)?)
+ } else {
+ None
+ };
let query = interruptible(py, &writer.spark_session(), || {
- writer
- .to_table_with_event_handler(tableName, post_started_event)
- .map_err(Box::new)
+ match &table {
+ Some(table) => writer.to_table_with_event_handler(table,
post_started_event),
+ None => writer.start_with_event_handler("",
post_started_event),
+ }
+ .map_err(Box::new)
})?;
Ok(PyStreamingQuery::new(query))
}
diff --git a/python/tests/test_dropin_offline.py
b/python/tests/test_dropin_offline.py
index 69b2e865..9232fddf 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -7610,6 +7610,317 @@ def
test_writers_take_a_bytes_path_as_pyspark(mock_connect):
assert parse_message(sent_command()[6][0])[11] == [b"s"]
+def test_catalog_takes_bytes_names_and_paths_as_pyspark(mock_connect):
+ # As PySpark's catalog, which sets each name, pattern and path in a string
field of its plan
+ # as it is, which protobuf's default backend (upb) converts: bytes are
sent decoded, bytes
+ # that are not UTF-8 raise the UnicodeDecodeError of their decoding, and
another object the
+ # TypeError of the field, before any request. The mock answers each
request with no rows.
+ spark, service = mock_connect
+ catalog = spark.catalog
+ # Relation.catalog=200 -> the Catalog operation of each call, of these
string fields.
+ for call, operation, fields in [
+ (lambda: catalog.setCurrentCatalog(b"c"), 25, {1: [b"c"]}),
+ (lambda: catalog.listCatalogs(b"c*"), 26, {1: [b"c*"]}),
+ (lambda: catalog.setCurrentDatabase(b"d"), 2, {1: [b"d"]}),
+ (lambda: catalog.listDatabases(b"d*"), 3, {1: [b"d*"]}),
+ (lambda: catalog.getDatabase(b"d"), 7, {1: [b"d"]}),
+ (lambda: catalog.databaseExists(b"d"), 10, {1: [b"d"]}),
+ (lambda: catalog.listTables(b"d", b"t*"), 4, {1: [b"d"], 2: [b"t*"]}),
+ (lambda: catalog.getTable(b"t"), 8, {1: [b"t"]}),
+ (lambda: catalog.tableExists(b"t"), 11, {1: [b"t"]}),
+ (lambda: catalog.listFunctions(b"d", b"f*"), 5, {1: [b"d"], 2:
[b"f*"]}),
+ (lambda: catalog.getFunction(b"f"), 9, {1: [b"f"]}),
+ (lambda: catalog.functionExists(b"f"), 12, {1: [b"f"]}),
+ (lambda: catalog.listColumns(b"t"), 6, {1: [b"t"]}),
+ (lambda: catalog.dropTempView(b"v"), 15, {1: [b"v"]}),
+ (lambda: catalog.dropGlobalTempView(b"v"), 16, {1: [b"v"]}),
+ (lambda: catalog.recoverPartitions(b"t"), 17, {1: [b"t"]}),
+ (lambda: catalog.isCached(b"t"), 18, {1: [b"t"]}),
+ (lambda: catalog.cacheTable(b"t"), 19, {1: [b"t"]}),
+ (lambda: catalog.uncacheTable(b"t"), 20, {1: [b"t"]}),
+ (lambda: catalog.refreshTable(b"t"), 22, {1: [b"t"]}),
+ (lambda: catalog.refreshByPath(b"/p"), 23, {1: [b"/p"]}),
+ (lambda: catalog.dropTable(b"t"), 27, {1: [b"t"]}),
+ (lambda: catalog.dropView(b"v"), 28, {1: [b"v"]}),
+ # CreateDatabase.properties=3, a map of strings, of entries of key=1
and value=2.
+ (lambda: catalog.createDatabase(b"d", properties={b"k": b"v"}), 29,
+ {1: [b"d"], 3: [message_field(1, "k") + message_field(2, "v")]}),
+ (lambda: catalog.dropDatabase(b"d"), 30, {1: [b"d"]}),
+ (lambda: catalog.listPartitions(b"t"), 31, {1: [b"t"]}),
+ (lambda: catalog.listViews(b"d", b"v*"), 32, {1: [b"d"], 2: [b"v*"]}),
+ (lambda: catalog.getTableProperties(b"t"), 33, {1: [b"t"]}),
+ (lambda: catalog.getCreateTableString(b"t"), 34, {1: [b"t"]}),
+ (lambda: catalog.truncateTable(b"t"), 35, {1: [b"t"]}),
+ (lambda: catalog.analyzeTable(b"t"), 36, {1: [b"t"]}),
+ ]:
+ requests = len(service.execute_requests)
+ with contextlib.suppress(Exception):
+ call()
+ assert len(service.execute_requests) == requests + 1
+ assert _sent_catalog(service.execute_requests[-1], operation) == fields
+ requests = len(service.execute_requests)
+ for name, error in [(b"\xff", UnicodeDecodeError), (1, TypeError)]:
+ for call in [
+ lambda: catalog.setCurrentDatabase(name),
+ lambda: catalog.listTables(pattern=name),
+ lambda: catalog.getTable(name),
+ lambda: catalog.cacheTable(name),
+ lambda: catalog.refreshByPath(name),
+ lambda: catalog.dropTable(name),
+ lambda: catalog.createDatabase("d", properties={"k": name}),
+ lambda: catalog.listViews(name),
+ ]:
+ with pytest.raises(error) as e:
+ call()
+ assert type(e.value) is error
+ # None is the TypeError of a field that PySpark's plan sets, while the
constructor of the
+ # message of cacheTable, dropTable, dropView, createDatabase and
dropDatabase leaves it unset.
+ with pytest.raises(TypeError, match="^bad argument type for built-in
operation$"):
+ catalog.getTable(None)
+ assert len(service.execute_requests) == requests
+ for call, operation in [
+ (lambda: catalog.cacheTable(None), 19),
+ (lambda: catalog.dropTable(None), 27),
+ (lambda: catalog.dropView(None), 28),
+ (lambda: catalog.createDatabase(None), 29),
+ (lambda: catalog.dropDatabase(None), 30),
+ ]:
+ with contextlib.suppress(Exception):
+ call()
+ assert _sent_catalog(service.execute_requests[-1], operation) == {}
+
+
+def test_catalog_converts_its_names_in_the_order_of_pyspark(mock_connect):
+ from pyspark.errors import PySparkTypeError
+
+ spark, service = mock_connect
+ catalog = spark.catalog
+ requests = len(service.execute_requests)
+ # createTable checks the schema, and then its plan sets the table, the
path, the source and
+ # the description, in this order, before the options.
+ with pytest.raises(PySparkTypeError) as error:
+ catalog.createTable(1, schema=5)
+ assert error.value.getCondition() == "NOT_EXPECTED_TYPE"
+ for kwargs, error in [
+ ({"tableName": b"\xff", "path": 1}, UnicodeDecodeError),
+ ({"tableName": "t", "path": b"\xff", "source": 1}, UnicodeDecodeError),
+ ({"tableName": "t", "path": 1, "source": b"\xff"}, TypeError),
+ ({"tableName": "t", "source": 1, "description": b"\xff"}, TypeError),
+ ({"tableName": "t", "description": b"\xff", "k": 1},
UnicodeDecodeError),
+ ]:
+ with pytest.raises(error) as e:
+ catalog.createTable(**kwargs)
+ assert type(e.value) is error
+ # createExternalTable warns first, and the deprecated dbName warns before
the names are set.
+ with pytest.warns(FutureWarning, match="createExternalTable is
deprecated"):
+ with pytest.raises(UnicodeDecodeError):
+ catalog.createExternalTable(b"\xff")
+ for call in [
+ lambda: catalog.tableExists(1, 2),
+ lambda: catalog.functionExists(1, 2),
+ lambda: catalog.listColumns(1, 2),
+ ]:
+ with pytest.warns(FutureWarning, match="`dbName` has been deprecated"):
+ with pytest.raises(TypeError, match="^bad argument type for
built-in operation$"):
+ call()
+ # cacheTable sets the table before it converts the storage level.
+ with pytest.raises(UnicodeDecodeError):
+ catalog.cacheTable(b"\xff", "not a level")
+ assert len(service.execute_requests) == requests
+ # listViews of a pattern without a database asks for the current database
first.
+ with contextlib.suppress(Exception):
+ catalog.listViews(pattern=1)
+ assert len(service.execute_requests) == requests + 1
+ assert _sent_catalog(service.execute_requests[-1], 1) == {}
+ catalog.createTable(b"t", path=b"/p", source=b"parquet", description=b"d")
+ # Catalog.create_table=14: table_name=1, path=2, source=3 and
description=4.
+ create = _sent_catalog(service.execute_requests[-1], 14)
+ assert (create[1], create[2], create[3], create[4]) == ([b"t"], [b"/p"],
[b"parquet"], [b"d"])
+ with pytest.warns(FutureWarning):
+ catalog.createExternalTable(b"e", path=b"/e")
+ create = _sent_catalog(service.execute_requests[-1], 14)
+ assert (create[1], create[2]) == ([b"e"], [b"/e"])
+
+
+def
test_tables_of_the_writers_readers_and_views_take_bytes_as_pyspark(mock_connect):
+ # As PySpark, which sets the table of saveAsTable, insertInto, read.table,
changes and the
+ # stream reader's, and the name of a view, in a string field of its plan
as it is: bytes are
+ # sent decoded, as protobuf's default backend (upb) converts them.
+ from pyspark.errors import AnalysisException, PySparkTypeError
+
+ spark, service = mock_connect
+ df = spark.range(1)
+
+ def sent_command():
+ # ExecutePlanRequest.plan=3 -> Plan.command=2.
+ plan = parse_message(parse_message(service.execute_requests[-1])[3][0])
+ return parse_message(plan[2][0])
+
+ # Command.write_operation=2 -> WriteOperation.table=4 ->
SaveTable.table_name=1 and
+ # save_method=2 (TABLE_SAVE_METHOD_SAVE_AS_TABLE=1,
TABLE_SAVE_METHOD_INSERT_INTO=2).
+ df.write.saveAsTable(b"t")
+ assert parse_message(parse_message(sent_command()[2][0])[4][0]) == {1:
[b"t"], 2: [1]}
+ df.write.insertInto(b"t")
+ assert parse_message(parse_message(sent_command()[2][0])[4][0]) == {1:
[b"t"], 2: [2]}
+ # The table of None is no table, so that the write is that of save()
without a path
+ # (WriteOperation.path=3), here of WriteOperation.source=2.
+ for write in [df.write.format("noop").saveAsTable,
df.write.format("noop").insertInto]:
+ write(None)
+ operation = parse_message(sent_command()[2][0])
+ assert 3 not in operation and 4 not in operation and operation[2] ==
[b"noop"]
+ # Command.create_dataframe_view=3 -> CreateDataFrameViewCommand.name=2.
+ for create in [df.createTempView, df.createOrReplaceTempView,
df.createGlobalTempView,
+ df.createOrReplaceGlobalTempView, df.registerTempTable]:
+ create(b"v")
+ assert parse_message(sent_command()[3][0])[2] == [b"v"]
+ # Relation.read=2 -> Read.named_table=1 ->
NamedTable.unparsed_identifier=1, and
+ # Relation.relation_changes=46 -> RelationChanges.unparsed_identifier=1,
in the requests of
+ # the schema.
+ for read in [spark.read.table, spark.readStream.table]:
+ assert read(b"t").schema is not None
+ named_table =
parse_message(_sent_relation(service.analyze_requests[-1], 2)[1][0])
+ assert named_table[1] == [b"t"]
+ for changes in [spark.read.changes, spark.readStream.changes]:
+ assert changes(b"t").schema is not None
+ assert _sent_relation(service.analyze_requests[-1], 46)[1] == [b"t"]
+ requests = (len(service.analyze_requests), len(service.execute_requests))
+ for name, error in [(b"\xff", UnicodeDecodeError), (1, TypeError)]:
+ for call in [
+ lambda: df.write.saveAsTable(name),
+ lambda: df.write.insertInto(name),
+ lambda: df.createTempView(name),
+ lambda: df.createOrReplaceGlobalTempView(name),
+ lambda: df.registerTempTable(name),
+ lambda: spark.read.table(name),
+ lambda: spark.readStream.table(name),
+ lambda: spark.read.changes(name),
+ lambda: spark.readStream.changes(name),
+ ]:
+ with pytest.raises(error) as e:
+ call()
+ assert type(e.value) is error
+ # The write sets the table after the bucket count and before it checks the
save mode.
+ with pytest.raises(UnicodeDecodeError):
+ df.write.mode("bogus").insertInto(b"\xff")
+ with pytest.raises(TypeError, match="^Field
spark.connect.WriteOperation.BucketBy.num_buckets"):
+ df.write.bucketBy(True, "id").saveAsTable(b"\xff")
+ # changes checks the schema of its reader first.
+ for reader in [spark.read, spark.readStream]:
+ with pytest.raises(AnalysisException) as error:
+ reader.schema("a INT").changes(b"\xff")
+ assert error.value.getCondition() == "_LEGACY_ERROR_TEMP_1189"
+ # spark.table still raises NOT_EXPECTED_TYPE for a name that is not a str,
as PySpark's.
+ with pytest.raises(PySparkTypeError) as error:
+ spark.table(b"t")
+ assert error.value.getCondition() == "NOT_EXPECTED_TYPE"
+ assert (len(service.analyze_requests), len(service.execute_requests)) ==
requests
+
+
+def
test_write_to_and_merge_into_set_their_table_at_each_write_as_pyspark(mock_connect):
+ # As PySpark's DataFrameWriterV2 and MergeIntoWriter, which keep the table
as it is given and
+ # set it in the string field of the command of each write: bytes are sent
decoded, None
+ # leaves the field unset, and a table that the field does not take fails
each write, and
+ # not the call that gives it.
+ import gc
+ import weakref
+
+ from pyspark.errors import PySparkTypeError
+ from pyspark.sql import functions as F
+
+ spark, service = mock_connect
+ df = spark.range(1)
+
+ def sent_command():
+ # ExecutePlanRequest.plan=3 -> Plan.command=2.
+ plan = parse_message(parse_message(service.execute_requests[-1])[3][0])
+ return parse_message(plan[2][0])
+
+ # Command.write_operation_v2=4 -> WriteOperationV2.table_name=2, mode=7
(MODE_APPEND=4).
+ df.writeTo(b"t").append()
+ operation = parse_message(sent_command()[4][0])
+ assert operation[2] == [b"t"] and operation[7] == [4]
+ df.writeTo(None).append()
+ assert 2 not in parse_message(sent_command()[4][0])
+ # Command.merge_into_table_command=16 ->
MergeIntoTableCommand.target_table_name=1.
+ df.mergeInto(b"t", F.lit(True)).whenMatched().delete().merge()
+ assert parse_message(sent_command()[16][0])[1] == [b"t"]
+ requests = len(service.execute_requests)
+ message = "^bad argument type for built-in operation$"
+ writer = df.writeTo(1).option("k", "v")
+ for write in [writer.create, writer.replace, writer.createOrReplace,
writer.append,
+ writer.overwritePartitions, lambda:
writer.overwrite(F.lit(True))]:
+ with pytest.raises(TypeError, match=message):
+ write()
+ writer = df.writeTo(b"\xff")
+ with pytest.raises(UnicodeDecodeError):
+ writer.append()
+ # overwrite converts its condition before the command sets the table.
+ with pytest.raises(PySparkTypeError) as error:
+ writer.overwrite(123)
+ assert error.value.getCondition() == "NOT_EXPECTED_TYPE"
+ merge = df.mergeInto(1, F.lit(True)).whenNotMatched().insertAll()
+ for _ in range(2):
+ with pytest.raises(TypeError, match=message):
+ merge.merge()
+ with pytest.raises(UnicodeDecodeError):
+ df.mergeInto(b"\xff", F.lit(True)).whenMatched().delete().merge()
+ assert len(service.execute_requests) == requests
+
+ # The writers keep such a table where Python's garbage collector sees it,
which frees a
+ # reference cycle through it.
+ class Table:
+ pass
+
+ for write in [lambda table: df.writeTo(table), lambda table:
df.mergeInto(table, F.lit(1))]:
+ table = Table()
+ table.writer = write(table)
+ ref = weakref.ref(table.writer)
+ del table
+ gc.collect()
+ assert ref() is None
+
+
+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
+ # 0 or "", starts the query on the sink of its format, and another is
converted as protobuf's
+ # default backend (upb) converts a string field.
+ 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")))
+ stream = spark.readStream.format("rate").load().writeStream.format("noop")
+
+ 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])
+
+ for false in [0, False, [], {}, "", b"", None]:
+ for start in [stream.start, stream.toTable]:
+ start(false)
+ # WriteStreamOperationStart.path=11 and table_name=12.
+ assert not {11, 12} & set(sent_start())
+ stream.toTable(b"t")
+ assert sent_start()[12] == [b"t"]
+ requests = len(service.execute_requests)
+ for call in [lambda: stream.start([1]), lambda: stream.toTable(1),
+ lambda: stream.toTable([1])]:
+ with pytest.raises(TypeError, match="^bad argument type for built-in
operation$"):
+ call()
+ with pytest.raises(UnicodeDecodeError):
+ stream.toTable(b"\xff")
+
+ class Ambiguous:
+ def __bool__(self):
+ raise ValueError("ambiguous")
+
+ for start in [stream.start, stream.toTable]:
+ with pytest.raises(ValueError, match="^ambiguous$"):
+ start(Ambiguous())
+ assert len(service.execute_requests) == requests
+
+
def
test_readers_keep_their_settings_when_the_path_is_not_a_str_as_pyspark(mock_connect):
# As PySpark, whose format readers set the options and the format before
they check the path,
# which is an AssertionError for a path that is not a str.
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]