alopex-sql 0.8.10

SQL parser components for the Alopex DB dialect
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
//! Type definitions for the Alopex SQL planner.
//!
//! This module defines [`ResolvedType`], the normalized type representation
//! used during type checking and planning phases.

use crate::ast::ddl::{DataType, VectorMetric};

/// Normalized type information for type checking.
///
/// This enum represents the resolved type after normalization from AST types.
/// For example, `INTEGER` and `INT` both resolve to [`ResolvedType::Integer`].
///
/// # Examples
///
/// ```
/// use alopex_sql::planner::types::ResolvedType;
/// use alopex_sql::ast::ddl::{DataType, VectorMetric};
///
/// // Convert from AST DataType
/// let int_type = ResolvedType::from_ast(&DataType::Integer);
/// assert_eq!(int_type, ResolvedType::Integer);
///
/// // VECTOR with omitted metric defaults to Cosine
/// let vec_type = ResolvedType::from_ast(&DataType::Vector { dimension: 128, metric: None });
/// assert_eq!(vec_type, ResolvedType::Vector { dimension: 128, metric: VectorMetric::Cosine });
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ResolvedType {
    /// Integer type (INTEGER, INT → Integer)
    Integer,
    /// Big integer type
    BigInt,
    /// Single-precision floating point
    Float,
    /// Double-precision floating point
    Double,
    /// Text/string type
    Text,
    /// Binary data type
    Blob,
    /// Boolean type (BOOLEAN, BOOL → Boolean)
    Boolean,
    /// Timestamp type
    Timestamp,
    /// Calendar date without a time zone, stored as days from 1970-01-01.
    Date,
    /// Time of day without a time zone, stored as microseconds after midnight.
    Time,
    /// Calendar interval stored as independent month, day, and microsecond parts.
    Interval,
    /// Exact fixed-precision decimal with up to 38 digits.
    Decimal { precision: u8, scale: u8 },
    /// Canonical native JSON value (`JSONB` is a dialect alias).
    Json,
    /// Variable-length homogeneous nested values (`LIST` is a dialect alias).
    Array(Box<ResolvedType>),
    /// Ordered key/value entries with homogeneous key and value types.
    Map {
        key: Box<ResolvedType>,
        value: Box<ResolvedType>,
    },
    /// Named heterogeneous nested fields.
    Struct(Vec<(String, ResolvedType)>),
    /// Vector type with dimension and metric
    /// Metric is always populated (defaults to Cosine if omitted in AST)
    Vector {
        dimension: u32,
        metric: VectorMetric,
    },
    /// NULL type (for NULL literals)
    Null,
}

