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 8c1c4184 [SPARK-61242][CONNECT] Read NOT NULL and COMMENT in 
DataType.from_ddl as PySpark does, and the typeName of intervals and UDTs
8c1c4184 is described below

commit 8c1c418422e2f38f1ef626209088244aaafaf8b6
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Mon Nov 9 20:41:28 2026 +0900

    [SPARK-61242][CONNECT] Read NOT NULL and COMMENT in DataType.from_ddl as 
PySpark does, and the typeName of intervals and UDTs
    
    ### What changes were proposed in this pull request?
    
    [SPARK-61242](https://issues.apache.org/jira/browse/SPARK-61242): 
`DataType::from_ddl` reads the `NOT NULL` and `COMMENT 'string'` clauses of a 
field as Spark's grammar does, and `DataType::type_name` gives PySpark's names 
for day-time intervals, year-month intervals and UDTs.
    
    - Field parsing (`parse_struct_field` and its helpers) takes `name [:] type 
[NOT NULL] [COMMENT 'string']`, both for the top-level form (`a INT NOT NULL, b 
STRING COMMENT 'x'`) and inside `struct<...>`, where the colon is optional as 
in Spark's `complexColType`. Keywords are case-insensitive, `!NULL` is `NOT 
NULL`, and the comment is one or more adjacent string literals. A `NOT NULL` 
field is non-nullable, and the comment goes in the field metadata under 
`comment`.
    - Quoted text is scanned as Spark's lexer does, so a comma, `<`, `(` or 
colon in a comment or a backquoted name does not split or nest a field. 
Comments are unescaped as `unescapeSQLString` does (`\\`, `\'`, `''`, `\n`, 
`\uXXXX`, octal, and so on), and backquoted names strip their quotes and 
undouble backquotes.
    - Empty fields (`a INT,,b INT`, `struct<a:int,>`) and unquoted names that 
are not ASCII letters, digits or underscores are errors, as in Spark. An empty 
schema (`""`, blank) is an empty struct, as PySpark's `fromDDL` gives it.
    - `type_name()` returns `daytimeinterval` and `yearmonthinterval` for the 
two interval types (`interval` stays for `CalendarIntervalType`). For 
`DataType::Udt` it returns the lower-cased class name of `python_class`, as 
`UserDefinedType.typeName()` does, and `udt` when there is no class. The tree 
string already used this rule, so its UDT arm now goes through `type_name()`. 
`simple_string()`, `json()` and the proto are unchanged.
    
    Official PySpark 4.3.0 (through the server's `DataType.fromDDL`) gives the 
same results for the cases of the tests below; I compared 83 DDL strings (NOT 
NULL, COMMENT with escapes, nesting, backquoted names, invalid forms) against 
the Rust parser, with no differences after this change. `typeName()` of 
`DayTimeIntervalType` and `YearMonthIntervalType` is `daytimeinterval` and 
`yearmonthinterval`, and of a UDT subclass `PointUDT` it is `pointudt`.
    
    ### Why are the changes needed?
    
    `DataType::to_ddl` writes ` NOT NULL` and ` COMMENT '...'` for a 
non-nullable or commented field, but `DataType::from_ddl` rejects both. So 
`from_ddl(to_ddl(x))` fails for any struct with such a field, and `from_ddl("a 
INT NOT NULL")` fails with `INVALID_DATATYPE_FORMAT`, while the server's parser 
accepts it. Separately, `type_name()` returned `interval` for the day-time and 
year-month interval types, so two different types had the same name.
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes, for the Rust API. `DataType::from_ddl` now accepts `NOT NULL` and 
`COMMENT` clauses and rejects empty fields and non-identifier unquoted names as 
Spark does. `type_name()` changes for day-time and year-month intervals (to 
`daytimeinterval` and `yearmonthinterval`) and for UDTs (to the lower-cased 
class name). The Python drop-in is rebuilt from this crate, and its 
`StructType` and type-string coercions pick up the new `from_ddl`. Its 
`typeName()` is class-based and is unchanged.
    
    ### How was this patch tested?
    
    - `from_ddl_reads_not_null_and_comment_as_spark` (new, 
`tests/types_roundtrip.rs`): NOT NULL and COMMENT at top level and nested, in 
any keyword case, the comment escapes, adjacent literals, `!NULL`, backquoted 
names, and the error cases.
    - `to_ddl_of_non_nullable_and_commented_fields_round_trips` (new): 
`from_ddl(to_ddl(x)) == x` for structs with non-nullable and commented fields 
at several levels, in an array and a map, with names that need backquotes.
    - `type_name_of_intervals_and_udts_as_pyspark` (new): the type names of 
both intervals, `CalendarInterval` and UDTs with and without a class.
    - `from_ddl_not_null_and_comment_agree_with_the_server_parser` (new, gated 
on `SPARK_REMOTE` as `to_ddl_comments_round_trip_through_the_server_parser`): 
the same parse as the server's DDL parser for 18 strings.
    - The new tests fail on the base code (`INVALID_DATATYPE_FORMAT` and the 
wrong names) and pass with the fix. The existing 
`test_golden_values_simple_strings` expectation for the two interval types is 
updated to the PySpark names.
    - The lib tests (522 passed), the build of all tests, the offline Python 
suites (2819 passed, 8 skipped) with the rebuilt extension, and 
`types_roundtrip` (16 passed, with the comparison against the server's parser), 
`types_behavior` (15 passed), `coverage_types_extra` (10 passed) and 
`coverage_plan_map_udtf` (6 passed) against a local Spark 4.3.0 server. Clippy 
reports no diagnostics in the changed lines.
    - Checked with official PySpark 4.3.0 on a Connect server: the 83 DDL 
strings above give identical schemas in Rust and on the server.
    
    ### 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 #420 from HyukjinKwon/SPARK-61242-ddl-not-null.
    
    Authored-by: Hyukjin Kwon <[email protected]>
    Signed-off-by: Hyukjin Kwon <[email protected]>
---
 crates/spark-connect/src/types.rs             | 444 +++++++++++++++++---------
 crates/spark-connect/tests/types_roundtrip.rs | 408 +++++++++++++++++++++++
 2 files changed, 697 insertions(+), 155 deletions(-)

diff --git a/crates/spark-connect/src/types.rs 
b/crates/spark-connect/src/types.rs
index 31b2e03e..7c491abb 100644
--- a/crates/spark-connect/src/types.rs
+++ b/crates/spark-connect/src/types.rs
@@ -167,6 +167,7 @@ impl DataType {
     /// - Complex types: array<...>, map<...,...>, struct<name:type,...>
     /// - Top-level struct can omit the "struct<>" wrapper for backward 
compatibility
     /// - DDL like "a INT, b STRING" is parsed as a struct
+    /// - A field may end with `NOT NULL` and `COMMENT 'text'`, as 
`StructType.toDDL` writes them
     ///
     /// Examples:
     /// ```ignore
@@ -248,15 +249,21 @@ impl DataType {
             DataType::TimestampNtzNanos { precision } => 
format!("timestamp_ntz({})", precision),
             DataType::TimestampLtzNanos { precision } => 
format!("timestamp_ltz({})", precision),
             DataType::CalendarInterval => "interval".to_string(),
-            DataType::YearMonthInterval { .. } => "interval".to_string(),
-            DataType::DayTimeInterval { .. } => "interval".to_string(),
+            DataType::YearMonthInterval { .. } => 
"yearmonthinterval".to_string(),
+            DataType::DayTimeInterval { .. } => "daytimeinterval".to_string(),
             DataType::Array { .. } => "array".to_string(),
             DataType::Map { .. } => "map".to_string(),
             DataType::Struct { .. } => "struct".to_string(),
             DataType::Variant => "variant".to_string(),
             DataType::Geometry { .. } => "geometry".to_string(),
             DataType::Geography { .. } => "geography".to_string(),
-            DataType::Udt { .. } => "udt".to_string(),
+            // UserDefinedType.typeName() is the lower-cased class name, the 
whole of it.
+            DataType::Udt { python_class, .. } => python_class
+                .as_deref()
+                .and_then(|c| c.rsplit('.').next())
+                .filter(|class_name| !class_name.is_empty())
+                .map(str::to_lowercase)
+                .unwrap_or_else(|| "udt".to_string()),
             DataType::Unparsed { .. } => "unparsed".to_string(),
         }
     }
@@ -1011,17 +1018,6 @@ impl DataType {
             | DataType::Time { .. }
             | DataType::YearMonthInterval { .. }
             | DataType::DayTimeInterval { .. } => self.simple_string(),
-            DataType::Udt {
-                python_class: Some(python_class),
-                ..
-            } => python_class
-                .rsplit('.')
-                .next()
-                .filter(|class_name| !class_name.is_empty())
-                // UserDefinedType.typeName() preserves the entire class name,
-                // unlike DataType.typeName(), which strips the "Type" suffix.
-                .map(str::to_lowercase)
-                .unwrap_or_else(|| self.type_name()),
             _ => self.type_name(),
         }
     }
@@ -1858,6 +1854,10 @@ fn spatial_srid(crs: &str) -> Option<i32> {
 /// Handles primitive types, complex types (array, map, struct), and top-level 
schemas.
 fn parse_datatype_string(input: &str) -> Result<DataType> {
     let trimmed = input.trim();
+    // An empty schema is an empty struct, as the server's parser gives it.
+    if trimmed.is_empty() {
+        return Ok(DataType::Struct { fields: vec![] });
+    }
 
     // A top-level schema is "a INT, b STRING" (multiple fields) OR a single 
"a INT"
     // (one field, no comma) -- both parse to a StructType, matching PySpark's
@@ -1876,91 +1876,302 @@ fn parse_datatype_string(input: &str) -> 
Result<DataType> {
     parse_single_type(trimmed)
 }
 
-/// Whether `s` has a top-level whitespace char (outside `<>`/`()`), i.e. it 
looks like a
+/// Whether `s` has a top-level whitespace char (outside `<>`/`()` and 
quotes), i.e. it looks like a
 /// "name type" field rather than a bare type such as `int` or `array<int>`.
 fn contains_top_level_whitespace(s: &str) -> bool {
+    top_level_positions(s)
+        .into_iter()
+        .any(|i| s[i..].chars().next().is_some_and(char::is_whitespace))
+}
+
+/// Check if a string contains a comma at the top level (not inside 
brackets/parens/quotes)
+fn contains_top_level_comma(s: &str) -> bool {
+    top_level_positions(s)
+        .into_iter()
+        .any(|i| s.as_bytes()[i] == b',')
+}
+
+/// The byte positions of the chars of `s` outside `<>`/`()` and outside 
quoted strings and
+/// backquoted names, so that a comment such as `'x, y'` does not split a 
field.
+fn top_level_positions(s: &str) -> Vec<usize> {
+    let bytes = s.as_bytes();
+    let mut positions = Vec::new();
     let mut depth = 0;
-    for c in s.chars() {
-        match c {
-            '<' | '(' => depth += 1,
-            '>' | ')' => depth -= 1,
-            _ if depth == 0 && c.is_whitespace() => return true,
+    let mut i = 0;
+    while i < bytes.len() {
+        match bytes[i] {
+            b'\'' | b'"' | b'`' => match quoted_end(s, i) {
+                Some(end) => {
+                    i = end;
+                    continue;
+                }
+                // An unterminated quote: the rest is not a field, so the 
parse fails later.
+                None => break,
+            },
+            b'<' | b'(' => depth += 1,
+            b'>' | b')' => depth -= 1,
+            _ if depth == 0 && s.is_char_boundary(i) => positions.push(i),
             _ => {}
         }
+        i += 1;
     }
-    false
+    positions
 }
 
-/// Check if a string contains a comma at the top level (not inside 
brackets/parens)
-fn contains_top_level_comma(s: &str) -> bool {
-    let mut depth = 0;
-    for c in s.chars() {
-        match c {
-            '<' | '(' => depth += 1,
-            '>' | ')' => depth -= 1,
-            ',' if depth == 0 => return true,
-            _ => {}
+/// The byte index just after the quoted string or backquoted name that opens 
at `start`, or
+/// `None` if it is not closed. A doubled quote is one quote. A backslash 
escapes the next char in
+/// a string, and a raw string (`R'...'`) has no escapes, as Spark's lexer 
reads them.
+fn quoted_end(s: &str, start: usize) -> Option<usize> {
+    let bytes = s.as_bytes();
+    let quote = *bytes.get(start)?;
+    let raw = quote != b'`'
+        && start > 0
+        && matches!(bytes[start - 1], b'R' | b'r')
+        && (start < 2 || !is_ident_byte(bytes[start - 2]));
+    let mut i = start + 1;
+    while i < bytes.len() {
+        let c = bytes[i];
+        if c == b'\\' && quote != b'`' && !raw {
+            i += 2;
+        } else if c == quote {
+            if !raw && bytes.get(i + 1) == Some(&quote) {
+                i += 2;
+            } else {
+                return Some(i + 1);
+            }
+        } else {
+            i += 1;
         }
     }
-    false
+    None
+}
+
+fn is_ident_byte(b: u8) -> bool {
+    b.is_ascii_alphanumeric() || b == b'_'
 }
 
 /// Parse a top-level schema like "a INT, b STRING" or "a: int, b: string"
 fn parse_top_level_schema(input: &str) -> Result<DataType> {
     let mut fields = Vec::new();
-    let parts = split_top_level_comma(input);
+    for part in split_top_level_comma(input) {
+        fields.push(parse_struct_field(part.trim())?);
+    }
 
-    for part in parts {
-        let trimmed = part.trim();
-        if trimmed.is_empty() {
-            continue;
-        }
+    Ok(DataType::Struct { fields })
+}
 
-        // Parse "name type" or "name: type" format
-        let (name, type_str) = if let Some(colon_idx) = trimmed.find(':') {
-            let name = trimmed[..colon_idx].trim();
-            let type_str = trimmed[colon_idx + 1..].trim();
-            (name, type_str)
-        } else {
-            // Assume first word is name, rest is type
-            let parts: Vec<&str> = trimmed.splitn(2, 
char::is_whitespace).collect();
-            if parts.len() != 2 {
-                return Err(SparkError::value(
-                    "INVALID_DATATYPE_FORMAT",
-                    &[("detail", &format!("Cannot parse field: {}", trimmed))],
-                ));
+/// Parses one field, `name [:] type [NOT NULL] [COMMENT 'string']`, as 
Spark's `colType` and
+/// `complexColType` grammar: the name is a backquoted name or an identifier, 
the keywords are in
+/// any case, `!NULL` is `NOT NULL`, and the comment is one or more adjacent 
string literals.
+fn parse_struct_field(part: &str) -> Result<StructField> {
+    let (name, rest) = parse_field_name(part)?;
+    let rest = rest.trim_start();
+    let rest = rest.strip_prefix(':').unwrap_or(rest).trim_start();
+    let (type_str, not_null, comment) = split_type_and_clause(rest, part)?;
+    let data_type = parse_single_type(type_str)?;
+    let metadata = comment
+        .map(|c| BTreeMap::from([("comment".to_string(), 
serde_json::Value::String(c))]))
+        .unwrap_or_default();
+    Ok(StructField {
+        name,
+        data_type,
+        nullable: !not_null,
+        metadata,
+    })
+}
+
+/// The name at the start of a field, and the text after it.
+fn parse_field_name(part: &str) -> Result<(String, &str)> {
+    let invalid = || {
+        SparkError::value(
+            "INVALID_DATATYPE_FORMAT",
+            &[("detail", &format!("Cannot parse field: {}", part))],
+        )
+    };
+    if part.starts_with('`') {
+        let end = quoted_end(part, 0).ok_or_else(invalid)?;
+        let name = part[1..end - 1].replace("``", "`");
+        return Ok((name, &part[end..]));
+    }
+    // An unquoted identifier is ASCII letters, digits and underscores, as 
Spark's parser accepts
+    // them: it rejects others, such as `이름`, with INVALID_IDENTIFIER (back 
quote them).
+    let end = part
+        .find(|c: char| c.is_whitespace() || c == ':')
+        .unwrap_or(part.len());
+    if end == 0 || !part.as_bytes()[..end].iter().all(|&b| is_ident_byte(b)) {
+        return Err(invalid());
+    }
+    Ok((part[..end].to_string(), &part[end..]))
+}
+
+/// Splits the text after a field name into its type and its `NOT NULL` and 
`COMMENT` clauses, in
+/// that order. Returns whether the field is `NOT NULL` and its comment, 
unescaped.
+fn split_type_and_clause<'a>(rest: &'a str, part: &str) -> Result<(&'a str, 
bool, Option<String>)> {
+    let invalid = || {
+        SparkError::value(
+            "INVALID_DATATYPE_FORMAT",
+            &[("detail", &format!("Cannot parse field: {}", part))],
+        )
+    };
+    let clause_start = top_level_positions(rest)
+        .into_iter()
+        .find(|&i| is_clause_start(rest, i));
+    let (type_str, clause) = match clause_start {
+        Some(i) => (&rest[..i], &rest[i..]),
+        None => (rest, ""),
+    };
+    let mut clause = clause.trim_start();
+    let mut not_null = false;
+    let mut comment = None;
+    if let Some(after) = strip_keyword(clause, "NOT").or_else(|| 
clause.strip_prefix('!')) {
+        let after = strip_keyword(after.trim_start(), 
"NULL").ok_or_else(invalid)?;
+        not_null = true;
+        clause = after.trim_start();
+    }
+    if let Some(after) = strip_keyword(clause, "COMMENT") {
+        let mut text = String::new();
+        let mut s = after.trim_start();
+        loop {
+            let (literal, next) = string_literal(s).ok_or_else(invalid)?;
+            text.push_str(&literal);
+            s = next.trim_start();
+            if !starts_string_literal(s) {
+                break;
             }
-            (parts[0], parts[1])
-        };
+        }
+        comment = Some(text);
+        clause = s;
+    }
+    if !clause.is_empty() || type_str.trim().is_empty() {
+        return Err(invalid());
+    }
+    Ok((type_str.trim_end(), not_null, comment))
+}
 
-        let data_type = parse_single_type(type_str)?;
-        fields.push(StructField {
-            name: name.to_string(),
-            data_type,
-            nullable: true,
-            metadata: BTreeMap::new(),
-        });
+/// Whether the text at `i` starts the `NOT NULL`, `!NULL` or `COMMENT` clause 
of a field type.
+fn is_clause_start(rest: &str, i: usize) -> bool {
+    let tail = &rest[i..];
+    if tail.starts_with('!') {
+        return true;
+    }
+    let after_ident = rest[..i]
+        .chars()
+        .last()
+        .is_some_and(|c| c.is_ascii_alphanumeric() || c == '_');
+    !after_ident
+        && (strip_keyword(tail, "NOT").is_some() || strip_keyword(tail, 
"COMMENT").is_some())
+}
+
+/// The text after a keyword at the start of `s`, if `s` starts with it (in 
any case) at a word
+/// boundary.
+fn strip_keyword<'a>(s: &'a str, keyword: &str) -> Option<&'a str> {
+    let head = s.get(..keyword.len())?;
+    let after = &s[keyword.len()..];
+    let boundary = after
+        .chars()
+        .next()
+        .is_none_or(|c| !(c.is_ascii_alphanumeric() || c == '_'));
+    (head.eq_ignore_ascii_case(keyword) && boundary).then_some(after)
+}
+
+fn starts_string_literal(s: &str) -> bool {
+    let raw = s.len() > 1
+        && matches!(s.as_bytes()[0], b'R' | b'r')
+        && matches!(s.as_bytes()[1], b'\'' | b'"');
+    raw || matches!(s.as_bytes().first(), Some(b'\'' | b'"'))
+}
+
+/// The value of the string literal at the start of `s`, and the text after 
it: a single-quoted
+/// or double-quoted string with Spark's escapes, or a raw string `R'...'`.
+fn string_literal(s: &str) -> Option<(String, &str)> {
+    if !starts_string_literal(s) {
+        return None;
     }
+    let start = if s.as_bytes()[0].is_ascii_alphabetic() {
+        1
+    } else {
+        0
+    };
+    let end = quoted_end(s, start)?;
+    let token = &s[start..end];
+    let text = if start == 1 {
+        token[1..token.len() - 1].to_string()
+    } else {
+        unescape_sql_string(token)
+    };
+    Some((text, &s[end..]))
+}
 
-    Ok(DataType::Struct { fields })
+/// The value of a quoted string token, as Spark's `unescapeSQLString` reads 
it: the quotes are
+/// removed, a doubled quote is one quote, and the escapes `\0 \b \n \r \t 
\Z`, `\uXXXX`,
+/// `\UXXXXXXXX` and three-digit octal `\NNN` are decoded. Any other escaped 
char is itself, except
+/// `\%` and `\_`, which keep their backslash.
+fn unescape_sql_string(token: &str) -> String {
+    let quote = token.as_bytes()[0] as char;
+    let chars: Vec<char> = token[1..token.len() - 1].chars().collect();
+    let n = chars.len();
+    let hex = |range: std::ops::Range<usize>| {
+        !range.is_empty() && chars[range].iter().all(|c| c.is_ascii_hexdigit())
+    };
+    let code_point = |range: std::ops::Range<usize>, radix: u32| {
+        let digits: String = chars[range].iter().collect();
+        u32::from_str_radix(&digits, radix)
+            .ok()
+            .and_then(char::from_u32)
+            .unwrap_or('\u{FFFD}')
+    };
+    let mut out = String::new();
+    let mut i = 0;
+    while i < n {
+        let c = chars[i];
+        if c == quote && chars.get(i + 1) == Some(&quote) {
+            out.push(quote);
+            i += 2;
+        } else if c != '\\' || i + 1 == n {
+            out.push(c);
+            i += 1;
+        } else {
+            i += 1;
+            let escaped = chars[i];
+            if escaped == 'u' && i + 5 <= n && hex(i + 1..i + 5) {
+                out.push(code_point(i + 1..i + 5, 16));
+                i += 5;
+            } else if escaped == 'U' && i + 9 <= n && hex(i + 1..i + 9) {
+                out.push(code_point(i + 1..i + 9, 16));
+                i += 9;
+            } else if i + 3 <= n
+                && matches!(chars[i], '0' | '1')
+                && chars[i + 1..i + 3].iter().all(|c| ('0'..='7').contains(c))
+            {
+                out.push(code_point(i..i + 3, 8));
+                i += 3;
+            } else {
+                match escaped {
+                    '0' => out.push('\0'),
+                    'b' => out.push('\u{8}'),
+                    'n' => out.push('\n'),
+                    'r' => out.push('\r'),
+                    't' => out.push('\t'),
+                    'Z' => out.push('\u{1A}'),
+                    // As Spark does, `\%` and `\_` keep their backslash.
+                    '%' | '_' => out.push_str(&format!("\\{escaped}")),
+                    other => out.push(other),
+                }
+                i += 1;
+            }
+        }
+    }
+    out
 }
 
-/// Split by top-level commas (respecting angle brackets and parentheses)
+/// Split by top-level commas (respecting angle brackets, parentheses and 
quotes)
 fn split_top_level_comma(s: &str) -> Vec<&str> {
     let mut result = Vec::new();
     let mut start = 0;
-    let mut depth = 0;
-    let bytes = s.as_bytes();
-
-    for (i, &b) in bytes.iter().enumerate() {
-        match b {
-            b'<' | b'(' => depth += 1,
-            b'>' | b')' => depth -= 1,
-            b',' if depth == 0 => {
-                result.push(&s[start..i]);
-                start = i + 1;
-            }
-            _ => {}
+    for i in top_level_positions(s) {
+        if s.as_bytes()[i] == b',' {
+            result.push(&s[start..i]);
+            start = i + 1;
         }
     }
     result.push(&s[start..]);
@@ -2124,24 +2335,7 @@ fn parse_map_type(input: &str) -> Result<DataType> {
 
 /// Split map key and value types by comma at the top level
 fn split_map_parts(s: &str) -> Result<Vec<&str>> {
-    let mut depth = 0;
-    let mut parts = Vec::new();
-    let mut start = 0;
-
-    for (i, c) in s.char_indices() {
-        match c {
-            '<' | '(' => depth += 1,
-            '>' | ')' => depth -= 1,
-            ',' if depth == 0 => {
-                parts.push(&s[start..i]);
-                start = i + 1;
-            }
-            _ => {}
-        }
-    }
-    parts.push(&s[start..]);
-
-    Ok(parts)
+    Ok(split_top_level_comma(s))
 }
 
 /// Parse struct<field1:type1,field2:type2,...>
@@ -2160,73 +2354,13 @@ fn parse_struct_type(input: &str) -> Result<DataType> {
     }
 
     let mut fields = Vec::new();
-    let parts = split_struct_fields(inner);
-
-    for part in parts {
-        let part_trimmed = part.trim();
-        if part_trimmed.is_empty() {
-            continue;
-        }
-
-        // Find the colon separating field name from type
-        if let Some(colon_idx) = find_unbracketed_colon(part_trimmed) {
-            let name = part_trimmed[..colon_idx].trim();
-            let type_str = part_trimmed[colon_idx + 1..].trim();
-
-            let data_type = parse_single_type(type_str)?;
-            fields.push(StructField {
-                name: name.to_string(),
-                data_type,
-                nullable: true,
-                metadata: BTreeMap::new(),
-            });
-        } else {
-            return Err(SparkError::value(
-                "INVALID_DATATYPE_FORMAT",
-                &[("detail", &format!("Invalid struct field: {}", 
part_trimmed))],
-            ));
-        }
+    for part in split_top_level_comma(inner) {
+        fields.push(parse_struct_field(part.trim())?);
     }
 
     Ok(DataType::Struct { fields })
 }
 
-/// Split struct fields by comma at the top level
-fn split_struct_fields(s: &str) -> Vec<&str> {
-    let mut depth = 0;
-    let mut parts = Vec::new();
-    let mut start = 0;
-
-    for (i, c) in s.char_indices() {
-        match c {
-            '<' | '(' => depth += 1,
-            '>' | ')' => depth -= 1,
-            ',' if depth == 0 => {
-                parts.push(&s[start..i]);
-                start = i + 1;
-            }
-            _ => {}
-        }
-    }
-    parts.push(&s[start..]);
-
-    parts
-}
-
-/// Find the position of an unbracketed colon
-fn find_unbracketed_colon(s: &str) -> Option<usize> {
-    let mut depth = 0;
-    for (i, c) in s.char_indices() {
-        match c {
-            '<' | '(' => depth += 1,
-            '>' | ')' => depth -= 1,
-            ':' if depth == 0 => return Some(i),
-            _ => {}
-        }
-    }
-    None
-}
-
 #[cfg(test)]
 mod tests {
     use super::*;
@@ -2694,7 +2828,7 @@ mod tests {
                     end_field: 3,
                 },
                 expected_simple: "interval day to second",
-                expected_type_name: "interval",
+                expected_type_name: "daytimeinterval",
             },
             TestCase {
                 dt: DataType::YearMonthInterval {
@@ -2702,7 +2836,7 @@ mod tests {
                     end_field: 1,
                 },
                 expected_simple: "interval year to month",
-                expected_type_name: "interval",
+                expected_type_name: "yearmonthinterval",
             },
             TestCase {
                 dt: DataType::Variant,
diff --git a/crates/spark-connect/tests/types_roundtrip.rs 
b/crates/spark-connect/tests/types_roundtrip.rs
index 80b7407d..bb08701e 100644
--- a/crates/spark-connect/tests/types_roundtrip.rs
+++ b/crates/spark-connect/tests/types_roundtrip.rs
@@ -389,6 +389,414 @@ fn from_ddl_full_grammar() {
     assert!(DataType::from_ddl("struct<a:>").is_err());
 }
 
+/// `from_ddl` reads the `NOT NULL` and `COMMENT` clauses of a field as 
Spark's grammar does,
+/// `colName dataType [NOT NULL] [COMMENT 'string']` (and `complexColType` for 
a struct field, whose
+/// colon is optional): keywords in any case, the comment's escapes, adjacent 
string literals, and
+/// backquoted names. The expected values are the server's `DataType.fromDDL` 
results.
+#[test]
+fn from_ddl_reads_not_null_and_comment_as_spark() {
+    fn field(
+        name: &str,
+        data_type: DataType,
+        nullable: bool,
+        comment: Option<&str>,
+    ) -> StructField {
+        let metadata = comment
+            .map(|c| {
+                BTreeMap::from([(
+                    "comment".to_string(),
+                    serde_json::Value::String(c.to_string()),
+                )])
+            })
+            .unwrap_or_default();
+        StructField {
+            name: name.to_string(),
+            data_type,
+            nullable,
+            metadata,
+        }
+    }
+    let struct_of = |fields: Vec<StructField>| DataType::Struct { fields };
+
+    // Top-level form, with and without a comma, in any keyword case.
+    assert_eq!(
+        DataType::from_ddl("x INT NOT NULL").unwrap(),
+        struct_of(vec![field("x", DataType::Integer, false, None)])
+    );
+    // A name of other letters than ASCII must be back quoted, as Spark's 
parser requires
+    // (INVALID_IDENTIFIER for `이름 INT`).
+    assert!(DataType::from_ddl("이름 INT NOT NULL").is_err());
+    assert_eq!(
+        DataType::from_ddl("`이름` INT NOT NULL, `café` INT COMMENT 
'c'").unwrap(),
+        struct_of(vec![
+            field("이름", DataType::Integer, false, None),
+            field("café", DataType::Integer, true, Some("c")),
+        ])
+    );
+    assert_eq!(
+        DataType::from_ddl("a INT NOT NULL, b STRING").unwrap(),
+        struct_of(vec![
+            field("a", DataType::Integer, false, None),
+            field(
+                "b",
+                DataType::String {
+                    collation: "UTF8_BINARY".into()
+                },
+                true,
+                None
+            ),
+        ])
+    );
+    assert_eq!(
+        DataType::from_ddl("a INT, b STRING COMMENT 'x'").unwrap(),
+        struct_of(vec![
+            field("a", DataType::Integer, true, None),
+            field(
+                "b",
+                DataType::String {
+                    collation: "UTF8_BINARY".into()
+                },
+                true,
+                Some("x")
+            ),
+        ])
+    );
+    assert_eq!(
+        DataType::from_ddl("a INT not null, b string Comment 'hi'").unwrap(),
+        struct_of(vec![
+            field("a", DataType::Integer, false, None),
+            field(
+                "b",
+                DataType::String {
+                    collation: "UTF8_BINARY".into()
+                },
+                true,
+                Some("hi")
+            ),
+        ])
+    );
+    assert_eq!(
+        DataType::from_ddl("a INT NOT NULL COMMENT 'x', b STRING").unwrap(),
+        struct_of(vec![
+            field("a", DataType::Integer, false, Some("x")),
+            field(
+                "b",
+                DataType::String {
+                    collation: "UTF8_BINARY".into()
+                },
+                true,
+                None
+            ),
+        ])
+    );
+    assert_eq!(
+        DataType::from_ddl("a INT !NULL").unwrap(),
+        struct_of(vec![field("a", DataType::Integer, false, None)])
+    );
+    assert_eq!(
+        DataType::from_ddl("a decimal(10, 2) NOT NULL, b interval day to 
second").unwrap(),
+        struct_of(vec![
+            field(
+                "a",
+                DataType::Decimal {
+                    precision: 10,
+                    scale: 2
+                },
+                false,
+                None
+            ),
+            field(
+                "b",
+                DataType::DayTimeInterval {
+                    start_field: 0,
+                    end_field: 3
+                },
+                true,
+                None
+            ),
+        ])
+    );
+
+    // Nested form, with the optional colon and the same clauses.
+    assert_eq!(
+        DataType::from_ddl("struct<a: INT NOT NULL>").unwrap(),
+        struct_of(vec![field("a", DataType::Integer, false, None)])
+    );
+    assert_eq!(
+        DataType::from_ddl("STRUCT<a: INT NOT NULL COMMENT 'x', b: 
STRING>").unwrap(),
+        DataType::Struct {
+            fields: vec![
+                field("a", DataType::Integer, false, Some("x")),
+                field(
+                    "b",
+                    DataType::String {
+                        collation: "UTF8_BINARY".into()
+                    },
+                    true,
+                    None
+                ),
+            ]
+        }
+    );
+    assert_eq!(
+        DataType::from_ddl("struct<a int comment 'x,y<z'>").unwrap(),
+        struct_of(vec![field("a", DataType::Integer, true, Some("x,y<z"))])
+    );
+    assert_eq!(
+        DataType::from_ddl("array<struct<c: LONG NOT NULL COMMENT 
'q'>>").unwrap(),
+        DataType::Array {
+            element_type: Box::new(struct_of(vec![field(
+                "c",
+                DataType::Long,
+                false,
+                Some("q")
+            )])),
+            contains_null: true,
+        }
+    );
+
+    // The escapes of the comment, as `unescapeSQLString` reads them.
+    for (ddl, comment) in [
+        (r"a INT COMMENT 'it\'s'", "it's"),
+        (r"a INT COMMENT 'it''s'", "it's"),
+        (r"a INT COMMENT 'a\\b'", r"a\b"),
+        (r"a INT COMMENT 'a\\'", r"a\"),
+        (r"a INT COMMENT '\''", "'"),
+        ("a INT COMMENT \"dq\"", "dq"),
+        (r"a INT COMMENT 'a' 'b'", "ab"),
+        (r"a INT COMMENT ''", ""),
+        (r"a INT COMMENT R'raw\x'", r"raw\x"),
+        (r"a INT COMMENT 'xA\101\n'", "xAA\n"),
+        (r"a INT COMMENT 'x\z\%\_'", r"xz\%\_"),
+        ("a INT COMMENT 'line\nbreak, comma'", "line\nbreak, comma"),
+    ] {
+        let parsed = DataType::from_ddl(ddl).unwrap_or_else(|e| panic!("{ddl}: 
{e:?}"));
+        assert_eq!(
+            parsed,
+            struct_of(vec![field("a", DataType::Integer, true, 
Some(comment))]),
+            "{ddl}"
+        );
+    }
+
+    // Backquoted names: the quotes go, the doubled backquote is one.
+    assert_eq!(
+        DataType::from_ddl("`a b` INT NOT NULL").unwrap(),
+        struct_of(vec![field("a b", DataType::Integer, false, None)])
+    );
+    assert_eq!(
+        DataType::from_ddl("`a``b` INT COMMENT 'c'").unwrap(),
+        struct_of(vec![field("a`b", DataType::Integer, true, Some("c"))])
+    );
+    assert_eq!(
+        DataType::from_ddl("`a,b` INT, `c:d` STRING").unwrap(),
+        struct_of(vec![
+            field("a,b", DataType::Integer, true, None),
+            field(
+                "c:d",
+                DataType::String {
+                    collation: "UTF8_BINARY".into()
+                },
+                true,
+                None
+            ),
+        ])
+    );
+    assert_eq!(
+        DataType::from_ddl("struct<`a b`: TIME(3) NOT NULL COMMENT 
'x'>").unwrap(),
+        struct_of(vec![field(
+            "a b",
+            DataType::Time { precision: 3 },
+            false,
+            Some("x")
+        )])
+    );
+
+    // A clause out of order, repeated, unterminated or without a string is an 
error.
+    for ddl in [
+        "a INT COMMENT 'x' NOT NULL",
+        "a INT NOT NULL NOT NULL",
+        "a INT COMMENT 'x' COMMENT 'y'",
+        "a INT NOT",
+        "a INT NOTNULL",
+        "a INT COMMENT x",
+        "a INT COMMENT 'x",
+        "a INT COMMENT 'it's'",
+        "struct<a: INT COMMENT 'x>",
+    ] {
+        assert!(DataType::from_ddl(ddl).is_err(), "{ddl} must not parse");
+    }
+}
+
+/// `to_ddl` writes a non-nullable or commented field, at every nesting level, 
and `from_ddl` reads
+/// that back as the same type.
+#[test]
+fn to_ddl_of_non_nullable_and_commented_fields_round_trips() {
+    let comment = |c: &str| {
+        BTreeMap::from([(
+            "comment".to_string(),
+            serde_json::Value::String(c.to_string()),
+        )])
+    };
+    let schemas = [
+        DataType::Struct {
+            fields: vec![
+                StructField {
+                    name: "a".to_string(),
+                    data_type: DataType::Integer,
+                    nullable: false,
+                    metadata: BTreeMap::new(),
+                },
+                StructField {
+                    name: "b".to_string(),
+                    data_type: DataType::Double,
+                    nullable: true,
+                    metadata: comment("it's a \\ comment, <with> (parens)"),
+                },
+                StructField {
+                    name: "c".to_string(),
+                    data_type: DataType::Long,
+                    nullable: false,
+                    metadata: comment("ends with a backslash\\"),
+                },
+            ],
+        },
+        DataType::Struct {
+            fields: vec![
+                StructField {
+                    name: "outer".to_string(),
+                    data_type: DataType::Struct {
+                        fields: vec![StructField {
+                            name: "inner".to_string(),
+                            data_type: DataType::Struct {
+                                fields: vec![StructField {
+                                    name: "deep".to_string(),
+                                    data_type: DataType::Date,
+                                    nullable: false,
+                                    metadata: comment("deep \"quoted\" 
'comment'\nline"),
+                                }],
+                            },
+                            nullable: false,
+                            metadata: comment("middle"),
+                        }],
+                    },
+                    nullable: true,
+                    metadata: BTreeMap::new(),
+                },
+                StructField {
+                    name: "arr".to_string(),
+                    data_type: DataType::Array {
+                        element_type: Box::new(DataType::Struct {
+                            fields: vec![StructField {
+                                name: "x".to_string(),
+                                data_type: DataType::Integer,
+                                nullable: false,
+                                metadata: comment("in an array"),
+                            }],
+                        }),
+                        contains_null: true,
+                    },
+                    nullable: false,
+                    metadata: BTreeMap::new(),
+                },
+                StructField {
+                    name: "m".to_string(),
+                    data_type: DataType::Map {
+                        key_type: Box::new(DataType::String {
+                            collation: "UTF8_BINARY".to_string(),
+                        }),
+                        value_type: Box::new(DataType::Struct {
+                            fields: vec![StructField {
+                                name: "v".to_string(),
+                                data_type: DataType::Integer,
+                                nullable: false,
+                                metadata: BTreeMap::new(),
+                            }],
+                        }),
+                        value_contains_null: true,
+                    },
+                    nullable: true,
+                    metadata: comment("a map"),
+                },
+                StructField {
+                    name: "a b`c".to_string(),
+                    data_type: DataType::Integer,
+                    nullable: false,
+                    metadata: BTreeMap::new(),
+                },
+            ],
+        },
+    ];
+    for schema in schemas {
+        let ddl = schema.to_ddl().unwrap();
+        assert_eq!(DataType::from_ddl(&ddl).unwrap(), schema, "{ddl}");
+    }
+}
+
+/// The type names of `DataType::type_name`, which mirror 
`DataType.typeName()`: a day-time and a
+/// year-month interval are not `interval`, and a UDT is its Python class name 
in lower case.
+#[test]
+fn type_name_of_intervals_and_udts_as_pyspark() {
+    let day_time = DataType::DayTimeInterval {
+        start_field: 0,
+        end_field: 3,
+    };
+    let year_month = DataType::YearMonthInterval {
+        start_field: 0,
+        end_field: 1,
+    };
+    assert_eq!(day_time.type_name(), "daytimeinterval");
+    assert_eq!(year_month.type_name(), "yearmonthinterval");
+    assert_eq!(DataType::CalendarInterval.type_name(), "interval");
+    let udt = |python_class: Option<&str>| DataType::Udt {
+        type_str: "point".to_string(),
+        jvm_class: None,
+        python_class: python_class.map(str::to_string),
+        serialized_python_class: None,
+        sql_type: None,
+    };
+    assert_eq!(udt(Some("mymod.PointUDT")).type_name(), "pointudt");
+    assert_eq!(udt(None).type_name(), "udt");
+}
+
+/// `from_ddl` agrees with the server's DDL parser on the `NOT NULL` and 
`COMMENT` clauses, the
+/// nested forms and the backquoted names. Runs only with `SPARK_REMOTE` set.
+#[test]
+fn from_ddl_not_null_and_comment_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 [
+        "x INT NOT NULL",
+        "`이름` INT NOT NULL, `café` STRING COMMENT 'c'",
+        "a INT NOT NULL, b BIGINT",
+        "a INT, b DOUBLE COMMENT 'x'",
+        "a INT not null, b int Comment 'hi, there'",
+        "a INT NOT NULL COMMENT 'x', b DATE",
+        "a INT COMMENT 'it\\'s', b INT COMMENT 'a\\\\b'",
+        "a INT COMMENT 'x' ''",
+        "`a b` INT NOT NULL",
+        "`a``b` INT COMMENT 'c'",
+        "struct<a: INT NOT NULL>",
+        "STRUCT<a: INT NOT NULL COMMENT 'x', b: STRING>",
+        "struct<a: int comment 'x,y<z'>",
+        "struct<`a b`: TIME(3) NOT NULL>",
+        "struct<a:int,b:array<struct<c: int NOT NULL COMMENT 'q'>>>",
+        "array<struct<a: INT COMMENT 'c'>>",
+        "map<string, struct<a: int not null>>",
+        "a decimal(10, 2) NOT NULL",
+        "a interval day to second NOT NULL",
+    ] {
+        let server = session
+            .parse_ddl(ddl)
+            .unwrap_or_else(|e| panic!("{ddl}: {e:?}"));
+        assert_eq!(DataType::from_ddl(ddl).unwrap(), server, "{ddl}");
+    }
+}
+
 #[test]
 fn timestamp_nanos_types() {
     use spark_connect_proto::data_type::{Kind, TimestampLtzNanos, 
TimestampNtzNanos};


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

Reply via email to