Skip to main content

graphos_common/types/
logical_type.rs

1//! Logical type system for Graphos.
2//!
3//! This module defines the type system used for schema definitions and
4//! type checking in queries.
5
6use serde::{Deserialize, Serialize};
7use std::fmt;
8
9/// Logical type for values in Graphos.
10///
11/// These types correspond to the GQL/Cypher type system and are used for:
12/// - Schema definitions (column types in node/edge tables)
13/// - Query type checking
14/// - Value coercion rules
15#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
16pub enum LogicalType {
17    /// Unknown or any type (used during type inference)
18    Any,
19
20    /// Null type (only value is NULL)
21    Null,
22
23    /// Boolean type
24    Bool,
25
26    /// 8-bit signed integer
27    Int8,
28
29    /// 16-bit signed integer
30    Int16,
31
32    /// 32-bit signed integer
33    Int32,
34
35    /// 64-bit signed integer
36    Int64,
37
38    /// 32-bit floating point
39    Float32,
40
41    /// 64-bit floating point
42    Float64,
43
44    /// Variable-length UTF-8 string
45    String,
46
47    /// Binary data
48    Bytes,
49
50    /// Date (year, month, day)
51    Date,
52
53    /// Time (hour, minute, second, nanosecond)
54    Time,
55
56    /// Timestamp with timezone
57    Timestamp,
58
59    /// Duration/interval
60    Duration,
61
62    /// Homogeneous list of elements
63    List(Box<LogicalType>),
64
65    /// Key-value map
66    Map {
67        /// Type of map keys (usually String)
68        key: Box<LogicalType>,
69        /// Type of map values
70        value: Box<LogicalType>,
71    },
72
73    /// Struct with named fields
74    Struct(Vec<(String, LogicalType)>),
75
76    /// Node reference
77    Node,
78
79    /// Edge reference
80    Edge,
81
82    /// Path (sequence of nodes and edges)
83    Path,
84}
85
86impl LogicalType {
87    /// Returns true if this type is numeric (integer or floating point).
88    #[must_use]
89    pub const fn is_numeric(&self) -> bool {
90        matches!(
91            self,
92            LogicalType::Int8
93                | LogicalType::Int16
94                | LogicalType::Int32
95                | LogicalType::Int64
96                | LogicalType::Float32
97                | LogicalType::Float64
98        )
99    }
100
101    /// Returns true if this type is an integer type.
102    #[must_use]
103    pub const fn is_integer(&self) -> bool {
104        matches!(
105            self,
106            LogicalType::Int8 | LogicalType::Int16 | LogicalType::Int32 | LogicalType::Int64
107        )
108    }
109
110    /// Returns true if this type is a floating point type.
111    #[must_use]
112    pub const fn is_float(&self) -> bool {
113        matches!(self, LogicalType::Float32 | LogicalType::Float64)
114    }
115
116    /// Returns true if this type is a temporal type.
117    #[must_use]
118    pub const fn is_temporal(&self) -> bool {
119        matches!(
120            self,
121            LogicalType::Date | LogicalType::Time | LogicalType::Timestamp | LogicalType::Duration
122        )
123    }
124
125    /// Returns true if this type is a graph element type.
126    #[must_use]
127    pub const fn is_graph_element(&self) -> bool {
128        matches!(self, LogicalType::Node | LogicalType::Edge | LogicalType::Path)
129    }
130
131    /// Returns true if this type is nullable (can hold NULL values).
132    ///
133    /// In Graphos, all types except Null itself are nullable by default.
134    #[must_use]
135    pub const fn is_nullable(&self) -> bool {
136        true
137    }
138
139    /// Returns the element type if this is a List, otherwise None.
140    #[must_use]
141    pub fn list_element_type(&self) -> Option<&LogicalType> {
142        match self {
143            LogicalType::List(elem) => Some(elem),
144            _ => None,
145        }
146    }
147
148    /// Checks if a value of `other` type can be implicitly coerced to this type.
149    #[must_use]
150    pub fn can_coerce_from(&self, other: &LogicalType) -> bool {
151        if self == other {
152            return true;
153        }
154
155        // Any accepts everything
156        if matches!(self, LogicalType::Any) {
157            return true;
158        }
159
160        // Null coerces to any nullable type
161        if matches!(other, LogicalType::Null) && self.is_nullable() {
162            return true;
163        }
164
165        // Numeric coercion: smaller integers coerce to larger
166        match (other, self) {
167            (LogicalType::Int8, LogicalType::Int16 | LogicalType::Int32 | LogicalType::Int64) => {
168                true
169            }
170            (LogicalType::Int16, LogicalType::Int32 | LogicalType::Int64) => true,
171            (LogicalType::Int32, LogicalType::Int64) => true,
172            (LogicalType::Float32, LogicalType::Float64) => true,
173            // Integers coerce to floats
174            (
175                LogicalType::Int8 | LogicalType::Int16 | LogicalType::Int32,
176                LogicalType::Float32 | LogicalType::Float64,
177            ) => true,
178            (LogicalType::Int64, LogicalType::Float64) => true,
179            _ => false,
180        }
181    }
182
183    /// Returns the common supertype of two types, if one exists.
184    #[must_use]
185    pub fn common_type(&self, other: &LogicalType) -> Option<LogicalType> {
186        if self == other {
187            return Some(self.clone());
188        }
189
190        // Handle Any
191        if matches!(self, LogicalType::Any) {
192            return Some(other.clone());
193        }
194        if matches!(other, LogicalType::Any) {
195            return Some(self.clone());
196        }
197
198        // Handle Null
199        if matches!(self, LogicalType::Null) {
200            return Some(other.clone());
201        }
202        if matches!(other, LogicalType::Null) {
203            return Some(self.clone());
204        }
205
206        // Numeric promotion
207        if self.is_numeric() && other.is_numeric() {
208            // Float64 is the ultimate numeric type
209            if self.is_float() || other.is_float() {
210                return Some(LogicalType::Float64);
211            }
212            // Otherwise promote to largest integer
213            return Some(LogicalType::Int64);
214        }
215
216        None
217    }
218}
219
220impl fmt::Display for LogicalType {
221    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
222        match self {
223            LogicalType::Any => write!(f, "ANY"),
224            LogicalType::Null => write!(f, "NULL"),
225            LogicalType::Bool => write!(f, "BOOL"),
226            LogicalType::Int8 => write!(f, "INT8"),
227            LogicalType::Int16 => write!(f, "INT16"),
228            LogicalType::Int32 => write!(f, "INT32"),
229            LogicalType::Int64 => write!(f, "INT64"),
230            LogicalType::Float32 => write!(f, "FLOAT32"),
231            LogicalType::Float64 => write!(f, "FLOAT64"),
232            LogicalType::String => write!(f, "STRING"),
233            LogicalType::Bytes => write!(f, "BYTES"),
234            LogicalType::Date => write!(f, "DATE"),
235            LogicalType::Time => write!(f, "TIME"),
236            LogicalType::Timestamp => write!(f, "TIMESTAMP"),
237            LogicalType::Duration => write!(f, "DURATION"),
238            LogicalType::List(elem) => write!(f, "LIST<{elem}>"),
239            LogicalType::Map { key, value } => write!(f, "MAP<{key}, {value}>"),
240            LogicalType::Struct(fields) => {
241                write!(f, "STRUCT<")?;
242                for (i, (name, ty)) in fields.iter().enumerate() {
243                    if i > 0 {
244                        write!(f, ", ")?;
245                    }
246                    write!(f, "{name}: {ty}")?;
247                }
248                write!(f, ">")
249            }
250            LogicalType::Node => write!(f, "NODE"),
251            LogicalType::Edge => write!(f, "EDGE"),
252            LogicalType::Path => write!(f, "PATH"),
253        }
254    }
255}
256
257impl Default for LogicalType {
258    fn default() -> Self {
259        LogicalType::Any
260    }
261}
262
263#[cfg(test)]
264mod tests {
265    use super::*;
266
267    #[test]
268    fn test_numeric_checks() {
269        assert!(LogicalType::Int64.is_numeric());
270        assert!(LogicalType::Float64.is_numeric());
271        assert!(!LogicalType::String.is_numeric());
272
273        assert!(LogicalType::Int64.is_integer());
274        assert!(!LogicalType::Float64.is_integer());
275
276        assert!(LogicalType::Float64.is_float());
277        assert!(!LogicalType::Int64.is_float());
278    }
279
280    #[test]
281    fn test_coercion() {
282        // Same type always coerces
283        assert!(LogicalType::Int64.can_coerce_from(&LogicalType::Int64));
284
285        // Null coerces to anything
286        assert!(LogicalType::Int64.can_coerce_from(&LogicalType::Null));
287        assert!(LogicalType::String.can_coerce_from(&LogicalType::Null));
288
289        // Integer widening
290        assert!(LogicalType::Int64.can_coerce_from(&LogicalType::Int32));
291        assert!(LogicalType::Int32.can_coerce_from(&LogicalType::Int16));
292        assert!(!LogicalType::Int32.can_coerce_from(&LogicalType::Int64));
293
294        // Float widening
295        assert!(LogicalType::Float64.can_coerce_from(&LogicalType::Float32));
296
297        // Int to float
298        assert!(LogicalType::Float64.can_coerce_from(&LogicalType::Int64));
299        assert!(LogicalType::Float32.can_coerce_from(&LogicalType::Int32));
300    }
301
302    #[test]
303    fn test_common_type() {
304        // Same types
305        assert_eq!(
306            LogicalType::Int64.common_type(&LogicalType::Int64),
307            Some(LogicalType::Int64)
308        );
309
310        // Numeric promotion
311        assert_eq!(
312            LogicalType::Int32.common_type(&LogicalType::Int64),
313            Some(LogicalType::Int64)
314        );
315        assert_eq!(
316            LogicalType::Int64.common_type(&LogicalType::Float64),
317            Some(LogicalType::Float64)
318        );
319
320        // Null handling
321        assert_eq!(
322            LogicalType::Null.common_type(&LogicalType::String),
323            Some(LogicalType::String)
324        );
325
326        // Incompatible types
327        assert_eq!(LogicalType::String.common_type(&LogicalType::Int64), None);
328    }
329
330    #[test]
331    fn test_display() {
332        assert_eq!(LogicalType::Int64.to_string(), "INT64");
333        assert_eq!(
334            LogicalType::List(Box::new(LogicalType::String)).to_string(),
335            "LIST<STRING>"
336        );
337        assert_eq!(
338            LogicalType::Map {
339                key: Box::new(LogicalType::String),
340                value: Box::new(LogicalType::Int64)
341            }
342            .to_string(),
343            "MAP<STRING, INT64>"
344        );
345    }
346}