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 f3f968b8 [SPARK-61601][FOLLOWUP][CONNECT][PYTHON] Raise the SRID
errors of PySpark where it converts a schema, read spatial JSON and DDL as
Spark does, and drift-check the SRID registry
f3f968b8 is described below
commit f3f968b817f19c83694aa1cd824e2add0258a87e
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Fri Nov 13 14:16:34 2026 +0900
[SPARK-61601][FOLLOWUP][CONNECT][PYTHON] Raise the SRID errors of PySpark
where it converts a schema, read spatial JSON and DDL as Spark does, and
drift-check the SRID registry
### What changes were proposed in this pull request?
A follow-up of #597 (SPARK-61601), from a post-merge review:
- **The SRID errors of PySpark where it converts a schema.** PySpark builds
`GeometryType`/`GeographyType` when it converts a proto schema, and raises
`IllegalArgumentException [ST_INVALID_SRID_VALUE]` for an SRID other than 0,
3857 or 4326. It does so in `df.schema`, `columns`, `dtypes`, `repr(df)`,
`printSchema` and `select(..).columns`. The Python client raised it only when
it built a Python type, so all of those answered (`DataFrame[g:
geometry(2154)]`). The check now runs with th [...]
- **Spatial JSON and DDL as Spark reads them**, in the Rust API:
- `DataType::from_json` reads a bare `geometry`/`geography` as SRID 4326,
`geography(<algorithm>)` as `OGC:CRS84` of that algorithm, and a CRS of the
form `\w+:-?\w+`. It compares the algorithm with `SPHERICAL`
case-insensitively, and raises `ST_INVALID_ALGORITHM_VALUE` otherwise.
- `geometry(<srid>)` and `geometry(any)`, which Spark's JSON does not
have, are format errors.
- `DataType::from_ddl` takes only a number or `any` as an SRID, as the
server's parser.
- Of 62 forms checked against the server's `json_to_ddl` and DDL parser,
30 differed before and 1 does now (a trailing space, which the crate accepts
after every JSON form, as PySpark's prefix matching does).
- A migration note is in `docs/compatibility.md`.
- **The SRID registry in the drift gate.**
`scripts/check_vendored_upstream.sh` checks the embedded
`crates/spark-connect/src/srs_registry.csv` against PySpark's
`python/pyspark/sql/srs_registry.csv` at the pinned tag
(`VENDORED_MAPPED_FILES`).
### Why are the changes needed?
To match PySpark and Spark 4.3.0, and to keep the registry in step with
Spark's.
### Does this PR introduce _any_ user-facing change?
Yes:
- In the Python client, a schema with an SRID that PySpark does not take
raises PySpark's error where PySpark raises it.
- In the Rust API, `from_json` and `from_ddl` read the spatial forms as
Spark does.
### How was this patch tested?
- A new offline test, `types_roundtrip` cases, and a new e2e test of the
type strings against the server. They fail without the change.
- The review's probes now match official pyspark-client 4.3.0 byte for byte.
- The lib tests (672 passed), `types_roundtrip` and the e2e test (39
passed), the whole `test_dropin_offline.py` (1963 passed, 8 skipped) and the
spatial e2e tests (28 passed) against a Spark 4.3.0 server.
- The drift script (also against a copy with one row changed, which it
reports), and `cargo fmt --all --check`.
### Was this patch authored or co-authored using generative AI tooling?
Generated-by: Claude Opus 5.5
This pull request and its description were written by Isaac.
Closes #612 from HyukjinKwon/SPARK-61601-followup.
Authored-by: Hyukjin Kwon <[email protected]>
Signed-off-by: Hyukjin Kwon <[email protected]>
---
crates/pyspark-rs/src/dataframe.rs | 76 +++++++---
crates/pyspark-rs/src/session.rs | 2 +-
crates/pyspark-rs/src/types.rs | 35 +++--
crates/spark-connect/src/srs.rs | 2 +
crates/spark-connect/src/types.rs | 172 ++++++++++++++--------
crates/spark-connect/tests/e2e_session_catalog.rs | 83 +++++++++++
crates/spark-connect/tests/types_roundtrip.rs | 172 ++++++++++++++++++++--
docs/compatibility.md | 8 +
docs/contributing.md | 10 +-
docs/types.md | 24 ++-
python/tests/test_dropin_offline.py | 77 ++++++++++
scripts/check_vendored_upstream.sh | 44 ++++--
12 files changed, 587 insertions(+), 118 deletions(-)
diff --git a/crates/pyspark-rs/src/dataframe.rs
b/crates/pyspark-rs/src/dataframe.rs
index 198aa899..3dfb2b35 100644
--- a/crates/pyspark-rs/src/dataframe.rs
+++ b/crates/pyspark-rs/src/dataframe.rs
@@ -121,7 +121,7 @@ impl PyDataFrame {
.collect_record_batches_with_schema()
.map_err(Box::new)
})?;
- check_nanosecond_timestamps(py, schema.as_ref())?;
+ check_schema_conversion(py, schema.as_ref())?;
let table = crate::pyarrow_export::record_batches_to_pyarrow(py,
batches)?;
let schema = match &schema {
Some(schema) => crate::types::data_type_to_py(py, schema)?,
@@ -2456,7 +2456,7 @@ impl PyDataFrame {
.collect_record_batches_with_schema()
.map_err(Box::new)
})?;
- check_nanosecond_timestamps(py, schema.as_ref())?;
+ check_schema_conversion(py, schema.as_ref())?;
let table = crate::pyarrow_export::record_batches_to_pyarrow(py,
batches)?;
let Some(schema) = schema else {
return Ok(table);
@@ -2626,7 +2626,7 @@ impl PyDataFrame {
let schema = interruptible(py, &self.dataframe.spark_session(), || {
self.dataframe.schema()
})?;
- check_nanosecond_timestamps(py, Some(&schema))?;
+ check_schema_conversion(py, Some(&schema))?;
crate::types::data_type_to_py(py, &schema)
}
@@ -2668,7 +2668,7 @@ impl PyDataFrame {
// The schema is cached, so the names come from it without another
request.
let session = self.dataframe.spark_session();
let schema = interruptible(py, &session, || self.dataframe.schema())?;
- check_nanosecond_timestamps(py, Some(&schema))?;
+ check_schema_conversion(py, Some(&schema))?;
interruptible(py, &session, || self.dataframe.columns())
}
@@ -2773,7 +2773,7 @@ impl PyDataFrame {
let schema = interruptible(py, &self.dataframe.spark_session(), || {
self.dataframe.schema()
})?;
- check_nanosecond_timestamps(py, Some(&schema))?;
+ check_schema_conversion(py, Some(&schema))?;
let depth = level
.map(crate::types::normalize_tree_depth)
.transpose()?
@@ -2789,7 +2789,7 @@ impl PyDataFrame {
let schema = interruptible(py, &self.dataframe.spark_session(), || {
self.dataframe.schema()
})?;
- check_nanosecond_timestamps(py, Some(&schema))?;
+ check_schema_conversion(py, Some(&schema))?;
let spark_connect::types::DataType::Struct { fields } = schema else {
unreachable!("schema() validates struct responses")
};
@@ -4725,23 +4725,65 @@ pub(crate) fn nanosecond_timestamp_text(
}
}
-/// Raises as PySpark does for a schema with a nanosecond-precision timestamp,
which PySpark cannot
-/// convert from the proto of the schema: the collecting APIs and every schema
surface raise (the
-/// schema, columns, dtypes, printSchema, a DDL string of a schema), though
the Rust core keeps
-/// these values, and count, show and describe work.
-pub(crate) fn check_nanosecond_timestamps(
+/// A type that PySpark's conversion of a schema from its proto,
`proto_schema_to_pyspark_data_type`,
+/// fails to build.
+enum UnconvertibleType {
+ /// A nanosecond-precision timestamp, which PySpark has no type of: the
proto text of it.
+ NanosecondTimestamp(String),
+ /// A spatial type of an SRID that PySpark's `GeometryType` or
`GeographyType` does not take.
+ SpatialSrid(i32),
+}
+
+/// The first type of `data_type` that PySpark's conversion of a schema from
its proto fails to
+/// build, in the order in which it converts them (the fields of a struct, the
element of an
+/// array, the key and then the value of a map): a nanosecond-precision
timestamp (see
+/// [`nanosecond_timestamp_text`]), or a spatial type of an SRID that PySpark
does not take (see
+/// [`crate::types::pyspark_converts_srid`]). PySpark builds a user-defined
type of its Python
+/// class, not of its SQL type, of which only a nanosecond timestamp counts.
+fn unconvertible_type(data_type: &spark_connect::types::DataType) ->
Option<UnconvertibleType> {
+ use spark_connect::types::DataType;
+ let spatial = |srid: i32, geographic: bool| {
+ (!crate::types::pyspark_converts_srid(srid, geographic))
+ .then_some(UnconvertibleType::SpatialSrid(srid))
+ };
+ match data_type {
+ DataType::Geometry { srid } => spatial(*srid, false),
+ DataType::Geography { srid } => spatial(*srid, true),
+ DataType::Struct { fields } => fields
+ .iter()
+ .find_map(|field| unconvertible_type(&field.data_type)),
+ DataType::Array { element_type, .. } =>
unconvertible_type(element_type),
+ DataType::Map {
+ key_type,
+ value_type,
+ ..
+ } => unconvertible_type(key_type).or_else(||
unconvertible_type(value_type)),
+ _ =>
nanosecond_timestamp_text(data_type).map(UnconvertibleType::NanosecondTimestamp),
+ }
+}
+
+/// Raises as PySpark does for a schema that it cannot convert from the proto
of the schema (see
+/// [`unconvertible_type`]): `UNSUPPORTED_OPERATION` for a
nanosecond-precision timestamp, and
+/// `ST_INVALID_SRID_VALUE` for a spatial type of an SRID that PySpark does
not take. The
+/// collecting APIs and every schema surface raise (the schema, columns,
dtypes, printSchema,
+/// repr, a DDL string of a schema), though the Rust core keeps these values,
and count, show and
+/// describe work.
+pub(crate) fn check_schema_conversion(
py: Python<'_>,
schema: Option<&spark_connect::types::DataType>,
) -> PyResult<()> {
- if let Some(text) = schema.and_then(nanosecond_timestamp_text) {
- return Err(crate::column::raise_pyspark(
+ match schema.and_then(unconvertible_type) {
+ Some(UnconvertibleType::NanosecondTimestamp(text)) =>
Err(crate::column::raise_pyspark(
py,
"PySparkValueError",
"UNSUPPORTED_OPERATION",
&[("operation", &format!("data type {text}"))],
- ));
+ )),
+ Some(UnconvertibleType::SpatialSrid(srid)) => {
+ Err(crate::types::invalid_schema_srid(py, srid))
+ }
+ None => Ok(()),
}
- Ok(())
}
/// Raises as PySpark's Arrow conversion of the rows does for a result of
`schema` with a
@@ -4805,7 +4847,7 @@ fn rows_to_py(
rows: &[spark_connect::row::Row],
schema: Option<&spark_connect::types::DataType>,
) -> PyResult<Vec<Py<PyAny>>> {
- check_nanosecond_timestamps(py, schema)?;
+ check_schema_conversion(py, schema)?;
check_arrow_schema(py, schema)?;
let binary_as_bytes = read_binary_as_bytes(py, dataframe)?;
check_collectable(py, schema)?;
@@ -4892,7 +4934,7 @@ impl PyLocalRowIterator {
if self.converters.is_none() {
if let Some(schema) =
self.iterator.as_ref().and_then(LocalRowIterator::schema) {
// The result is known once its first message arrives,
possibly with no rows.
- check_nanosecond_timestamps(py, Some(&schema))?;
+ check_schema_conversion(py, Some(&schema))?;
check_collectable(py, Some(&schema))?;
self.converters = Some(udt_field_converters(py,
Some(&schema))?);
self.nested_fields.note_udt_key_maps(&schema);
diff --git a/crates/pyspark-rs/src/session.rs b/crates/pyspark-rs/src/session.rs
index b4b6b995..d0e62eeb 100644
--- a/crates/pyspark-rs/src/session.rs
+++ b/crates/pyspark-rs/src/session.rs
@@ -2958,7 +2958,7 @@ impl PySparkSession {
/// `SparkSession._parse_ddl`, of a `DDLParse` of an `AnalyzePlanRequest`.
fn _parse_ddl(&self, py: Python<'_>, ddl: &str) -> PyResult<Py<PyAny>> {
let data_type = interruptible(py, &self.session, ||
self.session.parse_ddl(ddl))?;
- crate::dataframe::check_nanosecond_timestamps(py, Some(&data_type))?;
+ crate::dataframe::check_schema_conversion(py, Some(&data_type))?;
crate::types::data_type_to_py(py, &data_type)
}
diff --git a/crates/pyspark-rs/src/types.rs b/crates/pyspark-rs/src/types.rs
index 22851478..1be0deeb 100644
--- a/crates/pyspark-rs/src/types.rs
+++ b/crates/pyspark-rs/src/types.rs
@@ -3559,21 +3559,33 @@ fn pyspark_takes_srid(srid: i64, geographic: bool) ->
bool {
}
}
+/// Whether PySpark's conversion of a schema from its proto builds the spatial
type of the given
+/// kind of the SRID `srid` that the server sent, with `GeometryType(srid)` or
+/// `GeographyType(srid)`: the mixed SRID, or an SRID that PySpark takes.
+pub(crate) fn pyspark_converts_srid(srid: i32, geographic: bool) -> bool {
+ srid == spark_connect::types::SpatialType::MIXED_SRID
+ || pyspark_takes_srid(i64::from(srid), geographic)
+}
+
+/// The `ST_INVALID_SRID_VALUE` that PySpark raises for the SRID `srid` of a
spatial type of a
+/// schema that it does not convert (see [`pyspark_converts_srid`]).
+pub(crate) fn invalid_schema_srid(py: Python<'_>, srid: i32) -> PyErr {
+ crate::column::raise_pyspark(
+ py,
+ "IllegalArgumentException",
+ "ST_INVALID_SRID_VALUE",
+ &[("srid", &srid.to_string())],
+ )
+}
+
/// The SRID of a spatial type that the server sent in a schema, as PySpark's
schema conversion
/// builds it: the mixed SRID, or an SRID that PySpark takes, and
`ST_INVALID_SRID_VALUE` for
/// another one, which PySpark raises when it reads the schema.
fn schema_spatial_srid(py: Python<'_>, srid: i32, geographic: bool) ->
PyResult<i32> {
- if srid == spark_connect::types::SpatialType::MIXED_SRID
- || pyspark_takes_srid(i64::from(srid), geographic)
- {
+ if pyspark_converts_srid(srid, geographic) {
return Ok(srid);
}
- Err(crate::column::raise_pyspark(
- py,
- "IllegalArgumentException",
- "ST_INVALID_SRID_VALUE",
- &[("srid", &srid.to_string())],
- ))
+ Err(invalid_schema_srid(py, srid))
}
/// Parse a non-UDT DataType's Spark JSON (e.g. `"string collate UTF8_LCASE"`,
@@ -3912,8 +3924,9 @@ pub(crate) fn schema_data_type(
if schema.is_instance_of::<pyo3::types::PyString>() {
let ddl: String = schema.extract()?;
let parsed = crate::interrupt::interruptible(py, session, ||
session.parse_ddl(&ddl))?;
- // As PySpark converts the parsed type from its proto, which fails for
a nanosecond timestamp.
- crate::dataframe::check_nanosecond_timestamps(py, Some(&parsed))?;
+ // As PySpark converts the parsed type from its proto, which fails for
a nanosecond timestamp
+ // and for a spatial type of an SRID that PySpark does not take.
+ crate::dataframe::check_schema_conversion(py, Some(&parsed))?;
return Ok(parsed);
}
py_to_data_type(schema)
diff --git a/crates/spark-connect/src/srs.rs b/crates/spark-connect/src/srs.rs
index 709e56aa..89e8f461 100644
--- a/crates/spark-connect/src/srs.rs
+++ b/crates/spark-connect/src/srs.rs
@@ -3,6 +3,8 @@
//! from PROJ 9.8.1 (`dev/generate_srs_registry.py` in apache/spark) and adds
its own entries. The
//! registry is a copy of the file that Spark ships as `srs_registry.csv` (see
its header); both
//! name the same SRIDs by the same string IDs, so the JSON of a spatial type
reads on either side.
+//! `scripts/check_vendored_upstream.sh` keeps the copy byte-identical to the
file of the Spark tag
+//! that the client tracks, PySpark's `python/pyspark/sql/srs_registry.csv`.
use std::collections::HashMap;
use std::sync::OnceLock;
diff --git a/crates/spark-connect/src/types.rs
b/crates/spark-connect/src/types.rs
index af80d688..bdf0610d 100644
--- a/crates/spark-connect/src/types.rs
+++ b/crates/spark-connect/src/types.rs
@@ -1455,6 +1455,14 @@ fn parse_json_type_string(s: &str) -> Result<DataType> {
// that the drop-in's Python parser accepted before it delegated here.
"null" => Ok(DataType::Null),
"calendarinterval" => Ok(DataType::CalendarInterval),
+ // A bare spatial name is of the default CRS, `OGC:CRS84`, as Spark's
JSON reader reads
+ // it; DDL names a spatial type with its SRID only.
+ "geometry" => Ok(DataType::Geometry {
+ srid: GeometryType::DEFAULT_SRID,
+ }),
+ "geography" => Ok(DataType::Geography {
+ srid: GeographyType::DEFAULT_SRID,
+ }),
// The inverse of `json_value`, which writes
`unparsed(<data_type_string>)`.
s if s.starts_with("unparsed(") && s.ends_with(')') =>
Ok(DataType::Unparsed {
data_type_string: s["unparsed(".len()..s.len() - 1].to_string(),
@@ -1592,6 +1600,7 @@ fn parse_json_object(
/// | `interval <a> to <b>` | any two fields of one family, as
`DayTimeIntervalType(a, b)` | `b` later than `a` |
/// | `time` | not a type: the precision is required | `time(6)` |
/// | `string collate <name>` | the name as written | the name in its
canonical form, `system.builtin.` dropped |
+/// | `geometry(...)`, `geography(...)` | a CRS, and of a geography an
algorithm too (`geography(OGC:CRS84, SPHERICAL)`), or either alone, as Spark's
JSON reader; a bare `geometry` and `geography` are of `OGC:CRS84` | an SRID or
`any` (`geometry(4326)`) |
///
/// Neither checks the range of an argument, such as the precision of a
decimal: PySpark's types
/// take any, and the server refuses the type. A decimal that Arrow cannot
hold is refused when it
@@ -1673,6 +1682,10 @@ fn parse_parameterized_type(s: &str, grammar:
TypeStringGrammar) -> Option<Resul
precision: timestamp_nanos_precision(s, args)?,
})
}))
+ } else if let Some(args) = type_arguments(s, "geometry") {
+ Some(args.and_then(|args| parse_geometry(s, args, grammar)))
+ } else if let Some(args) = type_arguments(s, "geography") {
+ Some(args.and_then(|args| parse_geography(s, args, grammar)))
} else if s.starts_with("interval") {
Some(parse_interval_string(s, grammar))
} else if s
@@ -1680,10 +1693,6 @@ fn parse_parameterized_type(s: &str, grammar:
TypeStringGrammar) -> Option<Resul
.is_some_and(|rest| rest.starts_with(char::is_whitespace))
{
Some(parse_collated_string(s, grammar))
- } else if s.starts_with("geometry(") {
- Some(parse_geometry(s))
- } else if s.starts_with("geography(") {
- Some(parse_geography(s))
} else {
None
}
@@ -1831,11 +1840,7 @@ fn parse_collated_string(s: &str, grammar:
TypeStringGrammar) -> Result<DataType
}
_ => return Err(invalid()),
};
- let is_word = |c: char| match grammar {
- TypeStringGrammar::Json => c == '_' || c.is_alphanumeric(),
- TypeStringGrammar::Ddl => c == '_' || c.is_ascii_alphanumeric(),
- };
- if name.is_empty() || !name.chars().all(is_word) {
+ if !is_word(name, grammar) {
return Err(invalid());
}
Ok(DataType::String {
@@ -1846,6 +1851,17 @@ fn parse_collated_string(s: &str, grammar:
TypeStringGrammar) -> Result<DataType
})
}
+/// Whether `text` is a word: one or more letters, digits and underscores. Of
JSON they are of any
+/// script, as the `\w` of PySpark's patterns reads them, and of DDL of ASCII,
as Spark's lexer
+/// reads an unquoted identifier.
+fn is_word(text: &str, grammar: TypeStringGrammar) -> bool {
+ let is_word_char = |c: char| match grammar {
+ TypeStringGrammar::Json => c == '_' || c.is_alphanumeric(),
+ TypeStringGrammar::Ddl => c == '_' || c.is_ascii_alphanumeric(),
+ };
+ !text.is_empty() && text.chars().all(is_word_char)
+}
+
/// The parts of the multipart identifier `name` of DDL, as Spark's
`multipartIdentifier` reads
/// it: parts separated by dots, with any whitespace around them, each of them
either as it is
/// written or in backquotes, where a doubled backquote is one backquote.
`None` if `name` is
@@ -1879,36 +1895,55 @@ fn multipart_identifier(name: &str) ->
Option<Vec<String>> {
}
}
-fn parse_geometry(s: &str) -> Result<DataType> {
- let inner = s
- .strip_prefix("geometry(")
- .and_then(|s| s.strip_suffix(")"))
- .ok_or_else(|| {
- SparkError::value(
- "INVALID_DATATYPE_FORMAT",
- &[("detail", "Invalid geometry format")],
- )
- })?;
-
- let srid = spatial_srid(inner, false)?;
+/// Parses the arguments `args` of `geometry(...)`, the type string `s`: in
DDL its SRID (see
+/// [`spatial_ddl_srid`]), and in JSON its CRS, as the `geometry(<crs>)` of
Spark's JSON reader
+/// (see [`spatial_json_crs`] and [`spatial_crs_srid`]).
+fn parse_geometry(s: &str, args: &str, grammar: TypeStringGrammar) ->
Result<DataType> {
+ let srid = match grammar {
+ TypeStringGrammar::Ddl => spatial_ddl_srid(s, args, false)?,
+ TypeStringGrammar::Json => {
+ let crs =
+ spatial_json_crs(args).ok_or_else(|| invalid_type_string(s,
"geometry type"))?;
+ spatial_crs_srid(crs, false)?
+ }
+ };
Ok(DataType::Geometry { srid })
}
-fn parse_geography(s: &str) -> Result<DataType> {
- let inner = s
- .strip_prefix("geography(")
- .and_then(|s| s.strip_suffix(")"))
- .ok_or_else(|| {
- SparkError::value(
- "INVALID_DATATYPE_FORMAT",
- &[("detail", "Invalid geography format")],
- )
- })?;
-
- // The JSON form also names the algorithm, as in `OGC:CRS84, SPHERICAL`.
- let crs = inner.split(',').next().unwrap_or_default();
- let srid = spatial_srid(crs, true)?;
- Ok(DataType::Geography { srid })
+/// Parses the arguments `args` of `geography(...)`, the type string `s`: in
DDL its SRID (see
+/// [`spatial_ddl_srid`]), and in JSON its CRS, its algorithm or both, as the
patterns of Spark's
+/// JSON reader, `geography(<crs>)`, `geography(<alg>)` and `geography(<crs>,
<alg>)`, of the
+/// default CRS `OGC:CRS84` and the default algorithm `SPHERICAL`. As Spark's
+/// `GeographyType(crs, algorithm)`, the algorithm is checked before the CRS:
`SPHERICAL`, the one
+/// that Spark knows, is of any case, and another one is
`ST_INVALID_ALGORITHM_VALUE`.
+fn parse_geography(s: &str, args: &str, grammar: TypeStringGrammar) ->
Result<DataType> {
+ if grammar == TypeStringGrammar::Ddl {
+ return Ok(DataType::Geography {
+ srid: spatial_ddl_srid(s, args, true)?,
+ });
+ }
+ let invalid = || invalid_type_string(s, "geography type");
+ let (crs, algorithm) = match args.split_once(',') {
+ Some((crs, algorithm)) => (spatial_json_crs(crs).ok_or_else(invalid)?,
Some(algorithm)),
+ None => match spatial_json_crs(args) {
+ Some(crs) => (crs, None),
+ None => (GeographyType::DEFAULT_CRS, Some(args)),
+ },
+ };
+ if let Some(algorithm) = algorithm.map(str::trim) {
+ if !is_word(algorithm, grammar) {
+ return Err(invalid());
+ }
+ if !algorithm.eq_ignore_ascii_case(GeographyType::DEFAULT_ALG) {
+ return Err(SparkError::value(
+ "ST_INVALID_ALGORITHM_VALUE",
+ &[("alg", algorithm)],
+ ));
+ }
+ }
+ Ok(DataType::Geography {
+ srid: spatial_crs_srid(crs, true)?,
+ })
}
/// The coordinate reference system that a spatial type's SRID is named by in
its JSON, as
@@ -1925,31 +1960,51 @@ fn spatial_crs(srid: i32, geographic: bool) -> String {
}
}
-/// The SRID that a spatial type of the given kind names by `text`, the CRS of
its JSON or the
-/// SRID of its DDL: `any` or `SRID:ANY` (of any case) for a mixed SRID, a
string ID that Spark
-/// reads (its aliases included, and the match is exact), or an integer SRID.
An integer that the
-/// type does not take is `ST_INVALID_SRID_VALUE`, and any other text that is
no CRS of the type
-/// is `ST_INVALID_CRS_VALUE`, as the parsers of Spark raise them.
-fn spatial_srid(text: &str, geographic: bool) -> Result<i32> {
- let text = text.trim();
- if text.eq_ignore_ascii_case("any") ||
text.eq_ignore_ascii_case(SpatialType::MIXED_CRS) {
+/// The CRS `text` of the JSON of a spatial type, without the whitespace
around it, if it is of
+/// the form of the patterns of Spark's JSON reader, `\w+:-?\w+`: a word, a
colon, and a word that
+/// may follow a minus sign, as `EPSG:2154`, `OGC:CRS84` and `SRID:ANY`.
`None` if it is not, as
+/// `4326`, `any` and `SPHERICAL` are not.
+fn spatial_json_crs(text: &str) -> Option<&str> {
+ let crs = text.trim();
+ let (authority, code) = crs.split_once(':')?;
+ let code = code.strip_prefix('-').unwrap_or(code);
+ (is_word(authority, TypeStringGrammar::Json) && is_word(code,
TypeStringGrammar::Json))
+ .then_some(crs)
+}
+
+/// The SRID of the CRS `crs` of the JSON of a spatial type of the given kind,
as Spark's
+/// `GeometryType.toSrid` and `GeographyType.toSrid` read it: `SRID:ANY`, of
any case, is the mixed
+/// SRID, and another CRS is the SRID of the string ID of Spark's registry
that it is (the aliases
+/// included, and the match is exact) if the type takes it, else
`ST_INVALID_CRS_VALUE`.
+fn spatial_crs_srid(crs: &str, geographic: bool) -> Result<i32> {
+ if crs.eq_ignore_ascii_case(SpatialType::MIXED_CRS) {
return Ok(SpatialType::MIXED_SRID);
}
- if let Some(srid) = srs::srid(text, geographic) {
- return Ok(srid);
+ srs::srid(crs, geographic)
+ .ok_or_else(|| SparkError::value("ST_INVALID_CRS_VALUE", &[("crs",
crs)]))
+}
+
+/// The SRID of the argument `args` of the DDL `s` of a spatial type of the
given kind, as Spark's
+/// parser reads `GEOMETRY(<srid>)` and `GEOGRAPHY(<srid>)`, whose argument is
the keyword `ANY` or
+/// an unsigned integer: `any`, of any case, is the mixed SRID, and an integer
is an SRID that the
+/// type must take, else `ST_INVALID_SRID_VALUE`, as an integer out of the
32-bit range is too.
+/// Any other text, such as `-1`, `+5` or a CRS, is not of Spark's grammar,
whose
+/// `PARSE_SYNTAX_ERROR` it is: the `INVALID_DATATYPE_FORMAT` of a malformed
type of this parser.
+fn spatial_ddl_srid(s: &str, args: &str, geographic: bool) -> Result<i32> {
+ let text = args.trim();
+ if text.eq_ignore_ascii_case("any") {
+ return Ok(SpatialType::MIXED_SRID);
}
- let digits = text.strip_prefix(['+', '-']).unwrap_or(text);
- if !digits.is_empty() && digits.bytes().all(|b| b.is_ascii_digit()) {
- return match text.parse::<i32>() {
- Ok(srid) if srs::is_supported(srid, geographic) => Ok(srid),
- // An integer out of the 32-bit range is an SRID too, as in
Spark's parser.
- _ => Err(SparkError::value(
- "ST_INVALID_SRID_VALUE",
- &[("srid", text)],
- )),
- };
+ if text.is_empty() || !text.bytes().all(|b| b.is_ascii_digit()) {
+ return Err(invalid_type_string(s, "type argument"));
+ }
+ let invalid_srid = |srid: &str| SparkError::value("ST_INVALID_SRID_VALUE",
&[("srid", srid)]);
+ match text.parse::<i32>() {
+ Ok(srid) if srs::is_supported(srid, geographic) => Ok(srid),
+ // The SRID that the type is made of, as Spark's `GeometryType(srid)`
names it.
+ Ok(srid) => Err(invalid_srid(&srid.to_string())),
+ Err(_) => Err(invalid_srid(text)),
}
- Err(SparkError::value("ST_INVALID_CRS_VALUE", &[("crs", text)]))
}
/// Main DDL parser: parses DDL strings into DataType.
@@ -3788,7 +3843,8 @@ mod tests {
#[test]
fn test_from_json_geometry() {
- let json_geom = serde_json::json!("geometry(any)");
+ // JSON names the mixed SRID by its CRS, `SRID:ANY`; `geometry(any)`
is its DDL.
+ let json_geom = serde_json::json!("geometry(SRID:ANY)");
let dt = DataType::from_json(&json_geom).unwrap();
match dt {
DataType::Geometry { srid } => {
diff --git a/crates/spark-connect/tests/e2e_session_catalog.rs
b/crates/spark-connect/tests/e2e_session_catalog.rs
index 0577acbb..67ddd3e4 100644
--- a/crates/spark-connect/tests/e2e_session_catalog.rs
+++ b/crates/spark-connect/tests/e2e_session_catalog.rs
@@ -450,6 +450,89 @@ fn spatial_json_with_an_epsg_crs_is_read_by_the_server() {
let _ = spark.stop();
}
+/// `DataType::from_json` reads the spatial forms of JSON as the server's JSON
reader does
+/// (`json_to_ddl`), and `from_ddl` those of DDL as the server's parser does
(`parse_ddl`): the
+/// same type, or an error, which is the server's `ST_*` error with its
parameters where the
+/// server raises one, and a format error where the server's grammar does not
take the form.
+#[test]
+fn spatial_type_strings_are_read_as_the_server_reads_them() {
+ if !should_run() {
+ return;
+ }
+ use spark_connect::types::DataType;
+ use spark_connect::SparkError;
+ fn same_error(text: &str, ours: spark_connect::Result<DataType>, theirs:
SparkError) {
+ let ours = ours.expect_err(text);
+ if theirs.error_class.starts_with("ST_") {
+ assert_eq!(ours.error_class, theirs.error_class, "{text}");
+ assert_eq!(ours.params, theirs.params, "{text}");
+ } else {
+ assert!(
+ matches!(
+ ours.error_class.as_str(),
+ "INVALID_DATATYPE_FORMAT" | "INVALID_DATATYPE_STRING"
+ ),
+ "{text}: {ours:?}, and the server's {theirs:?}"
+ );
+ }
+ }
+ let spark = session();
+ for json in [
+ "geometry",
+ "geography",
+ "geometry(EPSG:2154)",
+ "geometry( SRID:ANY )",
+ "geometry(EPSG:-5)",
+ "geometry(4326)",
+ "geometry(any)",
+ "geometry(a:b:c)",
+ "geography(spherical)",
+ "geography(PLANAR)",
+ "geography(4326)",
+ "geography(EPSG:4269)",
+ "geography(OGC:CRS84, Spherical)",
+ "geography(FOO:1, PLANAR)",
+ "geography(FOO:1, SPHERICAL)",
+ "geography(OGC:CRS84, SPHERICAL, X)",
+ ] {
+ let schema = serde_json::json!({
+ "type": "struct",
+ "fields": [{"name": "g", "type": json, "nullable": true,
"metadata": {}}],
+ });
+ let ours =
DataType::from_json(&serde_json::Value::String(json.to_string()));
+ match spark.json_to_ddl(&schema.to_string()) {
+ // The DDL of the field, as `g GEOMETRY(2154)`.
+ Ok(ddl) => {
+ let theirs = DataType::from_ddl(ddl.strip_prefix("g
").expect(&ddl)).expect(&ddl);
+ assert_eq!(ours.expect(json), theirs, "JSON {json}");
+ }
+ Err(theirs) => same_error(json, ours, theirs),
+ }
+ }
+ for ddl in [
+ "GEOMETRY(2154)",
+ "GEOMETRY( 04326 )",
+ "GEOMETRY(any)",
+ "GEOGRAPHY(4269)",
+ "GEOMETRY(99999)",
+ "GEOMETRY(099999)",
+ "GEOMETRY(99999999999)",
+ "GEOGRAPHY(3857)",
+ "GEOMETRY(-1)",
+ "GEOMETRY(+5)",
+ "GEOMETRY(SRID:ANY)",
+ "GEOMETRY(EPSG:2154)",
+ "GEOGRAPHY(4326, SPHERICAL)",
+ "GEOMETRY",
+ ] {
+ match spark.parse_ddl(ddl) {
+ Ok(theirs) => assert_eq!(DataType::from_ddl(ddl).expect(ddl),
theirs, "DDL {ddl}"),
+ Err(theirs) => same_error(ddl, DataType::from_ddl(ddl), theirs),
+ }
+ }
+ let _ = spark.stop();
+}
+
/// The execution that the calling thread waits for is the one that its wait
interrupts, as
/// PySpark's `KeyboardInterrupt` does: the wait ends with the server's
cancellation, and the
/// session goes on.
diff --git a/crates/spark-connect/tests/types_roundtrip.rs
b/crates/spark-connect/tests/types_roundtrip.rs
index c60a83c2..b3019146 100644
--- a/crates/spark-connect/tests/types_roundtrip.rs
+++ b/crates/spark-connect/tests/types_roundtrip.rs
@@ -1214,8 +1214,106 @@ fn
spatial_json_rejects_a_crs_that_spark_does_not_take() {
}
}
+/// The JSON of a spatial type is read as Spark's JSON reader reads it: a bare
`geometry` or
+/// `geography`, and a geography of an algorithm alone, are of `OGC:CRS84`; a
CRS is of the form
+/// `\w+:-?\w+`; and the algorithm is `SPHERICAL`, of any case, checked before
the CRS. The SRID
+/// and the `any` of DDL are not JSON.
+#[test]
+fn spatial_json_reads_the_forms_of_the_json_reader_of_spark() {
+ let json = |text: &str| serde_json::Value::String(text.to_string());
+ for (text, expected) in [
+ ("geometry", DataType::Geometry { srid: 4326 }),
+ ("geography", DataType::Geography { srid: 4326 }),
+ ("geography(SPHERICAL)", DataType::Geography { srid: 4326 }),
+ ("geography( Spherical )", DataType::Geography { srid: 4326 }),
+ ("geography(OGC:CRS83)", DataType::Geography { srid: 4269 }),
+ (
+ "geography(OGC:CRS84, spherical)",
+ DataType::Geography { srid: 4326 },
+ ),
+ (
+ "geography( srid:any , spherical )",
+ DataType::Geography { srid: -1 },
+ ),
+ ("geometry( EPSG:2154 )", DataType::Geometry { srid: 2154 }),
+ ] {
+ let read = DataType::from_json(&json(text)).expect(text);
+ assert_eq!(read, expected, "{text}");
+ }
+ // An algorithm that Spark does not know, which is checked before the CRS,
and a CRS of the
+ // form of the patterns that Spark does not know.
+ for (text, error_class, param) in [
+ (
+ "geography(OGC:CRS84, PLANAR)",
+ "ST_INVALID_ALGORITHM_VALUE",
+ ("alg", "PLANAR"),
+ ),
+ (
+ "geography(FOO:1, PLANAR)",
+ "ST_INVALID_ALGORITHM_VALUE",
+ ("alg", "PLANAR"),
+ ),
+ (
+ "geography(PLANAR)",
+ "ST_INVALID_ALGORITHM_VALUE",
+ ("alg", "PLANAR"),
+ ),
+ (
+ "geography(4326)",
+ "ST_INVALID_ALGORITHM_VALUE",
+ ("alg", "4326"),
+ ),
+ (
+ "geography(any)",
+ "ST_INVALID_ALGORITHM_VALUE",
+ ("alg", "any"),
+ ),
+ (
+ "geography(FOO:1, SPHERICAL)",
+ "ST_INVALID_CRS_VALUE",
+ ("crs", "FOO:1"),
+ ),
+ (
+ "geometry(EPSG:-5)",
+ "ST_INVALID_CRS_VALUE",
+ ("crs", "EPSG:-5"),
+ ),
+ ] {
+ let error = DataType::from_json(&json(text)).expect_err(text);
+ assert_eq!(error.error_class, error_class, "{text}");
+ let expected = BTreeMap::from([(param.0.to_string(),
param.1.to_string())]);
+ assert_eq!(error.params, expected, "{text}");
+ }
+ // No form of the patterns: the SRID and the `any` of DDL, a CRS that is
not `\w+:-?\w+`, an
+ // algorithm of a geometry, a third argument, an empty one, and whitespace
after a bare name.
+ for text in [
+ "geometry(4326)",
+ "geometry(any)",
+ "geometry(a:b:c)",
+ "geometry(EPSG:2154, SPHERICAL)",
+ "geography(OGC:CRS84, SPHERICAL, X)",
+ "geography(OGC:CRS84,)",
+ "geography(, SPHERICAL)",
+ "geometry()",
+ "geography()",
+ "geometry ",
+ "geography ",
+ ] {
+ let error = DataType::from_json(&json(text)).expect_err(text);
+ assert!(
+ matches!(
+ error.error_class.as_str(),
+ "INVALID_DATATYPE_FORMAT" | "INVALID_DATATYPE_STRING"
+ ),
+ "{text}: {error:?}"
+ );
+ }
+}
+
/// The DDL of a spatial type names its SRID by its number, or `any`, and
Spark's parser rejects an
-/// SRID that the type does not take with `ST_INVALID_SRID_VALUE`.
+/// SRID that the type does not take with `ST_INVALID_SRID_VALUE`, which names
the SRID as the
+/// type would. Its grammar takes no other argument: a signed number or a CRS
is a syntax error,
+/// which is the format error of `from_ddl`.
#[test]
fn spatial_ddl_checks_the_srid_as_spark_does() {
assert_eq!(
@@ -1226,15 +1324,36 @@ fn spatial_ddl_checks_the_srid_as_spark_does() {
DataType::from_ddl("geography(4269)").unwrap(),
DataType::Geography { srid: 4269 }
);
+ assert_eq!(
+ DataType::from_ddl("GEOMETRY( 04326 )").unwrap(),
+ DataType::Geometry { srid: 4326 }
+ );
+ for (ddl, srid) in [
+ ("geometry(99999)", "99999"),
+ ("geometry(099999)", "99999"),
+ ("geometry(99999999999)", "99999999999"),
+ ("geography(3857)", "3857"),
+ ("geography(0)", "0"),
+ ] {
+ let error = DataType::from_ddl(ddl).expect_err(ddl);
+ assert_eq!(error.error_class, "ST_INVALID_SRID_VALUE", "{ddl}");
+ let expected = BTreeMap::from([("srid".to_string(),
srid.to_string())]);
+ assert_eq!(error.params, expected, "{ddl}");
+ }
for ddl in [
- "geometry(99999)",
"geometry(-1)",
- "geometry(99999999999)",
- "geography(3857)",
- "geography(0)",
+ "geometry(+5)",
+ "geometry(SRID:ANY)",
+ "geometry(EPSG:2154)",
+ "geometry(5L)",
+ "geography(-1)",
+ "geography(4326, SPHERICAL)",
+ "geography(OGC:CRS84)",
+ "geometry",
+ "geography",
] {
let error = DataType::from_ddl(ddl).expect_err(ddl);
- assert_eq!(error.error_class, "ST_INVALID_SRID_VALUE", "{ddl}");
+ assert_eq!(error.error_class, "INVALID_DATATYPE_FORMAT", "{ddl}");
}
// An SRID that Spark does not know is written `SRID:<srid>` in JSON,
which Spark rejects too.
assert_eq!(
@@ -1354,6 +1473,8 @@ fn
json_and_ddl_parsers_agree_on_the_atomic_and_parameterized_forms() {
start_field,
end_field,
};
+ let geometry = |srid| DataType::Geometry { srid };
+ let geography = |srid| DataType::Geography { srid };
// The same type of both parsers.
let same: Vec<(&str, DataType)> = vec![
@@ -1424,10 +1545,6 @@ fn
json_and_ddl_parsers_agree_on_the_atomic_and_parameterized_forms() {
"string collate sr_Cyrl_SRB_CI_AI",
string("sr_Cyrl_SRB_CI_AI"),
),
- // The spatial types, of an SRID or of a CRS.
- ("geometry(4326)", DataType::Geometry { srid: 4326 }),
- ("geometry(any)", DataType::Geometry { srid: -1 }),
- ("geography(4326)", DataType::Geography { srid: 4326 }),
];
for (text, expected) in &same {
assert_eq!(
@@ -1496,6 +1613,17 @@ fn
json_and_ddl_parsers_agree_on_the_atomic_and_parameterized_forms() {
"string collate sys tem.builtin.utf8_lcase",
"string collate system . . utf8_lcase",
"char(5) collate UNICODE",
+ // A spatial type of a signed SRID, of an algorithm that is not
SPHERICAL or of more than a
+ // CRS and an algorithm, of an SRID that the type does not take, or of
no argument.
+ "geometry(-1)",
+ "geometry(+5)",
+ "geography(-1)",
+ "geography(OGC:CRS84, PLANAR)",
+ "geography(OGC:CRS84, SPHERICAL, X)",
+ "geometry(99999)",
+ "geography(3857)",
+ "geometry()",
+ "geography()",
// Not a type.
"",
"foo",
@@ -1632,6 +1760,28 @@ fn
json_and_ddl_parsers_agree_on_the_atomic_and_parameterized_forms() {
}),
None,
),
+ // The JSON of a spatial type names its CRS, and that of a geography
its algorithm too, or
+ // either alone, as Spark's JSON reader reads them: a bare name is of
`OGC:CRS84`, and the
+ // algorithm is of any case. Its DDL names the SRID, or `any`, of any
case.
+ ("geometry", Some(geometry(4326)), None),
+ ("geography", Some(geography(4326)), None),
+ ("geometry(OGC:CRS84)", Some(geometry(4326)), None),
+ ("geometry(EPSG:2154)", Some(geometry(2154)), None),
+ ("geometry(SRID:ANY)", Some(geometry(-1)), None),
+ ("geometry(srid:any)", Some(geometry(-1)), None),
+ ("geography(SPHERICAL)", Some(geography(4326)), None),
+ ("geography(OGC:CRS83)", Some(geography(4269)), None),
+ (
+ "geography(OGC:CRS84, spherical)",
+ Some(geography(4326)),
+ None,
+ ),
+ ("geometry(4326)", None, Some(geometry(4326))),
+ ("geometry( 2154 )", None, Some(geometry(2154))),
+ ("geometry(any)", None, Some(geometry(-1))),
+ ("GEOMETRY(ANY)", None, Some(geometry(-1))),
+ ("geography(4326)", None, Some(geography(4326))),
+ ("geography(any)", None, Some(geography(-1))),
];
for (text, json, ddl) in &differ {
assert_ne!(json, ddl, "{text:?} is not a difference");
@@ -1674,6 +1824,8 @@ fn
json_and_ddl_parsers_agree_on_the_atomic_and_parameterized_forms() {
"interval ",
"string ",
"time ",
+ "geometry ",
+ "geography ",
] {
assert_eq!(parsed_as_json(text), None, "JSON {text:?}");
}
diff --git a/docs/compatibility.md b/docs/compatibility.md
index ac2b542a..3f594bea 100644
--- a/docs/compatibility.md
+++ b/docs/compatibility.md
@@ -189,6 +189,14 @@ as before. `None` sends no storage level, as PySpark's
`persist(None)`, and the
caches at its `spark.sql.defaultCacheStorageLevel`. `cache` is unchanged and
persists at
`MEMORY_AND_DISK_DESER`.
+`DataType::from_json` reads the spatial types as the JSON reader of Spark
does: a bare
+`geometry` or `geography` is of SRID 4326, `geography(<algorithm>)` is of the
CRS `OGC:CRS84`, a
+CRS is of the form `<authority>:<code>`, and an algorithm other than
`SPHERICAL` is
+`ST_INVALID_ALGORITHM_VALUE`. It no longer takes `geometry(<srid>)`,
`geometry(any)` and their
+`geography` forms, which are of the DDL, not of the JSON, of Spark.
`DataType::from_ddl` takes a
+number or `any` as an SRID, as the DDL parser of Spark does, and no longer
takes such forms as
+`geometry(+5)`, `geometry(SRID:ANY)` or `geography(4326, SPHERICAL)`.
+
## Native LogisticRegression
The native `spark_connect::ml::LogisticRegression` fits Spark's JVM
diff --git a/docs/contributing.md b/docs/contributing.md
index 90f68d43..11a3d232 100644
--- a/docs/contributing.md
+++ b/docs/contributing.md
@@ -180,10 +180,12 @@ listed tests that now pass, to be removed from the list.
### Vendored and generated code
Many modules under `python/pyspark` are verbatim copies of PySpark 4.3.0, such
as
-`pyspark.pandas`, `pyspark.cloudpickle` and much of `pyspark.ml` and
`pyspark.errors`.
-Do not edit them: they are listed in `scripts/check_vendored_upstream.sh` and
in the ruff
-excludes of `pyproject.toml`, and CI fails when one that the script lists
differs from
-the `v4.3.0` tag (the script fetches it from GitHub):
+`pyspark.pandas`, `pyspark.cloudpickle` and much of `pyspark.ml` and
`pyspark.errors`, and so
+is Spark's spatial reference system registry that the Rust crate embeds,
+`crates/spark-connect/src/srs_registry.csv`. Do not edit them: they are listed
in
+`scripts/check_vendored_upstream.sh` (and the Python ones in the ruff excludes
of
+`pyproject.toml`), and CI fails when one that the script lists differs from
the `v4.3.0` tag
+(the script fetches it from GitHub):
```bash
bash scripts/check_vendored_upstream.sh
diff --git a/docs/types.md b/docs/types.md
index 481aaf5f..1a741bf0 100644
--- a/docs/types.md
+++ b/docs/types.md
@@ -135,8 +135,10 @@ does not decode. To read one as JSON, select `to_json` of
it on the server.
A spatial type has the SRID of the spatial reference system of its values, or
allows any
SRID, which is `srid: -1` (`SpatialType::MIXED_SRID`) and `any` in DDL. A
value is collected as
a struct of its SRID and its WKB (well-known binary) geometry, and
`create_dataframe` takes the
-same struct. `from_ddl` checks the SRID as Spark's parser does: an SRID that
the type does not
-take, such as 99999, or a geography of 3857, is `ST_INVALID_SRID_VALUE`.
+same struct. `from_ddl` reads the SRID as Spark's parser does, of digits or
`any`: an SRID that
+the type does not take, such as 99999, or a geography of 3857, is
`ST_INVALID_SRID_VALUE`, and
+another argument, such as `-1`, `+5` or a CRS (`EPSG:2154`), is not one of
Spark's grammar, so it
+is an `INVALID_DATATYPE_FORMAT` error, where the server's parser raises
`PARSE_SYNTAX_ERROR`.
The SRIDs are those of Spark's spatial reference system registry (about 10,700
systems, embedded
from Spark's `srs_registry.csv`). A geometry takes any of them, and a
geography only a geographic
@@ -144,13 +146,21 @@ one. The JSON of a spatial type (`json()`) names its
reference system by the str
writes: `geometry(OGC:CRS84)` is SRID 4326, `geometry(EPSG:2154)` is SRID 2154
and
`geometry(SRID:0)` is SRID 0; a geography also names its algorithm, as
`geography(OGC:CRS83, SPHERICAL)` for SRID 4269. `DataType::from_json` and the
server read these
-back, and the aliases of the OGC systems, such as `EPSG:4269`, too. A CRS that
Spark does not
-know, or that the type does not take, is `ST_INVALID_CRS_VALUE`. DDL, and the
protobuf form in
-which the server sends a schema, carry any SRID.
+back, and the aliases of the OGC systems, such as `EPSG:4269`, too. As Spark's
JSON reader,
+`from_json` reads a bare `geometry` and `geography`, and a geography of its
algorithm alone
+(`geography(SPHERICAL)`), as of `OGC:CRS84`. The algorithm is `SPHERICAL` of
any case, and
+another one is `ST_INVALID_ALGORITHM_VALUE`. A CRS is of the form
`<authority>:<code>`, and one
+that Spark does not know, or that the type does not take, is
`ST_INVALID_CRS_VALUE`. The SRIDs
+and the `any` of DDL, as `geometry(4326)`, are not JSON. DDL, and the protobuf
form in which the
+server sends a schema, carry any SRID.
The drop-in is stricter, as PySpark 4.3.0 is: its `GeometryType` takes the
SRIDs 0, 3857 and 4326,
-and its `GeographyType` 4326, and it reads only the CRS names that those take,
so a schema of the
-server with another SRID raises `ST_INVALID_SRID_VALUE` when its type is read.
+and its `GeographyType` 4326, and it reads only the CRS names that those take,
and the algorithm
+`SPHERICAL` only in upper case. A schema of the server with another SRID raises
+`ST_INVALID_SRID_VALUE` wherever PySpark converts the schema, also of a type
nested in an array, a
+map or a struct: `df.schema`, `columns`, `dtypes`, `repr(df)`,
`printSchema()`, the collecting
+APIs (`collect`, `toPandas`, `toArrow`, ...) and a DDL schema, which the
server parses. `count`
+and `show` read no schema, and work.
### Other types
diff --git a/python/tests/test_dropin_offline.py
b/python/tests/test_dropin_offline.py
index d40a85bd..1f6ece0e 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -314,6 +314,83 @@ def
test_schema_spatial_srids_are_those_of_pyspark(mock_connect):
assert e.value.getMessageParameters() == {"srid": str(srid)}
+def
test_schema_surfaces_raise_for_a_spatial_srid_that_pyspark_does_not_take(mock_connect):
+ # As PySpark, which converts the schema from its proto wherever it reads
it: the schema, the
+ # columns, the dtypes, repr, printSchema, the columns of a projection and
a DDL schema that
+ # the server parses raise ST_INVALID_SRID_VALUE for an SRID that PySpark
does not take, also
+ # nested in an array, a map or a struct, while the SRIDs that it takes are
read. The first
+ # type that the conversion fails on decides, a nanosecond timestamp's
UNSUPPORTED_OPERATION
+ # included.
+ from pyspark.errors import IllegalArgumentException, PySparkValueError
+
+ spark, service = mock_connect
+ # repr reads the settings of the eager evaluation of the session, which
the server has.
+ service.confs = {"spark.sql.repl.eagerEval.enabled": "false",
+ "spark.sql.repl.eagerEval.maxNumRows": "20",
+ "spark.sql.repl.eagerEval.truncate": "20"}
+
+ def spatial(kind, srid):
+ # DataType.geometry=26 or geography=27, with its srid=1.
+ return message_field(26 if kind == "geometry" else 27, varint_field(1,
srid))
+
+ def struct(*fields):
+ # StructField: name=1, data_type=2, nullable=3; Struct.fields=1, and
DataType.struct=21.
+ return message_field(21, b"".join(
+ message_field(1, message_field(1, name) + message_field(2,
data_type)
+ + varint_field(3, 1))
+ for name, data_type in fields))
+
+ # DataType.long=7, string=11, array=20 (Array.element_type=1) and map=22
(Map.key_type=1,
+ # value_type=2), and timestamp_ntz_nanos=29 (precision=1).
+ long_type, string_type = message_field(7, b""), message_field(11, b"")
+ nanos = message_field(29, varint_field(1, 9))
+ for schema, srid in [
+ (struct(("g", spatial("geometry", 2154))), 2154),
+ (struct(("i", long_type), ("g", message_field(20, message_field(
+ 1, spatial("geography", 4269)) + varint_field(2, 1)))), 4269),
+ (struct(("g", message_field(22, message_field(1, string_type) +
message_field(
+ 2, spatial("geometry", 2154)) + varint_field(3, 1)))), 2154),
+ (struct(("s", struct(("g", spatial("geography", 3857))))), 3857),
+ (struct(("g", spatial("geometry", 2154)), ("t", nanos)), 2154),
+ ]:
+ service.data_type = schema
+ df = spark.range(1)
+ for surface in (
+ lambda: df.schema,
+ lambda: df.columns,
+ lambda: df.dtypes,
+ lambda: repr(df),
+ lambda: df.printSchema(),
+ lambda: df.select("g").columns,
+ ):
+ with pytest.raises(IllegalArgumentException) as e:
+ surface()
+ assert e.value.getCondition() == "ST_INVALID_SRID_VALUE"
+ assert e.value.getMessageParameters() == {"srid": str(srid)}
+ # A DDL schema, which the server parses (the mock parses these).
+ for ddl, srid in [("g geometry(2154)", 2154), ("g array<geography(4269)>",
4269)]:
+ with pytest.raises(IllegalArgumentException) as e:
+ spark.createDataFrame([], ddl)
+ assert e.value.getCondition() == "ST_INVALID_SRID_VALUE"
+ assert e.value.getMessageParameters() == {"srid": str(srid)}
+ # A nanosecond timestamp before the spatial type is the error of the
timestamp.
+ service.data_type = struct(("t", nanos), ("g", spatial("geometry", 2154)))
+ with pytest.raises(PySparkValueError) as e:
+ spark.range(1).columns
+ assert e.value.getCondition() == "UNSUPPORTED_OPERATION"
+ for kind, srid, simple in [
+ ("geometry", 3857, "geometry(3857)"),
+ ("geometry", 0, "geometry(0)"),
+ ("geometry", -1, "geometry(any)"),
+ ("geography", 4326, "geography(4326)"),
+ ]:
+ service.data_type = struct(("g", spatial(kind, srid)))
+ df = spark.range(1)
+ assert df.columns == ["g"]
+ assert df.dtypes == [("g", simple)]
+ assert repr(df) == f"DataFrame[g: {simple}]"
+
+
def test_json_forms_accept_trailing_whitespace_as_pyspark(mock_connect):
# As PySpark's `_parse_datatype_json_value`, whose patterns match a prefix
of the string: the
# whitespace after a form with an argument or a field is not a part of it.
A bare name is
diff --git a/scripts/check_vendored_upstream.sh
b/scripts/check_vendored_upstream.sh
index f38449a9..573467d2 100644
--- a/scripts/check_vendored_upstream.sh
+++ b/scripts/check_vendored_upstream.sh
@@ -21,7 +21,8 @@
# re-vendoring. Fails CI on drift.
#
# Extend VENDORED_DIRS (whole byte-identical trees) or VENDORED_FILES
(individual
-# byte-identical files whose sibling files are fork-adapted) as more is
vendored.
+# byte-identical files whose sibling files are fork-adapted) as more is
vendored, and
+# VENDORED_MAPPED_FILES for a byte-identical copy outside python/pyspark.
# Do NOT list Rust-backed shims here (anything importing `pyspark._pyspark`),
nor
# fork-adapted files (e.g. pipelines/api.py) — those intentionally differ from
upstream.
set -euo pipefail
@@ -269,6 +270,15 @@ VENDORED_FILES=(
"testing/utils.py"
)
+# Files vendored verbatim from upstream to a path of this repo outside
python/pyspark, as
+# "<path in this repo>=<path in Apache Spark>". Keep these byte-identical to
the tag.
+VENDORED_MAPPED_FILES=(
+ # Spark's spatial reference system registry, which the Rust crate embeds
(srs.rs) to map the
+ # SRIDs of the spatial types to their CRS strings. Spark generates it from
PROJ
+ # (dev/generate_srs_registry.py) and ships the same file in sql/api and in
PySpark.
+
"crates/spark-connect/src/srs_registry.csv=python/pyspark/sql/srs_registry.csv"
+)
+
REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
WORK="$(mktemp -d)"
trap 'rm -rf "$WORK"' EXIT
@@ -279,36 +289,47 @@ sparse_paths=("${VENDORED_DIRS[@]}")
for f in "${VENDORED_FILES[@]}"; do
sparse_paths+=("$(dirname "${f}")")
done
+sparse_paths=("${sparse_paths[@]/#/python/pyspark/}")
+for m in "${VENDORED_MAPPED_FILES[@]}"; do
+ sparse_paths+=("$(dirname "${m#*=}")")
+done
echo "Fetching Apache Spark ${SPARK_TAG} (sparse, blobless) ..."
git clone --quiet --depth 1 --branch "${SPARK_TAG}" --filter=blob:none
--sparse \
"${SPARK_REPO}" "${WORK}/spark"
-( cd "${WORK}/spark" && git sparse-checkout set \
- "${sparse_paths[@]/#/python/pyspark/}" >/dev/null )
+( cd "${WORK}/spark" && git sparse-checkout set "${sparse_paths[@]}"
>/dev/null )
status=0
-check_one() {
- local p="$1" flag="$2" extra_exclude="${3:-}"
- local ours="${REPO_ROOT}/python/pyspark/${p}"
- local theirs="${WORK}/spark/python/pyspark/${p}"
+# Compare the path $1 of this repo with the path $2 of Apache Spark at the tag.
+check_paths() {
+ local ours_path="$1" theirs_path="$2" flag="$3" extra_exclude="${4:-}"
+ local ours="${REPO_ROOT}/${ours_path}"
+ local theirs="${WORK}/spark/${theirs_path}"
+ local name="${ours_path}"
+ [[ "${ours_path}" != "${theirs_path}" ]] && name="${ours_path} (upstream
${theirs_path})"
# Always ignore __pycache__; a caller may add one more --exclude (e.g.
`tests` for the
# whole pandas tree, which upstream ships but we intentionally do not
vendor).
local excludes=(--exclude=__pycache__)
[[ -n "${extra_exclude}" ]] && excludes+=(--exclude="${extra_exclude}")
if [[ ! -e "${theirs}" ]]; then
- echo "ERROR: upstream path python/pyspark/${p} not found at ${SPARK_TAG}"
+ echo "ERROR: upstream path ${theirs_path} not found at ${SPARK_TAG}"
status=1
return
fi
if diff ${flag} "${excludes[@]}" "${ours}" "${theirs}" >/dev/null; then
- echo "OK python/pyspark/${p} matches Apache Spark ${SPARK_TAG}"
+ echo "OK ${name} matches Apache Spark ${SPARK_TAG}"
else
- echo "DRIFT python/pyspark/${p} differs from Apache Spark ${SPARK_TAG}:"
+ echo "DRIFT ${name} differs from Apache Spark ${SPARK_TAG}:"
diff ${flag} "${excludes[@]}" "${ours}" "${theirs}" || true
status=1
fi
}
+# Compare the path $1 under python/pyspark with the same path upstream.
+check_one() {
+ check_paths "python/pyspark/$1" "python/pyspark/$1" "$2" "${3:-}"
+}
+
for p in "${VENDORED_DIRS[@]}"; do
# The pandas-on-Spark tree is vendored in full EXCEPT its tests/ (which we
do not ship).
if [[ "${p}" == "pandas" ]]; then
@@ -320,6 +341,9 @@ done
for p in "${VENDORED_FILES[@]}"; do
check_one "${p}" ""
done
+for m in "${VENDORED_MAPPED_FILES[@]}"; do
+ check_paths "${m%%=*}" "${m#*=}" ""
+done
if [[ "${status}" -ne 0 ]]; then
echo
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]