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 4b7ca43a [SPARK-61308][CONNECT][PYTHON] Parse the interval ranges, 
name:type fields and type spellings of DataType.fromDDL as the server does
4b7ca43a is described below

commit 4b7ca43afa42686c5c731ed7e65559af9e06b703
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Tue Nov 10 08:53:58 2026 +0900

    [SPARK-61308][CONNECT][PYTHON] Parse the interval ranges, name:type fields 
and type spellings of DataType.fromDDL as the server does
    
    ### What changes were proposed in this pull request?
    
    [SPARK-61308](https://issues.apache.org/jira/browse/SPARK-61308): make 
`DataType.fromDDL` in the Rust client parse interval ranges, `name:type` fields 
and type spellings as the server's parser does.
    
    - Intervals: only `interval`, `interval <field>` and `interval <from> to 
<to>` are accepted. 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 
(trailing tokens, `NOT NULL` at type level, unknown or reversed fields, a 
missing end field) is an `INVALID_DATATYPE_FORMAT` error, where it used to 
return `CalendarInterval` or a reversed range.
    - Fields: a top-level colon names a field as a top-level space does, so 
`a:int`, `x:array<int>` and `x:struct<a:int>` give the same schema as the 
server. A colon inside brackets or quotes does not.
    - Spellings: `decimal` is `decimal(10,0)`, `decimal(p)` is `decimal(p,0)`, 
`dec` and `numeric` are decimal, `real` is float, `character(n)` is `char(n)`, 
`timestamp_ltz` is `timestamp`, `timestamp without time zone` is 
`timestamp_ntz`, `timestamp with local time zone` is `timestamp`, `time without 
time zone` is `time(6)`. `timestamp(6)` is the microsecond timestamp and 
`timestamp(p)` for p in 7..9 the nanosecond one, as the server gives them.
    - Python: the drop-in builds the string fragments of `StructType(["a 
decimal"])` in Rust, so those fragments now accept the same spellings. Official 
PySpark 4.3.0 has no such constructor, so the `StructType` path is drop-in only.
    
    ### Why are the changes needed?
    
    `DataType.fromDDL` returned a wrong type where the server raises: 
`DataType.fromDDL("interval year to second")` and `DataType.fromDDL("interval 
day to second NOT NULL")` gave `interval`, and `DataType.fromDDL("interval hour 
to day")` gave a `DayTimeInterval` with a reversed range. The server raises 
`ParseException` for each. `DataType.fromDDL("a:int")` failed with 
`INVALID_DATATYPE_FORMAT`, where the server returns `struct<a:int>`. 
`DataType.fromDDL("decimal")`, `"numeric(10,2)"`, `"r [...]
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes. `DataType.fromDDL` and `StructType.fromDDL` in the Rust client now 
reject the invalid interval forms and accept the `name:type` form and the 
spellings above, with the server's types. The drop-in's `StructType(["a 
decimal"])` fragments accept the same spellings, and `StructType(["a interval 
year to second"])` raises.
    
    ### How was this patch tested?
    
    - `from_ddl_interval_ranges_and_colon_fields_as_spark` and 
`from_ddl_type_spellings_as_spark` (offline, 
`crates/spark-connect/tests/types_roundtrip.rs`) check the interval forms, the 
`name:type` forms and the spellings, valid and invalid. They fail on the 
previous `types.rs` and pass with this change.
    - `from_ddl_interval_colon_and_spellings_agree_with_the_server_parser` 
(server-gated) compares the same strings with the server's `parse_ddl`, valid 
and invalid.
    - The cases were also run through `DataType.fromDDL` of official PySpark 
4.3.0 against the same server: the parse results agree (the `time` and 
nanosecond rows only differ in the client's own unsupported-type error, which 
the server's parse does not raise).
    - `types_roundtrip` (19 passed, with the comparisons against the server's 
parser) against a local Spark 4.3.0 server.
    - The lib tests of both crates (678 passed), the build of all tests, also 
with `wasm-udf`, the offline Python suites (2937 passed, 8 skipped), and the 
live drop-in and Arrow suites (237 passed) and live cases (14 passed) against a 
local Spark 4.3.0 server. Clippy reports no diagnostics in the changed lines.
    
    ### Was this patch authored or co-authored using generative AI tooling?
    
    Generated-by: Claude Opus 5.5
    
    This pull request and its description were written by Isaac.
    
    Closes #434 from HyukjinKwon/SPARK-61308-ddl-spellings.
    
    Authored-by: Hyukjin Kwon <[email protected]>
    Signed-off-by: Hyukjin Kwon <[email protected]>
---
 crates/spark-connect/src/types.rs             | 175 ++++++++++++------
 crates/spark-connect/tests/types_roundtrip.rs | 248 ++++++++++++++++++++++++++
 2 files changed, 367 insertions(+), 56 deletions(-)

diff --git a/crates/spark-connect/src/types.rs 
b/crates/spark-connect/src/types.rs
index 7c491abb..985ef6e4 100644
--- a/crates/spark-connect/src/types.rs
+++ b/crates/spark-connect/src/types.rs
@@ -1599,11 +1599,12 @@ fn parse_decimal(s: &str) -> Result<DataType> {
             )
         })?;
 
+    // A precision alone has scale 0, as Spark's `decimal(p)` does.
     let parts: Vec<&str> = inner.split(',').collect();
-    if parts.len() != 2 {
+    if parts.len() > 2 {
         return Err(SparkError::value(
             "INVALID_DATATYPE_FORMAT",
-            &[("detail", "Decimal requires precision and scale")],
+            &[("detail", "Decimal takes a precision and a scale")],
         ));
     }
 
@@ -1613,9 +1614,12 @@ fn parse_decimal(s: &str) -> Result<DataType> {
             &[("detail", "Invalid precision")],
         )
     })?;
-    let scale = parts[1].trim().parse::<i32>().map_err(|_| {
-        SparkError::value("INVALID_DATATYPE_FORMAT", &[("detail", "Invalid 
scale")])
-    })?;
+    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 })
 }
@@ -1713,64 +1717,69 @@ fn parse_timestamp_nanos(s: &str) -> Result<DataType> {
     })
 }
 
