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 d3190d24 [SPARK-61617][CONNECT][PYTHON] Match PySpark's
registerTempTable, the bool and properties arguments of the catalog and
writers, and createExternalTable's signature, in the Python client
d3190d24 is described below
commit d3190d24e08d492065c7cfe05b9e446b49835827
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Fri Nov 13 14:37:56 2026 +0900
[SPARK-61617][CONNECT][PYTHON] Match PySpark's registerTempTable, the bool
and properties arguments of the catalog and writers, and createExternalTable's
signature, in the Python client
### What changes were proposed in this pull request?
From the same review as #608 (SPARK-61613): four differences from PySpark
4.3.0's Connect client in the catalog and writer methods of the Python client,
which predate it.
- **`DataFrame.registerTempTable`** created the view, so a name of an
existing view raised `TEMP_TABLE_OR_VIEW_ALREADY_EXISTS`, and it gave no
warning. PySpark's warns `FutureWarning("Deprecated in 2.0, use
createOrReplaceTempView instead.")` and calls `createOrReplaceTempView`. It now
does both, in that order, so a warning filter of `error` raises before the name
is converted.
- **Bool arguments** took only a bool.
- `dropTable(ifExists, purge)`, `dropView(ifExists)`,
`createDatabase(ifNotExists)` and `dropDatabase(ifExists, cascade)`: PySpark
passes these to the constructor of a proto message, so they now take what upb's
bool conversion takes (an int by its truth, a NumPy bool; its errors
otherwise), with `None` as false.
- `getCreateTableString(asSerde)` and `analyzeTable(noScan)`: PySpark
sets these on the plan, so an omitted value is false and an explicit `None`
raises upb's `TypeError`.
- `insertInto(overwrite)` tests the truth of a value that is not `None`,
as PySpark's `if overwrite:`.
- `DataFrame.unpersist(blocking)` takes upb's conversion.
- **`createDatabase(properties=[])`** raised a `TypeError`, where PySpark's
`properties or {}` takes a false value as no properties. It now takes any
mapping, and a true non-mapping raises PySpark's `AttributeError` of `.items()`.
- **`createExternalTable`** took a fifth positional `description`.
PySpark's signature is `(tableName, path=None, source=None, schema=None,
**options)`, so a fifth positional argument raises Python's `TypeError`, and a
`description=` keyword goes through `**options` to `createTable`, as in
PySpark. `createTable` gives Python's counts of positional arguments too.
### Why are the changes needed?
To match PySpark 4.3.0. A probe of these four items (147 lines: errors,
warnings, the effects sent, row counts and signatures) now gives the same
output on official pyspark-client 4.3.0 and on this client. Before the change,
102 of its lines differed.
### Does this PR introduce _any_ user-facing change?
Yes, in the Python client:
- `registerTempTable` warns and replaces a view, as PySpark's does;
- these methods take PySpark's bool and properties values;
- `createExternalTable` has PySpark's signature.
### How was this patch tested?
- 4 new offline tests, after those of #608. They fail without the change.
- The whole `test_dropin_offline.py` (1971 passed, 8 skipped), and the
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 #614 from HyukjinKwon/SPARK-61617-catalog-args.
Authored-by: Hyukjin Kwon <[email protected]>
Signed-off-by: Hyukjin Kwon <[email protected]>
---
crates/pyspark-rs/src/catalog.rs | 147 +++++++++++++++++++++-----
crates/pyspark-rs/src/dataframe.rs | 33 ++++--
crates/pyspark-rs/src/streaming.rs | 5 +-
python/tests/test_dropin_offline.py | 198 ++++++++++++++++++++++++++++++++++++
4 files changed, 345 insertions(+), 38 deletions(-)
diff --git a/crates/pyspark-rs/src/catalog.rs b/crates/pyspark-rs/src/catalog.rs
index 74555e8f..8c53c177 100644
--- a/crates/pyspark-rs/src/catalog.rs
+++ b/crates/pyspark-rs/src/catalog.rs
@@ -42,6 +42,37 @@ fn constructor_name(name: &Bound<'_, PyAny>) ->
PyResult<String> {
crate::str_argument(name)
}
+/// A flag of a catalog method that PySpark passes to the constructor of its
message, which
+/// leaves the bool field unset (false) for None, as for an omitted argument,
and converts any
+/// other value as protobuf's default (upb) backend does
([`crate::streaming::proto_bool`]). The
+/// flags that PySpark's plan sets instead are
[`crate::streaming::ProtoBool`]s, of the
+/// `TypeError` of None.
+fn constructor_bool(flag: Option<&Bound<'_, PyAny>>) -> PyResult<bool> {
+ Ok(flag
+ .map(crate::streaming::proto_bool)
+ .transpose()?
+ .unwrap_or(false))
+}
+
+/// The `TypeError` that Python's binding of PySpark's `method` raises for the
positional
+/// arguments `extra` beyond its `count` parameters, of which the first, the
table name, is
+/// required, in Python's counts, which count `self`. PyO3 binds the other
arguments, and raises
+/// their `TypeError`s, as Python does.
+fn check_extra_positional(
+ method: &str,
+ count: usize,
+ extra: &Bound<'_, pyo3::types::PyTuple>,
+) -> PyResult<()> {
+ if extra.is_empty() {
+ return Ok(());
+ }
+ Err(pyo3::exceptions::PyTypeError::new_err(format!(
+ "{method}() takes from 2 to {} positional arguments but {} were given",
+ count + 1,
+ count + extra.len() + 1
+ )))
+}
+
/// The schema of `createTable`, a StructType, as PySpark's, else
`NOT_EXPECTED_TYPE`.
fn table_schema(
schema: Option<&Bound<'_, PyAny>>,
@@ -456,7 +487,10 @@ impl PyCatalog {
/// Create a table from a data source, as PySpark's: of a StructType
`schema` and string
/// `**options`, created on return.
- #[pyo3(signature = (tableName, path=None, source=None, schema=None,
description=None, **options))]
+ #[pyo3(
+ signature = (tableName, path=None, source=None, schema=None,
description=None, *extra, **options),
+ text_signature = "($self, tableName, path=None, source=None,
schema=None, description=None, **options)"
+ )]
#[allow(non_snake_case, clippy::too_many_arguments)]
fn createTable(
&self,
@@ -466,9 +500,11 @@ impl PyCatalog {
source: Option<&Bound<'_, PyAny>>,
schema: Option<&Bound<'_, PyAny>>,
description: Option<&Bound<'_, PyAny>>,
+ extra: &Bound<'_, pyo3::types::PyTuple>,
options: Option<&Bound<'_, pyo3::types::PyDict>>,
) -> PyResult<PyDataFrame> {
crate::options::check_keyword_keys(options)?;
+ check_extra_positional("Catalog.createTable", 5, extra)?;
let schema = table_schema(schema)?;
// In the order of PySpark's `CreateTable` plan, after its check of
the schema, and
// before the options.
@@ -492,9 +528,13 @@ impl PyCatalog {
.map(PyDataFrame::new)
}
- /// Create an external table from a data source: deprecated, as PySpark's,
which warns and
- /// creates the table as `createTable` does.
- #[pyo3(signature = (tableName, path=None, source=None, schema=None,
description=None, **options))]
+ /// Create an external table from a data source: deprecated, as PySpark's
+ /// `createExternalTable(tableName, path=None, source=None, schema=None,
**options)`, which
+ /// warns and creates the table as `createTable` does, of a `description`
of the options.
+ #[pyo3(
+ signature = (tableName, path=None, source=None, schema=None, *extra,
**options),
+ text_signature = "($self, tableName, path=None, source=None,
schema=None, **options)"
+ )]
#[allow(non_snake_case, clippy::too_many_arguments)]
fn createExternalTable(
&self,
@@ -503,10 +543,11 @@ impl PyCatalog {
path: Option<&Bound<'_, PyAny>>,
source: Option<&Bound<'_, PyAny>>,
schema: Option<&Bound<'_, PyAny>>,
- description: Option<&Bound<'_, PyAny>>,
+ extra: &Bound<'_, pyo3::types::PyTuple>,
options: Option<&Bound<'_, pyo3::types::PyDict>>,
) -> PyResult<PyDataFrame> {
crate::options::check_keyword_keys(options)?;
+ check_extra_positional("Catalog.createExternalTable", 4, extra)?;
py.import("warnings")?.call_method1(
"warn",
(
@@ -515,7 +556,28 @@ impl PyCatalog {
py.get_type::<pyo3::exceptions::PyFutureWarning>(),
),
)?;
- self.createTable(py, tableName, path, source, schema, description,
options)
+ // As PySpark's `self.createTable(tableName, path, source, schema,
**options)`, which
+ // binds a `description` of the options to the parameter of
createTable.
+ let options = options.map(|options| options.copy()).transpose()?;
+ let mut description = None;
+ if let Some(options) = &options {
+ description = options.get_item("description")?;
+ if description.is_some() {
+ options.del_item("description")?;
+ }
+ }
+ let description = description.filter(|description|
!description.is_none());
+ let none = pyo3::types::PyTuple::empty(py);
+ self.createTable(
+ py,
+ tableName,
+ path,
+ source,
+ schema,
+ description.as_ref(),
+ &none,
+ options.as_ref(),
+ )
}
/// Register a Python function as a UDF, returning the registered UDF.
Deprecated
@@ -546,20 +608,32 @@ impl PyCatalog {
}
/// 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))]
+ /// and values are converted as `crate::str_argument` converts them. As
PySpark's
+ /// `CreateDatabase`, which takes `properties or {}`, and then passes the
database and
+ /// `ifNotExists` to the constructor of its message before it sets each of
the
+ /// `properties.items()`.
+ #[pyo3(
+ signature = (dbName, ifNotExists=None, properties=None),
+ text_signature = "($self, dbName, ifNotExists=False, properties=None)"
+ )]
#[allow(non_snake_case)]
fn createDatabase(
&self,
py: Python<'_>,
dbName: &Bound<'_, PyAny>,
- ifNotExists: bool,
- properties: Option<&Bound<'_, pyo3::types::PyDict>>,
+ ifNotExists: Option<&Bound<'_, PyAny>>,
+ properties: Option<&Bound<'_, PyAny>>,
) -> PyResult<()> {
+ let properties = match properties {
+ Some(properties) if properties.is_truthy()? => Some(properties),
+ _ => None,
+ };
let dbName = constructor_name(dbName)?;
+ let ifNotExists = constructor_bool(ifNotExists)?;
let mut props = std::collections::HashMap::new();
- if let Some(dict) = properties {
- for (k, v) in dict.iter() {
+ if let Some(properties) = properties {
+ for item in properties.call_method0("items")?.try_iter()? {
+ let (k, v): (Bound<'_, PyAny>, Bound<'_, PyAny>) =
item?.extract()?;
props.insert(crate::str_argument(&k)?,
crate::str_argument(&v)?);
}
}
@@ -569,32 +643,40 @@ impl PyCatalog {
}
/// Drop a database.
- #[pyo3(signature = (dbName, ifExists=false, cascade=false))]
+ #[pyo3(
+ signature = (dbName, ifExists=None, cascade=None),
+ text_signature = "($self, dbName, ifExists=False, cascade=False)"
+ )]
#[allow(non_snake_case)]
fn dropDatabase(
&self,
py: Python<'_>,
dbName: &Bound<'_, PyAny>,
- ifExists: bool,
- cascade: bool,
+ ifExists: Option<&Bound<'_, PyAny>>,
+ cascade: Option<&Bound<'_, PyAny>>,
) -> PyResult<()> {
let dbName = constructor_name(dbName)?;
+ let (ifExists, cascade) = (constructor_bool(ifExists)?,
constructor_bool(cascade)?);
self.detached(py, |catalog| {
{ catalog.drop_database(&dbName, ifExists, cascade)
}.map_err(Box::new)
})
}
/// Drop a table.
- #[pyo3(signature = (tableName, ifExists=false, purge=false))]
+ #[pyo3(
+ signature = (tableName, ifExists=None, purge=None),
+ text_signature = "($self, tableName, ifExists=False, purge=False)"
+ )]
#[allow(non_snake_case)]
fn dropTable(
&self,
py: Python<'_>,
tableName: &Bound<'_, PyAny>,
- ifExists: bool,
- purge: bool,
+ ifExists: Option<&Bound<'_, PyAny>>,
+ purge: Option<&Bound<'_, PyAny>>,
) -> PyResult<()> {
let tableName = constructor_name(tableName)?;
+ let (ifExists, purge) = (constructor_bool(ifExists)?,
constructor_bool(purge)?);
self.detached(py, |catalog| {
catalog
.drop_table(&tableName, ifExists, purge)
@@ -603,15 +685,19 @@ impl PyCatalog {
}
/// Drop a view.
- #[pyo3(signature = (viewName, ifExists=false))]
+ #[pyo3(
+ signature = (viewName, ifExists=None),
+ text_signature = "($self, viewName, ifExists=False)"
+ )]
#[allow(non_snake_case)]
fn dropView(
&self,
py: Python<'_>,
viewName: &Bound<'_, PyAny>,
- ifExists: bool,
+ ifExists: Option<&Bound<'_, PyAny>>,
) -> PyResult<()> {
let viewName = constructor_name(viewName)?;
+ let ifExists = constructor_bool(ifExists)?;
self.detached(py, |catalog| {
catalog.drop_view(&viewName, ifExists).map_err(Box::new)
})
@@ -626,31 +712,40 @@ impl PyCatalog {
})
}
- /// Recover the statistics of a table.
- #[pyo3(signature = (tableName, noScan=false))]
+ /// Recover the statistics of a table, of `noScan` as PySpark's plan sets
it in its bool field.
+ #[pyo3(
+ signature = (tableName, noScan=crate::streaming::ProtoBool::default()),
+ text_signature = "($self, tableName, noScan=False)"
+ )]
#[allow(non_snake_case)]
fn analyzeTable(
&self,
py: Python<'_>,
tableName: &Bound<'_, PyAny>,
- noScan: bool,
+ noScan: crate::streaming::ProtoBool,
) -> PyResult<()> {
let tableName = crate::str_argument(tableName)?;
+ let noScan = noScan.value(py)?;
self.detached(py, |catalog| {
catalog.analyze_table(&tableName, noScan).map_err(Box::new)
})
}
- /// Get the `CREATE TABLE` string of a table.
- #[pyo3(signature = (tableName, asSerde=false))]
+ /// Get the `CREATE TABLE` string of a table, of `asSerde` as PySpark's
plan sets it in its
+ /// bool field.
+ #[pyo3(
+ signature = (tableName,
asSerde=crate::streaming::ProtoBool::default()),
+ text_signature = "($self, tableName, asSerde=False)"
+ )]
#[allow(non_snake_case)]
fn getCreateTableString(
&self,
py: Python<'_>,
tableName: &Bound<'_, PyAny>,
- asSerde: bool,
+ asSerde: crate::streaming::ProtoBool,
) -> PyResult<String> {
let tableName = crate::str_argument(tableName)?;
+ let asSerde = asSerde.value(py)?;
self.detached(py, |catalog| {
{ catalog.get_create_table_string(&tableName, asSerde)
}.map_err(Box::new)
})
diff --git a/crates/pyspark-rs/src/dataframe.rs
b/crates/pyspark-rs/src/dataframe.rs
index 3dfb2b35..43e2eebc 100644
--- a/crates/pyspark-rs/src/dataframe.rs
+++ b/crates/pyspark-rs/src/dataframe.rs
@@ -1674,13 +1674,19 @@ impl PyDataFrame {
Ok(slf)
}
- /// Mark the DataFrame as non-persistent.
- #[pyo3(signature = (blocking=false))]
+ /// Mark the DataFrame as non-persistent. As PySpark's, which sets
`blocking` in the bool
+ /// field of its request unless it is None, as
[`crate::streaming::proto_bool`] converts it;
+ /// None unpersists as False does.
+ #[pyo3(signature = (blocking=None), text_signature = "($self,
blocking=False)")]
fn unpersist<'py>(
slf: PyRef<'py, Self>,
py: Python<'py>,
- blocking: bool,
+ blocking: Option<&Bound<'py, PyAny>>,
) -> PyResult<PyRef<'py, Self>> {
+ let blocking = blocking
+ .map(crate::streaming::proto_bool)
+ .transpose()?
+ .unwrap_or(false);
// As PySpark's, which returns the DataFrame itself.
let df = slf.dataframe.clone();
interruptible(py, &df.spark_session(), || {
@@ -1924,13 +1930,18 @@ impl PyDataFrame {
})
}
- /// Deprecated alias for createOrReplaceTempView.
+ /// Deprecated alias for createOrReplaceTempView, as PySpark's, which
warns that it is
+ /// deprecated and then replaces the view as `createOrReplaceTempView`
does.
#[pyo3(name = "registerTempTable")]
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)
- })
+ py.import("warnings")?.call_method1(
+ "warn",
+ (
+ "Deprecated in 2.0, use createOrReplaceTempView instead.",
+ py.get_type::<pyo3::exceptions::PyFutureWarning>(),
+ ),
+ )?;
+ self.create_or_replace_temp_view(py, name)
}
/// Reliable checkpoint (materialize + truncate lineage), at once if
`eager`, as PySpark's.
@@ -3955,16 +3966,18 @@ impl PyDataFrameWriter {
}
/// Insert into an existing table. `overwrite` maps to overwrite/append
mode,
- /// mirroring reference `DataFrameWriter.insertInto(tableName,
overwrite=None)`.
+ /// mirroring reference `DataFrameWriter.insertInto(tableName,
overwrite=None)`, of its
+ /// truth when it is not None (`"overwrite" if overwrite else "append"`).
#[pyo3(name = "insertInto", signature = (tableName, overwrite=None))]
fn insert_into(
&self,
py: Python<'_>,
tableName: &Bound<'_, PyAny>,
- overwrite: Option<bool>,
+ overwrite: Option<&Bound<'_, PyAny>>,
) -> PyResult<()> {
let mut w = self.inner.get();
if let Some(ow) = overwrite {
+ let ow = ow.is_truthy()?;
w = w.mode(if ow { "overwrite" } else { "append" });
}
// PySpark sets the overwrite/append mode on the writer itself.
diff --git a/crates/pyspark-rs/src/streaming.rs
b/crates/pyspark-rs/src/streaming.rs
index 00057cb8..5a593031 100644
--- a/crates/pyspark-rs/src/streaming.rs
+++ b/crates/pyspark-rs/src/streaming.rs
@@ -1140,8 +1140,9 @@ fn positive_timeout(timeout: Option<&Bound<'_, PyAny>>)
-> PyResult<Option<f64>>
}
/// A bool argument that PySpark sets in a proto bool field, taken as it is
(None when it is
-/// omitted) and converted in the call by [`ProtoBool::value`], as PyO3 would
prefix the
-/// `TypeError` of the conversion of an argument with its name.
+/// omitted, its `default()`) and converted in the call by
[`ProtoBool::value`], as PyO3 would
+/// prefix the `TypeError` of the conversion of an argument with its name.
+#[derive(Default)]
pub(crate) struct ProtoBool(Option<Py<PyAny>>);
impl<'a, 'py> FromPyObject<'a, 'py> for ProtoBool {
diff --git a/python/tests/test_dropin_offline.py
b/python/tests/test_dropin_offline.py
index 1f6ece0e..8dff53db 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -7998,6 +7998,204 @@ def
test_stream_writer_skips_a_false_path_and_table_as_pyspark(mock_connect):
assert len(service.execute_requests) == requests
+def
test_register_temp_table_warns_and_replaces_the_view_as_pyspark(mock_connect):
+ # As PySpark's registerTempTable, which warns that it is deprecated, and
then replaces the view
+ # as createOrReplaceTempView does, which converts the name after the
warning.
+ import warnings
+
+ spark, service = mock_connect
+ df = spark.range(1)
+ message = "Deprecated in 2.0, use createOrReplaceTempView instead."
+ with pytest.warns(FutureWarning) as record:
+ df.registerTempTable("v")
+ assert [str(w.message) for w in record] == [message]
+ # ExecutePlanRequest.plan=3 -> Plan.command=2 ->
Command.create_dataframe_view=3:
+ # CreateDataFrameViewCommand.name=2 and replace=4, not is_global=3.
+ plan = parse_message(parse_message(service.execute_requests[-1])[3][0])
+ view = parse_message(parse_message(plan[2][0])[3][0])
+ assert (view[2], view[4], 3 in view) == ([b"v"], [1], False)
+ requests = len(service.execute_requests)
+ with pytest.warns(FutureWarning, match=re.escape(message)):
+ with pytest.raises(TypeError, match="^bad argument type for built-in
operation$"):
+ df.registerTempTable(1)
+ with warnings.catch_warnings():
+ warnings.simplefilter("error", FutureWarning)
+ with pytest.raises(FutureWarning, match=re.escape(message)):
+ df.registerTempTable(1)
+ assert len(service.execute_requests) == requests
+
+
+def test_catalog_writer_and_unpersist_flags_convert_as_pyspark(mock_connect):
+ # As PySpark: the flags that the catalog passes to the constructor of its
message (dropTable,
+ # dropView, createDatabase and dropDatabase) or sets in its plan (asSerde,
noScan), and the
+ # `blocking` of unpersist, are converted as protobuf's default backend
(upb) converts a bool
+ # field: an int by its truth, a NumPy bool, and the TypeError or
OverflowError of another
+ # object; None leaves a field of a constructor unset, and is the TypeError
of a field that the
+ # plan sets. insertInto takes the truth of an `overwrite` that is not None.
+ spark, service = mock_connect
+ catalog = spark.catalog
+ for call, operation, fields in [
+ (lambda: catalog.dropTable("t", ifExists=1, purge=np.bool_(True)), 27,
+ {1: [b"t"], 2: [1], 3: [1]}),
+ (lambda: catalog.dropTable("t", None, 0), 27, {1: [b"t"]}),
+ (lambda: catalog.dropView("v", ifExists=2), 28, {1: [b"v"], 2: [1]}),
+ (lambda: catalog.createDatabase("d", ifNotExists=-1), 29, {1: [b"d"],
2: [1]}),
+ (lambda: catalog.dropDatabase("d", 1, None), 30, {1: [b"d"], 2: [1]}),
+ (lambda: catalog.getCreateTableString("t", asSerde=1), 34, {1: [b"t"],
2: [1]}),
+ (lambda: catalog.analyzeTable("t", 1), 36, {1: [b"t"], 2: [1]}),
+ ]:
+ 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 flag, error, message in [
+ ("x", TypeError, "'str' object cannot be interpreted as an integer"),
+ (1.5, TypeError, "'float' object cannot be interpreted as an integer"),
+ (np.array([1]), TypeError, "[1] has type ndarray, but expected one of:
bool"),
+ (2**70, OverflowError, "Python int too large to convert to C long"),
+ ]:
+ for call in [
+ lambda: catalog.dropTable("t", ifExists=flag),
+ lambda: catalog.dropTable("t", purge=flag),
+ lambda: catalog.dropView("v", ifExists=flag),
+ lambda: catalog.createDatabase("d", ifNotExists=flag),
+ lambda: catalog.dropDatabase("d", cascade=flag),
+ lambda: catalog.getCreateTableString("t", asSerde=flag),
+ lambda: catalog.analyzeTable("t", noScan=flag),
+ lambda: spark.range(1).unpersist(flag),
+ ]:
+ with pytest.raises(error, match=f"^{re.escape(message)}$"):
+ call()
+ for call in [lambda: catalog.getCreateTableString("t", None),
+ lambda: catalog.analyzeTable("t", noScan=None)]:
+ with pytest.raises(TypeError, match="^'NoneType' object cannot be
interpreted as an "):
+ call()
+ # In the order of the fields: the name, and then each flag.
+ with pytest.raises(TypeError, match="^bad argument type for built-in
operation$"):
+ catalog.dropTable(1, ifExists="x")
+ with pytest.raises(TypeError, match="^'str' object"):
+ catalog.dropTable("t", ifExists="x", purge=1.5)
+ assert len(service.execute_requests) == requests
+ # AnalyzePlanRequest.unpersist=15 -> Unpersist.blocking=2, which None does
not set in PySpark,
+ # and unpersists without blocking as False does.
+ for blocking, sent in [(1, [1]), (np.bool_(False), [0])]:
+ spark.range(1).unpersist(blocking=blocking)
+ assert
parse_message(parse_message(service.analyze_requests[-1])[15][0])[2] == sent
+ spark.range(1).unpersist(None)
+
+ def sent_mode():
+ # ExecutePlanRequest.plan=3 -> Plan.command=2 ->
Command.write_operation=2 ->
+ # WriteOperation.mode=5 (SAVE_MODE_APPEND=1, SAVE_MODE_OVERWRITE=2).
+ plan = parse_message(parse_message(service.execute_requests[-1])[3][0])
+ return parse_message(parse_message(plan[2][0])[2][0]).get(5)
+
+ for overwrite, mode in [(1, [2]), ("x", [2]), ([1], [2]), (0, [1]), ("",
[1]), ([], [1])]:
+ spark.range(1).write.insertInto("t", overwrite=overwrite)
+ assert sent_mode() == mode
+
+ class Ambiguous:
+ def __bool__(self):
+ raise ValueError("ambiguous")
+
+ requests = len(service.execute_requests)
+ with pytest.raises(ValueError, match="^ambiguous$"):
+ spark.range(1).write.insertInto(1, overwrite=Ambiguous())
+ assert len(service.execute_requests) == requests
+
+
+def
test_create_database_takes_no_properties_of_a_false_value_as_pyspark(mock_connect):
+ # As PySpark's CreateDatabase, which takes `properties or {}`, before the
constructor of its
+ # message converts the database and `ifNotExists`, and then sets each of
the
+ # `properties.items()`.
+ import types
+
+ spark, service = mock_connect
+ catalog = spark.catalog
+ for properties in [[], 0, "", (), {}, None]:
+ catalog.createDatabase("d", properties=properties)
+ # Catalog.create_database=29: db_name=1, and properties=3, a map of
key=1 and value=2.
+ assert _sent_catalog(service.execute_requests[-1], 29) == {1: [b"d"]}
+ catalog.createDatabase("d", properties=types.MappingProxyType({"k": "v"}))
+ assert _sent_catalog(service.execute_requests[-1], 29)[3] == [
+ message_field(1, "k") + message_field(2, "v")]
+
+ class Ambiguous:
+ def __bool__(self):
+ raise ValueError("ambiguous")
+
+ requests = len(service.execute_requests)
+ for properties, error, message in [
+ ([("k", "v")], AttributeError, "'list' object has no attribute
'items'"),
+ ("kv", AttributeError, "'str' object has no attribute 'items'"),
+ ]:
+ with pytest.raises(error, match=f"^{re.escape(message)}$"):
+ catalog.createDatabase("d", properties=properties)
+ with pytest.raises(ValueError, match="^ambiguous$"):
+ catalog.createDatabase(1, properties=Ambiguous())
+ with pytest.raises(TypeError, match="^bad argument type for built-in
operation$"):
+ catalog.createDatabase(1, properties=[("k", "v")])
+ with pytest.raises(TypeError, match="^'str' object cannot be interpreted
as an integer$"):
+ catalog.createDatabase("d", ifNotExists="x", properties=[("k", "v")])
+ assert len(service.execute_requests) == requests
+
+
+def
test_create_table_and_create_external_table_bind_their_arguments_as_pyspark(mock_connect):
+ # As PySpark's createExternalTable(tableName, path=None, source=None,
schema=None, **options),
+ # which takes no description but of the options, which it passes to
createTable, and
+ # createTable(tableName, path=None, source=None, schema=None,
description=None, **options):
+ # Python's binding raises its TypeErrors, which count self, before the
method warns.
+ import inspect
+ import warnings
+
+ spark, service = mock_connect
+ catalog = spark.catalog
+ requests = len(service.execute_requests)
+ with warnings.catch_warnings(record=True) as record:
+ warnings.simplefilter("always")
+ for call, message in [
+ (lambda: catalog.createExternalTable("t", None, None, None, "d"),
+ "Catalog.createExternalTable() takes from 2 to 5 positional
arguments but 6 were "
+ "given"),
+ (lambda: catalog.createTable("t", None, None, None, None, "x",
"y"),
+ "Catalog.createTable() takes from 2 to 6 positional arguments but
8 were given"),
+ (lambda: catalog.createTable("t", None, None, 5, None, "x"),
+ "Catalog.createTable() takes from 2 to 6 positional arguments but
7 were given"),
+ (lambda: catalog.createExternalTable("t", None, None, None, 1,
path="p"),
+ "Catalog.createExternalTable() got multiple values for argument
'path'"),
+ (lambda: catalog.createExternalTable(path="p"),
+ "Catalog.createExternalTable() missing 1 required positional
argument: 'tableName'"),
+ ]:
+ with pytest.raises(TypeError, match=f"^{re.escape(message)}$"):
+ call()
+ assert record == [] and len(service.execute_requests) == requests
+ with pytest.warns(FutureWarning, match="createExternalTable is
deprecated"):
+ catalog.createExternalTable("t", "/p", description="d", k="v")
+ # Catalog.create_table=14: table_name=1, path=2, description=4 and
options=6.
+ create = _sent_catalog(service.execute_requests[-1], 14)
+ assert (create[1], create[2], create[4]) == ([b"t"], [b"/p"], [b"d"])
+ assert [parse_message(entry) for entry in create[6]] == [{1: [b"k"], 2:
[b"v"]}]
+ with pytest.warns(FutureWarning):
+ catalog.createExternalTable("t", description=None)
+ assert _sent_catalog(service.execute_requests[-1], 14) == {1: [b"t"]}
+ catalog.createTable("t", "/p", "parquet", None, "d")
+ create = _sent_catalog(service.execute_requests[-1], 14)
+ assert (create[2], create[3], create[4]) == ([b"/p"], [b"parquet"], [b"d"])
+
+ def parameters(method):
+ signature = inspect.signature(method)
+ return [(p.name, p.kind.name, p.default) for p in
signature.parameters.values()]
+
+ empty = inspect.Parameter.empty
+ head = [("tableName", "POSITIONAL_OR_KEYWORD", empty), ("path",
"POSITIONAL_OR_KEYWORD", None),
+ ("source", "POSITIONAL_OR_KEYWORD", None), ("schema",
"POSITIONAL_OR_KEYWORD", None)]
+ options = [("options", "VAR_KEYWORD", empty)]
+ assert parameters(catalog.createExternalTable) == head + options
+ assert parameters(catalog.createTable) == head + [
+ ("description", "POSITIONAL_OR_KEYWORD", None)] + options
+
+
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]