impl ResolvedType {
    /// Convert from AST [`DataType`] to [`ResolvedType`].
    ///
    /// For `VECTOR` types, if metric is omitted in the AST, it defaults to `Cosine`.
    ///
    /// # Examples
    ///
    /// ```
    /// use alopex_sql::planner::types::ResolvedType;
    /// use alopex_sql::ast::ddl::{DataType, VectorMetric};
    ///
    /// // INTEGER and INT both resolve to Integer
    /// assert_eq!(ResolvedType::from_ast(&DataType::Integer), ResolvedType::Integer);
    /// assert_eq!(ResolvedType::from_ast(&DataType::Int), ResolvedType::Integer);
    ///
    /// // BOOLEAN and BOOL both resolve to Boolean
    /// assert_eq!(ResolvedType::from_ast(&DataType::Boolean), ResolvedType::Boolean);
    /// assert_eq!(ResolvedType::from_ast(&DataType::Bool), ResolvedType::Boolean);
    ///
    /// // VECTOR with metric
    /// let vec_with_metric = ResolvedType::from_ast(&DataType::Vector {
    ///     dimension: 128,
    ///     metric: Some(VectorMetric::L2),
    /// });
    /// assert_eq!(vec_with_metric, ResolvedType::Vector {
    ///     dimension: 128,
    ///     metric: VectorMetric::L2,
    /// });
    ///
    /// // VECTOR without metric defaults to Cosine
    /// let vec_default = ResolvedType::from_ast(&DataType::Vector {
    ///     dimension: 256,
    ///     metric: None,
    /// });
    /// assert_eq!(vec_default, ResolvedType::Vector {
    ///     dimension: 256,
    ///     metric: VectorMetric::Cosine,
    /// });
    /// ```
    pub fn from_ast(dt: &DataType) -> Self {
        match dt {
            DataType::Integer | DataType::Int => Self::Integer,
            DataType::BigInt => Self::BigInt,
            DataType::Float => Self::Float,
            DataType::Double => Self::Double,
            DataType::Text => Self::Text,
            DataType::Blob => Self::Blob,
            DataType::Boolean | DataType::Bool => Self::Boolean,
            DataType::Timestamp => Self::Timestamp,
            DataType::Date => Self::Date,
            DataType::Time => Self::Time,
            DataType::Interval => Self::Interval,
            DataType::Decimal { precision, scale } => Self::Decimal {
                precision: *precision,
                scale: *scale,
            },
            DataType::Json => Self::Json,
            DataType::Array { element } => Self::Array(Box::new(Self::from_ast(element))),
            DataType::Map { key, value } => Self::Map {
                key: Box::new(Self::from_ast(key)),
                value: Box::new(Self::from_ast(value)),
            },
            DataType::Struct { fields } => Self::Struct(
                fields
                    .iter()
                    .map(|field| (field.name.clone(), Self::from_ast(&field.data_type)))
                    .collect(),
            ),
            DataType::Vector { dimension, metric } => Self::Vector {
                dimension: *dimension,
                metric: metric.unwrap_or(VectorMetric::Cosine),
            },
        }
    }

    /// Check if this type can be implicitly cast to the target type.
    ///
    /// Implicit conversion rules:
    /// - Same types are always compatible
    /// - `Null` can be cast to any type
    /// - Numeric widening: `Integer` → `BigInt`, `Float`, `Double`
    /// - Numeric widening: `BigInt` → `Double`
    /// - Numeric widening: `Float` → `Double`
    /// - TIMESTAMP accepts canonical timestamp text and integral epoch microseconds
    /// - `Vector` types require dimension check (done separately)
    ///
    /// # Examples
    ///
    /// ```
    /// use alopex_sql::planner::types::ResolvedType;
    ///
    /// // Same type
    /// assert!(ResolvedType::Integer.can_cast_to(&ResolvedType::Integer));
    ///
    /// // Null can cast to any type
    /// assert!(ResolvedType::Null.can_cast_to(&ResolvedType::Integer));
    /// assert!(ResolvedType::Null.can_cast_to(&ResolvedType::Text));
    ///
    /// // Numeric widening
    /// assert!(ResolvedType::Integer.can_cast_to(&ResolvedType::BigInt));
    /// assert!(ResolvedType::Integer.can_cast_to(&ResolvedType::Float));
    /// assert!(ResolvedType::Integer.can_cast_to(&ResolvedType::Double));
    /// assert!(ResolvedType::BigInt.can_cast_to(&ResolvedType::Double));
    /// assert!(ResolvedType::Float.can_cast_to(&ResolvedType::Double));
    ///
    /// // Incompatible types
    /// assert!(!ResolvedType::Text.can_cast_to(&ResolvedType::Integer));
    /// assert!(!ResolvedType::BigInt.can_cast_to(&ResolvedType::Integer));
    /// ```
    pub fn can_cast_to(&self, target: &ResolvedType) -> bool {
        use ResolvedType::*;

        match (self, target) {
            // Same type is always compatible
            (a, b) if a == b => true,

            // Null can be cast to any type
            (Null, _) => true,

            // Numeric widening conversions
            (Integer, BigInt | Float | Double | Decimal { .. }) => true,
            (BigInt, Double) => true,
            (Float, Double) => true,
            (BigInt | Float | Double | Text | Decimal { .. }, Decimal { .. }) => true,

            // A decimal literal is typed DOUBLE, so assigning one to a FLOAT
            // column needs this narrowing; the value is rounded to f32 at
            // execution time.
            (Double, Float) => true,

            // TIMESTAMP is stored as epoch microseconds. Text is parsed as a
            // canonical UTC timestamp and numeric values must be integral
            // microseconds at execution time.
            (Text | Integer | BigInt | Float | Double, Timestamp) => true,
            (Text, Date | Time | Interval) => true,
            (Text, Json) | (Json, Text) => true,
            (Array(source), Array(target)) => source.can_cast_to(target),
            (
                Map {
                    key: source_key,
                    value: source_value,
                },
                Map {
                    key: target_key,
                    value: target_value,
                },
            ) => source_key.can_cast_to(target_key) && source_value.can_cast_to(target_value),
            (Struct(source), Struct(target)) if source.len() == target.len() => source
                .iter()
                .zip(target)
                .all(|((source_name, source_type), (target_name, target_type))| {
                    source_name == target_name && source_type.can_cast_to(target_type)
                }),

            // Vector types require dimension check (done separately in TypeChecker)
            (Vector { .. }, Vector { .. }) => false,

            // All other conversions are not allowed
            _ => false,
        }
    }

