1use std::{fmt::Display, iter::Peekable, str::Chars, sync::Arc};
6
7use crate::{
8 ArrowError, DECIMAL32_MAX_PRECISION, DECIMAL64_MAX_PRECISION, DECIMAL128_MAX_PRECISION,
9 DECIMAL256_MAX_PRECISION, DataType, Field, Fields, IntervalUnit, TimeUnit, UnionFields,
10 UnionMode,
11};
12
13pub(crate) fn parse_data_type(val: &str) -> ArrowResult<DataType> {
17 Parser::new(val).parse()
18}
19
20type ArrowResult<T> = Result<T, ArrowError>;
21
22fn make_error(val: &str, msg: &str) -> ArrowError {
23 let msg = format!(
24 "Unsupported type '{val}'. Must be a supported arrow type name such as 'Int32' or 'Timestamp(ns)'. Error {msg}"
25 );
26 ArrowError::ParseError(msg)
27}
28
29fn make_error_expected(val: &str, expected: &Token, actual: &Token) -> ArrowError {
30 make_error(val, &format!("Expected '{expected}', got '{actual}'"))
31}
32
33#[derive(Debug)]
35struct Parser<'a> {
36 val: &'a str,
37 tokenizer: Peekable<Tokenizer<'a>>,
38}
39
40impl<'a> Parser<'a> {
41 fn new(val: &'a str) -> Self {
42 Self {
43 val,
44 tokenizer: Tokenizer::new(val).peekable(),
45 }
46 }
47
48 fn parse(mut self) -> ArrowResult<DataType> {
49 let data_type = self.parse_next_type()?;
50 if self.tokenizer.next().is_some() {
52 Err(make_error(
53 self.val,
54 &format!("checking trailing content after parsing '{data_type}'"),
55 ))
56 } else {
57 Ok(data_type)
58 }
59 }
60
61 fn parse_next_type(&mut self) -> ArrowResult<DataType> {
63 match self.next_token()? {
64 Token::SimpleType(data_type) => Ok(data_type),
65 Token::Timestamp => self.parse_timestamp(),
66 Token::Time32 => self.parse_time32(),
67 Token::Time64 => self.parse_time64(),
68 Token::Duration => self.parse_duration(),
69 Token::Interval => self.parse_interval(),
70 Token::FixedSizeBinary => self.parse_fixed_size_binary(),
71 Token::Decimal32 => self.parse_decimal_32(),
72 Token::Decimal64 => self.parse_decimal_64(),
73 Token::Decimal128 => self.parse_decimal_128(),
74 Token::Decimal256 => self.parse_decimal_256(),
75 Token::Dictionary => self.parse_dictionary(),
76 Token::List => self.parse_list(),
77 Token::ListView => self.parse_list_view(),
78 Token::LargeList => self.parse_large_list(),
79 Token::LargeListView => self.parse_large_list_view(),
80 Token::FixedSizeList => self.parse_fixed_size_list(),
81 Token::Struct => self.parse_struct(),
82 Token::Union => self.parse_union(),
83 Token::Map => self.parse_map(),
84 Token::RunEndEncoded => self.parse_run_end_encoded(),
85 tok => Err(make_error(
86 self.val,
87 &format!("finding next type, got unexpected '{tok}'"),
88 )),
89 }
90 }
91
92 fn parse_field(&mut self) -> ArrowResult<Field> {
97 let name = self.parse_double_quoted_string("Field")?;
98 self.expect_token(Token::Colon)?;
99 let nullable = self.parse_opt_nullable();
100 let data_type = self.parse_next_type()?;
101 Ok(Field::new(name, data_type, nullable))
102 }
103
104 fn parse_list_field(&mut self, context: &str) -> ArrowResult<Field> {
110 let nullable = self.parse_opt_nullable();
111 let data_type = self.parse_next_type()?;
112
113 let field_name = if self
115 .tokenizer
116 .next_if(|next| matches!(next, Ok(Token::Comma)))
117 .is_none()
118 {
119 Field::LIST_FIELD_DEFAULT_NAME.into()
120 } else {
121 self.expect_token(Token::Field)?;
123 self.expect_token(Token::Colon)?;
124 self.parse_single_quoted_string(context)?
125 };
126
127 Ok(Field::new(field_name, data_type, nullable))
128 }
129
130 fn parse_list(&mut self) -> ArrowResult<DataType> {
133 self.expect_token(Token::LParen)?;
134 let field = self.parse_list_field("List")?;
135 self.expect_token(Token::RParen)?;
136 Ok(DataType::List(Arc::new(field)))
137 }
138
139 fn parse_list_view(&mut self) -> ArrowResult<DataType> {
142 self.expect_token(Token::LParen)?;
143 let field = self.parse_list_field("ListView")?;
144 self.expect_token(Token::RParen)?;
145 Ok(DataType::ListView(Arc::new(field)))
146 }
147
148 fn parse_large_list(&mut self) -> ArrowResult<DataType> {
151 self.expect_token(Token::LParen)?;
152 let field = self.parse_list_field("LargeList")?;
153 self.expect_token(Token::RParen)?;
154 Ok(DataType::LargeList(Arc::new(field)))
155 }
156
157 fn parse_large_list_view(&mut self) -> ArrowResult<DataType> {
160 self.expect_token(Token::LParen)?;
161 let field = self.parse_list_field("LargeListView")?;
162 self.expect_token(Token::RParen)?;
163 Ok(DataType::LargeListView(Arc::new(field)))
164 }
165
166 fn parse_fixed_size_list(&mut self) -> ArrowResult<DataType> {
173 self.expect_token(Token::LParen)?;
174 let length = self.parse_i32("FixedSizeList")?;
175 if length < 0 {
176 return Err(make_error(
177 self.val,
178 &format!("FixedSizeList length must be non-negative, got {length}"),
179 ));
180 }
181 match self.next_token()? {
182 Token::X => {
184 let field = self.parse_list_field("FixedSizeList")?;
185 self.expect_token(Token::RParen)?;
186 Ok(DataType::FixedSizeList(Arc::new(field), length))
187 }
188 Token::Comma => {
190 let data_type = self.parse_next_type()?;
191 self.expect_token(Token::RParen)?;
192 Ok(DataType::FixedSizeList(
193 Arc::new(Field::new_list_field(data_type, true)),
194 length,
195 ))
196 }
197 tok => Err(make_error(
198 self.val,
199 &format!("Expected 'x' or ',' after length for FixedSizeList, got '{tok}'"),
200 )),
201 }
202 }
203
204 fn parse_time_unit(&mut self, context: &str) -> ArrowResult<TimeUnit> {
206 match self.next_token()? {
207 Token::TimeUnit(time_unit) => Ok(time_unit),
208 tok => Err(make_error(
209 self.val,
210 &format!("finding TimeUnit for {context}, got {tok}"),
211 )),
212 }
213 }
214
215 fn parse_double_quoted_string(&mut self, context: &str) -> ArrowResult<String> {
217 let token = self.next_token()?;
218 if let Token::DoubleQuotedString(string) = token {
219 Ok(string)
220 } else {
221 Err(make_error(
222 self.val,
223 &format!("expected double quoted string for {context}, got '{token}'"),
224 ))
225 }
226 }
227
228 fn parse_single_quoted_string(&mut self, context: &str) -> ArrowResult<String> {
230 let token = self.next_token()?;
231 if let Token::SingleQuotedString(string) = token {
232 Ok(string)
233 } else {
234 Err(make_error(
235 self.val,
236 &format!("expected single quoted string for {context}, got '{token}'"),
237 ))
238 }
239 }
240
241 fn parse_i64(&mut self, context: &str) -> ArrowResult<i64> {
243 match self.next_token()? {
244 Token::Integer(v) => Ok(v),
245 tok => Err(make_error(
246 self.val,
247 &format!("finding i64 for {context}, got '{tok}'"),
248 )),
249 }
250 }
251
252 fn parse_i32(&mut self, context: &str) -> ArrowResult<i32> {
254 let length = self.parse_i64(context)?;
255 length.try_into().map_err(|e| {
256 make_error(
257 self.val,
258 &format!("converting {length} into i32 for {context}: {e}"),
259 )
260 })
261 }
262
263 fn parse_i8(&mut self, context: &str) -> ArrowResult<i8> {
265 let length = self.parse_i64(context)?;
266 length.try_into().map_err(|e| {
267 make_error(
268 self.val,
269 &format!("converting {length} into i8 for {context}: {e}"),
270 )
271 })
272 }
273
274 fn parse_u8(&mut self, context: &str) -> ArrowResult<u8> {
276 let length = self.parse_i64(context)?;
277 length.try_into().map_err(|e| {
278 make_error(
279 self.val,
280 &format!("converting {length} into u8 for {context}: {e}"),
281 )
282 })
283 }
284
285 fn parse_timestamp(&mut self) -> ArrowResult<DataType> {
287 self.expect_token(Token::LParen)?;
288 let time_unit = self.parse_time_unit("Timestamp")?;
289
290 let timezone;
291 match self.next_token()? {
292 Token::Comma => {
293 match self.next_token()? {
294 Token::None => {
296 timezone = None;
297 }
298 Token::Some => {
300 self.expect_token(Token::LParen)?;
301 timezone = Some(self.parse_double_quoted_string("Timezone")?);
302 self.expect_token(Token::RParen)?;
303 }
304 Token::DoubleQuotedString(tz) => {
305 timezone = Some(tz);
307 }
308 tok => {
309 return Err(make_error(
310 self.val,
311 &format!("Expected None, Some, or a timezone string, got {tok:?}"),
312 ));
313 }
314 }
315 self.expect_token(Token::RParen)?;
316 }
317 Token::RParen => {
319 timezone = None;
320 }
321 next_token => {
322 return Err(make_error(
323 self.val,
324 &format!("Expected comma followed by a timezone, or an ), got {next_token:?}"),
325 ));
326 }
327 }
328 Ok(DataType::Timestamp(time_unit, timezone.map(Into::into)))
329 }
330
331 fn parse_time32(&mut self) -> ArrowResult<DataType> {
333 self.expect_token(Token::LParen)?;
334 let time_unit = self.parse_time_unit("Time32")?;
335 match time_unit {
336 TimeUnit::Second | TimeUnit::Millisecond => (),
337 TimeUnit::Microsecond | TimeUnit::Nanosecond => {
338 return Err(make_error(
339 self.val,
340 &format!("Time32 time unit must be 's' or 'ms', got '{time_unit}'"),
341 ));
342 }
343 }
344 self.expect_token(Token::RParen)?;
345 Ok(DataType::Time32(time_unit))
346 }
347
348 fn parse_time64(&mut self) -> ArrowResult<DataType> {
350 self.expect_token(Token::LParen)?;
351 let time_unit = self.parse_time_unit("Time64")?;
352 match time_unit {
353 TimeUnit::Microsecond | TimeUnit::Nanosecond => (),
354 TimeUnit::Second | TimeUnit::Millisecond => {
355 return Err(make_error(
356 self.val,
357 &format!("Time64 time unit must be 'µs' or 'ns', got '{time_unit}'"),
358 ));
359 }
360 }
361 self.expect_token(Token::RParen)?;
362 Ok(DataType::Time64(time_unit))
363 }
364
365 fn parse_duration(&mut self) -> ArrowResult<DataType> {
367 self.expect_token(Token::LParen)?;
368 let time_unit = self.parse_time_unit("Duration")?;
369 self.expect_token(Token::RParen)?;
370 Ok(DataType::Duration(time_unit))
371 }
372
373 fn parse_interval(&mut self) -> ArrowResult<DataType> {
375 self.expect_token(Token::LParen)?;
376 let interval_unit = match self.next_token()? {
377 Token::IntervalUnit(interval_unit) => interval_unit,
378 tok => {
379 return Err(make_error(
380 self.val,
381 &format!("finding IntervalUnit for Interval, got {tok}"),
382 ));
383 }
384 };
385 self.expect_token(Token::RParen)?;
386 Ok(DataType::Interval(interval_unit))
387 }
388
389 fn parse_fixed_size_binary(&mut self) -> ArrowResult<DataType> {
391 self.expect_token(Token::LParen)?;
392 let length = self.parse_i32("FixedSizeBinary")?;
393 if length < 0 {
394 return Err(make_error(
395 self.val,
396 &format!("FixedSizeBinary length must be non-negative, got {length}"),
397 ));
398 }
399 self.expect_token(Token::RParen)?;
400 Ok(DataType::FixedSizeBinary(length))
401 }
402
403 fn validate_decimal(
404 &self,
405 precision: u8,
406 scale: i8,
407 type_name: &str,
408 max_precision: u8,
409 ) -> ArrowResult<()> {
410 if precision == 0 || precision > max_precision {
411 return Err(make_error(
412 self.val,
413 &format!(
414 "{type_name} precision must be in range [1, {max_precision}], got '{precision}'"
415 ),
416 ));
417 }
418 if scale > 0 && scale as u8 > precision {
419 return Err(make_error(
420 self.val,
421 &format!(
422 "{type_name} scale '{scale}' cannot be greater than precision '{precision}'"
423 ),
424 ));
425 }
426 Ok(())
427 }
428
429 fn parse_decimal_32(&mut self) -> ArrowResult<DataType> {
431 self.expect_token(Token::LParen)?;
432 let precision = self.parse_u8("Decimal32")?;
433 self.expect_token(Token::Comma)?;
434 let scale = self.parse_i8("Decimal32")?;
435 self.expect_token(Token::RParen)?;
436 self.validate_decimal(precision, scale, "Decimal32", DECIMAL32_MAX_PRECISION)?;
437 Ok(DataType::Decimal32(precision, scale))
438 }
439
440 fn parse_decimal_64(&mut self) -> ArrowResult<DataType> {
442 self.expect_token(Token::LParen)?;
443 let precision = self.parse_u8("Decimal64")?;
444 self.expect_token(Token::Comma)?;
445 let scale = self.parse_i8("Decimal64")?;
446 self.expect_token(Token::RParen)?;
447 self.validate_decimal(precision, scale, "Decimal64", DECIMAL64_MAX_PRECISION)?;
448 Ok(DataType::Decimal64(precision, scale))
449 }
450
451 fn parse_decimal_128(&mut self) -> ArrowResult<DataType> {
453 self.expect_token(Token::LParen)?;
454 let precision = self.parse_u8("Decimal128")?;
455 self.expect_token(Token::Comma)?;
456 let scale = self.parse_i8("Decimal128")?;
457 self.expect_token(Token::RParen)?;
458 self.validate_decimal(precision, scale, "Decimal128", DECIMAL128_MAX_PRECISION)?;
459 Ok(DataType::Decimal128(precision, scale))
460 }
461
462 fn parse_decimal_256(&mut self) -> ArrowResult<DataType> {
464 self.expect_token(Token::LParen)?;
465 let precision = self.parse_u8("Decimal256")?;
466 self.expect_token(Token::Comma)?;
467 let scale = self.parse_i8("Decimal256")?;
468 self.expect_token(Token::RParen)?;
469 self.validate_decimal(precision, scale, "Decimal256", DECIMAL256_MAX_PRECISION)?;
470 Ok(DataType::Decimal256(precision, scale))
471 }
472
473 fn parse_dictionary(&mut self) -> ArrowResult<DataType> {
475 self.expect_token(Token::LParen)?;
476 let key_type = self.parse_next_type()?;
477 self.expect_token(Token::Comma)?;
478 let value_type = self.parse_next_type()?;
479 self.expect_token(Token::RParen)?;
480 Ok(DataType::Dictionary(
481 Box::new(key_type),
482 Box::new(value_type),
483 ))
484 }
485
486 fn parse_struct(&mut self) -> ArrowResult<DataType> {
488 self.expect_token(Token::LParen)?;
489 let mut fields = Vec::new();
490 loop {
491 if self
492 .tokenizer
493 .next_if(|next| matches!(next, Ok(Token::RParen)))
494 .is_some()
495 {
496 break;
497 }
498
499 let field = self.parse_field()?;
500 fields.push(Arc::new(field));
501 match self.next_token()? {
502 Token::Comma => {}
503 Token::RParen => break,
504 tok => {
505 return Err(make_error(
506 self.val,
507 &format!(
508 "Unexpected token while parsing Struct fields. Expected ',' or ')', but got '{tok}'"
509 ),
510 ));
511 }
512 }
513 }
514 Ok(DataType::Struct(Fields::from(fields)))
515 }
516
517 fn parse_union(&mut self) -> ArrowResult<DataType> {
520 self.expect_token(Token::LParen)?;
521 let union_mode = self.parse_union_mode()?;
522 let mut type_ids = vec![];
523 let mut fields = vec![];
524 loop {
525 if self
526 .tokenizer
527 .next_if(|next| matches!(next, Ok(Token::RParen)))
528 .is_some()
529 {
530 break;
531 }
532 self.expect_token(Token::Comma)?;
533 let (type_id, field) = self.parse_union_field()?;
534 type_ids.push(type_id);
535 fields.push(field);
536 }
537 Ok(DataType::Union(
538 UnionFields::try_new(type_ids, fields)?,
539 union_mode,
540 ))
541 }
542
543 fn parse_union_mode(&mut self) -> ArrowResult<UnionMode> {
545 match self.next_token()? {
546 Token::UnionMode(union_mode) => Ok(union_mode),
547 tok => Err(make_error(
548 self.val,
549 &format!("finding UnionMode for Union, got {tok}"),
550 )),
551 }
552 }
553
554 fn parse_union_field(&mut self) -> ArrowResult<(i8, Field)> {
557 let type_id = self.parse_i8("UnionField")?;
558 self.expect_token(Token::Colon)?;
559 self.expect_token(Token::LParen)?;
560 let field = self.parse_field()?;
561 self.expect_token(Token::RParen)?;
562 Ok((type_id, field))
563 }
564
565 fn parse_map(&mut self) -> ArrowResult<DataType> {
568 self.expect_token(Token::LParen)?;
569 let field = self.parse_field()?;
570 if field.is_nullable() {
571 return Err(make_error(self.val, "Map entries field cannot be nullable"));
572 }
573 if let DataType::Struct(fields) = field.data_type() {
574 if fields.len() != 2 {
575 return Err(make_error(
576 self.val,
577 &format!(
578 "Map entries must contain two children, got {}",
579 fields.len()
580 ),
581 ));
582 }
583 if fields[0].is_nullable() {
584 return Err(make_error(self.val, "Map key field cannot be nullable"));
585 }
586 } else {
587 return Err(make_error(
588 self.val,
589 &format!(
590 "Map entries must be a Struct type, got {}",
591 field.data_type()
592 ),
593 ));
594 }
595 self.expect_token(Token::Comma)?;
596 let sorted = self.parse_map_sorted()?;
597 self.expect_token(Token::RParen)?;
598 Ok(DataType::Map(Arc::new(field), sorted))
599 }
600
601 fn parse_map_sorted(&mut self) -> ArrowResult<bool> {
603 match self.next_token()? {
604 Token::MapSorted(sorted) => Ok(sorted),
605 tok => Err(make_error(
606 self.val,
607 &format!("Expected sorted or unsorted for a map; got {tok:?}"),
608 )),
609 }
610 }
611
612 fn parse_run_end_encoded(&mut self) -> ArrowResult<DataType> {
617 self.expect_token(Token::LParen)?;
618
619 let verbose = matches!(
621 self.tokenizer.peek(),
622 Some(Ok(Token::DoubleQuotedString(_)))
623 );
624
625 let (run_ends, values) = if verbose {
626 let run_ends = self.parse_field()?;
627 if run_ends.is_nullable() {
628 return Err(make_error(
629 self.val,
630 "RunEndEncoded run_ends field cannot be nullable",
631 ));
632 }
633 self.expect_token(Token::Comma)?;
634 let values = self.parse_field()?;
635 (run_ends, values)
636 } else {
637 if self.parse_opt_nullable() {
638 return Err(make_error(
639 self.val,
640 "RunEndEncoded run_ends field cannot be nullable",
641 ));
642 }
643 let re_type = self.parse_next_type()?;
644 self.expect_token(Token::Comma)?;
645 let v_nullable = self.parse_opt_nullable();
646 let v_type = self.parse_next_type()?;
647 (
648 Field::new(Field::REE_RUN_ENDS_FIELD_DEFAULT_NAME, re_type, false),
649 Field::new(Field::REE_VALUES_FIELD_DEFAULT_NAME, v_type, v_nullable),
650 )
651 };
652
653 self.expect_token(Token::RParen)?;
654 Ok(DataType::RunEndEncoded(
655 Arc::new(run_ends),
656 Arc::new(values),
657 ))
658 }
659
660 fn parse_opt_nullable(&mut self) -> bool {
662 let tok = self
663 .tokenizer
664 .next_if(|next| matches!(next, Ok(Token::NonNull | Token::Nullable)));
665 !matches!(tok, Some(Ok(Token::NonNull)))
666 }
667
668 fn next_token(&mut self) -> ArrowResult<Token> {
670 match self.tokenizer.next() {
671 None => Err(make_error(self.val, "finding next token")),
672 Some(token) => token,
673 }
674 }
675
676 fn expect_token(&mut self, tok: Token) -> ArrowResult<()> {
678 let next_token = self.next_token()?;
679 if next_token == tok {
680 Ok(())
681 } else {
682 Err(make_error_expected(self.val, &tok, &next_token))
683 }
684 }
685}
686
687fn is_separator(c: char) -> bool {
689 c == '(' || c == ')' || c == ',' || c == ':' || c == ' '
690}
691
692enum QuoteType {
693 Double,
694 Single,
695}
696
697#[derive(Debug)]
698struct Tokenizer<'a> {
707 val: &'a str,
708 chars: Peekable<Chars<'a>>,
709 word: String,
711}
712
713impl<'a> Tokenizer<'a> {
714 fn new(val: &'a str) -> Self {
715 Self {
716 val,
717 chars: val.chars().peekable(),
718 word: String::new(),
719 }
720 }
721
722 fn peek_next_char(&mut self) -> Option<char> {
724 self.chars.peek().copied()
725 }
726
727 fn next_char(&mut self) -> Option<char> {
729 self.chars.next()
730 }
731
732 fn parse_word(&mut self) -> ArrowResult<Token> {
735 self.word.clear();
737 loop {
738 match self.peek_next_char() {
739 None => break,
740 Some(c) if is_separator(c) => break,
741 Some(c) => {
742 self.next_char();
743 self.word.push(c);
744 }
745 }
746 }
747
748 if let Some(c) = self.word.chars().next() {
749 if c == '-' || c.is_numeric() {
751 let val: i64 = self.word.parse().map_err(|e| {
752 make_error(self.val, &format!("parsing {} as integer: {e}", self.word))
753 })?;
754 return Ok(Token::Integer(val));
755 }
756 }
757
758 let token = match self.word.as_str() {
760 "Null" => Token::SimpleType(DataType::Null),
761 "Boolean" => Token::SimpleType(DataType::Boolean),
762
763 "Int8" => Token::SimpleType(DataType::Int8),
764 "Int16" => Token::SimpleType(DataType::Int16),
765 "Int32" => Token::SimpleType(DataType::Int32),
766 "Int64" => Token::SimpleType(DataType::Int64),
767
768 "UInt8" => Token::SimpleType(DataType::UInt8),
769 "UInt16" => Token::SimpleType(DataType::UInt16),
770 "UInt32" => Token::SimpleType(DataType::UInt32),
771 "UInt64" => Token::SimpleType(DataType::UInt64),
772
773 "Utf8" => Token::SimpleType(DataType::Utf8),
774 "LargeUtf8" => Token::SimpleType(DataType::LargeUtf8),
775 "Utf8View" => Token::SimpleType(DataType::Utf8View),
776 "Binary" => Token::SimpleType(DataType::Binary),
777 "BinaryView" => Token::SimpleType(DataType::BinaryView),
778 "LargeBinary" => Token::SimpleType(DataType::LargeBinary),
779
780 "Float16" => Token::SimpleType(DataType::Float16),
781 "Float32" => Token::SimpleType(DataType::Float32),
782 "Float64" => Token::SimpleType(DataType::Float64),
783
784 "Date32" => Token::SimpleType(DataType::Date32),
785 "Date64" => Token::SimpleType(DataType::Date64),
786
787 "List" => Token::List,
788 "ListView" => Token::ListView,
789 "LargeList" => Token::LargeList,
790 "LargeListView" => Token::LargeListView,
791 "FixedSizeList" => Token::FixedSizeList,
792
793 "s" | "Second" => Token::TimeUnit(TimeUnit::Second),
794 "ms" | "Millisecond" => Token::TimeUnit(TimeUnit::Millisecond),
795 "µs" | "us" | "Microsecond" => Token::TimeUnit(TimeUnit::Microsecond),
796 "ns" | "Nanosecond" => Token::TimeUnit(TimeUnit::Nanosecond),
797
798 "Timestamp" => Token::Timestamp,
799 "Time32" => Token::Time32,
800 "Time64" => Token::Time64,
801 "Duration" => Token::Duration,
802 "Interval" => Token::Interval,
803 "Dictionary" => Token::Dictionary,
804
805 "FixedSizeBinary" => Token::FixedSizeBinary,
806
807 "Decimal32" => Token::Decimal32,
808 "Decimal64" => Token::Decimal64,
809 "Decimal128" => Token::Decimal128,
810 "Decimal256" => Token::Decimal256,
811
812 "YearMonth" => Token::IntervalUnit(IntervalUnit::YearMonth),
813 "DayTime" => Token::IntervalUnit(IntervalUnit::DayTime),
814 "MonthDayNano" => Token::IntervalUnit(IntervalUnit::MonthDayNano),
815
816 "Some" => Token::Some,
817 "None" => Token::None,
818
819 "non-null" => Token::NonNull,
820 "nullable" => Token::Nullable,
821 "field" => Token::Field,
822 "x" => Token::X,
823
824 "Struct" => Token::Struct,
825
826 "Union" => Token::Union,
827 "Sparse" => Token::UnionMode(UnionMode::Sparse),
828 "Dense" => Token::UnionMode(UnionMode::Dense),
829
830 "Map" => Token::Map,
831 "sorted" => Token::MapSorted(true),
832 "unsorted" => Token::MapSorted(false),
833
834 "RunEndEncoded" => Token::RunEndEncoded,
835
836 token => {
837 return Err(make_error(self.val, &format!("unknown token: {token}")));
838 }
839 };
840 Ok(token)
841 }
842
843 fn parse_quoted_string(&mut self, quote_type: QuoteType) -> ArrowResult<Token> {
845 let quote = match quote_type {
846 QuoteType::Double => '\"',
847 QuoteType::Single => '\'',
848 };
849
850 if self.next_char() != Some(quote) {
851 return Err(make_error(self.val, "Expected \""));
852 }
853
854 self.word.clear();
856
857 loop {
858 match self.next_char() {
859 None => {
860 return Err(ArrowError::ParseError(format!(
861 "Unterminated string at: \"{}",
862 self.word
863 )));
864 }
865 Some(c) if c == quote => break,
866 Some('\\') => {
867 let c = self.parse_escape()?;
868 self.word.push(c);
869 }
870 Some(c) => self.word.push(c),
871 }
872 }
873
874 let val = self.word.clone();
875
876 if val.is_empty() {
877 return Err(make_error(self.val, "empty strings aren't allowed"));
879 }
880
881 match quote_type {
882 QuoteType::Double => Ok(Token::DoubleQuotedString(val)),
883 QuoteType::Single => Ok(Token::SingleQuotedString(val)),
884 }
885 }
886
887 fn parse_escape(&mut self) -> ArrowResult<char> {
889 match self.next_char() {
890 Some('\\') => Ok('\\'),
891 Some('"') => Ok('"'),
892 Some('\'') => Ok('\''),
893 Some('n') => Ok('\n'),
894 Some('r') => Ok('\r'),
895 Some('t') => Ok('\t'),
896 Some('0') => Ok('\0'),
897 Some('u') => self.parse_unicode_escape(),
898 Some(c) => Err(make_error(
899 self.val,
900 &format!("invalid escape sequence: \\{c}"),
901 )),
902 None => Err(make_error(self.val, "unterminated escape sequence")),
903 }
904 }
905
906 fn parse_unicode_escape(&mut self) -> ArrowResult<char> {
907 if self.next_char() != Some('{') {
908 return Err(make_error(self.val, "expected '{' after \\u"));
909 }
910
911 let mut value = 0;
912 let mut digits = 0;
913 loop {
914 match self.next_char() {
915 Some('}') if digits != 0 => {
916 return char::from_u32(value)
917 .ok_or_else(|| make_error(self.val, "invalid Unicode scalar value"));
918 }
919 Some(c) if c.is_ascii_hexdigit() && digits < 6 => {
920 value = value * 16 + c.to_digit(16).unwrap();
921 digits += 1;
922 }
923 _ => return Err(make_error(self.val, "invalid Unicode escape")),
924 }
925 }
926 }
927}
928
929impl Iterator for Tokenizer<'_> {
930 type Item = ArrowResult<Token>;
931
932 fn next(&mut self) -> Option<Self::Item> {
933 loop {
934 match self.peek_next_char()? {
935 ' ' => {
936 self.next_char();
938 }
939 '"' => {
940 return Some(self.parse_quoted_string(QuoteType::Double));
941 }
942 '\'' => {
943 return Some(self.parse_quoted_string(QuoteType::Single));
944 }
945 '(' => {
946 self.next_char();
947 return Some(Ok(Token::LParen));
948 }
949 ')' => {
950 self.next_char();
951 return Some(Ok(Token::RParen));
952 }
953 ',' => {
954 self.next_char();
955 return Some(Ok(Token::Comma));
956 }
957 ':' => {
958 self.next_char();
959 return Some(Ok(Token::Colon));
960 }
961 _ => return Some(self.parse_word()),
962 }
963 }
964 }
965}
966
967#[derive(Debug, PartialEq)]
970enum Token {
971 SimpleType(DataType),
973 Timestamp,
974 Time32,
975 Time64,
976 Duration,
977 Interval,
978 FixedSizeBinary,
979 Decimal32,
980 Decimal64,
981 Decimal128,
982 Decimal256,
983 Dictionary,
984 TimeUnit(TimeUnit),
985 IntervalUnit(IntervalUnit),
986 LParen,
987 RParen,
988 Comma,
989 Colon,
990 Some,
991 None,
992 Integer(i64),
993 DoubleQuotedString(String),
994 SingleQuotedString(String),
995 List,
996 ListView,
997 LargeList,
998 LargeListView,
999 FixedSizeList,
1000 Struct,
1001 Union,
1002 UnionMode(UnionMode),
1003 Map,
1004 MapSorted(bool),
1005 RunEndEncoded,
1006 NonNull,
1007 Nullable,
1008 Field,
1009 X,
1010}
1011
1012impl Display for Token {
1013 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1014 match self {
1015 Token::SimpleType(t) => write!(f, "{t}"),
1016 Token::List => write!(f, "List"),
1017 Token::ListView => write!(f, "ListView"),
1018 Token::LargeList => write!(f, "LargeList"),
1019 Token::LargeListView => write!(f, "LargeListView"),
1020 Token::FixedSizeList => write!(f, "FixedSizeList"),
1021 Token::Timestamp => write!(f, "Timestamp"),
1022 Token::Time32 => write!(f, "Time32"),
1023 Token::Time64 => write!(f, "Time64"),
1024 Token::Duration => write!(f, "Duration"),
1025 Token::Interval => write!(f, "Interval"),
1026 Token::TimeUnit(u) => write!(f, "TimeUnit({u:?})"),
1027 Token::IntervalUnit(u) => write!(f, "IntervalUnit({u:?})"),
1028 Token::LParen => write!(f, "("),
1029 Token::RParen => write!(f, ")"),
1030 Token::Comma => write!(f, ","),
1031 Token::Colon => write!(f, ":"),
1032 Token::Some => write!(f, "Some"),
1033 Token::None => write!(f, "None"),
1034 Token::FixedSizeBinary => write!(f, "FixedSizeBinary"),
1035 Token::Decimal32 => write!(f, "Decimal32"),
1036 Token::Decimal64 => write!(f, "Decimal64"),
1037 Token::Decimal128 => write!(f, "Decimal128"),
1038 Token::Decimal256 => write!(f, "Decimal256"),
1039 Token::Dictionary => write!(f, "Dictionary"),
1040 Token::Integer(v) => write!(f, "Integer({v})"),
1041 Token::DoubleQuotedString(s) => write!(f, "DoubleQuotedString({s})"),
1042 Token::SingleQuotedString(s) => write!(f, "SingleQuotedString({s})"),
1043 Token::Struct => write!(f, "Struct"),
1044 Token::Union => write!(f, "Union"),
1045 Token::UnionMode(m) => write!(f, "{m:?}"),
1046 Token::Map => write!(f, "Map"),
1047 Token::MapSorted(sorted) => {
1048 write!(f, "{}", if *sorted { "sorted" } else { "unsorted" })
1049 }
1050 Token::RunEndEncoded => write!(f, "RunEndEncoded"),
1051 Token::NonNull => write!(f, "non-null"),
1052 Token::Nullable => write!(f, "nullable"),
1053 Token::Field => write!(f, "field"),
1054 Token::X => write!(f, "x"),
1055 }
1056 }
1057}
1058
1059#[cfg(test)]
1060mod test {
1061 use super::*;
1062
1063 #[test]
1064 fn test_escaped_strings_round_trip() {
1065 for name in [
1066 "a\"b",
1067 "a'b",
1068 "a\\b",
1069 "trailing\\",
1070 "\\\"",
1071 "\\\\\"",
1072 "line\nbreak",
1073 "tab\treturn\r",
1074 "nul\0",
1075 "control\u{7f}",
1076 "unicode\u{200d}é",
1077 r"\n",
1078 r"trailing\\",
1079 "\u{1}\u{8}\u{b}\u{c}\u{1b}",
1080 ] {
1081 let field = Arc::new(Field::new(name, DataType::Int32, true));
1082 for data_type in [
1083 DataType::Struct(vec![field.clone()].into()),
1084 DataType::List(field.clone()),
1085 DataType::LargeList(field.clone()),
1086 DataType::ListView(field.clone()),
1087 DataType::LargeListView(field.clone()),
1088 DataType::FixedSizeList(field, 2),
1089 DataType::Timestamp(TimeUnit::Second, Some(name.into())),
1090 ] {
1091 round_trip(data_type);
1092 }
1093 }
1094 }
1095
1096 #[test]
1097 fn test_parse_quoted_escapes() {
1098 for (input, expected) in [
1099 (r#""a\"b""#, "a\"b"),
1100 (r"'a\'b'", "a'b"),
1101 (r#""a\\b""#, "a\\b"),
1102 (r#""\n\r\t\0""#, "\n\r\t\0"),
1103 (r#""\u{1f980}""#, "🦀"),
1104 (r#""\u{000061}""#, "a"),
1105 (r#""\u{10ffff}""#, "\u{10ffff}"),
1106 ] {
1107 let token = Tokenizer::new(input).next().unwrap().unwrap();
1108 assert!(
1109 matches!(token, Token::DoubleQuotedString(s) | Token::SingleQuotedString(s) if s == expected)
1110 );
1111 }
1112 }
1113
1114 #[test]
1115 fn test_invalid_quoted_escapes() {
1116 for input in [
1117 r#""\q""#,
1118 r#""trailing\"#,
1119 r#""\u{}""#,
1120 r#""\u{xyz}""#,
1121 r#""\u{d800}""#,
1122 r#""\u{110000}""#,
1123 r#""\u{0000000}""#,
1124 r#""\u1234""#,
1125 r#""\u{1234""#,
1126 ] {
1127 assert!(matches!(
1128 Tokenizer::new(input).next().unwrap(),
1129 Err(ArrowError::ParseError(_))
1130 ));
1131 }
1132 }
1133
1134 #[test]
1135 fn test_parse_data_type() {
1136 for dt in list_datatypes() {
1138 round_trip(dt)
1139 }
1140 }
1141
1142 fn round_trip(data_type: DataType) {
1145 let data_type_string = data_type.to_string();
1146 println!("Input '{data_type_string}' ({data_type:?})");
1147 let parsed_type = parse_data_type(&data_type_string).unwrap();
1148 assert_eq!(
1149 data_type, parsed_type,
1150 "Mismatch parsing {data_type_string}"
1151 );
1152 }
1153
1154 fn list_datatypes() -> Vec<DataType> {
1155 vec![
1156 DataType::Null,
1160 DataType::Boolean,
1161 DataType::Int8,
1162 DataType::Int16,
1163 DataType::Int32,
1164 DataType::Int64,
1165 DataType::UInt8,
1166 DataType::UInt16,
1167 DataType::UInt32,
1168 DataType::UInt64,
1169 DataType::Float16,
1170 DataType::Float32,
1171 DataType::Float64,
1172 DataType::Timestamp(TimeUnit::Second, None),
1173 DataType::Timestamp(TimeUnit::Millisecond, None),
1174 DataType::Timestamp(TimeUnit::Microsecond, None),
1175 DataType::Timestamp(TimeUnit::Nanosecond, None),
1176 DataType::Timestamp(TimeUnit::Nanosecond, Some("+00:00".into())),
1178 DataType::Timestamp(TimeUnit::Microsecond, Some("+00:00".into())),
1179 DataType::Timestamp(TimeUnit::Millisecond, Some("+00:00".into())),
1180 DataType::Timestamp(TimeUnit::Second, Some("+00:00".into())),
1181 DataType::Timestamp(TimeUnit::Nanosecond, Some("+08:00".into())),
1182 DataType::Timestamp(TimeUnit::Microsecond, Some("+08:00".into())),
1183 DataType::Timestamp(TimeUnit::Millisecond, Some("+08:00".into())),
1184 DataType::Timestamp(TimeUnit::Second, Some("+08:00".into())),
1185 DataType::Date32,
1186 DataType::Date64,
1187 DataType::Time32(TimeUnit::Second),
1188 DataType::Time32(TimeUnit::Millisecond),
1189 DataType::Time64(TimeUnit::Microsecond),
1190 DataType::Time64(TimeUnit::Nanosecond),
1191 DataType::Duration(TimeUnit::Second),
1192 DataType::Duration(TimeUnit::Millisecond),
1193 DataType::Duration(TimeUnit::Microsecond),
1194 DataType::Duration(TimeUnit::Nanosecond),
1195 DataType::Interval(IntervalUnit::YearMonth),
1196 DataType::Interval(IntervalUnit::DayTime),
1197 DataType::Interval(IntervalUnit::MonthDayNano),
1198 DataType::Binary,
1199 DataType::BinaryView,
1200 DataType::FixedSizeBinary(0),
1201 DataType::FixedSizeBinary(1234),
1202 DataType::LargeBinary,
1203 DataType::Utf8,
1204 DataType::Utf8View,
1205 DataType::LargeUtf8,
1206 DataType::Decimal32(7, 6),
1207 DataType::Decimal64(6, 5),
1208 DataType::Decimal128(7, 6),
1209 DataType::Decimal256(6, 5),
1210 DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8)),
1214 DataType::Dictionary(Box::new(DataType::Int8), Box::new(DataType::Utf8)),
1215 DataType::Dictionary(
1216 Box::new(DataType::Int8),
1217 Box::new(DataType::Timestamp(TimeUnit::Nanosecond, None)),
1218 ),
1219 DataType::Dictionary(
1220 Box::new(DataType::Int8),
1221 Box::new(DataType::FixedSizeBinary(23)),
1222 ),
1223 DataType::Dictionary(
1224 Box::new(DataType::Int8),
1225 Box::new(
1226 DataType::Dictionary(Box::new(DataType::Int8), Box::new(DataType::Utf8)),
1228 ),
1229 ),
1230 DataType::Struct(Fields::from(vec![
1231 Field::new("f1", DataType::Int64, true),
1232 Field::new("f2", DataType::Float64, true),
1233 Field::new(
1234 "f3",
1235 DataType::Timestamp(TimeUnit::Second, Some("+08:00".into())),
1236 true,
1237 ),
1238 Field::new(
1239 "f4",
1240 DataType::Dictionary(
1241 Box::new(DataType::Int8),
1242 Box::new(DataType::FixedSizeBinary(23)),
1243 ),
1244 true,
1245 ),
1246 ])),
1247 DataType::Struct(Fields::from(vec![
1248 Field::new("Int64", DataType::Int64, true),
1249 Field::new("Float64", DataType::Float64, true),
1250 ])),
1251 DataType::Struct(Fields::from(vec![
1252 Field::new("f1", DataType::Int64, true),
1253 Field::new(
1254 "nested_struct",
1255 DataType::Struct(Fields::from(vec![Field::new("n1", DataType::Int64, true)])),
1256 true,
1257 ),
1258 ])),
1259 DataType::Struct(Fields::from(vec![Field::new("f1", DataType::Int64, true)])),
1260 DataType::Struct(Fields::empty()),
1261 DataType::List(Arc::new(Field::new_list_field(DataType::Int64, true))),
1262 DataType::List(Arc::new(Field::new_list_field(DataType::Int64, false))),
1263 DataType::List(Arc::new(Field::new("Int64", DataType::Int64, true))),
1264 DataType::List(Arc::new(Field::new("Int64", DataType::Int64, false))),
1265 DataType::List(Arc::new(Field::new(
1266 "nested_list",
1267 DataType::List(Arc::new(Field::new("Int64", DataType::Int64, true))),
1268 true,
1269 ))),
1270 DataType::ListView(Arc::new(Field::new_list_field(DataType::Int64, true))),
1271 DataType::ListView(Arc::new(Field::new_list_field(DataType::Int64, false))),
1272 DataType::ListView(Arc::new(Field::new("Int64", DataType::Int64, true))),
1273 DataType::ListView(Arc::new(Field::new("Int64", DataType::Int64, false))),
1274 DataType::ListView(Arc::new(Field::new(
1275 "nested_list_view",
1276 DataType::ListView(Arc::new(Field::new("Int64", DataType::Int64, true))),
1277 true,
1278 ))),
1279 DataType::LargeList(Arc::new(Field::new_list_field(DataType::Int64, true))),
1280 DataType::LargeList(Arc::new(Field::new_list_field(DataType::Int64, false))),
1281 DataType::LargeList(Arc::new(Field::new("Int64", DataType::Int64, true))),
1282 DataType::LargeList(Arc::new(Field::new("Int64", DataType::Int64, false))),
1283 DataType::LargeList(Arc::new(Field::new(
1284 "nested_large_list",
1285 DataType::LargeList(Arc::new(Field::new("Int64", DataType::Int64, true))),
1286 true,
1287 ))),
1288 DataType::LargeListView(Arc::new(Field::new_list_field(DataType::Int64, true))),
1289 DataType::LargeListView(Arc::new(Field::new_list_field(DataType::Int64, false))),
1290 DataType::LargeListView(Arc::new(Field::new("Int64", DataType::Int64, true))),
1291 DataType::LargeListView(Arc::new(Field::new("Int64", DataType::Int64, false))),
1292 DataType::LargeListView(Arc::new(Field::new(
1293 "nested_large_list_view",
1294 DataType::LargeListView(Arc::new(Field::new("Int64", DataType::Int64, true))),
1295 true,
1296 ))),
1297 DataType::FixedSizeList(Arc::new(Field::new_list_field(DataType::Int64, true)), 2),
1298 DataType::FixedSizeList(Arc::new(Field::new_list_field(DataType::Int64, false)), 2),
1299 DataType::FixedSizeList(Arc::new(Field::new("Int64", DataType::Int64, true)), 2),
1300 DataType::FixedSizeList(Arc::new(Field::new("Int64", DataType::Int64, false)), 2),
1301 DataType::FixedSizeList(
1302 Arc::new(Field::new(
1303 "nested_fixed_size_list",
1304 DataType::FixedSizeList(
1305 Arc::new(Field::new("Int64", DataType::Int64, true)),
1306 2,
1307 ),
1308 true,
1309 )),
1310 2,
1311 ),
1312 DataType::Union(
1313 UnionFields::from_fields(vec![
1314 Field::new("Int32", DataType::Int32, false),
1315 Field::new("Utf8", DataType::Utf8, true),
1316 ]),
1317 UnionMode::Sparse,
1318 ),
1319 DataType::Union(
1320 UnionFields::from_fields(vec![
1321 Field::new("Int32", DataType::Int32, false),
1322 Field::new("Utf8", DataType::Utf8, true),
1323 ]),
1324 UnionMode::Dense,
1325 ),
1326 DataType::Union(
1327 UnionFields::from_fields(vec![
1328 Field::new_union(
1329 "nested_union",
1330 vec![0, 1],
1331 vec![
1332 Field::new("Int32", DataType::Int32, false),
1333 Field::new("Utf8", DataType::Utf8, true),
1334 ],
1335 UnionMode::Dense,
1336 ),
1337 Field::new("Utf8", DataType::Utf8, true),
1338 ]),
1339 UnionMode::Sparse,
1340 ),
1341 DataType::Union(
1342 UnionFields::from_fields(vec![Field::new("Int32", DataType::Int32, false)]),
1343 UnionMode::Dense,
1344 ),
1345 DataType::Union(
1346 UnionFields::try_new(Vec::<i8>::new(), Vec::<Field>::new()).unwrap(),
1347 UnionMode::Sparse,
1348 ),
1349 DataType::RunEndEncoded(
1350 Arc::new(Field::new(
1351 Field::REE_RUN_ENDS_FIELD_DEFAULT_NAME,
1352 DataType::UInt32,
1353 false,
1354 )),
1355 Arc::new(Field::new(
1356 Field::REE_VALUES_FIELD_DEFAULT_NAME,
1357 DataType::Int32,
1358 true,
1359 )),
1360 ),
1361 DataType::RunEndEncoded(
1362 Arc::new(Field::new(
1363 Field::REE_RUN_ENDS_FIELD_DEFAULT_NAME,
1364 DataType::RunEndEncoded(
1365 Arc::new(Field::new(
1366 Field::REE_RUN_ENDS_FIELD_DEFAULT_NAME,
1367 DataType::UInt32,
1368 false,
1369 )),
1370 Arc::new(Field::new(
1371 Field::REE_VALUES_FIELD_DEFAULT_NAME,
1372 DataType::Int32,
1373 true,
1374 )),
1375 ),
1376 false,
1377 )),
1378 Arc::new(Field::new(
1379 Field::REE_VALUES_FIELD_DEFAULT_NAME,
1380 DataType::Int32,
1381 true,
1382 )),
1383 ),
1384 DataType::RunEndEncoded(
1386 Arc::new(Field::new(
1387 Field::REE_RUN_ENDS_FIELD_DEFAULT_NAME,
1388 DataType::RunEndEncoded(
1389 Arc::new(Field::new(
1390 Field::REE_RUN_ENDS_FIELD_DEFAULT_NAME,
1391 DataType::UInt32,
1392 false,
1393 )),
1394 Arc::new(Field::new(
1395 Field::REE_VALUES_FIELD_DEFAULT_NAME,
1396 DataType::Int32,
1397 true,
1398 )),
1399 ),
1400 false,
1401 )),
1402 Arc::new(Field::new("named_values", DataType::Int32, false)),
1403 ),
1404 DataType::RunEndEncoded(
1406 Arc::new(Field::new(
1407 Field::REE_RUN_ENDS_FIELD_DEFAULT_NAME,
1408 DataType::RunEndEncoded(
1409 Arc::new(Field::new(
1410 Field::REE_RUN_ENDS_FIELD_DEFAULT_NAME,
1411 DataType::UInt32,
1412 false,
1413 )),
1414 Arc::new(Field::new(
1415 Field::REE_VALUES_FIELD_DEFAULT_NAME,
1416 DataType::Int32,
1417 false,
1418 )),
1419 ),
1420 false,
1421 )),
1422 Arc::new(Field::new("named_values", DataType::Int32, false)),
1423 ),
1424 ]
1425 }
1426
1427 #[test]
1428 fn test_parse_data_type_whitespace_tolerance() {
1429 let cases = [
1431 ("Int8", DataType::Int8),
1432 (
1433 "Timestamp (ns)",
1434 DataType::Timestamp(TimeUnit::Nanosecond, None),
1435 ),
1436 (
1437 "Timestamp (ns) ",
1438 DataType::Timestamp(TimeUnit::Nanosecond, None),
1439 ),
1440 (
1441 " Timestamp (ns )",
1442 DataType::Timestamp(TimeUnit::Nanosecond, None),
1443 ),
1444 (
1445 "Timestamp (ns ) ",
1446 DataType::Timestamp(TimeUnit::Nanosecond, None),
1447 ),
1448 ];
1449
1450 for (data_type_string, expected_data_type) in cases {
1451 let parsed_data_type = parse_data_type(data_type_string).unwrap();
1452 assert_eq!(
1453 parsed_data_type, expected_data_type,
1454 "Parsing '{data_type_string}', expecting '{expected_data_type}'"
1455 );
1456 }
1457 }
1458
1459 #[test]
1461 fn test_parse_data_type_backwards_compatibility() {
1462 use DataType::*;
1463 use IntervalUnit::*;
1464 use TimeUnit::*;
1465 for t in list_datatypes() {
1467 println!(r#"("{t}", {t:?}),"#);
1468 }
1469 let cases = [
1471 ("Timestamp(Nanosecond, None)", Timestamp(Nanosecond, None)),
1472 ("Timestamp(Microsecond, None)", Timestamp(Microsecond, None)),
1473 ("Timestamp(Millisecond, None)", Timestamp(Millisecond, None)),
1474 ("Timestamp(Second, None)", Timestamp(Second, None)),
1475 ("Timestamp(Nanosecond, None)", Timestamp(Nanosecond, None)),
1476 (
1478 r#"Timestamp(Nanosecond, Some("+00:00"))"#,
1479 Timestamp(Nanosecond, Some("+00:00".into())),
1480 ),
1481 (
1482 r#"Timestamp(Microsecond, Some("+00:00"))"#,
1483 Timestamp(Microsecond, Some("+00:00".into())),
1484 ),
1485 (
1486 r#"Timestamp(Millisecond, Some("+00:00"))"#,
1487 Timestamp(Millisecond, Some("+00:00".into())),
1488 ),
1489 (
1490 r#"Timestamp(Second, Some("+00:00"))"#,
1491 Timestamp(Second, Some("+00:00".into())),
1492 ),
1493 ("Null", Null),
1494 ("Boolean", Boolean),
1495 ("Int8", Int8),
1496 ("Int16", Int16),
1497 ("Int32", Int32),
1498 ("Int64", Int64),
1499 ("UInt8", UInt8),
1500 ("UInt16", UInt16),
1501 ("UInt32", UInt32),
1502 ("UInt64", UInt64),
1503 ("Float16", Float16),
1504 ("Float32", Float32),
1505 ("Float64", Float64),
1506 ("Timestamp(s)", Timestamp(Second, None)),
1507 ("Timestamp(ms)", Timestamp(Millisecond, None)),
1508 ("Timestamp(µs)", Timestamp(Microsecond, None)),
1509 ("Timestamp(ns)", Timestamp(Nanosecond, None)),
1510 (
1511 r#"Timestamp(ns, "+00:00")"#,
1512 Timestamp(Nanosecond, Some("+00:00".into())),
1513 ),
1514 (
1515 r#"Timestamp(µs, "+00:00")"#,
1516 Timestamp(Microsecond, Some("+00:00".into())),
1517 ),
1518 (
1519 r#"Timestamp(ms, "+00:00")"#,
1520 Timestamp(Millisecond, Some("+00:00".into())),
1521 ),
1522 (
1523 r#"Timestamp(s, "+00:00")"#,
1524 Timestamp(Second, Some("+00:00".into())),
1525 ),
1526 (
1527 r#"Timestamp(ns, "+08:00")"#,
1528 Timestamp(Nanosecond, Some("+08:00".into())),
1529 ),
1530 (
1531 r#"Timestamp(µs, "+08:00")"#,
1532 Timestamp(Microsecond, Some("+08:00".into())),
1533 ),
1534 (
1535 r#"Timestamp(ms, "+08:00")"#,
1536 Timestamp(Millisecond, Some("+08:00".into())),
1537 ),
1538 (
1539 r#"Timestamp(s, "+08:00")"#,
1540 Timestamp(Second, Some("+08:00".into())),
1541 ),
1542 ("Date32", Date32),
1543 ("Date64", Date64),
1544 ("Time32(s)", Time32(Second)),
1545 ("Time32(ms)", Time32(Millisecond)),
1546 ("Time64(µs)", Time64(Microsecond)),
1547 ("Time64(ns)", Time64(Nanosecond)),
1548 ("Duration(s)", Duration(Second)),
1549 ("Duration(ms)", Duration(Millisecond)),
1550 ("Duration(µs)", Duration(Microsecond)),
1551 ("Duration(ns)", Duration(Nanosecond)),
1552 ("Interval(YearMonth)", Interval(YearMonth)),
1553 ("Interval(DayTime)", Interval(DayTime)),
1554 ("Interval(MonthDayNano)", Interval(MonthDayNano)),
1555 ("Binary", Binary),
1556 ("BinaryView", BinaryView),
1557 ("FixedSizeBinary(0)", FixedSizeBinary(0)),
1558 ("FixedSizeBinary(1234)", FixedSizeBinary(1234)),
1559 ("LargeBinary", LargeBinary),
1560 ("Utf8", Utf8),
1561 ("Utf8View", Utf8View),
1562 ("LargeUtf8", LargeUtf8),
1563 ("Decimal32(7, 6)", Decimal32(7, 6)),
1564 ("Decimal64(6, 5)", Decimal64(6, 5)),
1565 ("Decimal128(7, 6)", Decimal128(7, 6)),
1566 ("Decimal256(6, 5)", Decimal256(6, 5)),
1567 (
1568 "Dictionary(Int32, Utf8)",
1569 Dictionary(Box::new(Int32), Box::new(Utf8)),
1570 ),
1571 (
1572 "Dictionary(Int8, Utf8)",
1573 Dictionary(Box::new(Int8), Box::new(Utf8)),
1574 ),
1575 (
1576 "Dictionary(Int8, Timestamp(ns))",
1577 Dictionary(Box::new(Int8), Box::new(Timestamp(Nanosecond, None))),
1578 ),
1579 (
1580 "Dictionary(Int8, FixedSizeBinary(23))",
1581 Dictionary(Box::new(Int8), Box::new(FixedSizeBinary(23))),
1582 ),
1583 (
1584 "Dictionary(Int8, Dictionary(Int8, Utf8))",
1585 Dictionary(
1586 Box::new(Int8),
1587 Box::new(Dictionary(Box::new(Int8), Box::new(Utf8))),
1588 ),
1589 ),
1590 (
1591 r#"Struct("f1": nullable Int64, "f2": nullable Float64, "f3": nullable Timestamp(s, "+08:00"), "f4": nullable Dictionary(Int8, FixedSizeBinary(23)))"#,
1592 Struct(Fields::from(vec![
1593 Field::new("f1", Int64, true),
1594 Field::new("f2", Float64, true),
1595 Field::new("f3", Timestamp(Second, Some("+08:00".into())), true),
1596 Field::new(
1597 "f4",
1598 Dictionary(Box::new(Int8), Box::new(FixedSizeBinary(23))),
1599 true,
1600 ),
1601 ])),
1602 ),
1603 (
1604 r#"Struct("Int64": nullable Int64, "Float64": nullable Float64)"#,
1605 Struct(Fields::from(vec![
1606 Field::new("Int64", Int64, true),
1607 Field::new("Float64", Float64, true),
1608 ])),
1609 ),
1610 (
1611 r#"Struct("f1": nullable Int64, "nested_struct": nullable Struct("n1": nullable Int64))"#,
1612 Struct(Fields::from(vec![
1613 Field::new("f1", Int64, true),
1614 Field::new(
1615 "nested_struct",
1616 Struct(Fields::from(vec![Field::new("n1", Int64, true)])),
1617 true,
1618 ),
1619 ])),
1620 ),
1621 (r"Struct()", Struct(Fields::empty())),
1622 (
1623 "FixedSizeList(4, Int64)",
1624 FixedSizeList(Arc::new(Field::new_list_field(Int64, true)), 4),
1625 ),
1626 (
1627 "List(Int64)",
1628 List(Arc::new(Field::new_list_field(Int64, true))),
1629 ),
1630 (
1631 "LargeList(Int64)",
1632 LargeList(Arc::new(Field::new_list_field(Int64, true))),
1633 ),
1634 ];
1635
1636 for (data_type_string, expected_data_type) in cases {
1637 let parsed_data_type = parse_data_type(data_type_string).unwrap();
1638 assert_eq!(
1639 parsed_data_type, expected_data_type,
1640 "Parsing '{data_type_string}', expecting '{expected_data_type}'"
1641 );
1642 }
1643 }
1644
1645 #[test]
1646 fn parse_data_type_errors() {
1647 let cases = [
1649 ("", "Unsupported type ''"),
1650 ("", "Error finding next token"),
1651 ("null", "Unsupported type 'null'"),
1652 ("Nu", "Unsupported type 'Nu'"),
1653 (r"Timestamp(ns, +00:00)", "Error unknown token: +00"),
1654 (
1655 r#"Timestamp(ns, "+00:00)"#,
1656 r#"Unterminated string at: "+00:00)"#,
1657 ),
1658 (r#"Timestamp(ns, "")"#, r"empty strings aren't allowed"),
1659 (
1660 r#"Timestamp(ns, "+00:00"")"#,
1661 r#"Parser error: Unterminated string at: ")"#,
1662 ),
1663 ("Timestamp(ns, ", "Error finding next token"),
1664 (
1665 "Float32 Float32",
1666 "trailing content after parsing 'Float32'",
1667 ),
1668 ("Int32, ", "trailing content after parsing 'Int32'"),
1669 ("Int32(3), ", "trailing content after parsing 'Int32'"),
1670 (
1671 "FixedSizeBinary(Int32), ",
1672 "Error finding i64 for FixedSizeBinary, got 'Int32'",
1673 ),
1674 (
1675 "FixedSizeBinary(3.0), ",
1676 "Error parsing 3.0 as integer: invalid digit found in string",
1677 ),
1678 (
1680 "FixedSizeBinary(4000000000), ",
1681 "Error converting 4000000000 into i32 for FixedSizeBinary:",
1682 ),
1683 (
1685 "FixedSizeBinary(-1), ",
1686 "FixedSizeBinary length must be non-negative, got -1",
1687 ),
1688 (
1689 "FixedSizeList(-1, Int64), ",
1690 "FixedSizeList length must be non-negative, got -1",
1691 ),
1692 (
1694 "Decimal32(-3, 5)",
1695 "Error converting -3 into u8 for Decimal32:",
1696 ),
1697 (
1698 "Decimal64(-3, 5)",
1699 "Error converting -3 into u8 for Decimal64:",
1700 ),
1701 (
1702 "Decimal128(-3, 5)",
1703 "Error converting -3 into u8 for Decimal128:",
1704 ),
1705 (
1706 "Decimal256(-3, 5)",
1707 "Error converting -3 into u8 for Decimal256:",
1708 ),
1709 (
1710 "Decimal32(3, 500)",
1711 "Error converting 500 into i8 for Decimal32:",
1712 ),
1713 (
1714 "Decimal64(3, 500)",
1715 "Error converting 500 into i8 for Decimal64:",
1716 ),
1717 (
1718 "Decimal128(3, 500)",
1719 "Error converting 500 into i8 for Decimal128:",
1720 ),
1721 (
1722 "Decimal256(3, 500)",
1723 "Error converting 500 into i8 for Decimal256:",
1724 ),
1725 ("Struct(f1 Int64)", "Error unknown token: f1"),
1726 ("Struct(\"f1\" Int64)", "Expected ':'"),
1727 (
1728 "Struct(\"f1\": )",
1729 "Error finding next type, got unexpected ')'",
1730 ),
1731 (
1733 "Time32(µs)",
1734 "Error Time32 time unit must be 's' or 'ms', got 'µs'",
1735 ),
1736 (
1737 "Time32(ns)",
1738 "Error Time32 time unit must be 's' or 'ms', got 'ns'",
1739 ),
1740 (
1741 "Time64(s)",
1742 "Error Time64 time unit must be 'µs' or 'ns', got 's'",
1743 ),
1744 (
1745 "Time64(ms)",
1746 "Error Time64 time unit must be 'µs' or 'ns', got 'ms'",
1747 ),
1748 (
1750 "Decimal32(5, 6)",
1751 "Error Decimal32 scale '6' cannot be greater than precision '5'",
1752 ),
1753 (
1754 "Decimal64(5, 6)",
1755 "Error Decimal64 scale '6' cannot be greater than precision '5'",
1756 ),
1757 (
1758 "Decimal128(5, 6)",
1759 "Error Decimal128 scale '6' cannot be greater than precision '5'",
1760 ),
1761 (
1762 "Decimal256(5, 6)",
1763 "Error Decimal256 scale '6' cannot be greater than precision '5'",
1764 ),
1765 (
1767 "Decimal32(10, 0)",
1768 "Error Decimal32 precision must be in range [1, 9], got '10'",
1769 ),
1770 (
1771 "Decimal64(19, 0)",
1772 "Error Decimal64 precision must be in range [1, 18], got '19'",
1773 ),
1774 (
1775 "Decimal128(39, 0)",
1776 "Error Decimal128 precision must be in range [1, 38], got '39'",
1777 ),
1778 (
1779 "Decimal256(77, 0)",
1780 "Error Decimal256 precision must be in range [1, 76], got '77'",
1781 ),
1782 (
1784 "Decimal32(0, 0)",
1785 "Error Decimal32 precision must be in range [1, 9], got '0'",
1786 ),
1787 (
1788 "Decimal64(0, 0)",
1789 "Error Decimal64 precision must be in range [1, 18], got '0'",
1790 ),
1791 (
1792 "Decimal128(0, 0)",
1793 "Error Decimal128 precision must be in range [1, 38], got '0'",
1794 ),
1795 (
1796 "Decimal256(0, 0)",
1797 "Error Decimal256 precision must be in range [1, 76], got '0'",
1798 ),
1799 (
1801 r#"RunEndEncoded("re": nullable Int32, "v": non-null Utf8)"#,
1802 "RunEndEncoded run_ends field cannot be nullable",
1803 ),
1804 (
1805 r#"RunEndEncoded("re": Int32, "v": non-null Utf8)"#,
1806 "RunEndEncoded run_ends field cannot be nullable",
1807 ),
1808 (
1809 "RunEndEncoded(nullable Int32, non-null Utf8)",
1810 "RunEndEncoded run_ends field cannot be nullable",
1811 ),
1812 (
1814 r#"Map("entries": Struct("key": non-null Utf8, "value": nullable Int32), unsorted)"#,
1815 "Map entries field cannot be nullable",
1816 ),
1817 (
1819 r#"Map("entries": non-null Struct("key": nullable Utf8, "value": nullable Int32), unsorted)"#,
1820 "Map key field cannot be nullable",
1821 ),
1822 (
1823 r#"Map("entries": non-null Struct("key": Utf8, "value": nullable Int32), unsorted)"#,
1824 "Map key field cannot be nullable",
1825 ),
1826 ];
1827
1828 for (data_type_string, expected_message) in cases {
1829 println!("Parsing '{data_type_string}', expecting '{expected_message}'");
1830 match parse_data_type(data_type_string) {
1831 Ok(d) => panic!("Expected error while parsing '{data_type_string}', but got '{d}'"),
1832 Err(e) => {
1833 let message = e.to_string();
1834 assert!(
1835 message.contains(expected_message),
1836 "\n\ndid not find expected in actual.\n\nexpected: {expected_message}\nactual: {message}\n"
1837 );
1838
1839 if !message.contains("Unterminated string") {
1840 assert!(message.contains("Must be a supported arrow type name such as 'Int32' or 'Timestamp(ns)'"), "message: {message}");
1842 }
1843 }
1844 }
1845 }
1846 }
1847
1848 #[test]
1849 fn parse_error_type() {
1850 let err = parse_data_type("foobar").unwrap_err();
1851 assert!(matches!(err, ArrowError::ParseError(_)));
1852 assert_eq!(
1853 err.to_string(),
1854 "Parser error: Unsupported type 'foobar'. Must be a supported arrow type name such as 'Int32' or 'Timestamp(ns)'. Error unknown token: foobar"
1855 );
1856 }
1857}