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 d1b3576b [SPARK-61442][CONNECT] Parse the atomic and parameterized 
type strings of JSON and of DDL with one parser
d1b3576b is described below

commit d1b3576b1b7d29d555ff813de617587265758919
Author: Liang-Chi Hsieh <[email protected]>
AuthorDate: Thu Nov 12 06:57:11 2026 +0900

    [SPARK-61442][CONNECT] Parse the atomic and parameterized type strings of 
JSON and of DDL with one parser
    
    ### What changes were proposed in this pull request?
    
    `DataType::from_json` and `DataType::from_ddl` 
(`crates/spark-connect/src/types.rs`) each had a table of the atomic type names 
and a chain of prefix checks for `decimal(p,s)`, `char(n)`, `varchar(n)`, 
`time(p)`, `timestamp_ntz(p)`, intervals and collated strings, and each read 
`string collate <name>` with its own code.
    
    Both now go through two shared functions:
    
    - `common_atomic_type`: the names that are a type in both grammars.
    - `parse_parameterized_type(s, grammar)`: every form that takes arguments 
or is of several words.
    
    `grammar` is a `TypeStringGrammar` (`Json` or `Ddl`). It is consulted only 
where the two grammars of PySpark really differ, `_parse_datatype_json_value` 
on the client and the server's parser of DDL:
    
    | form | JSON | DDL |
    |---|---|---|
    | letter case and spacing | as written: lower case, single spaces | any 
case, any whitespace between keywords |
    | `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 | `b` later than `a` 
|
    | `string collate <name>` | the name as written | the canonical name, 
`system.builtin.` dropped |
    
    The names of one grammar alone stay with their parser (`tinyint`, `int`, 
`dec`, `timestamp_ltz`, ... for DDL; `calendarinterval`, `unparsed(...)` for 
JSON).
    
    Neither parser checks the range of a decimal's precision or scale, as 
before and as PySpark's does not. The check that SPARK-61423 added at the 
conversion to Arrow is untouched.
    
    ### Why are the changes needed?
    
    The leaf functions were shared without knowing which grammar they were 
reading, so a change made for one grammar changed the other, and both had 
drifted from PySpark:
    
    - JSON read `decimal(5)`, which `_FIXED_DECIMAL` does not. It came with the 
DDL form of SPARK-61308.
    - JSON did not read `interval second to day`, the `json()` of 
`DayTimeIntervalType(3, 0)`, so the JSON of such a type did not read back. 
PySpark reads it.
    - DDL read a negative scale, `decimal(10,-2)`, which is not an 
`INTEGER_VALUE` of Spark's grammar.
    - Both read a signed argument (`char(-3)`, `time(+6)`, `decimal(+5,2)`), 
because the arguments were parsed as `i32`. PySpark's patterns are `\d+`.
    - `string collate` without a name and `string collateX` were read by both, 
by DDL as a string of the empty collation. JSON did not read `string  collate  
X`, which `\s+` does. Neither required the name to be `\w+`.
    - DDL did not read `string collate system.builtin.<name>`, which 
`CollationFactory.resolveFullyQualifiedName` does.
    
    PySpark's patterns are applied with `re.match`, so it also reads a type 
string with trailing text, such as `decimal(10,2)xyz`, or `interval day to 
year` as `interval day`. That is not followed: both parsers still raise for 
them.
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes, for the type strings listed above:
    
    - `DataType::from_json` no longer reads `decimal(p)`, a signed precision or 
length, an interval of several spaces between its words, or a collated string 
without a `\w+` name. It now reads an interval range of any two fields of one 
family, and `string collate <name>` of any whitespace.
    - `DataType::from_ddl` no longer reads a signed argument (a negative scale 
among them) or a collated string without a `\w+` name. It now reads a collation 
qualified as `system.builtin.<name>`.
    
    `_parse_datatype_json_string` of the Python client reads its string forms 
with `DataType::from_json`, so it changes the same way.
    
    ### How was this patch tested?
    
    A new table-driven test, 
`json_and_ddl_parsers_agree_on_the_atomic_and_parameterized_forms` in 
`crates/spark-connect/tests/types_roundtrip.rs`, feeds each form through both 
parsers. It has three tables: the forms that are the same type of both, those 
that are an error of both, and the listed differences with what each parser 
makes of them. A DDL string is read alone and as the element of an array, and 
the two have to agree. Out-of-range decimals (`decimal(39,0)`, 
`decimal(300,0)`, `de [...]
    
    - `cargo test -p apache-spark-connect --release --lib`: 599 passed.
    - `cargo test -p apache-spark-connect --release`: all pass.
    - `cargo test -p apache-spark-connect --release --no-run`, with and without 
`--features wasm-udf`.
    - `cargo fmt --all --check`.
    
    The DDL behavior was checked against `SqlBaseParser.g4` and 
