This is an automated email from the ASF dual-hosted git repository.

github-merge-queue[bot] pushed a commit to branch 
gh-readonly-queue/main/pr-11931-00788df81b052d817e16dade9cf67f6ebd81c97a
in repository https://gitbox.apache.org/repos/asf/arrow-rs.git

commit 64e0425477213641fd717a7ae2b283ca60f51669
Author: timmyb32r <[email protected]>
AuthorDate: Fri Nov 13 01:44:02 2026 +0000

    Fix escaping in DataType parsing and list field names (#11931)
    
    ### Which issue does this PR close?
    
    None — standalone bug fix.
    
    ### Rationale for this change
    
    Formatting a `DataType` and parsing it back can change field names or
    fail when names contain quotes or backslashes. The parser preserves
    escape characters instead of decoding them, and list field names are
    formatted without escaping.
    
    For example, a struct field named `a"b` gains an extra backslash after a
    round trip.
    
    ### What changes are included in this PR?
    
    Decode escaped quotes, backslashes, control characters, and Unicode
    escapes in quoted strings. Reject malformed escape sequences.
    
    Escape custom field names consistently for List, LargeList, ListView,
    LargeListView, and FixedSizeList.
    
    ### Are these changes tested?
    
    Added regression tests covering:
    - Round trips for struct field names, list field names, and timestamp
    strings containing special characters.
    - The exact escaped representation of list field names.
    - Decoding supported escapes and rejecting malformed escapes and invalid
    Unicode scalar values.
    
    The round-trip regression test fails before the fix and passes
    afterward.
    
    ### Are there any significant user-facing changes?
    
    No breaking public API changes. Malformed escape sequences now return a
    parse error.
    
    ### AI assistance
    
    Codex identified the issue, generated the fix and regression tests, ran
    validation, and drafted this PR description.
---
 arrow-schema/src/datatype_display.rs |  31 +++++---
 arrow-schema/src/datatype_parse.rs   | 138 +++++++++++++++++++++++++++++------
 2 files changed, 137 insertions(+), 32 deletions(-)

diff --git a/arrow-schema/src/datatype_display.rs 
b/arrow-schema/src/datatype_display.rs
index 691b831b1f..ef2d23f81d 100644
--- a/arrow-schema/src/datatype_display.rs
+++ b/arrow-schema/src/datatype_display.rs
@@ -26,6 +26,15 @@ impl Display for DataType {
             format!("{name:?}: {maybe_nullable}{data_type}{metadata_str}")
         }
 
+        fn format_list_field_name(name: &str) -> String {
+            if name == "item" {
+                String::new()
+            } else {
+                let escaped: String = 
name.chars().flat_map(char::escape_debug).collect();
+                format!(", field: '{escaped}'")
+            }
+        }
+
         // A lot of these can still be improved a lot.
         // _Some_ of these can be parsed with `FromStr`, but not all (YET!).
         // The goal is that the formatting should always be
@@ -85,11 +94,7 @@ impl Display for DataType {
                 let name = field.name();
                 let maybe_nullable = format_nullability(field);
                 let data_type = field.data_type();
-                let field_name_str = if name == "item" {
-                    String::default()
-                } else {
-                    format!(", field: '{name}'")
-                };
+                let field_name_str = format_list_field_name(name);
                 let metadata_str = format_metadata(field.metadata());
 
                 // e.g. `LargeList(non-null Uint32)
@@ -102,11 +107,7 @@ impl Display for DataType {
                 let name = field.name();
                 let maybe_nullable = format_nullability(field);
                 let data_type = field.data_type();
-                let field_name_str = if name == "item" {
-                    String::default()
-                } else {
-                    format!(", field: '{name}'")
-                };
+                let field_name_str = format_list_field_name(name);
                 let metadata_str = format_metadata(field.metadata());
 
                 write!(
@@ -212,6 +213,16 @@ mod tests {
 
     use super::*;
 
+    #[test]
+    fn test_display_escaped_list_field_name() {
+        let field = Arc::new(Field::new("a'b\\c\"d\n", DataType::Int32, true));
+        let data_type = DataType::List(field);
+        assert_eq!(
+            data_type.to_string(),
+            r#"List(Int32, field: 'a\'b\\c\"d\n')"#
+        );
+    }
+
     #[test]
     fn test_display_list() {
         let list_data_type = 
DataType::List(Arc::new(Field::new_list_field(DataType::Int32, true)));
diff --git a/arrow-schema/src/datatype_parse.rs 
b/arrow-schema/src/datatype_parse.rs
index 5d7d80645e..69e9e50581 100644
--- a/arrow-schema/src/datatype_parse.rs
+++ b/arrow-schema/src/datatype_parse.rs
@@ -854,8 +854,6 @@ impl<'a> Tokenizer<'a> {
         // reset temp space
         self.word.clear();
 
-        let mut is_escaped = false;
-
         loop {
             match self.next_char() {
                 None => {
@@ -864,29 +862,16 @@ impl<'a> Tokenizer<'a> {
                         self.word
                     )));
                 }
-                Some(c) => match c {
-                    '\\' => {
-                        is_escaped = true;
-                        self.word.push(c);
-                    }
-                    c if c == quote => {
-                        if is_escaped {
-                            self.word.push(c);
-                            is_escaped = false;
-                        } else {
-                            break;
-                        }
-                    }
-                    c => {
-                        self.word.push(c);
-                    }
-                },
+                Some(c) if c == quote => break,
+                Some('\\') => {
+                    let c = self.parse_escape()?;
+                    self.word.push(c);
+                }
+                Some(c) => self.word.push(c),
             }
         }
 
-        let val: String = self.word.parse().map_err(|err| {
-            ArrowError::ParseError(format!("Failed to parse string: \"{}\": 
{err}", self.word))
-        })?;
+        let val = self.word.clone();
 
         if val.is_empty() {
             // Using empty strings as field names is just asking for trouble
@@ -898,6 +883,47 @@ impl<'a> Tokenizer<'a> {
             QuoteType::Single => Ok(Token::SingleQuotedString(val)),
         }
     }
+
+    /// Decodes an escape emitted by Rust debug formatting.
+    fn parse_escape(&mut self) -> ArrowResult<char> {
+        match self.next_char() {
+            Some('\\') => Ok('\\'),
+            Some('"') => Ok('"'),
+            Some('\'') => Ok('\''),
+            Some('n') => Ok('\n'),
+            Some('r') => Ok('\r'),
+            Some('t') => Ok('\t'),
+            Some('0') => Ok('\0'),
+            Some('u') => self.parse_unicode_escape(),
+            Some(c) => Err(make_error(
+                self.val,
+                &format!("invalid escape sequence: \\{c}"),
+            )),
+            None => Err(make_error(self.val, "unterminated escape sequence")),
+        }
+    }
+
+    fn parse_unicode_escape(&mut self) -> ArrowResult<char> {
+        if self.next_char() != Some('{') {
+            return Err(make_error(self.val, "expected '{' after \\u"));
+        }
+
+        let mut value = 0;
+        let mut digits = 0;
+        loop {
+            match self.next_char() {
+                Some('}') if digits != 0 => {
+                    return char::from_u32(value)
+                        .ok_or_else(|| make_error(self.val, "invalid Unicode 
scalar value"));
+                }
+                Some(c) if c.is_ascii_hexdigit() && digits < 6 => {
+                    value = value * 16 + c.to_digit(16).unwrap();
+                    digits += 1;
+                }
+                _ => return Err(make_error(self.val, "invalid Unicode 
escape")),
+            }
+        }
+    }
 }
 
 impl Iterator for Tokenizer<'_> {
@@ -1034,6 +1060,74 @@ impl Display for Token {
 mod test {
     use super::*;
 
+    #[test]
+    fn test_escaped_strings_round_trip() {
+        for name in [
+            "a\"b",
+            "a'b",
+            "a\\b",
+            "trailing\\",
+            "\\\"",
+            "\\\\\"",
+            "line\nbreak",
+            "tab\treturn\r",
+            "nul\0",
+            "control\u{7f}",
+            "unicode\u{200d}é",
+            r"\n",
+            r"trailing\\",
+            "\u{1}\u{8}\u{b}\u{c}\u{1b}",
+        ] {
+            let field = Arc::new(Field::new(name, DataType::Int32, true));
+            for data_type in [
+                DataType::Struct(vec![field.clone()].into()),
+                DataType::List(field.clone()),
+                DataType::LargeList(field.clone()),
+                DataType::ListView(field.clone()),
+                DataType::LargeListView(field.clone()),
+                DataType::FixedSizeList(field, 2),
+                DataType::Timestamp(TimeUnit::Second, Some(name.into())),
+            ] {
+                round_trip(data_type);
+            }
+        }
+    }
+
+    #[test]
+    fn test_parse_quoted_escapes() {
+        for (input, expected) in [
+            (r#""a\"b""#, "a\"b"),
+            (r"'a\'b'", "a'b"),
+            (r#""a\\b""#, "a\\b"),
+            (r#""\n\r\t\0""#, "\n\r\t\0"),
+            (r#""\u{1f980}""#, "🦀"),
+            (r#""\u{000061}""#, "a"),
+            (r#""\u{10ffff}""#, "\u{10ffff}"),
+        ] {
+            let token = Tokenizer::new(input).next().unwrap().unwrap();
+            assert!(
+                matches!(token, Token::DoubleQuotedString(s) | 
Token::SingleQuotedString(s) if s == expected)
+            );
+        }
+    }
+
+    #[test]
+    fn test_invalid_quoted_escapes() {
+        for input in [
+            r#""\q""#,
+            r#""trailing\"#,
+            r#""\u{}""#,
+            r#""\u{xyz}""#,
+            r#""\u{d800}""#,
+            r#""\u{110000}""#,
+            r#""\u{0000000}""#,
+            r#""\u1234""#,
+            r#""\u{1234""#,
+        ] {
+            assert!(Tokenizer::new(input).next().unwrap().is_err(), "{input}");
+        }
+    }
+
     #[test]
     fn test_parse_data_type() {
         // this ensures types can be parsed correctly from their string 
representations

Reply via email to