+/// 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> {
-    if s == "interval" {
-        return Ok(DataType::CalendarInterval);
-    }
-
+    let invalid = || {
+        SparkError::value(
+            "INVALID_DATATYPE_FORMAT",
+            &[("detail", &format!("Invalid interval format: {s}"))],
+        )
+    };
     let parts: Vec<&str> = s.split_whitespace().collect();
-    if parts.len() < 2 {
-        return Ok(DataType::CalendarInterval);
-    }
-
-    if parts.len() == 2 {
-        // Single field like "interval day"
-        let field_name = parts[1];
-        for &(name, code) in YEAR_MONTH_FIELDS {
-            if name == field_name {
-                return Ok(DataType::YearMonthInterval {
+    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,
-                });
-            }
-        }
-        for &(name, code) in DAY_TIME_FIELDS {
-            if name == field_name {
-                return Ok(DataType::DayTimeInterval {
+                })
+            } else if let Some(code) = interval_field(field, DAY_TIME_FIELDS) {
+                Ok(DataType::DayTimeInterval {
                     start_field: code,
                     end_field: code,
-                });
+                })
+            } else {
+                Err(invalid())
             }
         }
-    } else if parts.len() == 4 && parts[2] == "to" {
-        // Range like "interval day to second"
-        let start = parts[1];
-        let end = parts[3];
-
-        // Try year-month fields
-        if let (Some(&(_, start_code)), Some(&(_, end_code))) = (
-            YEAR_MONTH_FIELDS.iter().find(|(name, _)| *name == start),
-            YEAR_MONTH_FIELDS.iter().find(|(name, _)| *name == end),
-        ) {
-            return Ok(DataType::YearMonthInterval {
-                start_field: start_code,
-                end_field: end_code,
-            });
-        }
-
-        // Try day-time fields
-        if let (Some(&(_, start_code)), Some(&(_, end_code))) = (
-            DAY_TIME_FIELDS.iter().find(|(name, _)| *name == start),
-            DAY_TIME_FIELDS.iter().find(|(name, _)| *name == end),
-        ) {
-            return Ok(DataType::DayTimeInterval {
-                start_field: start_code,
-                end_field: end_code,
-            });
+        ["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())
         }
+        _ => Err(invalid()),
     }
+}
 
