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 df70cccc [SPARK-61226][CONNECT][PYTHON] Make StructField.fromDDL
return the parsed type, as DataType.fromDDL does in PySpark
df70cccc is described below
commit df70cccc6e832e6452bee4720a87947c76e1e66d
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Mon Nov 9 17:31:31 2026 +0900
[SPARK-61226][CONNECT][PYTHON] Make StructField.fromDDL return the parsed
type, as DataType.fromDDL does in PySpark
### What changes were proposed in this pull request?
[SPARK-61226](https://issues.apache.org/jira/browse/SPARK-61226): Make
`StructField.fromDDL` return the parsed type, as `DataType.fromDDL` does in
PySpark.
- `StructField.fromDDL` was a fork override that returned a `StructField`,
split at the first whitespace. It now parses the DDL string with the same
function as `DataType.fromDDL`, so it returns the same type and raises the same
errors. For example, `StructField.fromDDL("a int")` is
`StructType([StructField("a", IntegerType())])`, and
`StructField.fromDDL("int")` is `IntegerType()`.
- Two existing tests that asserted the old `StructField` result now assert
the `StructType` result of PySpark.
### Why are the changes needed?
With the override, `StructField.fromDDL("`x y` int")` gave the name "`x"
with the type `struct<y`:int>`, and `StructField.fromDDL("a int not null")`
raised `ValueError`. A `StructField` cannot be used as a schema, so
`spark.createDataFrame([(1,)], StructField.fromDDL("a int"))` raised
`PySparkTypeError [NOT_EXPECTED_TYPE]`. PySpark returns
`StructType([StructField('a', IntegerType(), True)])` and the DataFrame
`[Row(a=1)]`.
### Does this PR introduce _any_ user-facing change?
Yes. `StructField.fromDDL` returns the parsed type, as PySpark does,
instead of a `StructField`.
### How was this patch tested?
- `test_struct_field_from_ddl_is_data_type_from_ddl_as_pyspark` (offline):
the results of `StructField.fromDDL` for the "a int", "`x y` int", "a int not
null", "int" and nested struct DDL strings.
- `test_struct_field_from_ddl_parses_as_data_type_from_ddl_as_pyspark`
(live): `StructField.fromDDL` equals `DataType.fromDDL` for several DDL
strings, a parse error gives the same error condition for "a INT," and "a
BOGUS", and the `StructType` creates `[Row(a=1)]`. The same results come from
official PySpark 4.3.0.
- The existing assertions of `StructField.fromDDL` in
`test_udf_udtf_determinism_and_extras` and `test_datatype_from_ddl_parsing` now
assert the `StructType` result. `test_datatype_from_ddl_parsing` now takes the
`mock_connect` fixture, as DDL parsing needs the session.
- The lib tests of both crates (658 passed), the build of all tests, also
with `wasm-udf`, the offline Python suites (2808 passed, 8 skipped), and the
live drop-in and Arrow suites (225 passed) and live cases (12 passed) against a
local Spark 4.3.0 server. Clippy reports no diagnostics in the changed lines.
### 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 #408 from HyukjinKwon/SPARK-61226-fu-p6.
Authored-by: Hyukjin Kwon <[email protected]>
Signed-off-by: Hyukjin Kwon <[email protected]>
---
crates/pyspark-rs/src/types.rs | 30 +++++++-----------------------
python/tests/test_dropin_e2e.py | 19 +++++++++++++++++++
python/tests/test_dropin_offline.py | 30 ++++++++++++++++++++++--------
3 files changed, 48 insertions(+), 31 deletions(-)
diff --git a/crates/pyspark-rs/src/types.rs b/crates/pyspark-rs/src/types.rs
index 53b0cd63..669a1c91 100644
--- a/crates/pyspark-rs/src/types.rs
+++ b/crates/pyspark-rs/src/types.rs
@@ -2209,35 +2209,19 @@ impl PyStructField {
};
Ok(format!("{provider}.{collation}"))
}
- /// Parse a single-field DDL string (e.g. "a INT" or "a: int") into a
StructField.
- /// Mirrors `StructField.fromDDL`.
+ /// The type of the DDL string `ddl`, as PySpark's `DataType.fromDDL`,
which `StructField`
+ /// inherits: the parsed type (a StructType for "a int"), not a
StructField.
#[classmethod]
#[pyo3(name = "fromDDL")]
fn __sf_from_ddl(
_cls: &Bound<'_, pyo3::types::PyType>,
py: Python<'_>,
ddl: &str,
- ) -> PyResult<PyStructField> {
- let trimmed = ddl.trim();
- // Split "name type" at the first run of whitespace; tolerate a
"name:" colon.
- let split = trimmed.find(char::is_whitespace).ok_or_else(|| {
- PyErr::new::<pyo3::exceptions::PyValueError, _>(
- "fromDDL expects 'name type', e.g. 'a INT'",
- )
- })?;
- let name = trimmed[..split].trim_end_matches(':').to_string();
- let type_str = trimmed[split..].trim();
- let data_type = DataType::from_ddl(type_str)
- .map_err(|e| PyErr::new::<pyo3::exceptions::PyValueError,
_>(e.to_string()))?;
- PyStructField::from_field(
- py,
- StructField {
- name,
- data_type,
- nullable: true,
- metadata: BTreeMap::new(),
- },
- )
+ ) -> PyResult<Py<PyAny>> {
+ Ok(py
+ .import("pyspark.sql.types")?
+ .call_method1("_parse_datatype_string", (ddl,))?
+ .unbind())
}
#[classmethod]
diff --git a/python/tests/test_dropin_e2e.py b/python/tests/test_dropin_e2e.py
index 9cf910e7..bb26e818 100644
--- a/python/tests/test_dropin_e2e.py
+++ b/python/tests/test_dropin_e2e.py
@@ -2631,6 +2631,25 @@ def test_sql_runs_statements_eagerly(session):
assert [tuple(r) for r in query.collect()] == [(1,)]
+def
test_struct_field_from_ddl_parses_as_data_type_from_ddl_as_pyspark(session):
+ # As PySpark: StructField inherits DataType.fromDDL, so it parses a DDL
string to the type
+ # that DataType.fromDDL gives, with the same errors, and a StructType
creates a DataFrame.
+ from pyspark.errors import ParseException
+ from pyspark.sql import types as T
+
+ for ddl in ["a int", "`x y` int", "a int not null", "b: string", "a int, b
string", "int"]:
+ assert T.StructField.fromDDL(ddl) == T.DataType.fromDDL(ddl)
+ assert T.StructField.fromDDL("`x y` int") == T.StructType([
+ T.StructField("x y", T.IntegerType()),
+ ])
+ df = session.createDataFrame([(1,)], T.StructField.fromDDL("a int"))
+ assert df.collect() == [Row(a=1)]
+ for ddl, condition in [("a INT,", "PARSE_SYNTAX_ERROR"), ("a BOGUS",
"UNSUPPORTED_DATATYPE")]:
+ with pytest.raises(ParseException) as error:
+ T.StructField.fromDDL(ddl)
+ assert error.value.getCondition() == condition
+
+
def test_struct_types_take_their_keys_and_fields_as_pyspark(session):
# As PySpark's StructType: add takes the JSON value of a data type, and a
missing field is
# KEY_NOT_EXISTS.
diff --git a/python/tests/test_dropin_offline.py
b/python/tests/test_dropin_offline.py
index dbd7f181..43b2723b 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -2977,7 +2977,7 @@ def test_udf_registration_has_java_methods():
assert hasattr(UDFRegistration, m), f"UDFRegistration missing {m}"
-def test_udf_udtf_determinism_and_extras():
+def test_udf_udtf_determinism_and_extras(mock_connect):
from pyspark.sql import functions as F
from pyspark.sql.udf import udf, UserDefinedFunction
from pyspark.sql.udtf import udtf
@@ -3000,9 +3000,9 @@ def test_udf_udtf_determinism_and_extras():
# functions.random is an alias for rand.
assert F.random is F.rand
- # StructField.fromDDL.
- assert T.StructField.fromDDL("a int").simpleString() == "a:int"
- assert T.StructField.fromDDL("b: string").simpleString() == "b:string"
+ # StructField.fromDDL is DataType.fromDDL, which parses a list of fields
to a StructType.
+ assert T.StructField.fromDDL("a int").simpleString() == "struct<a:int>"
+ assert T.StructField.fromDDL("b: string").simpleString() ==
"struct<b:string>"
def test_catalog_result_classes():
@@ -4772,16 +4772,16 @@ def test_row_as_dict():
assert error.value.getCondition() == "CANNOT_CONVERT_TYPE"
-def test_datatype_from_ddl_parsing():
+def test_datatype_from_ddl_parsing(mock_connect):
"""Test DataType.fromDDL parsing of DDL strings."""
# StructField DDL parsing
import pyspark.sql.types as types_module
- # StructField.fromDDL is what works offline
+ # StructField.fromDDL is DataType.fromDDL, which works offline
sf = T.StructField.fromDDL("a int")
- assert sf.simpleString() == "a:int"
+ assert sf.simpleString() == "struct<a:int>"
sf2 = T.StructField.fromDDL("b: string")
- assert sf2.simpleString() == "b:string"
+ assert sf2.simpleString() == "struct<b:string>"
def test_decimal_type_methods():
@@ -6422,6 +6422,20 @@ def test_functions_stack():
assert type(result).__name__ == "Column"
+def test_struct_field_from_ddl_is_data_type_from_ddl_as_pyspark(mock_connect):
+ # As PySpark: StructField inherits DataType.fromDDL, so it returns the
parsed type, a
+ # StructType for a list of fields (its errors are checked against the
server, live).
+ assert T.StructField.fromDDL("a int") == T.StructType([T.StructField("a",
T.IntegerType())])
+ assert T.StructField.fromDDL("int") == T.IntegerType()
+ assert T.StructField.fromDDL("`x y` int") == T.StructType([
+ T.StructField("x y", T.IntegerType()),
+ ])
+ assert T.StructField.fromDDL("a int not null").simpleString() ==
"struct<a:int>"
+ assert T.StructField.fromDDL("st struct<a:int,b:double>").simpleString()
== (
+ "struct<st:struct<a:int,b:double>>"
+ )
+
+
def test_functions_sort_array():
"""Test sort_array function."""
from pyspark.sql import functions as F
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]