    /// Get a human-readable name for this type.
    ///
    /// Used for error messages.
    pub fn type_name(&self) -> &'static str {
        match self {
            Self::Integer => "Integer",
            Self::BigInt => "BigInt",
            Self::Float => "Float",
            Self::Double => "Double",
            Self::Text => "Text",
            Self::Blob => "Blob",
            Self::Boolean => "Boolean",
            Self::Timestamp => "Timestamp",
            Self::Date => "Date",
            Self::Time => "Time",
            Self::Interval => "Interval",
            Self::Decimal { .. } => "Decimal",
            Self::Json => "Json",
            Self::Array(_) => "Array",
            Self::Map { .. } => "Map",
            Self::Struct(_) => "Struct",
            Self::Vector { .. } => "Vector",
            Self::Null => "Null",
        }
    }
}

impl std::fmt::Display for ResolvedType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Integer => write!(f, "INTEGER"),
            Self::BigInt => write!(f, "BIGINT"),
            Self::Float => write!(f, "FLOAT"),
            Self::Double => write!(f, "DOUBLE"),
            Self::Text => write!(f, "TEXT"),
            Self::Blob => write!(f, "BLOB"),
            Self::Boolean => write!(f, "BOOLEAN"),
            Self::Timestamp => write!(f, "TIMESTAMP"),
            Self::Date => write!(f, "DATE"),
            Self::Time => write!(f, "TIME"),
            Self::Interval => write!(f, "INTERVAL"),
            Self::Decimal { precision, scale } => write!(f, "DECIMAL({precision},{scale})"),
            Self::Json => write!(f, "JSON"),
            Self::Array(element) => write!(f, "ARRAY<{element}>"),
            Self::Map { key, value } => write!(f, "MAP<{key},{value}>"),
            Self::Struct(fields) => {
                write!(f, "STRUCT<")?;
                for (index, (name, data_type)) in fields.iter().enumerate() {
                    if index > 0 {
                        write!(f, ",")?;
                    }
                    write!(f, "{name} {data_type}")?;
                }
                write!(f, ">")
            }
            Self::Vector { dimension, metric } => {
                write!(f, "VECTOR({}, {:?})", dimension, metric)
            }
            Self::Null => write!(f, "NULL"),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_from_ast_integer() {
        assert_eq!(
            ResolvedType::from_ast(&DataType::Integer),
            ResolvedType::Integer
        );
        assert_eq!(
            ResolvedType::from_ast(&DataType::Int),
            ResolvedType::Integer
        );
    }

    #[test]
    fn test_from_ast_boolean() {
        assert_eq!(
            ResolvedType::from_ast(&DataType::Boolean),
            ResolvedType::Boolean
        );
        assert_eq!(
            ResolvedType::from_ast(&DataType::Bool),
            ResolvedType::Boolean
        );
    }

    #[test]
    fn test_from_ast_vector_with_metric() {
        let dt = DataType::Vector {
            dimension: 128,
            metric: Some(VectorMetric::L2),
        };
        assert_eq!(
            ResolvedType::from_ast(&dt),
            ResolvedType::Vector {
                dimension: 128,
                metric: VectorMetric::L2,
            }
        );
    }

    #[test]
    fn test_from_ast_vector_default_metric() {
        let dt = DataType::Vector {
            dimension: 256,
            metric: None,
        };
        assert_eq!(
            ResolvedType::from_ast(&dt),
            ResolvedType::Vector {
                dimension: 256,
                metric: VectorMetric::Cosine,
            }
        );
    }

    #[test]
    fn test_can_cast_same_type() {
        assert!(ResolvedType::Integer.can_cast_to(&ResolvedType::Integer));
        assert!(ResolvedType::Text.can_cast_to(&ResolvedType::Text));
    }

    #[test]
    fn test_can_cast_null() {
        assert!(ResolvedType::Null.can_cast_to(&ResolvedType::Integer));
        assert!(ResolvedType::Null.can_cast_to(&ResolvedType::Text));
        assert!(ResolvedType::Null.can_cast_to(&ResolvedType::Boolean));
    }

    #[test]
    fn test_can_cast_numeric_widening() {
        // Integer → BigInt/Float/Double
        assert!(ResolvedType::Integer.can_cast_to(&ResolvedType::BigInt));
        assert!(ResolvedType::Integer.can_cast_to(&ResolvedType::Float));
        assert!(ResolvedType::Integer.can_cast_to(&ResolvedType::Double));

        // BigInt → Double
        assert!(ResolvedType::BigInt.can_cast_to(&ResolvedType::Double));

        // Float → Double
        assert!(ResolvedType::Float.can_cast_to(&ResolvedType::Double));

        assert!(
            ResolvedType::Decimal {
                precision: 5,
                scale: 3,
            }
            .can_cast_to(&ResolvedType::Decimal {
                precision: 10,
                scale: 2,
            })
        );
    }

    #[test]
    fn test_can_cast_incompatible() {
        // Text cannot cast to numeric
        assert!(!ResolvedType::Text.can_cast_to(&ResolvedType::Integer));

        // Numeric narrowing not allowed
        assert!(!ResolvedType::BigInt.can_cast_to(&ResolvedType::Integer));
    }

    #[test]
    fn double_narrows_to_float_because_decimal_literals_are_double() {
        // The lexer types every decimal literal as DOUBLE, so rejecting this
        // narrowing would make FLOAT columns impossible to populate.
        assert!(ResolvedType::Double.can_cast_to(&ResolvedType::Float));
    }

    #[test]
    fn test_can_cast_vector() {
        let vec1 = ResolvedType::Vector {
            dimension: 128,
            metric: VectorMetric::Cosine,
        };
        let vec2 = ResolvedType::Vector {
            dimension: 128,
            metric: VectorMetric::L2,
        };
        // Vector dimension check is done separately
        assert!(!vec1.can_cast_to(&vec2));
    }

    #[test]
    fn test_display() {
        assert_eq!(format!("{}", ResolvedType::Integer), "INTEGER");
        assert_eq!(format!("{}", ResolvedType::Text), "TEXT");
        assert_eq!(
            format!(
                "{}",
                ResolvedType::Vector {
                    dimension: 128,
                    metric: VectorMetric::Cosine
                }
            ),
            "VECTOR(128, Cosine)"
        );
    }
}