`DataTypeAstBuilder.scala` of Spark v4.3.0, and the JSON behavior against 
`python/pyspark/sql/types.py` of the same tag. The server-backed tests of 
`parse_ddl`, the Python tests of the drop-in and the official-test parity gate 
were not run. `cargo clippy` reports nothing on the changed lines.
    
    ### Was this patch authored or co-authored using generative AI tooling?
    
    Generated-by: Claude Code (claude-fable-5-2)
    
    Closes #510 from viirya/SPARK-61442.
    
    Authored-by: Liang-Chi Hsieh <[email protected]>
    Signed-off-by: Hyukjin Kwon <[email protected]>
---
 crates/spark-connect/src/types.rs             | 518 +++++++++++++-------------
 crates/spark-connect/tests/types_roundtrip.rs | 294 +++++++++++++++
 2 files changed, 546 insertions(+), 266 deletions(-)

diff --git a/crates/spark-connect/src/types.rs 
b/crates/spark-connect/src/types.rs
index 829e56e2..fba1e7cf 100644
--- a/crates/spark-connect/src/types.rs
+++ b/crates/spark-connect/src/types.rs
@@ -1440,56 +1440,28 @@ fn parse_json_value(
     }
 }
 
+/// Parses the string of a type of JSON, as PySpark's 
`_parse_datatype_json_value` reads one: a
+/// name of [`common_atomic_type`], or a form of [`parse_parameterized_type`] 
of
+/// [`TypeStringGrammar::Json`].
 fn parse_json_type_string(s: &str) -> Result<DataType> {
+    if let Some(data_type) = common_atomic_type(s) {
+        return Ok(data_type);
+    }
     match s {
         // `null` and `calendarinterval` are lenient aliases that the 
drop-in's Python parser
         // accepted before it delegated here.
-        "void" | "null" => Ok(DataType::Null),
-        "boolean" => Ok(DataType::Boolean),
-        "byte" => Ok(DataType::Byte),
-        "short" => Ok(DataType::Short),
-        "integer" => Ok(DataType::Integer),
-        "long" => Ok(DataType::Long),
-        "float" => Ok(DataType::Float),
-        "double" => Ok(DataType::Double),
-        "binary" => Ok(DataType::Binary),
-        "date" => Ok(DataType::Date),
-        "timestamp" => Ok(DataType::Timestamp),
-        "timestamp_ntz" => Ok(DataType::TimestampNtz),
-        // A bare `time`, as `TimeType().typeName()` names it, is the default 
time(6).
-        "time" => Ok(DataType::Time { precision: 6 }),
-        "interval" | "calendarinterval" => Ok(DataType::CalendarInterval),
-        "variant" => Ok(DataType::Variant),
-        // A bare `decimal`, as `DecimalType().typeName()` names it, is the 
default decimal(10,0).
-        "decimal" => Ok(DataType::Decimal {
-            precision: 10,
-            scale: 0,
-        }),
-        s if s.starts_with("decimal(") => parse_decimal(s),
-        s if s.starts_with("char(") => parse_char(s),
-        s if s.starts_with("varchar(") => parse_varchar(s),
-        s if s.starts_with("time(") => parse_time(s),
-        s if s.starts_with("timestamp_ntz(") || 
s.starts_with("timestamp_ltz(") => {
-            parse_timestamp_nanos(s)
-        }
-        s if s.starts_with("interval") => parse_interval_string(s),
-        s if s.starts_with("string collate") => {
-            let collation = s.trim_start_matches("string 
collate").trim().to_string();
-            Ok(DataType::String { collation })
-        }
-        "string" => Ok(DataType::String {
-            collation: "UTF8_BINARY".to_string(),
-        }),
-        s if s.starts_with("geometry(") => parse_geometry(s),
-        s if s.starts_with("geography(") => parse_geography(s),
+        "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(),
         }),
-        _ => Err(SparkError::value(
-            "INVALID_DATATYPE_STRING",
-            &[("detail", &format!("Unknown type string: {}", s))],
-        )),
+        _ => parse_parameterized_type(s, 
TypeStringGrammar::Json).unwrap_or_else(|| {
+            Err(SparkError::value(
+                "INVALID_DATATYPE_STRING",
+                &[("detail", &format!("Unknown type string: {}", s))],
+            ))
+        }),
     }
 }
 
@@ -1594,187 +1566,211 @@ fn parse_json_object(
     }
 }
 