-    Ok(DataType::CalendarInterval)
+/// The code of an interval field name in `fields`, such as `second` in the 
day-time fields.
+fn interval_field(name: &str, fields: &[(&str, i32)]) -> Option<i32> {
+    fields
+        .iter()
+        .find(|(field, _)| *field == name)
+        .map(|&(_, code)| code)
 }
 
 fn parse_geometry(s: &str) -> Result<DataType> {
@@ -1864,9 +1873,11 @@ fn parse_datatype_string(input: &str) -> 
Result<DataType> {
     // _parse_datatype_string. Detect either a top-level comma or a top-level 
space
     // separating a field name from its type; fall back to single-type parsing 
if the
     // schema interpretation fails (e.g. a bare type that itself contains 
spaces such as
-    // "interval day to second").
+    // "interval day to second"). A top-level colon names a field too, as in 
"a:int".
     if !trimmed.to_lowercase().starts_with("struct<")
-        && (contains_top_level_comma(trimmed) || 
contains_top_level_whitespace(trimmed))
+        && (contains_top_level_comma(trimmed)
+            || contains_top_level_whitespace(trimmed)
+            || contains_top_level_colon(trimmed))
     {
         if let Ok(dt) = parse_top_level_schema(trimmed) {
             return Ok(dt);
@@ -1884,6 +1895,14 @@ fn contains_top_level_whitespace(s: &str) -> bool {
         .any(|i| s[i..].chars().next().is_some_and(char::is_whitespace))
 }
 
+/// Whether `s` has a top-level colon, which names a field as in "a:int" 
(outside `<>`/`()` and
+/// quotes, so that "x:array<int>" is a field and "array<a:int>" is not).
+fn contains_top_level_colon(s: &str) -> bool {
+    top_level_positions(s)
+        .into_iter()
+        .any(|i| s.as_bytes()[i] == b':')
+}
+
 /// 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)
@@ -2207,9 +2226,48 @@ fn canonical_collation_name(name: &str) -> String {
         .join("_")
 }
 
+/// The spelling of a type under the name that [`parse_single_type`] takes, 
for the aliases of
+/// Spark's grammar: `dec` and `numeric` are `decimal`, `real` is `float` and 
`character` is `char`.
+/// A time zone clause names the timestamp type (`timestamp without time zone` 
is `timestamp_ntz`,
+/// `timestamp with local time zone` is `timestamp_ltz`), `timestamp(6)` is 
the microsecond
+/// timestamp and `timestamp(p)` the nanosecond one. Keywords may be separated 
by any whitespace.
+/// Any other spelling is returned as it is.
+fn canonical_type_spelling(s: &str) -> String {
+    let words = s.split_whitespace().collect::<Vec<_>>().join(" ");
+    let (base, zone) = if let Some(base) = words.strip_suffix(" without time 
zone") {
+        (base, Some("ntz"))
+    } else if let Some(base) = words.strip_suffix(" with local time zone") {
+        (base, Some("ltz"))
+    } else {
+        (words.as_str(), None)
+    };
+    let (head, args) = match base.find('(') {
+        Some(i) => base.split_at(i),
+        None => (base, ""),
+    };
+    let head = head.trim_end();
+    let args = if head.starts_with("timestamp") && args == "(6)" {
+        ""
+    } else {
+        args
+    };
+    let head = match (head, zone) {
+        ("timestamp", Some("ntz")) => "timestamp_ntz",
+        ("timestamp", Some("ltz")) => "timestamp_ltz",
+        ("time", Some("ntz")) => "time",
+        ("timestamp", None) if !args.is_empty() => "timestamp_ltz",
+        ("dec" | "numeric", None) => "decimal",
+        ("character", None) => "char",
+        ("real", None) => "float",
+        (_, Some(_)) => return s.to_string(),
+        (head, None) => head,
+    };
+    format!("{head}{args}")
+}
+
 /// Parse a single type (primitive or complex)
 fn parse_single_type(input: &str) -> Result<DataType> {
-    let trimmed = input.trim().to_lowercase();
+    let trimmed = canonical_type_spelling(&input.trim().to_lowercase());
 
     // Complex types
     if trimmed.starts_with("array<") {
@@ -2237,12 +2295,17 @@ fn parse_single_type(input: &str) -> Result<DataType> {
         }),
         "binary" => Ok(DataType::Binary),
         "date" => Ok(DataType::Date),
-        "timestamp" => Ok(DataType::Timestamp),
+        "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,
+        }),
         _ => {
             // Try complex parsing with already-lowercased trimmed version
             if trimmed.starts_with("decimal(") {
diff --git a/crates/spark-connect/tests/types_roundtrip.rs 
b/crates/spark-connect/tests/types_roundtrip.rs
index bb08701e..8a255787 100644
--- a/crates/spark-connect/tests/types_roundtrip.rs
+++ b/crates/spark-connect/tests/types_roundtrip.rs
@@ -834,6 +834,254 @@ fn timestamp_nanos_types() {
     );
 }
 
+/// `from_ddl` reads an interval as the server's parser does: `interval`, 
`interval <field>` and
+/// `interval <from> to <to>`, the end field later than the start field within 
one family. The
+/// other forms are errors. A top-level `name:type` names a field, as `name 
type` does.
+#[test]
+fn from_ddl_interval_ranges_and_colon_fields_as_spark() {
+    let field = |name: &str, data_type: DataType| DataType::Struct {
+        fields: vec![StructField {
+            name: name.to_string(),
+            data_type,
+            nullable: true,
+            metadata: BTreeMap::new(),
+        }],
+    };
+    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,
+    };
+    for (ddl, expected) in [
+        ("interval", DataType::CalendarInterval),
+        ("interval year", year_month(0, 0)),
+        ("interval year to month", year_month(0, 1)),
+        ("interval day", day_time(0, 0)),
+        ("interval day to second", day_time(0, 3)),
+        ("interval hour to second", day_time(1, 3)),
+        ("INTERVAL  DAY   TO SECOND", day_time(0, 3)),
+        ("a:interval day to hour", field("a", day_time(0, 1))),
+        ("a:int", field("a", DataType::Integer)),
+        (
+            "x:array<int>",
+            field(
+                "x",
+                DataType::Array {
+                    element_type: Box::new(DataType::Integer),
+                    contains_null: true,
+                },
+            ),
+        ),
+        ("x:struct<a:int>", field("x", field("a", DataType::Integer))),
+        ("int:int", field("int", DataType::Integer)),
+        ("`a:b`:int", field("a:b", DataType::Integer)),
+    ] {
+        assert_eq!(DataType::from_ddl(ddl).unwrap(), expected, "{ddl}");
+    }
+    let string = DataType::String {
+        collation: "UTF8_BINARY".to_string(),
+    };
+    assert_eq!(
+        DataType::from_ddl("a:int, b:string").unwrap(),
+        DataType::Struct {
+            fields: vec![
+                StructField {
+                    name: "a".to_string(),
+                    data_type: DataType::Integer,
+                    nullable: true,
+                    metadata: BTreeMap::new(),
+                },
+                StructField {
+                    name: "b".to_string(),
+                    data_type: string,
+                    nullable: true,
+                    metadata: BTreeMap::new(),
+                },
+            ],
+        }
+    );
+    let comment = BTreeMap::from([(
+        "comment".to_string(),
+        serde_json::Value::String("x:y".to_string()),
+    )]);
+    assert_eq!(
+        DataType::from_ddl("a:int COMMENT 'x:y'").unwrap(),
+        DataType::Struct {
+            fields: vec![StructField {
+                name: "a".to_string(),
+                data_type: DataType::Integer,
+                nullable: true,
+                metadata: comment,
+            }],
+        }
+    );
+    for ddl in [
+        "interval year to second",
+        "interval day to second NOT NULL",
+        "interval day to second xyz",
+        "interval day to second foo",
+        "interval day to",
+        "interval foo",
+        "interval to second",
+        "interval day second",
+        "interval year month",
+        "interval day to second to hour",
+        "intervalday",
+        "interval year to year",
+        "interval day to day",
+        "interval hour to day",
+        "interval month to year",
+        "interval second to second",
+        "a interval year to second",
+        "a:'x:y' int",
+    ] {
+        assert!(DataType::from_ddl(ddl).is_err(), "{ddl}");
+    }
+}
+
+/// The spellings of Spark's grammar for the decimal, real, character, 
timestamp and time types:
+/// `dec` and `numeric` are decimal, a bare `decimal` is decimal(10,0), `real` 
is float, and the
+/// time zone clauses name the timestamp and time types, as the server's 
parser reads them.
+#[test]
+fn from_ddl_type_spellings_as_spark() {
+    let field = |name: &str, data_type: DataType| DataType::Struct {
+        fields: vec![StructField {
+            name: name.to_string(),
+            data_type,
+            nullable: true,
+            metadata: BTreeMap::new(),
+        }],
+    };
+    let decimal = |precision, scale| DataType::Decimal { precision, scale };
+    for (ddl, expected) in [
+        ("decimal", decimal(10, 0)),
+        ("decimal(10)", decimal(10, 0)),
+        ("decimal (10, 2)", decimal(10, 2)),
+        ("dec", decimal(10, 0)),
+        ("dec(5,1)", decimal(5, 1)),
+        ("dec(5)", decimal(5, 0)),
+        ("NUMERIC", decimal(10, 0)),
+        ("numeric(10,2)", decimal(10, 2)),
+        ("real", DataType::Float),
+        ("character(5)", DataType::Char { length: 5 }),
+        ("timestamp_ltz", DataType::Timestamp),
+        ("timestamp without time zone", DataType::TimestampNtz),
+        ("timestamp with local time zone", DataType::Timestamp),
+        ("Timestamp  With Local Time Zone", DataType::Timestamp),
+        ("timestamp(6)", DataType::Timestamp),
+        ("timestamp(6) without time zone", DataType::TimestampNtz),
+        ("timestamp_ntz(6)", DataType::TimestampNtz),
+        ("timestamp(9)", DataType::TimestampLtzNanos { precision: 9 }),
+        (
+            "timestamp(9) without time zone",
+            DataType::TimestampNtzNanos { precision: 9 },
+        ),
+        (
+            "timestamp_ltz(7)",
+            DataType::TimestampLtzNanos { precision: 7 },
+        ),
+        ("time without time zone", DataType::Time { precision: 6 }),
+        ("time(3) without time zone", DataType::Time { precision: 3 }),
+        ("a decimal", field("a", decimal(10, 0))),
+        ("a: numeric(10,2)", field("a", decimal(10, 2))),
+        ("a real", field("a", DataType::Float)),
+        (
+            "a timestamp without time zone",
+            field("a", DataType::TimestampNtz),
+        ),
+    ] {
+        assert_eq!(DataType::from_ddl(ddl).unwrap(), expected, "{ddl}");
+    }
+    for ddl in [
+        "character",
+        "char",
+        "varchar",
+        "timestamp(3)",
+        "timestamp with time zone",
+        "time with local time zone",
+        "timestamp_ltz(9) with local time zone",
+        "timestamp(9) with time zone",
+        "decimal()",
+        "decimal(10,2,3)",
+        "numeric(10,2,3)",
+    ] {
+        assert!(DataType::from_ddl(ddl).is_err(), "{ddl}");
+    }
+}
+
+/// `from_ddl` agrees with the server's parser on the interval ranges, the 
`name:type` fields and
+/// the type spellings above, valid and invalid. Runs only with `SPARK_REMOTE` 
set.
+#[test]
+fn from_ddl_interval_colon_and_spellings_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 [
+        "interval",
+        "interval year",
+        "interval year to month",
+        "interval hour to second",
+        "INTERVAL  DAY   TO SECOND",
+        "a:int",
+        "x:array<int>",
+        "x:struct<a:int>",
+        "int:int",
+        "a: int",
+        "a:int, b:string",
+        "`a:b`:int",
+        "a:int COMMENT 'x:y'",
+        "x:map<string,int>",
+        "a:decimal",
+        "decimal",
+        "decimal(10)",
+        "decimal (10,2)",
+        "dec(5,1)",
+        "numeric",
+        "numeric(10,2)",
+        "real",
+        "a real",
+        "character(5)",
+        "timestamp_ltz",
+        "timestamp without time zone",
+        "timestamp with local time zone",
+        "timestamp(6) with local time zone",
+        "timestamp(9)",
+        "timestamp(9) without time zone",
+        "time without time zone",
+        "a timestamp without time zone",
+        "a: timestamp with local time zone",
+    ] {
+        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 [
+        "interval year to second",
+        "interval day to second xyz",
+        "interval day to",
+        "interval foo",
+        "interval hour to day",
+        "a interval year to second",
+        "a:'x:y' int",
+        "character",
+        "timestamp(3)",
+        "timestamp with time zone",
+        "time with local time zone",
+        "decimal()",
+    ] {
+        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() {


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

Reply via email to