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 a8bd7f00 [SPARK-61442][CONNECT][FOLLOWUP] Read trailing whitespace in
JSON type strings and backquoted collation names in DDL, as PySpark and Spark do
a8bd7f00 is described below
commit a8bd7f0067538a9a07cbe01951dd6c42119eddbe
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Thu Nov 12 09:50:04 2026 +0900
[SPARK-61442][CONNECT][FOLLOWUP] Read trailing whitespace in JSON type
strings and backquoted collation names in DDL, as PySpark and Spark do
### What changes were proposed in this pull request?
A follow-up of #510 (SPARK-61442), from a review of it
(`crates/spark-connect/src/types.rs`):
- **JSON reads whitespace after a form with arguments or fields**, as
PySpark's `_parse_datatype_json_value` does with its `re.match` patterns, and
as this client did before #510: `"string collate UNICODE "`, `"interval day "`,
`"interval day to second "`, `"decimal(10,2) "` and the like. A bare name with
whitespace after it (`"integer "`, `"interval "`) is still not a type, as in
PySpark.
- **DDL reads a collation name in backquotes**, in each part of a qualified
name too (`` string collate `UTF8_LCASE` ``, `` `system`.`builtin`.`utf8_lcase`
``, also in a struct field with a comment), with a doubled backquote read as
one, as Spark's parser unquotes a `multipartIdentifier`. It gives the canonical
name that the server gives. An unquoted name is of ASCII letters, digits and
underscores only, as Spark's lexer reads it, so `string collate été` is an
error of DDL, as it is o [...]
- **A bare `time` is no longer a JSON type**: Spark and PySpark name a time
in JSON with its precision only (`TimeType().json()` is `"time(6)"`, and
PySpark 4.3.0 raises CANNOT_PARSE_DATATYPE for `"time"`). DDL `time` is still
`time(6)`, as the server reads it.
- **`null` is no longer a DDL type**, as the server's DDL parser rejects
it. JSON keeps reading `null`, which Spark's JSON reader accepts for the
schemas written before NullType was named `void`; it is now listed in the test
as a documented difference from PySpark.
`char(n) collate X` and `varchar(n) collate X` stay errors: Spark accepts
them, but the Connect protocol's `Char` and `VarChar` carry no collation (the
server's own DDL parse of `char(3) collate UNICODE` returns `char(3)`), so
reading them would drop the collation silently.
### Why are the changes needed?
#510 made both parsers reject trailing whitespace that PySpark and the
earlier code accept, and DDL rejected the backquoted collation names that Spark
accepts. The test table of #510 also listed two JSON forms that PySpark rejects
as forms that both parsers read the same.
### Does this PR introduce _any_ user-facing change?
Yes, on unreleased behavior, in `DataType::from_json` / `from_ddl` and in
the drop-in's `_parse_datatype_json_string`: the forms above parse, or are
errors, as in PySpark 4.3.0 and Spark 4.3.0.
### How was this patch tested?
- New rows in
`json_and_ddl_parsers_agree_on_the_atomic_and_parameterized_forms`,
`from_ddl_unquotes_a_backquoted_collation_name_of_a_field`, and the live
`ddl_collations_and_trailing_whitespace_agree_with_the_server_parser` in
`crates/spark-connect/tests/types_roundtrip.rs` (run against Spark 4.3.0
servers); `test_json_forms_accept_trailing_whitespace_as_pyspark` and the
updated `test_time_types_parse_as_pyspark` in
`python/tests/test_dropin_offline.py`. They fail without the change.
- `cargo test -p apache-spark-connect --release --lib` (608 passed),
`--test types_roundtrip` (offline 22 passed), the `--no-run` builds, the
offline drop-in suites (1836 + 110 passed), `cargo fmt --all -- --check`, `ruff
check python/tests` and `scripts/audit_no_stubs.sh`.
`from_ddl_interval_colon_and_spellings_agree_with_the_server_parser` fails
against a local server without `spark.sql.timestampNanosTypes.enabled`, also on
master.
### 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 #527 from HyukjinKwon/SPARK-61442-followup-type-strings.
Authored-by: Hyukjin Kwon <[email protected]>
Signed-off-by: Hyukjin Kwon <[email protected]>
---
crates/spark-connect/src/types.rs | 106 +++++++++++++++-----
crates/spark-connect/tests/types_roundtrip.rs | 135 +++++++++++++++++++++++++-
python/tests/test_dropin_offline.py | 25 ++++-
3 files changed, 232 insertions(+), 34 deletions(-)
diff --git a/crates/spark-connect/src/types.rs
b/crates/spark-connect/src/types.rs
index fba1e7cf..a090c3c4 100644
--- a/crates/spark-connect/src/types.rs
+++ b/crates/spark-connect/src/types.rs
@@ -1448,20 +1448,32 @@ fn parse_json_type_string(s: &str) -> Result<DataType> {
return Ok(data_type);
}
match s {
- // `null` and `calendarinterval` are lenient aliases that the
drop-in's Python parser
- // accepted before it delegated here.
+ // `null` is read as the server's JSON parser reads it, for the
schemas written before
+ // NullType was named `void`, and PySpark rejects it.
`calendarinterval` is a lenient alias
+ // that the drop-in's Python parser accepted before it delegated here.
"null" => Ok(DataType::Null),
"calendarinterval" => Ok(DataType::CalendarInterval),
// 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(),
}),
- _ => parse_parameterized_type(s,
TypeStringGrammar::Json).unwrap_or_else(|| {
- Err(SparkError::value(
- "INVALID_DATATYPE_STRING",
- &[("detail", &format!("Unknown type string: {}", s))],
- ))
- }),
+ _ => {
+ // PySpark's patterns match a prefix of the string, so whitespace
after a form with
+ // arguments or fields is not a part of it and is accepted. A bare
name is matched
+ // whole, so whitespace after it, as in `interval `, is not a type.
+ let trimmed = s.trim_end();
+ let form = if common_atomic_type(trimmed).is_some() {
+ s
+ } else {
+ trimmed
+ };
+ parse_parameterized_type(form,
TypeStringGrammar::Json).unwrap_or_else(|| {
+ Err(SparkError::value(
+ "INVALID_DATATYPE_STRING",
+ &[("detail", &format!("Unknown type string: {}", s))],
+ ))
+ })
+ }
}
}
@@ -1576,6 +1588,7 @@ fn parse_json_object(
/// | `decimal(p)` | not a type: the scale is required | scale 0 |
/// | `decimal(p,-s)` | a negative scale | not a type: an argument is an
unsigned integer |
/// | `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 |
///
/// Neither checks the range of an argument, such as the precision of a
decimal: PySpark's types
@@ -1605,8 +1618,6 @@ fn common_atomic_type(s: &str) -> Option<DataType> {
"date" => DataType::Date,
"timestamp" => DataType::Timestamp,
"timestamp_ntz" => DataType::TimestampNtz,
- // A bare `time`, as `TimeType().typeName()` and Spark's `TIME`, is
the default time(6).
- "time" => DataType::Time { precision: 6 },
"interval" => DataType::CalendarInterval,
"variant" => DataType::Variant,
// A bare `decimal`, as `DecimalType().typeName()` and Spark's
`DECIMAL`, is the default
@@ -1785,40 +1796,79 @@ fn interval_field(name: &str, fields: &[(&str, i32)])
-> Option<i32> {
}
/// Parses `string collate <name>`, of any whitespace between its words, whose
name is of letters,
-/// digits and underscores, as the `\w+` of PySpark's `_STRING_WITH_COLLATION`.
+/// digits and underscores.
///
-/// In JSON the collation is the name as it is written, as PySpark's
`StringType(name)` keeps it.
-/// In DDL it is the name in the canonical form that the server gives it (see
-/// [`canonical_collation_name`]), which may be qualified as
`system.builtin.<name>`, as Spark's
-/// `CollationFactory.resolveFullyQualifiedName` reads it.
+/// In JSON the name is of the letters of any script, as the `\w+` of PySpark's
+/// `_STRING_WITH_COLLATION` reads them, and the collation is the name as it
is written, as
+/// PySpark's `StringType(name)` keeps it. In DDL the name is a multipart
identifier of ASCII
+/// letters, digits and underscores, as Spark's lexer reads an unquoted one,
and each of its parts
+/// may be in backquotes (see [`multipart_identifier`]). The collation is the
name in the canonical
+/// form that the server gives it (see [`canonical_collation_name`]), which
may be qualified as
+/// `system.builtin.<name>`, as Spark's
`CollationFactory.resolveFullyQualifiedName` reads it.
fn parse_collated_string(s: &str, grammar: TypeStringGrammar) ->
Result<DataType> {
let invalid = || invalid_type_string(s, "collated string type");
let words: Vec<&str> = s.split_whitespace().collect();
let ["string", "collate", name] = words[..] else {
return Err(invalid());
};
- if s.ends_with(char::is_whitespace) {
- return Err(invalid());
- }
- let name = match (grammar, name.split('.').collect::<Vec<_>>().as_slice())
{
- (TypeStringGrammar::Ddl, [catalog, schema, unqualified])
+ let parts = match grammar {
+ TypeStringGrammar::Json => vec![name.to_string()],
+ TypeStringGrammar::Ddl =>
multipart_identifier(name).ok_or_else(invalid)?,
+ };
+ let name = match parts.as_slice() {
+ [name] => name,
+ [catalog, schema, name]
if catalog.eq_ignore_ascii_case("system") &&
schema.eq_ignore_ascii_case("builtin") =>
{
- unqualified
+ name
}
- _ => name,
+ _ => return Err(invalid()),
};
- if name.is_empty() || !name.chars().all(|c| c == '_' ||
c.is_alphanumeric()) {
+ 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) {
return Err(invalid());
}
Ok(DataType::String {
collation: match grammar {
- TypeStringGrammar::Json => name.to_string(),
+ TypeStringGrammar::Json => name.clone(),
TypeStringGrammar::Ddl => canonical_collation_name(name),
},
})
}
+/// The parts of the multipart identifier `name` of DDL, as Spark's
`multipartIdentifier` reads
+/// it: parts separated by dots, each of them either as it is written or in
backquotes, where a
+/// doubled backquote is one backquote. `None` if `name` is malformed.
+fn multipart_identifier(name: &str) -> Option<Vec<String>> {
+ let mut parts = Vec::new();
+ let mut chars = name.chars().peekable();
+ loop {
+ let mut part = String::new();
+ if chars.next_if_eq(&'`').is_some() {
+ loop {
+ match chars.next()? {
+ '`' if chars.next_if_eq(&'`').is_some() => part.push('`'),
+ '`' => break,
+ c => part.push(c),
+ }
+ }
+ } else {
+ while let Some(c) = chars.next_if(|c| *c != '.') {
+ part.push(c);
+ }
+ }
+ parts.push(part);
+ match chars.next() {
+ Some('.') => {}
+ None => return Some(parts),
+ Some(_) => return None,
+ }
+ }
+}
+
fn parse_geometry(s: &str) -> Result<DataType> {
let inner = s
.strip_prefix("geometry(")
@@ -2342,7 +2392,9 @@ fn parse_single_type(input: &str) -> Result<DataType> {
return Ok(data_type);
}
match trimmed.as_str() {
- "null" => Ok(DataType::Null),
+ // A bare `time` is the default time(6) of Spark's grammar; JSON names
a time with its
+ // precision only, as `time(p)`.
+ "time" => Ok(DataType::Time { precision: 6 }),
"tinyint" => Ok(DataType::Byte),
"smallint" => Ok(DataType::Short),
"int" => Ok(DataType::Integer),
@@ -3060,8 +3112,10 @@ mod tests {
DataType::from_ddl("time").unwrap(),
DataType::Time { precision: 6 }
);
+ // JSON names a time with its precision only, as `TimeType.jsonValue`
does.
+ assert!(DataType::from_json_str("\"time\"").is_err());
assert_eq!(
- DataType::from_json_str("\"time\"").unwrap(),
+ DataType::from_json_str("\"time(6)\"").unwrap(),
DataType::Time { precision: 6 }
);
}
diff --git a/crates/spark-connect/tests/types_roundtrip.rs
b/crates/spark-connect/tests/types_roundtrip.rs
index da2a81b4..7a7b91c4 100644
--- a/crates/spark-connect/tests/types_roundtrip.rs
+++ b/crates/spark-connect/tests/types_roundtrip.rs
@@ -1082,6 +1082,42 @@ fn
from_ddl_interval_colon_and_spellings_agree_with_the_server_parser() {
}
}
+/// The collations of DDL, backquoted or qualified as the server reads them,
and the names that it
+/// refuses, agree with the server's parser; so do the `time` of DDL and a
trailing whitespace.
+#[test]
+fn ddl_collations_and_trailing_whitespace_agree_with_the_server_parser() {
+ let Ok(url) = std::env::var("SPARK_REMOTE") else {
+ return;
+ };
+ let session = spark_connect::session::SparkSession::builder()
+ .remote(&url)
+ .get_or_create()
+ .expect("session");
+ for ddl in [
+ "string collate `UTF8_LCASE`",
+ "string collate `system`.`builtin`.`utf8_lcase`",
+ "string collate `system`.builtin.`utf8_lcase`",
+ "string collate UNICODE ",
+ "time",
+ ] {
+ let server = session
+ .parse_ddl(ddl)
+ .unwrap_or_else(|e| panic!("{ddl}: {e:?}"));
+ assert_eq!(DataType::from_ddl(ddl).unwrap(), server, "{ddl}");
+ }
+ for ddl in [
+ "string collate `system`.`builtin`",
+ "string collate `UNI``CODE`",
+ "string collate `été`",
+ "string collate été",
+ "string collate `system.builtin.utf8_lcase`",
+ "null",
+ ] {
+ assert!(session.parse_ddl(ddl).is_err(), "{ddl}");
+ assert!(DataType::from_ddl(ddl).is_err(), "{ddl}");
+ }
+}
+
/// Spatial types name their SRID by its CRS in JSON, as PySpark does, and
read it back.
#[test]
fn spatial_json_names_the_crs_as_pyspark() {
@@ -1228,7 +1264,6 @@ fn
json_and_ddl_parsers_agree_on_the_atomic_and_parameterized_forms() {
// The same type of both parsers.
let same: Vec<(&str, DataType)> = vec![
("void", DataType::Null),
- ("null", DataType::Null),
("boolean", DataType::Boolean),
("byte", DataType::Byte),
("short", DataType::Short),
@@ -1244,7 +1279,6 @@ fn
json_and_ddl_parsers_agree_on_the_atomic_and_parameterized_forms() {
("variant", DataType::Variant),
// The defaults of the bare names.
("decimal", decimal(10, 0)),
- ("time", DataType::Time { precision: 6 }),
("interval", DataType::CalendarInterval),
// decimal(p,s), with whitespace around its arguments.
("decimal(10,2)", decimal(10, 2)),
@@ -1360,6 +1394,11 @@ fn
json_and_ddl_parsers_agree_on_the_atomic_and_parameterized_forms() {
"string collate 'UNICODE'",
"string UNICODE",
"string collate other.builtin.UNICODE",
+ "string collate `UNI``CODE`",
+ "string collate `été`",
+ "string collate `system`.`builtin`",
+ "string collate `system.builtin.utf8_lcase`",
+ "string collate `system`.`builtin`.`utf8_lcase`.`x`",
"char(5) collate UNICODE",
// Not a type.
"",
@@ -1422,6 +1461,28 @@ fn
json_and_ddl_parsers_agree_on_the_atomic_and_parameterized_forms() {
None,
Some(string("UTF8_LCASE")),
),
+ // DDL takes a name in backquotes, as Spark's grammar does, and reads
each part of a
+ // qualified name; JSON has no quoting.
+ (
+ "string collate `UTF8_LCASE`",
+ None,
+ Some(string("UTF8_LCASE")),
+ ),
+ (
+ "string collate `system`.`builtin`.`utf8_lcase`",
+ None,
+ Some(string("UTF8_LCASE")),
+ ),
+ (
+ "string collate `system`.builtin.`utf8_lcase`",
+ None,
+ Some(string("UTF8_LCASE")),
+ ),
+ ("string collate `UNICODE`", None, Some(string("UNICODE"))),
+ // JSON reads a name of letters, digits and underscores, as PySpark's
`\w+` does, and a
+ // letter of any script is one. DDL's unquoted identifiers are of
ASCII letters, digits and
+ // underscores only, as Spark's lexer reads them.
+ ("string collate été", Some(string("été")), None),
// JSON is in lower case and of single spaces; the keywords of DDL are
of any case and
// any whitespace.
("DECIMAL(10,2)", None, Some(decimal(10, 2))),
@@ -1436,8 +1497,9 @@ fn
json_and_ddl_parsers_agree_on_the_atomic_and_parameterized_forms() {
Some(string("UNICODE_CI")),
),
(" decimal(10,2)", None, Some(decimal(10, 2))),
- ("decimal(10,2) ", None, Some(decimal(10, 2))),
- // The names of Spark's grammar alone.
+ // The names of Spark's grammar alone: the server reads `time` as
`time(6)`, which JSON
+ // names only with its precision, as PySpark's `TimeType.jsonValue`
does.
+ ("time", None, Some(DataType::Time { precision: 6 })),
("tinyint", None, Some(DataType::Byte)),
("smallint", None, Some(DataType::Short)),
("int", None, Some(DataType::Integer)),
@@ -1448,7 +1510,10 @@ fn
json_and_ddl_parsers_agree_on_the_atomic_and_parameterized_forms() {
("character(3)", None, Some(DataType::Char { length: 3 })),
("timestamp_ltz", None, Some(DataType::Timestamp)),
("timestamp_ntz(6)", None, Some(DataType::TimestampNtz)),
- // The names of JSON alone.
+ // The names of JSON alone. The server's JSON parser reads `null` for
the schemas written
+ // before NullType was named `void` (its `nameToType`, "for backwards
compatibility"), and
+ // its DDL parser has no such name. PySpark rejects it.
+ ("null", Some(DataType::Null), None),
("calendarinterval", Some(DataType::CalendarInterval), None),
(
"unparsed(x)",
@@ -1464,6 +1529,45 @@ fn
json_and_ddl_parsers_agree_on_the_atomic_and_parameterized_forms() {
assert_eq!(&parsed_as_ddl(text), ddl, "DDL {text:?}");
}
+ // Whitespace after a form that PySpark's patterns match as a prefix is
not a part of it, and
+ // is accepted: the JSON of PySpark's `_parse_datatype_json_value` is
`re.match`, and DDL is
+ // trimmed. A bare name is matched whole, so whitespace after it is not a
type in JSON.
+ let trailing: Vec<(&str, DataType)> = vec![
+ ("string collate UNICODE ", string("UNICODE")),
+ ("string collate UNICODE\t", string("UNICODE")),
+ ("interval day ", day_time(0, 0)),
+ ("interval day to second ", day_time(0, 3)),
+ ("interval year to month ", year_month(0, 1)),
+ ("decimal(10,2) ", decimal(10, 2)),
+ ("char(3) ", DataType::Char { length: 3 }),
+ ("varchar(20) ", DataType::Varchar { length: 20 }),
+ ("time(6) ", DataType::Time { precision: 6 }),
+ ];
+ for (text, expected) in &trailing {
+ assert_eq!(
+ parsed_as_json(text).as_ref(),
+ Some(expected),
+ "JSON {text:?}"
+ );
+ assert_eq!(parsed_as_ddl(text).as_ref(), Some(expected), "DDL
{text:?}");
+ }
+ // A JSON-only trailing whitespace: the negative scale of JSON, and bare
names.
+ assert_eq!(
+ parsed_as_json("decimal(10,-2) "),
+ Some(decimal(10, -2)),
+ "JSON decimal(10,-2) with trailing whitespace"
+ );
+ for text in [
+ "integer ",
+ "void ",
+ "decimal ",
+ "interval ",
+ "string ",
+ "time ",
+ ] {
+ assert_eq!(parsed_as_json(text), None, "JSON {text:?}");
+ }
+
// The JSON of a type is read back as the type, also of an interval that
DDL cannot name.
for data_type in [
decimal(10, -2),
@@ -1478,3 +1582,24 @@ fn
json_and_ddl_parsers_agree_on_the_atomic_and_parameterized_forms() {
);
}
}
+
+/// A backquoted collation name in DDL is unquoted, as Spark's parser unquotes
it, also in a struct
+/// field, where a comment follows the type.
+#[test]
+fn from_ddl_unquotes_a_backquoted_collation_name_of_a_field() {
+ let dt = DataType::from_ddl("a: string collate `UTF8_LCASE` COMMENT 'x'")
+ .expect("a backquoted collation name of a field");
+ match dt {
+ DataType::Struct { fields } => {
+ assert_eq!(fields.len(), 1);
+ assert_eq!(fields[0].name, "a");
+ assert_eq!(
+ fields[0].data_type,
+ DataType::String {
+ collation: "UTF8_LCASE".to_string()
+ }
+ );
+ }
+ other => panic!("expected struct, got {other:?}"),
+ }
+}
diff --git a/python/tests/test_dropin_offline.py
b/python/tests/test_dropin_offline.py
index f7a57d08..b9e00192 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -282,6 +282,24 @@ def test_spatial_and_collated_json_forms_parse():
assert want.json() == json.dumps(j)
+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
+ # matched whole, so `integer ` is not a type.
+ import json
+
+ cases = {
+ "string collate UNICODE ": T.StringType("UNICODE"),
+ "interval day ": T.DayTimeIntervalType(0),
+ "interval day to second ": T.DayTimeIntervalType(0, 3),
+ "decimal(10,2) ": T.DecimalType(10, 2),
+ }
+ for j, want in cases.items():
+ assert T._parse_datatype_json_string(json.dumps(j)) == want
+ with pytest.raises(ValueError):
+ T._parse_datatype_json_string(json.dumps("integer "))
+
+
def test_private_type_helpers_are_those_of_pyspark():
# As PySpark's pyspark.sql.types: the inference, merging, conversion and
verification of the
# types of Python objects and their tables, including tuple-based Rows.
@@ -3063,11 +3081,12 @@ def test_window_specs_pickle_as_pyspark(mock_connect):
def test_time_types_parse_as_pyspark(mock_connect):
- # As PySpark's: a bare time is TimeType(), of the default precision 6, in
a DDL string and
- # in the JSON of a type.
+ # As PySpark's: a bare time is TimeType(), of the default precision 6, in
a DDL string. The
+ # JSON of a type names a time with its precision, and the bare name is not
a type of JSON.
assert T.DataType.fromDDL("t time") == T.StructType([T.StructField("t",
T.TimeType(6))])
assert T.DataType.fromDDL("t time(3)") == T.StructType([T.StructField("t",
T.TimeType(3))])
- assert T._parse_datatype_json_string('"time"') == T.TimeType(6)
+ with pytest.raises(ValueError):
+ T._parse_datatype_json_string('"time"')
assert T._parse_datatype_json_string('"time(0)"') == T.TimeType(0)
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]