-fn parse_decimal(s: &str) -> Result<DataType> {
-    let inner = s
-        .strip_prefix("decimal(")
-        .and_then(|s| s.strip_suffix(")"))
-        .ok_or_else(|| {
-            SparkError::value(
-                "INVALID_DATATYPE_FORMAT",
-                &[("detail", "Invalid decimal format")],
-            )
-        })?;
+/// The grammar that a type string is read by. The JSON and the DDL parsers 
share one parser of
+/// each atomic and parameterized form, [`common_atomic_type`] and 
[`parse_parameterized_type`],
+/// and this names the few places where the two grammars really differ, as 
PySpark's do:
+///
+/// | form | [`Json`](Self::Json) (PySpark's `_parse_datatype_json_value`) | 
[`Ddl`](Self::Ddl) (the server's parser) |
+/// |---|---|---|
+/// | letter case and spacing | as written: lower case, single spaces | any 
case, any whitespace between keywords |
+/// | `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` |
+/// | `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
+/// take any, and the server refuses the type. A decimal that Arrow cannot 
hold is refused when it
+/// is converted (see `decimal128_precision_and_scale` of the session).
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+enum TypeStringGrammar {
+    Json,
+    Ddl,
+}
+
+/// The type of a name that is one in both grammars, as it is written in JSON, 
in lower case.
+fn common_atomic_type(s: &str) -> Option<DataType> {
+    Some(match s {
+        "void" => DataType::Null,
+        "boolean" => DataType::Boolean,
+        "byte" => DataType::Byte,
+        "short" => DataType::Short,
+        "integer" => DataType::Integer,
+        "long" => DataType::Long,
+        "float" => DataType::Float,
+        "double" => DataType::Double,
+        "string" => DataType::String {
+            collation: "UTF8_BINARY".to_string(),
+        },
+        "binary" => DataType::Binary,
+        "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
+        // decimal(10,0).
+        "decimal" => DataType::Decimal {
+            precision: 10,
+            scale: 0,
+        },
+        _ => return None,
+    })
+}
 
-    // A precision alone has scale 0, as Spark's `decimal(p)` does.
-    let parts: Vec<&str> = inner.split(',').collect();
-    if parts.len() > 2 {
-        return Err(SparkError::value(
-            "INVALID_DATATYPE_FORMAT",
-            &[("detail", "Decimal takes a precision and a scale")],
-        ));
+/// Parses `s` if it is of a form that takes arguments or is of several words: 
`decimal(p,s)`,
+/// `char(n)`, `varchar(n)`, `time(p)`, `timestamp_ntz(p)`, 
`timestamp_ltz(p)`, `interval ...`,
+/// `string collate <name>`, `geometry(...)` or `geography(...)`. `None` if it 
is of none of them,
+/// and an error if it is a malformed one.
+///
+/// This is the one parser of these forms, of the JSON and of the DDL parser: 
a DDL string comes
+/// in lower case and with its whitespace collapsed (see 
[`canonical_type_spelling`]), so that it
+/// is spelled as the JSON form is. `grammar` selects what 
[`TypeStringGrammar`] lists.
+fn parse_parameterized_type(s: &str, grammar: TypeStringGrammar) -> 
Option<Result<DataType>> {
+    if let Some(args) = type_arguments(s, "decimal") {
+        Some(args.and_then(|args| parse_decimal(s, args, grammar)))
+    } else if let Some(args) = type_arguments(s, "char") {
+        Some(args.and_then(|args| {
+            Ok(DataType::Char {
+                length: type_argument(s, args, false)?,
+            })
+        }))
+    } else if let Some(args) = type_arguments(s, "varchar") {
+        Some(args.and_then(|args| {
+            Ok(DataType::Varchar {
+                length: type_argument(s, args, false)?,
+            })
+        }))
+    } else if let Some(args) = type_arguments(s, "time") {
+        Some(args.and_then(|args| {
+            Ok(DataType::Time {
+                precision: type_argument(s, args, false)?,
+            })
+        }))
+    } else if let Some(args) = type_arguments(s, "timestamp_ntz") {
+        Some(args.and_then(|args| {
+            Ok(DataType::TimestampNtzNanos {
+                precision: timestamp_nanos_precision(s, args)?,
+            })
+        }))
+    } else if let Some(args) = type_arguments(s, "timestamp_ltz") {
+        Some(args.and_then(|args| {
+            Ok(DataType::TimestampLtzNanos {
+                precision: timestamp_nanos_precision(s, args)?,
+            })
+        }))
+    } else if s.starts_with("interval") {
+        Some(parse_interval_string(s, grammar))
+    } else if s
+        .strip_prefix("string")
+        .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
     }
-
-    let precision = parts[0].trim().parse::<i32>().map_err(|_| {
-        SparkError::value(
-            "INVALID_DATATYPE_FORMAT",
-            &[("detail", "Invalid precision")],
-        )
-    })?;
-    let scale = match parts.get(1) {
-        Some(scale) => scale.trim().parse::<i32>().map_err(|_| {
-            SparkError::value("INVALID_DATATYPE_FORMAT", &[("detail", "Invalid 
scale")])
-        })?,
-        None => 0,
-    };
-
-    Ok(DataType::Decimal { precision, scale })
 }
 
-fn parse_char(s: &str) -> Result<DataType> {
-    let inner = s
-        .strip_prefix("char(")
-        .and_then(|s| s.strip_suffix(")"))
-        .ok_or_else(|| {
-            SparkError::value(
-                "INVALID_DATATYPE_FORMAT",
-                &[("detail", "Invalid char format")],
-            )
-        })?;
-
-    let length = inner.trim().parse::<i32>().map_err(|_| {
-        SparkError::value(
-            "INVALID_DATATYPE_FORMAT",
-            &[("detail", "Invalid char length")],
-        )
-    })?;
-
-    Ok(DataType::Char { length })
+/// The `INVALID_DATATYPE_FORMAT` error of the type string `s` that is not a 
valid `what`.
+fn invalid_type_string(s: &str, what: &str) -> SparkError {
+    SparkError::value(
+        "INVALID_DATATYPE_FORMAT",
+        &[("detail", &format!("Invalid {what}: {s}"))],
+    )
 }
 
-fn parse_varchar(s: &str) -> Result<DataType> {
-    let inner = s
-        .strip_prefix("varchar(")
-        .and_then(|s| s.strip_suffix(")"))
-        .ok_or_else(|| {
-            SparkError::value(
-                "INVALID_DATATYPE_FORMAT",
-                &[("detail", "Invalid varchar format")],
-            )
-        })?;
-
-    let length = inner.trim().parse::<i32>().map_err(|_| {
-        SparkError::value(
-            "INVALID_DATATYPE_FORMAT",
-            &[("detail", "Invalid varchar length")],
-        )
-    })?;
-
-    Ok(DataType::Varchar { length })
+/// The text between the parentheses of `s` if it is `name(...)`: `None` if 
`s` does not start
+/// with `name(`, and an error if it does not end with the `)`.
+fn type_arguments<'a>(s: &'a str, name: &str) -> Option<Result<&'a str>> {
+    let rest = s.strip_prefix(name)?.strip_prefix('(')?;
+    Some(
+        rest.strip_suffix(')')
+            .ok_or_else(|| invalid_type_string(s, &format!("{name} type"))),
+    )
 }
 
-fn parse_time(s: &str) -> Result<DataType> {
-    let inner = s
-        .strip_prefix("time(")
-        .and_then(|s| s.strip_suffix(")"))
-        .ok_or_else(|| {
-            SparkError::value(
-                "INVALID_DATATYPE_FORMAT",
-                &[("detail", "Invalid time format")],
-            )
-        })?;
-
-    let precision = inner.trim().parse::<i32>().map_err(|_| {
-        SparkError::value(
-            "INVALID_DATATYPE_FORMAT",
-            &[("detail", "Invalid time precision")],
-        )
-    })?;
+/// The integer argument `arg` of the type string `s`, which may have 
whitespace around it: only
+/// digits, as the `\d+` of PySpark's patterns of JSON and the `INTEGER_VALUE` 
of Spark's grammar,
+/// so not `+5`, and `-5` only where the argument is `signed`, the scale of a 
decimal of JSON.
+fn type_argument(s: &str, arg: &str, signed: bool) -> Result<i32> {
+    let arg = arg.trim();
+    let digits = match arg.strip_prefix('-') {
+        Some(digits) if signed => digits,
+        _ => arg,
+    };
+    if digits.is_empty() || !digits.bytes().all(|b| b.is_ascii_digit()) {
+        return Err(invalid_type_string(s, "type argument"));
+    }
+    arg.parse()
+        .map_err(|_| invalid_type_string(s, "type argument"))
+}
 
-    Ok(DataType::Time { precision })
+/// Parses the arguments of `decimal(p,s)`. In DDL, `decimal(p)` has scale 0, 
as Spark's does; in
+/// JSON, which names a decimal with both, the scale may be negative, as 
PySpark's `_FIXED_DECIMAL`.
+/// The range of neither is checked, as [`TypeStringGrammar`] says.
+fn parse_decimal(s: &str, args: &str, grammar: TypeStringGrammar) -> 
Result<DataType> {
+    let (precision, scale) = match (args.split_once(','), grammar) {
+        (Some((precision, scale)), _) => (precision, Some(scale)),
+        (None, TypeStringGrammar::Ddl) => (args, None),
+        (None, TypeStringGrammar::Json) => return Err(invalid_type_string(s, 
"decimal type")),
+    };
+    Ok(DataType::Decimal {
+        precision: type_argument(s, precision, false)?,
+        scale: match scale {
+            Some(scale) => type_argument(s, scale, grammar == 
TypeStringGrammar::Json)?,
+            None => 0,
+        },
+    })
 }
 
-/// Parses `timestamp_ntz(p)` / `timestamp_ltz(p)` (p in 7..=9), mirroring the
+/// The precision of `timestamp_ntz(p)` / `timestamp_ltz(p)` (p in 7..=9), 
mirroring the
 /// `TIMESTAMP_{NTZ,LTZ}_NANOS_TYPE` patterns in Scala `DataType.nameToType`.
-fn parse_timestamp_nanos(s: &str) -> Result<DataType> {
-    let (ntz, rest) = if let Some(r) = s.strip_prefix("timestamp_ntz(") {
-        (true, r)
-    } else if let Some(r) = s.strip_prefix("timestamp_ltz(") {
-        (false, r)
-    } else {
-        return Err(SparkError::value(
-            "INVALID_DATATYPE_FORMAT",
-            &[("detail", "Invalid timestamp format")],
-        ));
-    };
-    let precision = rest
-        .strip_suffix(")")
-        .and_then(|p| p.trim().parse::<i32>().ok())
+fn timestamp_nanos_precision(s: &str, args: &str) -> Result<i32> {
+    type_argument(s, args, false)
+        .ok()
         .filter(|p| (7..=9).contains(p))
-        .ok_or_else(|| {
-            SparkError::value(
-                "INVALID_DATATYPE_FORMAT",
-                &[("detail", "Invalid timestamp precision (expected 7..9)")],
-            )
-        })?;
-    Ok(if ntz {
-        DataType::TimestampNtzNanos { precision }
-    } else {
-        DataType::TimestampLtzNanos { precision }
-    })
+        .ok_or_else(|| invalid_type_string(s, "timestamp precision (expected 
7..9)"))
 }
 
-/// Parses `interval`, `interval <field>` or `interval <field> to <field>`, as 
the grammar of
-/// Spark's parser does: a range is in one family (`year to month`, or `day` 
to `second`), and its
-/// end field is later than its start field. Anything else is an error, as the 
server's parser
-/// rejects it.
-fn parse_interval_string(s: &str) -> Result<DataType> {
-    let invalid = || {
-        SparkError::value(
-            "INVALID_DATATYPE_FORMAT",
-            &[("detail", &format!("Invalid interval format: {s}"))],
-        )
+/// Parses `interval`, `interval <field>` or `interval <field> to <field>`, 
its words separated
+/// by single spaces. A range is in one family (`year` and `month`, or `day` 
to `second`).
+///
+/// In DDL its end field is later than its start field, as the grammar of 
Spark's parser has it,
+/// and anything else is an error, as the server's parser rejects it. In JSON 
it is of any two
+/// fields of its family, as PySpark's `_INTERVAL_DAYTIME` and 
`_INTERVAL_YEARMONTH` read
+/// `interval second to day` as `DayTimeIntervalType(3, 0)`, whose JSON it is.
+fn parse_interval_string(s: &str, grammar: TypeStringGrammar) -> 
Result<DataType> {
+    let invalid = || invalid_type_string(s, "interval type");
+    let words: Vec<&str> = s.split(' ').collect();
+    let (start, end, range) = match words[..] {
+        ["interval"] => return Ok(DataType::CalendarInterval),
+        ["interval", field] => (field, field, false),
+        ["interval", start, "to", end] => (start, end, true),
+        _ => return Err(invalid()),
     };
-    let parts: Vec<&str> = s.split_whitespace().collect();
-    match parts.as_slice() {
-        ["interval"] => Ok(DataType::CalendarInterval),
-        ["interval", field] => {
-            if let Some(code) = interval_field(field, YEAR_MONTH_FIELDS) {
-                Ok(DataType::YearMonthInterval {
-                    start_field: code,
-                    end_field: code,
-                })
-            } else if let Some(code) = interval_field(field, DAY_TIME_FIELDS) {
-                Ok(DataType::DayTimeInterval {
-                    start_field: code,
-                    end_field: code,
-                })
-            } else {
-                Err(invalid())
-            }
+    let fields_of = |fields: &[(&str, i32)]| {
+        Some((interval_field(start, fields)?, interval_field(end, fields)?))
+    };
+    let in_order = |start_field: i32, end_field: i32| {
+        !range || grammar == TypeStringGrammar::Json || start_field < end_field
+    };
+    match (fields_of(YEAR_MONTH_FIELDS), fields_of(DAY_TIME_FIELDS)) {
+        (Some((start_field, end_field)), _) if in_order(start_field, 
end_field) => {
+            Ok(DataType::YearMonthInterval {
+                start_field,
+                end_field,
+            })
         }
-        ["interval", start, "to", end] => {
-            if let (Some(start_field), Some(end_field)) = (
-                interval_field(start, YEAR_MONTH_FIELDS),
-                interval_field(end, YEAR_MONTH_FIELDS),
-            ) {
-                if start_field < end_field {
-                    return Ok(DataType::YearMonthInterval {
-                        start_field,
-                        end_field,
-                    });
-                }
-            } else if let (Some(start_field), Some(end_field)) = (
-                interval_field(start, DAY_TIME_FIELDS),
-                interval_field(end, DAY_TIME_FIELDS),
-            ) {
-                if start_field < end_field {
-                    return Ok(DataType::DayTimeInterval {
-                        start_field,
-                        end_field,
-                    });
-                }
-            }
-            Err(invalid())
+        (_, Some((start_field, end_field))) if in_order(start_field, 
end_field) => {
+            Ok(DataType::DayTimeInterval {
+                start_field,
+                end_field,
+            })
         }
         _ => Err(invalid()),
     }
@@ -1788,6 +1784,41 @@ fn interval_field(name: &str, fields: &[(&str, i32)]) -> 
Option<i32> {
         .map(|&(_, code)| code)
 }
 
+/// 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`.
+///
+/// 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.
+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])
+            if catalog.eq_ignore_ascii_case("system") && 
schema.eq_ignore_ascii_case("builtin") =>
+        {
+            unqualified
+        }
+        _ => name,
+    };
+    if name.is_empty() || !name.chars().all(|c| c == '_' || 
c.is_alphanumeric()) {
+        return Err(invalid());
+    }
+    Ok(DataType::String {
+        collation: match grammar {
+            TypeStringGrammar::Json => name.to_string(),
+            TypeStringGrammar::Ddl => canonical_collation_name(name),
+        },
+    })
+}
+
 fn parse_geometry(s: &str) -> Result<DataType> {
     let inner = s
         .strip_prefix("geometry(")
@@ -2306,68 +2337,23 @@ fn parse_single_type(input: &str) -> Result<DataType> {
         return parse_struct_type(input);
     }
 
-    // Primitive types
+    // The names of both grammars, then those of DDL alone, then the forms 
with arguments.
+    if let Some(data_type) = common_atomic_type(&trimmed) {
+        return Ok(data_type);
+    }
     match trimmed.as_str() {
-        "null" | "void" => Ok(DataType::Null),
-        "boolean" => Ok(DataType::Boolean),
-        "byte" | "tinyint" => Ok(DataType::Byte),
-        "short" | "smallint" => Ok(DataType::Short),
-        "int" | "integer" => Ok(DataType::Integer),
-        "long" | "bigint" => Ok(DataType::Long),
-        "float" => Ok(DataType::Float),
-        "double" => Ok(DataType::Double),
-        "string" => Ok(DataType::String {
-            collation: "UTF8_BINARY".to_string(),
-        }),
-        "binary" => Ok(DataType::Binary),
-        "date" => Ok(DataType::Date),
-        "timestamp" | "timestamp_ltz" => Ok(DataType::Timestamp),
-        "timestamp_ntz" => Ok(DataType::TimestampNtz),
-        // As Spark's `TIME`, of the default precision.
-        "time" => Ok(DataType::Time { precision: 6 }),
-        "interval" => Ok(DataType::CalendarInterval),
-        "variant" => Ok(DataType::Variant),
-        // As Spark's `DECIMAL`, of the default precision and scale.
-        "decimal" => Ok(DataType::Decimal {
-            precision: 10,
-            scale: 0,
+        "null" => Ok(DataType::Null),
+        "tinyint" => Ok(DataType::Byte),
+        "smallint" => Ok(DataType::Short),
+        "int" => Ok(DataType::Integer),
+        "bigint" => Ok(DataType::Long),
+        "timestamp_ltz" => Ok(DataType::Timestamp),
+        _ => parse_parameterized_type(&trimmed, 
TypeStringGrammar::Ddl).unwrap_or_else(|| {
+            Err(SparkError::value(
+                "INVALID_DATATYPE_FORMAT",
+                &[("detail", &format!("Unknown type: {}", input))],
+            ))
         }),
-        _ => {
-            // Try complex parsing with already-lowercased trimmed version
-            if trimmed.starts_with("decimal(") {
-                parse_decimal(&trimmed)
-            } else if trimmed.starts_with("char(") {
-                parse_char(&trimmed)
-            } else if trimmed.starts_with("varchar(") {
-                parse_varchar(&trimmed)
-            } else if trimmed.starts_with("time(") {
-                parse_time(&trimmed)
-            } else if trimmed.starts_with("timestamp_ntz(") || 
trimmed.starts_with("timestamp_ltz(")
-            {
-                parse_timestamp_nanos(&trimmed)
-            } else if trimmed.starts_with("interval") {
-                parse_interval_string(&trimmed)
-            } else if trimmed.starts_with("string collate") {
-                // The name is taken from the input, not from `trimmed`, which 
is lowercased.
-                let collation = input
-                    .split_whitespace()
-                    .skip(2)
-                    .collect::<Vec<_>>()
-                    .join(" ");
-                Ok(DataType::String {
-                    collation: canonical_collation_name(&collation),
-                })
-            } else if trimmed.starts_with("geometry(") {
-                parse_geometry(&trimmed)
-            } else if trimmed.starts_with("geography(") {
-                parse_geography(&trimmed)
-            } else {
-                Err(SparkError::value(
-                    "INVALID_DATATYPE_FORMAT",
-                    &[("detail", &format!("Unknown type: {}", input))],
-                ))
-            }
-        }
     }
 }
 
diff --git a/crates/spark-connect/tests/types_roundtrip.rs 
b/crates/spark-connect/tests/types_roundtrip.rs
index 8a255787..da2a81b4 100644
--- a/crates/spark-connect/tests/types_roundtrip.rs
+++ b/crates/spark-connect/tests/types_roundtrip.rs
@@ -1184,3 +1184,297 @@ fn 
to_ddl_comments_round_trip_through_the_server_parser() {
         );
     }
 }
+
+/// What one of the two parsers of type strings makes of a string: a type, or 
an error.
+type Parsed = Option<DataType>;
+
+/// `text` as the JSON parser reads it, the string of a type of 
`DataType::from_json`.
+fn parsed_as_json(text: &str) -> Parsed {
+    DataType::from_json(&serde_json::Value::String(text.to_string())).ok()
+}
+
+/// `text` as the DDL parser reads it. It is read alone and as the element of 
an array, where it
+/// cannot be taken for a `name type` field, and the two have to agree.
+fn parsed_as_ddl(text: &str) -> Parsed {
+    let alone = DataType::from_ddl(text).ok();
+    let element = match DataType::from_ddl(&format!("array<{text}>")) {
+        Ok(DataType::Array { element_type, .. }) => Some(*element_type),
+        Ok(other) => panic!("array<{text}> is not an array: {other:?}"),
+        Err(_) => None,
+    };
+    assert_eq!(alone, element, "DDL {text:?} alone and in an array");
+    alone
+}
+
+/// The JSON and the DDL parser share one parser of each atomic and 
parameterized form, so a form
+/// is the same type, or the same error, of both. The exceptions are the 
differences of the two
+/// grammars of PySpark: those of `_parse_datatype_json_value`, which reads 
JSON on the client,
+/// and of the server's parser, which reads DDL. Each row of the tables is fed 
through both.
+#[test]
+fn json_and_ddl_parsers_agree_on_the_atomic_and_parameterized_forms() {
+    let decimal = |precision, scale| DataType::Decimal { precision, scale };
+    let string = |collation: &str| DataType::String {
+        collation: collation.to_string(),
+    };
+    let year_month = |start_field, end_field| DataType::YearMonthInterval {
+        start_field,
+        end_field,
+    };
+    let day_time = |start_field, end_field| DataType::DayTimeInterval {
+        start_field,
+        end_field,
+    };
+
+    // 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),
+        ("integer", DataType::Integer),
+        ("long", DataType::Long),
+        ("float", DataType::Float),
+        ("double", DataType::Double),
+        ("string", string("UTF8_BINARY")),
+        ("binary", DataType::Binary),
+        ("date", DataType::Date),
+        ("timestamp", DataType::Timestamp),
+        ("timestamp_ntz", DataType::TimestampNtz),
+        ("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)),
+        ("decimal( 10 , 2 )", decimal(10, 2)),
+        ("decimal(38,18)", decimal(38, 18)),
+        // Neither parser checks the range of a precision or a scale, as 
PySpark's does not: the
+        // server refuses the type, and the conversion to Arrow refuses what 
Arrow cannot hold.
+        ("decimal(39,0)", decimal(39, 0)),
+        ("decimal(300,0)", decimal(300, 0)),
+        ("decimal(5,6)", decimal(5, 6)),
+        ("decimal(0,0)", decimal(0, 0)),
+        // char(n), varchar(n) and time(p).
+        ("char(3)", DataType::Char { length: 3 }),
+        ("char( 3 )", DataType::Char { length: 3 }),
+        ("char(0)", DataType::Char { length: 0 }),
+        ("varchar(20)", DataType::Varchar { length: 20 }),
+        ("varchar( 20 )", DataType::Varchar { length: 20 }),
+        ("time(0)", DataType::Time { precision: 0 }),
+        ("time( 3 )", DataType::Time { precision: 3 }),
+        ("time(6)", DataType::Time { precision: 6 }),
+        ("time(9)", DataType::Time { precision: 9 }),
+        // The nanosecond timestamps.
+        (
+            "timestamp_ntz(9)",
+            DataType::TimestampNtzNanos { precision: 9 },
+        ),
+        (
+            "timestamp_ltz(7)",
+            DataType::TimestampLtzNanos { precision: 7 },
+        ),
+        // Intervals of one field, and of a range whose end is later than its 
start.
+        ("interval year", year_month(0, 0)),
+        ("interval month", year_month(1, 1)),
+        ("interval year to month", year_month(0, 1)),
+        ("interval day", day_time(0, 0)),
+        ("interval hour", day_time(1, 1)),
+        ("interval minute", day_time(2, 2)),
+        ("interval second", day_time(3, 3)),
+        ("interval day to hour", day_time(0, 1)),
+        ("interval day to second", day_time(0, 3)),
+        ("interval hour to minute", day_time(1, 2)),
+        ("interval minute to second", day_time(2, 3)),
+        // A collation that is written in its canonical form, of any 
whitespace.
+        ("string collate UTF8_BINARY", string("UTF8_BINARY")),
+        ("string collate UTF8_LCASE", string("UTF8_LCASE")),
+        ("string collate UNICODE_CI", string("UNICODE_CI")),
+        ("string  collate\tUNICODE", string("UNICODE")),
+        (
+            "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!(
+            parsed_as_json(text).as_ref(),
+            Some(expected),
+            "JSON {text:?}"
+        );
+        assert_eq!(parsed_as_ddl(text).as_ref(), Some(expected), "DDL 
{text:?}");
+    }
+
+    // An error of both parsers.
+    let neither = [
+        // An argument is of digits alone: no sign, but for the scale of a 
decimal of JSON.
+        "decimal()",
+        "decimal(,2)",
+        "decimal(a,2)",
+        "decimal(10,b)",
+        "decimal(10,2,3)",
+        "decimal(-5,2)",
+        "decimal(+5,2)",
+        "decimal(10,+2)",
+        "decimal(10,2",
+        "decimal(10 2)",
+        "decimal(1 0,2)",
+        "decimal(99999999999,0)",
+        "char()",
+        "char(x)",
+        "char(-3)",
+        "char(+3)",
+        "char(3,4)",
+        "char(3",
+        "varchar()",
+        "varchar(-1)",
+        "varchar(+1)",
+        "time()",
+        "time(a)",
+        "time(-1)",
+        "time(+6)",
+        "timestamp_ntz(3)",
+        "timestamp_ltz(10)",
+        "timestamp_ntz(+9)",
+        // An interval is of one family, and of nothing more.
+        "interval foo",
+        "intervalday",
+        "interval year to day",
+        "interval day to month",
+        "interval day to",
+        "interval to second",
+        "interval day second",
+        "interval day to second to hour",
+        "interval day to second xyz",
+        // A collated string names one collation, of letters, digits and 
underscores.
+        "string collate",
+        "string collate ",
+        "string collateUNICODE",
+        "string collate UNICODE CI",
+        "string collate UNI-CODE",
+        "string collate 'UNICODE'",
+        "string UNICODE",
+        "string collate other.builtin.UNICODE",
+        "char(5) collate UNICODE",
+        // Not a type.
+        "",
+        "foo",
+        "decimals",
+        "strings",
+    ];
+    for text in neither {
+        assert_eq!(parsed_as_json(text), None, "JSON {text:?}");
+        // An empty DDL string alone is the empty schema, so it is read as an 
element only.
+        if text.is_empty() {
+            assert!(DataType::from_ddl("array<>").is_err());
+        } else {
+            assert_eq!(parsed_as_ddl(text), None, "DDL {text:?}");
+        }
+    }
+
+    // The differences of the two grammars: (the string, of JSON, of DDL).
+    let differ: Vec<(&str, Parsed, Parsed)> = vec![
+        // JSON names a decimal with its scale (PySpark's `_FIXED_DECIMAL`); 
Spark's `decimal(p)`
+        // has scale 0.
+        ("decimal(5)", None, Some(decimal(5, 0))),
+        ("decimal( 5 )", None, Some(decimal(5, 0))),
+        // The JSON of `DecimalType(10, -2)` has its negative scale; an 
argument of Spark's
+        // grammar is an unsigned integer.
+        ("decimal(10,-2)", Some(decimal(10, -2)), None),
+        ("decimal(10, -2)", Some(decimal(10, -2)), None),
+        // PySpark reads the JSON of an interval of any two fields of a 
family, which is that
+        // of the type of its constructor, as `DayTimeIntervalType(3, 0)`; the 
end field of
+        // Spark's grammar is later than the start field.
+        ("interval second to day", Some(day_time(3, 0)), None),
+        ("interval hour to day", Some(day_time(1, 0)), None),
+        ("interval day to day", Some(day_time(0, 0)), None),
+        ("interval month to year", Some(year_month(1, 0)), None),
+        ("interval year to year", Some(year_month(0, 0)), None),
+        // PySpark keeps the collation of JSON as it is written; the server 
gives the collation
+        // of DDL in its canonical form, and takes it qualified.
+        (
+            "string collate unicode_ci",
+            Some(string("unicode_ci")),
+            Some(string("UNICODE_CI")),
+        ),
+        (
+            "string collate utf8_binary",
+            Some(string("utf8_binary")),
+            Some(string("UTF8_BINARY")),
+        ),
+        (
+            "string collate SR_CYRL_SRB_ci",
+            Some(string("SR_CYRL_SRB_ci")),
+            Some(string("sr_Cyrl_SRB_CI")),
+        ),
+        (
+            "string collate system.builtin.unicode_ci",
+            None,
+            Some(string("UNICODE_CI")),
+        ),
+        (
+            "string collate SYSTEM.BUILTIN.UTF8_LCASE",
+            None,
+            Some(string("UTF8_LCASE")),
+        ),
+        // 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))),
+        ("decimal (10,2)", None, Some(decimal(10, 2))),
+        ("Char(3)", None, Some(DataType::Char { length: 3 })),
+        ("TIME(3)", None, Some(DataType::Time { precision: 3 })),
+        ("INTERVAL DAY TO SECOND", None, Some(day_time(0, 3))),
+        ("interval  day\tto second", None, Some(day_time(0, 3))),
+        (
+            "STRING COLLATE UNICODE_CI",
+            None,
+            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.
+        ("tinyint", None, Some(DataType::Byte)),
+        ("smallint", None, Some(DataType::Short)),
+        ("int", None, Some(DataType::Integer)),
+        ("bigint", None, Some(DataType::Long)),
+        ("real", None, Some(DataType::Float)),
+        ("dec(5,1)", None, Some(decimal(5, 1))),
+        ("numeric(5,1)", None, Some(decimal(5, 1))),
+        ("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.
+        ("calendarinterval", Some(DataType::CalendarInterval), None),
+        (
+            "unparsed(x)",
+            Some(DataType::Unparsed {
+                data_type_string: "x".to_string(),
+            }),
+            None,
+        ),
+    ];
+    for (text, json, ddl) in &differ {
+        assert_ne!(json, ddl, "{text:?} is not a difference");
+        assert_eq!(&parsed_as_json(text), json, "JSON {text:?}");
+        assert_eq!(&parsed_as_ddl(text), ddl, "DDL {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),
+        decimal(300, 0),
+        day_time(3, 0),
+        year_month(1, 0),
+        string("unicode_ci"),
+    ] {
+        assert_eq!(
+            DataType::from_json(&data_type.json_value()).unwrap(),
+            data_type
+        );
+    }
+}


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to