Skip to main content

zu_common/
types.rs

1//! The two layer type model (gql/plan/02 sections 2 and 3).
2//!
3//! zu has had one notion of type and it is physical: `PropType { Str,
4//! Int }` in storage and a ten arm `PhysType` in the vector layer. GQL
5//! needs two, and conflating them is what makes an engine either slow
6//! or wrong. A logical type is what the language talks about, with its
7//! nullability and its declared width and its element types. A physical
8//! type is what a vector holds, and it is a small closed set with no
9//! nullability in it, because validity is a bitmap, and no precision in
10//! it, because precision is a check and not a layout.
11//!
12//! The GV family is 52 of the standard's 228 optional features and
13//! nothing else in the standard can be evaluated without it, which is
14//! why it comes first. Nineteen of the 52 are the integer tower, and
15//! they are one implementation with a width on it, so the family is
16//! 23% of the conformance surface and closer to 6% of the work.
17//!
18//! This module is the lattice and the mapping. It holds no values and
19//! reads no storage: a `LogicalType` is what a column or an expression
20//! is declared to be, and [`LogicalType::physical`] is the only bridge
21//! to the layer that holds bytes.
22
23use std::fmt;
24
25/// Width of an integer type, in bits.
26///
27/// The tower stops at 256 because the standard does, and every width is
28/// a fixed stride, so the FOR and delta cascades in `zu-encoding` need
29/// the width registered and nothing else.
30#[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    /// The width in bits.
42    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    /// Whether a 64 bit lane word is a value of an integer type this
54    /// wide.
55    ///
56    /// The word is two's complement for a signed type and plain for an
57    /// unsigned one, which is the reading the lane gives it, so this
58    /// asks about the value rather than about the bits. A type 64 bits
59    /// or wider holds every word there is, since a word is all a lane
60    /// carries and the wide towers have no lane of their own.
61    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    /// The narrowest width that holds `digits` decimal digits, which is
76    /// what `INT(p)` (GV09) asks for. `None` when no width in the tower
77    /// is wide enough.
78    ///
79    /// The bound is the count of decimal digits a width holds in full:
80    /// an i64 reaches 9_223_372_036_854_775_807, so it holds every 18
81    /// digit number and only some 19 digit ones, and a type that
82    /// promised 19 would be promising a range it does not have.
83    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/// Width of a floating point type, in bits.
97///
98/// 16, 128 and 256 have no hardware anywhere zu runs. They are here
99/// because the standard has them; they compute in software and the
100/// benchmark matrix never uses them, which gql/plan/09 section 6 says
101/// out loud so nobody reads a soft float number as an engine number.
102#[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    /// The width in bits.
113    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    /// The narrowest binary width whose significand holds `digits`
124    /// decimal digits, which is what `FLOAT(p)` (GV22) asks for.
125    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/// The two duration kinds, which do not mix.
138///
139/// A year-month duration plus a day-time duration is a type error and
140/// not a normalisation, because a month is not a number of days. An
141/// engine that stores months, days and nanoseconds in one value has to
142/// invent an answer for "one month after 31 January" and the standard
143/// does not ask it to. zu stores two types and refuses the arithmetic
144/// that would need the invention.
145#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
146pub enum DurationKind {
147    YearMonth,
148    DayTime,
149}
150
151/// One field of a record type.
152#[derive(Clone, PartialEq, Eq, Debug, Hash)]
153pub struct Field {
154    pub name: String,
155    pub ty: LogicalType,
156}
157
158/// A record type: named fields, and whether fields outside the list are
159/// allowed.
160///
161/// `open` is GV47 and closed is GV46, one boolean between them, and
162/// GV48 (nested records) falls out of the type being recursive.
163#[derive(Clone, PartialEq, Eq, Debug, Hash)]
164pub struct RecordType {
165    pub fields: Vec<Field>,
166    pub open: bool,
167}
168
169impl RecordType {
170    /// A closed record, the common case.
171    pub fn closed(fields: Vec<Field>) -> Self {
172        RecordType {
173            fields,
174            open: false,
175        }
176    }
177
178    /// An open record, which may carry fields the type does not name.
179    /// This is the one place in the type system where a per value map
180    /// exists, and that map is the honest cost of GV47.
181    pub fn open(fields: Vec<Field>) -> Self {
182        RecordType { fields, open: true }
183    }
184
185    /// The declared field of this name, if the type names one.
186    pub fn field(&self, name: &str) -> Option<&Field> {
187        self.fields.iter().find(|f| f.name == name)
188    }
189}
190
191/// What GQL talks about: the language facing type lattice.
192///
193/// Never present in a vector. A vector holds a [`PhysicalType`] and a
194/// validity bitmap, and the logical type is what the binder knows about
195/// the column, which is a different and larger thing: `INT(4) NOT NULL`
196/// and `BIGINT` are two logical types over one physical layout.
197#[derive(Clone, PartialEq, Eq, Debug, Hash)]
198pub enum LogicalType {
199    /// GV71. The type of the null literal, which every nullable type
200    /// accepts and which carries no other value.
201    Null,
202    /// GV72. The empty type: no value has it. A column can never be
203    /// declared with it, an expression can have it, and the binder
204    /// refuses anything that would have to materialise one.
205    Nothing,
206
207    Bool,
208    /// GV01 to GV19. `signed` and the width are the tower; `precision`
209    /// is the declared decimal digit count of `INT(p)`, kept because it
210    /// is a check the engine owes the user and not a layout.
211    Int {
212        signed: bool,
213        bits: IntBits,
214        precision: Option<u16>,
215    },
216    /// GV17. Exact decimal, stored in the narrowest integer width that
217    /// holds `precision` digits and scaled by `scale`.
218    Decimal {
219        precision: u16,
220        scale: u16,
221    },
222    /// GV20 to GV26.
223    Float {
224        bits: FloatBits,
225        precision: Option<u16>,
226    },
227    /// GV30 to GV32. Lengths are in characters, and a character is a
228    /// Unicode scalar value. `fixed` is GV32, the one length constraint
229    /// that changes the layout rather than adding a check.
230    Str {
231        min: Option<u32>,
232        max: Option<u32>,
233        fixed: bool,
234    },
235    /// GV35 to GV38. Lengths are in octets.
236    Bytes {
237        min: Option<u32>,
238        max: Option<u32>,
239        fixed: bool,
240    },
241
242    /// GV39. Proleptic Gregorian, no zone.
243    Date,
244    /// GV39. Time of day with no zone and therefore no DST.
245    LocalTime,
246    /// GV39. An instant with no zone.
247    LocalDatetime,
248    /// GV40. Time of day with an offset from UTC in minutes.
249    ZonedTime,
250    /// GV40. An instant with an offset from UTC in minutes.
251    ZonedDatetime,
252    /// GV41.
253    Duration(DurationKind),
254
255    /// A node reference, optionally of a named node type.
256    Node(Option<String>),
257    /// An edge reference, optionally of a named edge type.
258    Edge(Option<String>),
259    /// GV60. A graph handle: a catalog id and a snapshot epoch, not
260    /// data. Making it a value is what turns `USE` from a statement
261    /// prefix into something composable.
262    Graph(Option<String>),
263    /// GV61. A binding table handle, with the record type of its rows
264    /// when that is known.
265    BindingTable(Option<RecordType>),
266
267    /// GV55. A path, whose type describes the alternating node and edge
268    /// types it walks.
269    Path(Option<Box<PathType>>),
270    /// GV50.
271    List {
272        elem: Box<LogicalType>,
273        max: Option<u32>,
274    },
275    /// GV45 to GV48.
276    Record(RecordType),
277
278    /// GV65 and GV66. The open dynamic union: any type at all.
279    Any,
280    /// GV67. A closed dynamic union, `ANY<INT|STRING>`.
281    Union(Vec<LogicalType>),
282    /// GV68. Any type a property may hold, which is `Any` minus the
283    /// reference and constructed types.
284    AnyProperty,
285
286    /// GV90, orthogonal to everything above. Nullability is a wrapper
287    /// and not a flag on each variant, so no variant can forget it.
288    Nullable(Box<LogicalType>),
289}
290
291/// The alternating node and edge types a path walks.
292///
293/// `nodes` is one longer than `edges` for a path type that describes a
294/// fixed walk. A path type that describes a repeated segment is left to
295/// the language surface in G6, which is where the syntax for it lands.
296#[derive(Clone, PartialEq, Eq, Debug, Hash)]
297pub struct PathType {
298    pub nodes: Vec<Option<String>>,
299    pub edges: Vec<Option<String>>,
300}
301
302/// What a vector holds. Fifteen layouts, each one either a fixed stride
303/// or an offsets buffer plus a child, so every kernel in perf/02 and
304/// every SIMD tier in perf/11 can address them, and so Parquet and
305/// Arrow ingest map onto them without a transcode.
306///
307/// No nullability: validity is a separate bitmap and null is never a
308/// value in a vector. No precision: that is a check the logical type
309/// carries.
310#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
311pub enum PhysicalType {
312    /// One bit per row, packed in words.
313    Bool,
314    I8,
315    I16,
316    I32,
317    I64,
318    U8,
319    U16,
320    U32,
321    U64,
322    /// 16 byte stride. Serves the 128 bit integers and decimals up to
323    /// 38 digits.
324    I128,
325    /// 32 byte stride. Serves the 256 bit integers and decimals up to
326    /// 76 digits.
327    I256,
328    F32,
329    F64,
330    /// 16 byte stride, computed in software.
331    F128,
332    /// Offsets plus an arena.
333    Str,
334    /// Offsets plus an arena, compared by octet and never dictionary
335    /// encoded.
336    Bytes,
337    /// i32 stride: days since 1970-01-01.
338    Days32,
339    /// i64 stride: nanoseconds, since midnight for a time and since the
340    /// epoch for a datetime, and the whole of a day-time duration.
341    Nanos64,
342    /// Two buffers: i64 nanoseconds and an i16 offset in minutes.
343    Zoned,
344    /// i32 stride: whole months, and nothing else, which is what makes
345    /// the two duration kinds refuse to mix.
346    Months32,
347    /// Offsets plus a child vector.
348    ListOffsets,
349    /// Child vectors and no bytes of its own.
350    Struct,
351}
352
353impl PhysicalType {
354    /// Bytes per value for the fixed stride layouts.
355    ///
356    /// `None` for `Bool`, which is bit packed, and for the four layouts
357    /// that are offsets or children rather than a stride. A caller that
358    /// wants "how much space does a row take" cannot get an answer from
359    /// those without the data, and returning a number would be a lie
360    /// rather than an approximation.
361    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    /// A nullable version of this type, without stacking wrappers.
381    pub fn nullable(self) -> LogicalType {
382        match self {
383            LogicalType::Nullable(_) => self,
384            other => LogicalType::Nullable(Box::new(other)),
385        }
386    }
387
388    /// Whether a value of this type may be null. `NULL` itself is
389    /// nullable and nothing else is unless it says so, which is the
390    /// GV90 reading: a declared type is not null until wrapped.
391    pub fn is_nullable(&self) -> bool {
392        matches!(self, LogicalType::Nullable(_) | LogicalType::Null)
393    }
394
395    /// This type with any nullability wrapper removed, which is the
396    /// form every layout question is asked about.
397    pub fn base(&self) -> &LogicalType {
398        match self {
399            LogicalType::Nullable(inner) => inner.base(),
400            other => other,
401        }
402    }
403
404    /// Whether this type may hold a value at all. The immaterial types
405    /// (GV71, GV72) cannot: `NOTHING` has no values and `NULL` has one
406    /// that is never stored in a vector.
407    pub fn is_material(&self) -> bool {
408        !matches!(self.base(), LogicalType::Null | LogicalType::Nothing)
409    }
410
411    /// The layout a vector of this type uses, or `None` when there is
412    /// nothing to lay out.
413    ///
414    /// The dynamic unions map to `Struct`, which holds a type code
415    /// child and one child per member. That is the one construct in the
416    /// system that puts a tag back next to each value, and it is
417    /// confined to columns declared as unions, which in practice is the
418    /// schemaless ingest path and nothing else.
419    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                // 128 and 256 have one stride each and carry their sign
433                // in the value, because there is no hardware difference
434                // to gain from two layouts at these widths.
435                (_, 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                // A 16 bit float stores as f32 and computes as f32,
448                // which is what every SIMD unit does with one anyway.
449                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            // References are one word each: a node or edge row id, and
461            // a handle for the two catalog references.
462            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    /// The common integer spellings, so a caller does not write the
476    /// struct out to say `BIGINT`.
477    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    /// A string with no length constraint.
501    pub fn string() -> LogicalType {
502        LogicalType::Str {
503            min: None,
504            max: None,
505            fixed: false,
506        }
507    }
508
509    /// A byte string with no length constraint.
510    pub fn bytes() -> LogicalType {
511        LogicalType::Bytes {
512            min: None,
513            max: None,
514            fixed: false,
515        }
516    }
517}
518
519/// Resolves a type name, with its synonyms and its parenthesised
520/// arguments, to a logical type.
521///
522/// Synonym resolution is a table and not a parser branch, because the
523/// standard's spellings are a list and not a grammar: `SMALLINT`,
524/// `INT`, `BIGINT`, `SIGNED`, `UNSIGNED`, `REAL`, `DOUBLE PRECISION`
525/// and the rest name types the tower already has. The parenthesised
526/// argument is the only structure here: `INT(p)` and `FLOAT(p)` are
527/// decimal digit counts, the string and byte lengths are counts of
528/// characters and octets, and `DECIMAL(p,s)` takes both.
529///
530/// The name is matched case insensitively and internal whitespace is
531/// collapsed, so `double   precision` and `DOUBLE PRECISION` are one
532/// name. A trailing `NOT NULL` is not handled here: nullability is a
533/// wrapper the binder applies, and letting it into the name table would
534/// make every entry two entries.
535pub 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        // The standard's bare INT is the implementation's regular
550        // width, and zu's row ids, degrees and counts are all 64 bit,
551        // so a narrower default would surprise every user of it.
552        ("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        // GV09 and GV22: a declared decimal digit count, kept on the
563        // type as a check and widened to the narrowest layout holding
564        // it. A count no width holds is not a type.
565        ("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
651/// Splits `INT(4)` into `("INT", [4])` and `INT` into `("INT", [])`.
652/// Returns `None` when the parentheses do not close or an argument is
653/// not a number, so a caller gets one answer for "not a type name" and
654/// not two.
655fn 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    /// The spelling that goes in a diagnostic record, so the two type
675    /// names in a `22G0x` say what the user wrote rather than what the
676    /// enum looks like.
677    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        // 19 digits do not fit an i64 in full, so INT(19) is a 128.
799        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        // The declared digit count survives on the type, because the
904        // range check it asks for is narrower than the layout.
905        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        // Not that the spelling round trips, since synonyms collapse,
1012        // but that what a diagnostic prints is a name the engine
1013        // accepts. A type whose printed form is not a type name is a
1014        // message the user cannot act on.
1015        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}