1use std::fmt;
24
25#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
31pub enum IntBits {
32 B8,
33 B16,
34 B32,
35 B64,
36 B128,
37 B256,
38}
39
40impl IntBits {
41 pub fn bits(self) -> u16 {
43 match self {
44 IntBits::B8 => 8,
45 IntBits::B16 => 16,
46 IntBits::B32 => 32,
47 IntBits::B64 => 64,
48 IntBits::B128 => 128,
49 IntBits::B256 => 256,
50 }
51 }
52
53 pub fn holds(self, word: u64, signed: bool) -> bool {
62 let width = u32::from(self.bits());
63 if width >= 64 {
64 return true;
65 }
66 match signed {
67 true => {
68 let bound = 1i64 << (width - 1);
69 (-bound..bound).contains(&(word as i64))
70 }
71 false => word < 1u64 << width,
72 }
73 }
74
75 pub fn for_digits(digits: u16) -> Option<IntBits> {
84 Some(match digits {
85 0..=2 => IntBits::B8,
86 3..=4 => IntBits::B16,
87 5..=9 => IntBits::B32,
88 10..=18 => IntBits::B64,
89 19..=38 => IntBits::B128,
90 39..=76 => IntBits::B256,
91 _ => return None,
92 })
93 }
94}
95
96#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
103pub enum FloatBits {
104 B16,
105 B32,
106 B64,
107 B128,
108 B256,
109}
110
111impl FloatBits {
112 pub fn bits(self) -> u16 {
114 match self {
115 FloatBits::B16 => 16,
116 FloatBits::B32 => 32,
117 FloatBits::B64 => 64,
118 FloatBits::B128 => 128,
119 FloatBits::B256 => 256,
120 }
121 }
122
123 pub fn for_digits(digits: u16) -> Option<FloatBits> {
126 Some(match digits {
127 0..=3 => FloatBits::B16,
128 4..=6 => FloatBits::B32,
129 7..=15 => FloatBits::B64,
130 16..=33 => FloatBits::B128,
131 34..=71 => FloatBits::B256,
132 _ => return None,
133 })
134 }
135}
136
137#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
146pub enum DurationKind {
147 YearMonth,
148 DayTime,
149}
150
151#[derive(Clone, PartialEq, Eq, Debug, Hash)]
153pub struct Field {
154 pub name: String,
155 pub ty: LogicalType,
156}
157
158#[derive(Clone, PartialEq, Eq, Debug, Hash)]
164pub struct RecordType {
165 pub fields: Vec<Field>,
166 pub open: bool,
167}
168
169impl RecordType {
170 pub fn closed(fields: Vec<Field>) -> Self {
172 RecordType {
173 fields,
174 open: false,
175 }
176 }
177
178 pub fn open(fields: Vec<Field>) -> Self {
182 RecordType { fields, open: true }
183 }
184
185 pub fn field(&self, name: &str) -> Option<&Field> {
187 self.fields.iter().find(|f| f.name == name)
188 }
189}
190
191#[derive(Clone, PartialEq, Eq, Debug, Hash)]
198pub enum LogicalType {
199 Null,
202 Nothing,
206
207 Bool,
208 Int {
212 signed: bool,
213 bits: IntBits,
214 precision: Option<u16>,
215 },
216 Decimal {
219 precision: u16,
220 scale: u16,
221 },
222 Float {
224 bits: FloatBits,
225 precision: Option<u16>,
226 },
227 Str {
231 min: Option<u32>,
232 max: Option<u32>,
233 fixed: bool,
234 },
235 Bytes {
237 min: Option<u32>,
238 max: Option<u32>,
239 fixed: bool,
240 },
241
242 Date,
244 LocalTime,
246 LocalDatetime,
248 ZonedTime,
250 ZonedDatetime,
252 Duration(DurationKind),
254
255 Node(Option<String>),
257 Edge(Option<String>),
259 Graph(Option<String>),
263 BindingTable(Option<RecordType>),
266
267 Path(Option<Box<PathType>>),
270 List {
272 elem: Box<LogicalType>,
273 max: Option<u32>,
274 },
275 Record(RecordType),
277
278 Any,
280 Union(Vec<LogicalType>),
282 AnyProperty,
285
286 Nullable(Box<LogicalType>),
289}
290
291#[derive(Clone, PartialEq, Eq, Debug, Hash)]
297pub struct PathType {
298 pub nodes: Vec<Option<String>>,
299 pub edges: Vec<Option<String>>,
300}
301
302#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
311pub enum PhysicalType {
312 Bool,
314 I8,
315 I16,
316 I32,
317 I64,
318 U8,
319 U16,
320 U32,
321 U64,
322 I128,
325 I256,
328 F32,
329 F64,
330 F128,
332 Str,
334 Bytes,
337 Days32,
339 Nanos64,
342 Zoned,
344 Months32,
347 ListOffsets,
349 Struct,
351}
352
353impl PhysicalType {
354 pub fn stride(self) -> Option<usize> {
362 Some(match self {
363 PhysicalType::Bool => return None,
364 PhysicalType::I8 | PhysicalType::U8 => 1,
365 PhysicalType::I16 | PhysicalType::U16 | PhysicalType::Months32 => 2,
366 PhysicalType::I32 | PhysicalType::U32 | PhysicalType::F32 | PhysicalType::Days32 => 4,
367 PhysicalType::I64 | PhysicalType::U64 | PhysicalType::F64 | PhysicalType::Nanos64 => 8,
368 PhysicalType::I128 | PhysicalType::F128 => 16,
369 PhysicalType::I256 => 32,
370 PhysicalType::Str
371 | PhysicalType::Bytes
372 | PhysicalType::Zoned
373 | PhysicalType::ListOffsets
374 | PhysicalType::Struct => return None,
375 })
376 }
377}
378
379impl LogicalType {
380 pub fn nullable(self) -> LogicalType {
382 match self {
383 LogicalType::Nullable(_) => self,
384 other => LogicalType::Nullable(Box::new(other)),
385 }
386 }
387
388 pub fn is_nullable(&self) -> bool {
392 matches!(self, LogicalType::Nullable(_) | LogicalType::Null)
393 }
394
395 pub fn base(&self) -> &LogicalType {
398 match self {
399 LogicalType::Nullable(inner) => inner.base(),
400 other => other,
401 }
402 }
403
404 pub fn is_material(&self) -> bool {
408 !matches!(self.base(), LogicalType::Null | LogicalType::Nothing)
409 }
410
411 pub fn physical(&self) -> Option<PhysicalType> {
420 Some(match self.base() {
421 LogicalType::Null | LogicalType::Nothing => return None,
422 LogicalType::Bool => PhysicalType::Bool,
423 LogicalType::Int { signed, bits, .. } => match (signed, bits) {
424 (true, IntBits::B8) => PhysicalType::I8,
425 (true, IntBits::B16) => PhysicalType::I16,
426 (true, IntBits::B32) => PhysicalType::I32,
427 (true, IntBits::B64) => PhysicalType::I64,
428 (false, IntBits::B8) => PhysicalType::U8,
429 (false, IntBits::B16) => PhysicalType::U16,
430 (false, IntBits::B32) => PhysicalType::U32,
431 (false, IntBits::B64) => PhysicalType::U64,
432 (_, IntBits::B128) => PhysicalType::I128,
436 (_, IntBits::B256) => PhysicalType::I256,
437 },
438 LogicalType::Decimal { precision, .. } => {
439 match IntBits::for_digits(*precision).unwrap_or(IntBits::B256) {
440 IntBits::B8 | IntBits::B16 | IntBits::B32 => PhysicalType::I32,
441 IntBits::B64 => PhysicalType::I64,
442 IntBits::B128 => PhysicalType::I128,
443 IntBits::B256 => PhysicalType::I256,
444 }
445 }
446 LogicalType::Float { bits, .. } => match bits {
447 FloatBits::B16 | FloatBits::B32 => PhysicalType::F32,
450 FloatBits::B64 => PhysicalType::F64,
451 FloatBits::B128 | FloatBits::B256 => PhysicalType::F128,
452 },
453 LogicalType::Str { .. } => PhysicalType::Str,
454 LogicalType::Bytes { .. } => PhysicalType::Bytes,
455 LogicalType::Date => PhysicalType::Days32,
456 LogicalType::LocalTime | LogicalType::LocalDatetime => PhysicalType::Nanos64,
457 LogicalType::ZonedTime | LogicalType::ZonedDatetime => PhysicalType::Zoned,
458 LogicalType::Duration(DurationKind::YearMonth) => PhysicalType::Months32,
459 LogicalType::Duration(DurationKind::DayTime) => PhysicalType::Nanos64,
460 LogicalType::Node(_)
463 | LogicalType::Edge(_)
464 | LogicalType::Graph(_)
465 | LogicalType::BindingTable(_) => PhysicalType::U64,
466 LogicalType::Path(_) | LogicalType::Record(_) => PhysicalType::Struct,
467 LogicalType::List { .. } => PhysicalType::ListOffsets,
468 LogicalType::Any | LogicalType::Union(_) | LogicalType::AnyProperty => {
469 PhysicalType::Struct
470 }
471 LogicalType::Nullable(_) => unreachable!("base() removed the wrapper"),
472 })
473 }
474
475 pub fn int(bits: IntBits) -> LogicalType {
478 LogicalType::Int {
479 signed: true,
480 bits,
481 precision: None,
482 }
483 }
484
485 pub fn uint(bits: IntBits) -> LogicalType {
486 LogicalType::Int {
487 signed: false,
488 bits,
489 precision: None,
490 }
491 }
492
493 pub fn float(bits: FloatBits) -> LogicalType {
494 LogicalType::Float {
495 bits,
496 precision: None,
497 }
498 }
499
500 pub fn string() -> LogicalType {
502 LogicalType::Str {
503 min: None,
504 max: None,
505 fixed: false,
506 }
507 }
508
509 pub fn bytes() -> LogicalType {
511 LogicalType::Bytes {
512 min: None,
513 max: None,
514 fixed: false,
515 }
516 }
517}
518
519pub fn type_by_name(name: &str) -> Option<LogicalType> {
536 let (head, args) = split_args(name)?;
537 let head = head.split_whitespace().collect::<Vec<_>>().join(" ");
538 let head = head.to_ascii_uppercase();
539 let arg = |i: usize| args.get(i).copied();
540 Some(match (head.as_str(), args.len()) {
541 ("BOOL" | "BOOLEAN", 0) => LogicalType::Bool,
542
543 ("INT8" | "TINYINT", 0) => LogicalType::int(IntBits::B8),
544 ("INT16" | "SMALLINT", 0) => LogicalType::int(IntBits::B16),
545 ("INT32", 0) => LogicalType::int(IntBits::B32),
546 ("INT64" | "BIGINT" | "SIGNED", 0) => LogicalType::int(IntBits::B64),
547 ("INT128", 0) => LogicalType::int(IntBits::B128),
548 ("INT256", 0) => LogicalType::int(IntBits::B256),
549 ("INT" | "INTEGER", 0) => LogicalType::int(IntBits::B64),
553
554 ("UINT8", 0) => LogicalType::uint(IntBits::B8),
555 ("UINT16" | "USMALLINT", 0) => LogicalType::uint(IntBits::B16),
556 ("UINT32", 0) => LogicalType::uint(IntBits::B32),
557 ("UINT64" | "UBIGINT" | "UNSIGNED", 0) => LogicalType::uint(IntBits::B64),
558 ("UINT128", 0) => LogicalType::uint(IntBits::B128),
559 ("UINT256", 0) => LogicalType::uint(IntBits::B256),
560 ("UINT" | "UINTEGER", 0) => LogicalType::uint(IntBits::B64),
561
562 ("INT" | "INTEGER", 1) => LogicalType::Int {
566 signed: true,
567 bits: IntBits::for_digits(arg(0)?)?,
568 precision: Some(arg(0)?),
569 },
570 ("UINT" | "UINTEGER", 1) => LogicalType::Int {
571 signed: false,
572 bits: IntBits::for_digits(arg(0)?)?,
573 precision: Some(arg(0)?),
574 },
575 ("FLOAT", 1) => LogicalType::Float {
576 bits: FloatBits::for_digits(arg(0)?)?,
577 precision: Some(arg(0)?),
578 },
579
580 ("FLOAT16" | "HALF", 0) => LogicalType::float(FloatBits::B16),
581 ("FLOAT32" | "REAL", 0) => LogicalType::float(FloatBits::B32),
582 ("FLOAT64" | "DOUBLE" | "DOUBLE PRECISION" | "FLOAT", 0) => {
583 LogicalType::float(FloatBits::B64)
584 }
585 ("FLOAT128", 0) => LogicalType::float(FloatBits::B128),
586 ("FLOAT256", 0) => LogicalType::float(FloatBits::B256),
587
588 ("DECIMAL" | "DEC", 1) => LogicalType::Decimal {
589 precision: arg(0)?,
590 scale: 0,
591 },
592 ("DECIMAL" | "DEC", 2) => LogicalType::Decimal {
593 precision: arg(0)?,
594 scale: arg(1)?,
595 },
596
597 ("STRING" | "VARCHAR", 0) => LogicalType::string(),
598 ("STRING" | "VARCHAR", 1) => LogicalType::Str {
599 min: None,
600 max: Some(u32::from(arg(0)?)),
601 fixed: false,
602 },
603 ("STRING" | "VARCHAR", 2) => LogicalType::Str {
604 min: Some(u32::from(arg(0)?)),
605 max: Some(u32::from(arg(1)?)),
606 fixed: false,
607 },
608 ("CHAR", 1) => LogicalType::Str {
609 min: Some(u32::from(arg(0)?)),
610 max: Some(u32::from(arg(0)?)),
611 fixed: true,
612 },
613 ("BYTES" | "VARBINARY", 0) => LogicalType::bytes(),
614 ("BYTES" | "VARBINARY", 1) => LogicalType::Bytes {
615 min: None,
616 max: Some(u32::from(arg(0)?)),
617 fixed: false,
618 },
619 ("BINARY", 1) => LogicalType::Bytes {
620 min: Some(u32::from(arg(0)?)),
621 max: Some(u32::from(arg(0)?)),
622 fixed: true,
623 },
624
625 ("DATE", 0) => LogicalType::Date,
626 ("LOCAL TIME" | "TIME WITHOUT TIME ZONE", 0) => LogicalType::LocalTime,
627 ("LOCAL DATETIME" | "TIMESTAMP WITHOUT TIME ZONE", 0) => LogicalType::LocalDatetime,
628 ("ZONED TIME" | "TIME WITH TIME ZONE" | "TIME", 0) => LogicalType::ZonedTime,
629 ("ZONED DATETIME" | "TIMESTAMP WITH TIME ZONE" | "TIMESTAMP", 0) => {
630 LogicalType::ZonedDatetime
631 }
632 ("DURATION" | "INTERVAL", 0) => LogicalType::Duration(DurationKind::DayTime),
633 ("YEAR MONTH DURATION", 0) => LogicalType::Duration(DurationKind::YearMonth),
634 ("DAY TIME DURATION", 0) => LogicalType::Duration(DurationKind::DayTime),
635
636 ("NULL", 0) => LogicalType::Null,
637 ("NOTHING", 0) => LogicalType::Nothing,
638 ("ANY", 0) => LogicalType::Any,
639 ("ANY PROPERTY VALUE" | "PROPERTY VALUE", 0) => LogicalType::AnyProperty,
640
641 ("NODE" | "VERTEX", 0) => LogicalType::Node(None),
642 ("EDGE" | "RELATIONSHIP", 0) => LogicalType::Edge(None),
643 ("GRAPH", 0) => LogicalType::Graph(None),
644 ("BINDING TABLE" | "TABLE", 0) => LogicalType::BindingTable(None),
645 ("PATH", 0) => LogicalType::Path(None),
646
647 _ => return None,
648 })
649}
650
651fn split_args(name: &str) -> Option<(&str, Vec<u16>)> {
656 let name = name.trim();
657 let Some(open) = name.find('(') else {
658 return Some((name, Vec::new()));
659 };
660 let rest = name.strip_suffix(')')?;
661 let (head, args) = rest.split_at(open);
662 let args = args
663 .trim_start_matches('(')
664 .split(',')
665 .map(|a| a.trim().parse().ok())
666 .collect::<Option<Vec<u16>>>()?;
667 if args.is_empty() {
668 return None;
669 }
670 Some((head, args))
671}
672
673impl fmt::Display for LogicalType {
674 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
678 match self {
679 LogicalType::Null => write!(f, "NULL"),
680 LogicalType::Nothing => write!(f, "NOTHING"),
681 LogicalType::Bool => write!(f, "BOOL"),
682 LogicalType::Int {
683 signed,
684 bits,
685 precision,
686 } => {
687 let u = if *signed { "" } else { "U" };
688 match precision {
689 Some(p) => write!(f, "{u}INT({p})"),
690 None => write!(f, "{u}INT{}", bits.bits()),
691 }
692 }
693 LogicalType::Decimal { precision, scale } => write!(f, "DECIMAL({precision},{scale})"),
694 LogicalType::Float { bits, precision } => match precision {
695 Some(p) => write!(f, "FLOAT({p})"),
696 None => write!(f, "FLOAT{}", bits.bits()),
697 },
698 LogicalType::Str { min, max, fixed } => write_len(f, "STRING", *min, *max, *fixed),
699 LogicalType::Bytes { min, max, fixed } => write_len(f, "BYTES", *min, *max, *fixed),
700 LogicalType::Date => write!(f, "DATE"),
701 LogicalType::LocalTime => write!(f, "LOCAL TIME"),
702 LogicalType::LocalDatetime => write!(f, "LOCAL DATETIME"),
703 LogicalType::ZonedTime => write!(f, "ZONED TIME"),
704 LogicalType::ZonedDatetime => write!(f, "ZONED DATETIME"),
705 LogicalType::Duration(DurationKind::YearMonth) => write!(f, "YEAR MONTH DURATION"),
706 LogicalType::Duration(DurationKind::DayTime) => write!(f, "DAY TIME DURATION"),
707 LogicalType::Node(t) => write_ref(f, "NODE", t.as_deref()),
708 LogicalType::Edge(t) => write_ref(f, "EDGE", t.as_deref()),
709 LogicalType::Graph(t) => write_ref(f, "GRAPH", t.as_deref()),
710 LogicalType::BindingTable(_) => write!(f, "BINDING TABLE"),
711 LogicalType::Path(_) => write!(f, "PATH"),
712 LogicalType::List { elem, max } => match max {
713 Some(n) => write!(f, "LIST<{elem}>[{n}]"),
714 None => write!(f, "LIST<{elem}>"),
715 },
716 LogicalType::Record(r) => {
717 write!(f, "RECORD<")?;
718 for (i, field) in r.fields.iter().enumerate() {
719 if i > 0 {
720 write!(f, ", ")?;
721 }
722 write!(f, "{}: {}", field.name, field.ty)?;
723 }
724 if r.open {
725 write!(f, "{}..", if r.fields.is_empty() { "" } else { ", " })?;
726 }
727 write!(f, ">")
728 }
729 LogicalType::Any => write!(f, "ANY"),
730 LogicalType::Union(members) => {
731 write!(f, "ANY<")?;
732 for (i, m) in members.iter().enumerate() {
733 if i > 0 {
734 write!(f, "|")?;
735 }
736 write!(f, "{m}")?;
737 }
738 write!(f, ">")
739 }
740 LogicalType::AnyProperty => write!(f, "ANY PROPERTY VALUE"),
741 LogicalType::Nullable(inner) => write!(f, "{inner}?"),
742 }
743 }
744}
745
746fn write_len(
747 f: &mut fmt::Formatter<'_>,
748 name: &str,
749 min: Option<u32>,
750 max: Option<u32>,
751 fixed: bool,
752) -> fmt::Result {
753 match (min, max, fixed) {
754 (Some(n), _, true) => write!(f, "{name}({n}) FIXED"),
755 (Some(lo), Some(hi), false) => write!(f, "{name}({lo}..{hi})"),
756 (None, Some(hi), false) => write!(f, "{name}({hi})"),
757 _ => write!(f, "{name}"),
758 }
759}
760
761fn write_ref(f: &mut fmt::Formatter<'_>, name: &str, ty: Option<&str>) -> fmt::Result {
762 match ty {
763 Some(t) => write!(f, "{name}<{t}>"),
764 None => write!(f, "{name}"),
765 }
766}
767
768#[cfg(test)]
769mod tests {
770 use super::*;
771
772 #[test]
773 fn the_integer_tower_is_one_implementation_with_a_width_on_it() {
774 for (bits, signed, want) in [
775 (IntBits::B8, true, PhysicalType::I8),
776 (IntBits::B16, true, PhysicalType::I16),
777 (IntBits::B32, true, PhysicalType::I32),
778 (IntBits::B64, true, PhysicalType::I64),
779 (IntBits::B8, false, PhysicalType::U8),
780 (IntBits::B64, false, PhysicalType::U64),
781 (IntBits::B128, true, PhysicalType::I128),
782 (IntBits::B256, false, PhysicalType::I256),
783 ] {
784 let ty = LogicalType::Int {
785 signed,
786 bits,
787 precision: None,
788 };
789 assert_eq!(ty.physical(), Some(want), "{ty}");
790 }
791 }
792
793 #[test]
794 fn a_declared_digit_count_picks_the_narrowest_width_that_holds_it() {
795 assert_eq!(IntBits::for_digits(1), Some(IntBits::B8));
796 assert_eq!(IntBits::for_digits(4), Some(IntBits::B16));
797 assert_eq!(IntBits::for_digits(9), Some(IntBits::B32));
798 assert_eq!(IntBits::for_digits(18), Some(IntBits::B64));
800 assert_eq!(IntBits::for_digits(19), Some(IntBits::B128));
801 assert_eq!(IntBits::for_digits(76), Some(IntBits::B256));
802 assert_eq!(IntBits::for_digits(77), None);
803 }
804
805 #[test]
806 fn the_two_duration_kinds_are_two_types_and_two_layouts() {
807 let ym = LogicalType::Duration(DurationKind::YearMonth);
808 let dt = LogicalType::Duration(DurationKind::DayTime);
809 assert_ne!(ym, dt);
810 assert_eq!(ym.physical(), Some(PhysicalType::Months32));
811 assert_eq!(dt.physical(), Some(PhysicalType::Nanos64));
812 }
813
814 #[test]
815 fn the_immaterial_types_have_no_layout() {
816 assert_eq!(LogicalType::Null.physical(), None);
817 assert_eq!(LogicalType::Nothing.physical(), None);
818 assert!(!LogicalType::Nothing.is_material());
819 assert!(!LogicalType::Null.clone().nullable().is_material());
820 assert!(LogicalType::Bool.is_material());
821 }
822
823 #[test]
824 fn nullability_is_a_wrapper_that_does_not_stack_or_change_the_layout() {
825 let ty = LogicalType::int(IntBits::B32);
826 let once = ty.clone().nullable();
827 let twice = once.clone().nullable();
828 assert_eq!(once, twice);
829 assert!(once.is_nullable());
830 assert!(!ty.is_nullable());
831 assert_eq!(once.base(), &ty);
832 assert_eq!(once.physical(), ty.physical());
833 }
834
835 #[test]
836 fn every_temporal_type_has_the_layout_the_plan_names() {
837 for (ty, want) in [
838 (LogicalType::Date, PhysicalType::Days32),
839 (LogicalType::LocalTime, PhysicalType::Nanos64),
840 (LogicalType::LocalDatetime, PhysicalType::Nanos64),
841 (LogicalType::ZonedTime, PhysicalType::Zoned),
842 (LogicalType::ZonedDatetime, PhysicalType::Zoned),
843 ] {
844 assert_eq!(ty.physical(), Some(want), "{ty}");
845 }
846 }
847
848 #[test]
849 fn a_fixed_stride_knows_its_width_and_the_others_admit_they_do_not() {
850 assert_eq!(PhysicalType::I8.stride(), Some(1));
851 assert_eq!(PhysicalType::Months32.stride(), Some(2));
852 assert_eq!(PhysicalType::Days32.stride(), Some(4));
853 assert_eq!(PhysicalType::Nanos64.stride(), Some(8));
854 assert_eq!(PhysicalType::I128.stride(), Some(16));
855 assert_eq!(PhysicalType::I256.stride(), Some(32));
856 assert_eq!(PhysicalType::Bool.stride(), None);
857 assert_eq!(PhysicalType::Str.stride(), None);
858 assert_eq!(PhysicalType::Zoned.stride(), None);
859 assert_eq!(PhysicalType::Struct.stride(), None);
860 }
861
862 #[test]
863 fn the_spellings_resolve_to_the_types_they_name() {
864 for (name, want) in [
865 ("BOOL", LogicalType::Bool),
866 ("boolean", LogicalType::Bool),
867 ("SMALLINT", LogicalType::int(IntBits::B16)),
868 ("BIGINT", LogicalType::int(IntBits::B64)),
869 ("int", LogicalType::int(IntBits::B64)),
870 ("UNSIGNED", LogicalType::uint(IntBits::B64)),
871 ("REAL", LogicalType::float(FloatBits::B32)),
872 ("double precision", LogicalType::float(FloatBits::B64)),
873 ("DOUBLE PRECISION", LogicalType::float(FloatBits::B64)),
874 ("FLOAT", LogicalType::float(FloatBits::B64)),
875 ("STRING", LogicalType::string()),
876 ("DATE", LogicalType::Date),
877 ("zoned datetime", LogicalType::ZonedDatetime),
878 (
879 "year month duration",
880 LogicalType::Duration(DurationKind::YearMonth),
881 ),
882 ("ANY", LogicalType::Any),
883 ("any property value", LogicalType::AnyProperty),
884 ] {
885 assert_eq!(type_by_name(name), Some(want), "{name}");
886 }
887 assert_eq!(type_by_name("QUUX"), None);
888 assert_eq!(type_by_name("INT("), None);
889 assert_eq!(type_by_name("INT()"), None);
890 assert_eq!(type_by_name("INT(x)"), None);
891 }
892
893 #[test]
894 fn a_parenthesised_argument_is_a_count_and_not_a_width() {
895 assert_eq!(
896 type_by_name("INT(4)"),
897 Some(LogicalType::Int {
898 signed: true,
899 bits: IntBits::B16,
900 precision: Some(4),
901 })
902 );
903 assert_eq!(
906 type_by_name("INT(4)").unwrap().physical(),
907 type_by_name("INT16").unwrap().physical()
908 );
909 assert_ne!(type_by_name("INT(4)"), type_by_name("INT16"));
910 assert_eq!(type_by_name("INT(100)"), None);
911 assert_eq!(
912 type_by_name("DECIMAL(20,4)"),
913 Some(LogicalType::Decimal {
914 precision: 20,
915 scale: 4,
916 })
917 );
918 assert_eq!(
919 type_by_name("DECIMAL(20,4)").unwrap().physical(),
920 Some(PhysicalType::I128)
921 );
922 assert_eq!(
923 type_by_name("STRING(1,5)"),
924 Some(LogicalType::Str {
925 min: Some(1),
926 max: Some(5),
927 fixed: false,
928 })
929 );
930 assert_eq!(
931 type_by_name("CHAR(3)"),
932 Some(LogicalType::Str {
933 min: Some(3),
934 max: Some(3),
935 fixed: true,
936 })
937 );
938 }
939
940 #[test]
941 fn a_record_carries_open_closed_and_nesting_in_one_type() {
942 let inner = RecordType::closed(vec![Field {
943 name: "since".into(),
944 ty: LogicalType::Date,
945 }]);
946 let outer = RecordType::open(vec![
947 Field {
948 name: "name".into(),
949 ty: LogicalType::string(),
950 },
951 Field {
952 name: "meta".into(),
953 ty: LogicalType::Record(inner),
954 },
955 ]);
956 assert!(outer.open);
957 assert_eq!(
958 outer.field("name").map(|f| &f.ty),
959 Some(&LogicalType::string())
960 );
961 assert_eq!(outer.field("nope"), None);
962 assert_eq!(
963 LogicalType::Record(outer).physical(),
964 Some(PhysicalType::Struct)
965 );
966 }
967
968 #[test]
969 fn a_type_prints_the_way_a_diagnostic_needs_to_name_it() {
970 assert_eq!(LogicalType::int(IntBits::B64).to_string(), "INT64");
971 assert_eq!(type_by_name("INT(4)").unwrap().to_string(), "INT(4)");
972 assert_eq!(type_by_name("UNSIGNED").unwrap().to_string(), "UINT64");
973 assert_eq!(
974 type_by_name("CHAR(3)").unwrap().to_string(),
975 "STRING(3) FIXED"
976 );
977 assert_eq!(
978 type_by_name("STRING(1,5)").unwrap().to_string(),
979 "STRING(1..5)"
980 );
981 assert_eq!(LogicalType::string().nullable().to_string(), "STRING?");
982 assert_eq!(
983 LogicalType::List {
984 elem: Box::new(LogicalType::Date),
985 max: Some(4),
986 }
987 .to_string(),
988 "LIST<DATE>[4]"
989 );
990 assert_eq!(
991 LogicalType::Union(vec![LogicalType::int(IntBits::B64), LogicalType::string()])
992 .to_string(),
993 "ANY<INT64|STRING>"
994 );
995 assert_eq!(
996 LogicalType::Record(RecordType::open(vec![Field {
997 name: "n".into(),
998 ty: LogicalType::Bool,
999 }]))
1000 .to_string(),
1001 "RECORD<n: BOOL, ..>"
1002 );
1003 assert_eq!(
1004 LogicalType::Node(Some("person".into())).to_string(),
1005 "NODE<person>"
1006 );
1007 }
1008
1009 #[test]
1010 fn every_name_the_table_resolves_prints_back_to_a_name_it_resolves() {
1011 for name in [
1016 "BOOL",
1017 "SMALLINT",
1018 "BIGINT",
1019 "UNSIGNED",
1020 "REAL",
1021 "DOUBLE PRECISION",
1022 "STRING",
1023 "BYTES",
1024 "DATE",
1025 "LOCAL TIME",
1026 "LOCAL DATETIME",
1027 "ZONED TIME",
1028 "ZONED DATETIME",
1029 "DURATION",
1030 "YEAR MONTH DURATION",
1031 "NULL",
1032 "NOTHING",
1033 "ANY",
1034 "ANY PROPERTY VALUE",
1035 "NODE",
1036 "EDGE",
1037 "GRAPH",
1038 "BINDING TABLE",
1039 "PATH",
1040 "INT(4)",
1041 "FLOAT(3)",
1042 ] {
1043 let ty = type_by_name(name).unwrap_or_else(|| panic!("{name} is not a type"));
1044 let printed = ty.to_string();
1045 assert_eq!(
1046 type_by_name(&printed),
1047 Some(ty.clone()),
1048 "{name} prints as {printed}, which does not resolve back"
1049 );
1050 }
1051 }
1052}