Skip to main content

sqlglot_rust/optimizer/
annotate_types.rs

1//! Type annotation pass for SQL expressions.
2//!
3//! Infers and propagates SQL data types across AST nodes using schema metadata.
4//! Inspired by Python sqlglot's `annotate_types` optimizer pass.
5//!
6//! # Overview
7//!
8//! The pass walks the AST bottom-up, resolving types for:
9//! - **Literals**: `42` → `Int`, `'hello'` → `Varchar`, `TRUE` → `Boolean`
10//! - **Column references**: looked up from the provided [`Schema`]
11//! - **Binary operators**: result type from operand coercion (e.g. `INT + FLOAT → FLOAT`)
12//! - **CAST / TRY_CAST**: the target data type
13//! - **Functions**: return type based on function signature and argument types
14//! - **CASE**: common type across all THEN / ELSE branches
15//! - **Aggregates**: `COUNT → BigInt`, `SUM` depends on input, etc.
16//! - **Subqueries**: type of the single output column
17//!
18//! # Example
19//!
20//! ```rust
21//! use sqlglot_rust::optimizer::annotate_types::annotate_types;
22//! use sqlglot_rust::schema::{MappingSchema, Schema};
23//! use sqlglot_rust::ast::DataType;
24//! use sqlglot_rust::{parse, Dialect};
25//!
26//! let mut schema = MappingSchema::new(Dialect::Ansi);
27//! schema.add_table(&["t"], vec![
28//!     ("id".to_string(), DataType::Int),
29//!     ("name".to_string(), DataType::Varchar(Some(255))),
30//! ]).unwrap();
31//!
32//! let stmt = parse("SELECT id, name FROM t WHERE id > 1", Dialect::Ansi).unwrap();
33//! let annotations = annotate_types(&stmt, &schema);
34//! // annotations now contains inferred types for every expression node
35//! ```
36
37use std::collections::HashMap;
38
39use crate::ast::*;
40use crate::schema::Schema;
41
42// ═══════════════════════════════════════════════════════════════════════
43// TypeAnnotations — the result of type inference
44// ═══════════════════════════════════════════════════════════════════════
45
46/// Stores inferred [`DataType`] annotations for expression nodes in an AST.
47///
48/// Annotations are keyed by raw pointer identity, so this structure is valid
49/// only as long as the underlying AST is not moved, cloned, or dropped.
50/// Intended for single-pass analysis over a borrowed AST.
51pub struct TypeAnnotations {
52    types: HashMap<*const Expr, DataType>,
53}
54
55// Raw pointers are not Send/Sync by default, but our usage is safe because
56// the pointers are derived from shared references with a known lifetime.
57unsafe impl Send for TypeAnnotations {}
58unsafe impl Sync for TypeAnnotations {}
59
60impl TypeAnnotations {
61    fn new() -> Self {
62        Self {
63            types: HashMap::new(),
64        }
65    }
66
67    fn set(&mut self, expr: &Expr, dt: DataType) {
68        self.types.insert(expr as *const Expr, dt);
69    }
70
71    /// Retrieve the inferred type of an expression, if annotated.
72    #[must_use]
73    pub fn get_type(&self, expr: &Expr) -> Option<&DataType> {
74        self.types.get(&(expr as *const Expr))
75    }
76
77    /// Number of annotated nodes.
78    #[must_use]
79    pub fn len(&self) -> usize {
80        self.types.len()
81    }
82
83    /// Returns `true` if no annotations were recorded.
84    #[must_use]
85    pub fn is_empty(&self) -> bool {
86        self.types.is_empty()
87    }
88}
89
90// ═══════════════════════════════════════════════════════════════════════
91// Public entry point
92// ═══════════════════════════════════════════════════════════════════════
93
94/// Annotate all expression nodes in a statement with inferred SQL types.
95///
96/// Walks the AST bottom-up, resolving types from literals, schema column
97/// lookups, operator/function signatures, and type coercion rules.
98///
99/// The returned [`TypeAnnotations`] is valid only while the borrowed `stmt`
100/// is alive and unmodified.
101#[must_use]
102pub fn annotate_types<S: Schema>(stmt: &Statement, schema: &S) -> TypeAnnotations {
103    let mut ann = TypeAnnotations::new();
104    let mut ctx = AnnotationContext::new(schema);
105    annotate_statement(stmt, &mut ctx, &mut ann);
106    ann
107}
108
109// ═══════════════════════════════════════════════════════════════════════
110// Internal context
111// ═══════════════════════════════════════════════════════════════════════
112
113/// Carries schema reference and table alias mappings through the walk.
114struct AnnotationContext<'s, S: Schema> {
115    schema: &'s S,
116    /// Maps table alias or name → table path for column type lookups.
117    table_aliases: HashMap<String, Vec<String>>,
118}
119
120impl<'s, S: Schema> AnnotationContext<'s, S> {
121    fn new(schema: &'s S) -> Self {
122        Self {
123            schema,
124            table_aliases: HashMap::new(),
125        }
126    }
127
128    /// Register a table (by ref) so that columns can be looked up by alias.
129    fn register_table(&mut self, table_ref: &TableRef) {
130        let path = vec![table_ref.name.clone()];
131        let alias = table_ref
132            .alias
133            .as_deref()
134            .unwrap_or(&table_ref.name)
135            .to_string();
136        self.table_aliases.insert(alias, path);
137    }
138
139    /// Look up the type of a column, resolving through table aliases.
140    fn resolve_column_type(&self, table: Option<&str>, column: &str) -> Option<DataType> {
141        if let Some(tbl) = table {
142            // Qualified column — look up via alias map
143            if let Some(path) = self.table_aliases.get(tbl) {
144                let path_refs: Vec<&str> = path.iter().map(String::as_str).collect();
145                return self.schema.get_column_type(&path_refs, column).ok();
146            }
147            // Try the table name directly
148            return self.schema.get_column_type(&[tbl], column).ok();
149        }
150        // Unqualified — search all registered tables
151        for path in self.table_aliases.values() {
152            let path_refs: Vec<&str> = path.iter().map(String::as_str).collect();
153            if let Ok(dt) = self.schema.get_column_type(&path_refs, column) {
154                return Some(dt);
155            }
156        }
157        None
158    }
159}
160
161// ═══════════════════════════════════════════════════════════════════════
162// Statement-level annotation
163// ═══════════════════════════════════════════════════════════════════════
164
165fn annotate_statement<S: Schema>(
166    stmt: &Statement,
167    ctx: &mut AnnotationContext<S>,
168    ann: &mut TypeAnnotations,
169) {
170    match stmt {
171        Statement::Select(sel) => annotate_select(sel, ctx, ann),
172        Statement::SetOperation(set_op) => {
173            annotate_statement(&set_op.left, ctx, ann);
174            annotate_statement(&set_op.right, ctx, ann);
175        }
176        Statement::Insert(ins) => {
177            if let InsertSource::Query(q) = &ins.source {
178                annotate_statement(q, ctx, ann);
179            }
180            for row in match &ins.source {
181                InsertSource::Values(rows) => rows.as_slice(),
182                _ => &[],
183            } {
184                for expr in row {
185                    annotate_expr(expr, ctx, ann);
186                }
187            }
188        }
189        Statement::Update(upd) => {
190            for (_, expr) in &upd.assignments {
191                annotate_expr(expr, ctx, ann);
192            }
193            if let Some(wh) = &upd.where_clause {
194                annotate_expr(wh, ctx, ann);
195            }
196        }
197        Statement::Delete(del) => {
198            if let Some(wh) = &del.where_clause {
199                annotate_expr(wh, ctx, ann);
200            }
201        }
202        Statement::Expression(expr) => {
203            annotate_expr(expr, ctx, ann);
204        }
205        Statement::Explain(expl) => {
206            annotate_statement(&expl.statement, ctx, ann);
207        }
208        // DDL / transaction / other statements — no expression types to annotate
209        _ => {}
210    }
211}
212
213fn annotate_select<S: Schema>(
214    sel: &SelectStatement,
215    ctx: &mut AnnotationContext<S>,
216    ann: &mut TypeAnnotations,
217) {
218    // 1. Register CTEs
219    for cte in &sel.ctes {
220        annotate_statement(&cte.query, ctx, ann);
221    }
222
223    // 2. Register FROM sources
224    if let Some(from) = &sel.from {
225        register_table_source(&from.source, ctx);
226    }
227    for join in &sel.joins {
228        register_table_source(&join.table, ctx);
229    }
230
231    // 3. Annotate WHERE clause
232    if let Some(wh) = &sel.where_clause {
233        annotate_expr(wh, ctx, ann);
234    }
235
236    // 4. Annotate SELECT columns
237    for item in &sel.columns {
238        if let SelectItem::Expr { expr, .. } = item {
239            annotate_expr(expr, ctx, ann);
240        }
241    }
242
243    // 5. Annotate GROUP BY
244    for expr in &sel.group_by {
245        annotate_expr(expr, ctx, ann);
246    }
247
248    // 6. Annotate HAVING
249    if let Some(having) = &sel.having {
250        annotate_expr(having, ctx, ann);
251    }
252
253    // 7. Annotate ORDER BY
254    for ob in &sel.order_by {
255        annotate_expr(&ob.expr, ctx, ann);
256    }
257
258    // 8. Annotate LIMIT / OFFSET
259    if let Some(limit) = &sel.limit {
260        annotate_expr(limit, ctx, ann);
261    }
262    if let Some(offset) = &sel.offset {
263        annotate_expr(offset, ctx, ann);
264    }
265    if let Some(fetch) = &sel.fetch_first {
266        annotate_expr(fetch, ctx, ann);
267    }
268
269    // 9. Annotate QUALIFY
270    if let Some(qualify) = &sel.qualify {
271        annotate_expr(qualify, ctx, ann);
272    }
273
274    // 10. Annotate JOIN ON conditions
275    for join in &sel.joins {
276        if let Some(on) = &join.on {
277            annotate_expr(on, ctx, ann);
278        }
279    }
280}
281
282fn register_table_source<S: Schema>(source: &TableSource, ctx: &mut AnnotationContext<S>) {
283    match source {
284        TableSource::Table(tref) => ctx.register_table(tref),
285        TableSource::Subquery { alias, .. } => {
286            // Subqueries as sources don't have schema entries to register.
287            // Their output column types would come from recursive annotation.
288            let _ = alias;
289        }
290        TableSource::TableFunction { alias, .. } => {
291            let _ = alias;
292        }
293        TableSource::Lateral { source } => register_table_source(source, ctx),
294        TableSource::Unnest { .. } => {}
295    }
296}
297
298// ═══════════════════════════════════════════════════════════════════════
299// Expression-level annotation (bottom-up)
300// ═══════════════════════════════════════════════════════════════════════
301
302fn annotate_expr<S: Schema>(expr: &Expr, ctx: &AnnotationContext<S>, ann: &mut TypeAnnotations) {
303    // First annotate children, then determine this node's type.
304    annotate_children(expr, ctx, ann);
305
306    let dt = infer_type(expr, ctx, ann);
307    if let Some(t) = dt {
308        ann.set(expr, t);
309    }
310}
311
312/// Recursively annotate child expressions before the parent.
313fn annotate_children<S: Schema>(
314    expr: &Expr,
315    ctx: &AnnotationContext<S>,
316    ann: &mut TypeAnnotations,
317) {
318    match expr {
319        Expr::BinaryOp { left, right, .. } => {
320            annotate_expr(left, ctx, ann);
321            annotate_expr(right, ctx, ann);
322        }
323        Expr::UnaryOp { expr: inner, .. } => annotate_expr(inner, ctx, ann),
324        Expr::Function { args, filter, .. } => {
325            for arg in args {
326                annotate_expr(arg, ctx, ann);
327            }
328            if let Some(f) = filter {
329                annotate_expr(f, ctx, ann);
330            }
331        }
332        Expr::Between {
333            expr: e, low, high, ..
334        } => {
335            annotate_expr(e, ctx, ann);
336            annotate_expr(low, ctx, ann);
337            annotate_expr(high, ctx, ann);
338        }
339        Expr::InList { expr: e, list, .. } => {
340            annotate_expr(e, ctx, ann);
341            for item in list {
342                annotate_expr(item, ctx, ann);
343            }
344        }
345        Expr::InSubquery {
346            expr: e, subquery, ..
347        } => {
348            annotate_expr(e, ctx, ann);
349            let mut sub_ctx = AnnotationContext::new(ctx.schema);
350            annotate_statement(subquery, &mut sub_ctx, ann);
351        }
352        Expr::IsNull { expr: e, .. } | Expr::IsBool { expr: e, .. } => {
353            annotate_expr(e, ctx, ann);
354        }
355        Expr::Like {
356            expr: e,
357            pattern,
358            escape,
359            ..
360        }
361        | Expr::ILike {
362            expr: e,
363            pattern,
364            escape,
365            ..
366        } => {
367            annotate_expr(e, ctx, ann);
368            annotate_expr(pattern, ctx, ann);
369            if let Some(esc) = escape {
370                annotate_expr(esc, ctx, ann);
371            }
372        }
373        Expr::Case {
374            operand,
375            when_clauses,
376            else_clause,
377        } => {
378            if let Some(op) = operand {
379                annotate_expr(op, ctx, ann);
380            }
381            for (cond, result) in when_clauses {
382                annotate_expr(cond, ctx, ann);
383                annotate_expr(result, ctx, ann);
384            }
385            if let Some(el) = else_clause {
386                annotate_expr(el, ctx, ann);
387            }
388        }
389        Expr::Nested(inner) => annotate_expr(inner, ctx, ann),
390        Expr::Cast { expr: e, .. } | Expr::TryCast { expr: e, .. } => {
391            annotate_expr(e, ctx, ann);
392        }
393        Expr::Extract { expr: e, .. } => annotate_expr(e, ctx, ann),
394        Expr::Interval { value, .. } => annotate_expr(value, ctx, ann),
395        Expr::ArrayLiteral(items) | Expr::Tuple(items) | Expr::Coalesce(items) => {
396            for item in items {
397                annotate_expr(item, ctx, ann);
398            }
399        }
400        Expr::If {
401            condition,
402            true_val,
403            false_val,
404        } => {
405            annotate_expr(condition, ctx, ann);
406            annotate_expr(true_val, ctx, ann);
407            if let Some(fv) = false_val {
408                annotate_expr(fv, ctx, ann);
409            }
410        }
411        Expr::NullIf { expr: e, r#else } => {
412            annotate_expr(e, ctx, ann);
413            annotate_expr(r#else, ctx, ann);
414        }
415        Expr::Collate { expr: e, .. } => annotate_expr(e, ctx, ann),
416        Expr::Alias { expr: e, .. } => annotate_expr(e, ctx, ann),
417        Expr::ArrayIndex { expr: e, index } => {
418            annotate_expr(e, ctx, ann);
419            annotate_expr(index, ctx, ann);
420        }
421        Expr::JsonAccess { expr: e, path, .. } => {
422            annotate_expr(e, ctx, ann);
423            annotate_expr(path, ctx, ann);
424        }
425        Expr::Lambda { body, .. } => annotate_expr(body, ctx, ann),
426        Expr::AnyOp { expr: e, right, .. } | Expr::AllOp { expr: e, right, .. } => {
427            annotate_expr(e, ctx, ann);
428            annotate_expr(right, ctx, ann);
429        }
430        Expr::Subquery(sub) => {
431            let mut sub_ctx = AnnotationContext::new(ctx.schema);
432            annotate_statement(sub, &mut sub_ctx, ann);
433        }
434        Expr::Exists { subquery, .. } => {
435            let mut sub_ctx = AnnotationContext::new(ctx.schema);
436            annotate_statement(subquery, &mut sub_ctx, ann);
437        }
438        Expr::TypedFunction { func, filter, .. } => {
439            annotate_typed_function_children(func, ctx, ann);
440            if let Some(f) = filter {
441                annotate_expr(f, ctx, ann);
442            }
443        }
444        Expr::Cube { exprs } | Expr::Rollup { exprs } | Expr::GroupingSets { sets: exprs } => {
445            for item in exprs {
446                annotate_expr(item, ctx, ann);
447            }
448        }
449        // Leaf nodes — no children to annotate
450        Expr::Column { .. }
451        | Expr::Number(_)
452        | Expr::StringLiteral(_)
453        | Expr::Boolean(_)
454        | Expr::Null
455        | Expr::Wildcard
456        | Expr::Star
457        | Expr::Parameter(_)
458        | Expr::TypeExpr(_)
459        | Expr::QualifiedWildcard { .. }
460        | Expr::Default => {}
461    }
462}
463
464/// Annotate children of a TypedFunction.
465fn annotate_typed_function_children<S: Schema>(
466    func: &TypedFunction,
467    ctx: &AnnotationContext<S>,
468    ann: &mut TypeAnnotations,
469) {
470    // Use walk_children to visit all child expressions and annotate each
471    func.walk_children(&mut |child| {
472        annotate_expr(child, ctx, ann);
473        true
474    });
475}
476
477// ═══════════════════════════════════════════════════════════════════════
478// Type inference for a single expression node
479// ═══════════════════════════════════════════════════════════════════════
480
481fn infer_type<S: Schema>(
482    expr: &Expr,
483    ctx: &AnnotationContext<S>,
484    ann: &TypeAnnotations,
485) -> Option<DataType> {
486    match expr {
487        // ── Literals ───────────────────────────────────────────────────
488        Expr::Number(s) => Some(infer_number_type(s)),
489        Expr::StringLiteral(_) => Some(DataType::Varchar(None)),
490        Expr::Boolean(_) => Some(DataType::Boolean),
491        Expr::Null => Some(DataType::Null),
492
493        // ── Column reference ──────────────────────────────────────────
494        Expr::Column { table, name, .. } => ctx.resolve_column_type(table.as_deref(), name),
495
496        // ── Binary operators ──────────────────────────────────────────
497        Expr::BinaryOp { left, op, right } => {
498            infer_binary_op_type(op, ann.get_type(left), ann.get_type(right))
499        }
500
501        // ── Unary operators ───────────────────────────────────────────
502        Expr::UnaryOp { op, expr: inner } => match op {
503            UnaryOperator::Not => Some(DataType::Boolean),
504            UnaryOperator::Minus | UnaryOperator::Plus => ann.get_type(inner).cloned(),
505            UnaryOperator::BitwiseNot => ann.get_type(inner).cloned(),
506        },
507
508        // ── CAST / TRY_CAST ──────────────────────────────────────────
509        Expr::Cast { data_type, .. } | Expr::TryCast { data_type, .. } => Some(data_type.clone()),
510
511        // ── CASE expression ──────────────────────────────────────────
512        Expr::Case {
513            when_clauses,
514            else_clause,
515            ..
516        } => {
517            let mut result_types: Vec<&DataType> = Vec::new();
518            for (_, result) in when_clauses {
519                if let Some(t) = ann.get_type(result) {
520                    result_types.push(t);
521                }
522            }
523            if let Some(el) = else_clause {
524                if let Some(t) = ann.get_type(el.as_ref()) {
525                    result_types.push(t);
526                }
527            }
528            common_type(&result_types)
529        }
530
531        // ── IF expression ────────────────────────────────────────────
532        Expr::If {
533            true_val,
534            false_val,
535            ..
536        } => {
537            let mut types = Vec::new();
538            if let Some(t) = ann.get_type(true_val) {
539                types.push(t);
540            }
541            if let Some(fv) = false_val {
542                if let Some(t) = ann.get_type(fv.as_ref()) {
543                    types.push(t);
544                }
545            }
546            common_type(&types)
547        }
548
549        // ── COALESCE ─────────────────────────────────────────────────
550        Expr::Coalesce(items) => {
551            let types: Vec<&DataType> = items.iter().filter_map(|e| ann.get_type(e)).collect();
552            common_type(&types)
553        }
554
555        // ── NULLIF ───────────────────────────────────────────────────
556        Expr::NullIf { expr: e, .. } => ann.get_type(e.as_ref()).cloned(),
557
558        // ── Generic function ─────────────────────────────────────────
559        Expr::Function { name, args, .. } => infer_generic_function_type(name, args, ctx, ann),
560
561        // ── Typed functions ──────────────────────────────────────────
562        Expr::TypedFunction { func, .. } => infer_typed_function_type(func, ann),
563
564        // ── Subquery (scalar) ────────────────────────────────────────
565        Expr::Subquery(sub) => infer_subquery_type(sub, ann),
566
567        // ── EXISTS → Boolean ─────────────────────────────────────────
568        Expr::Exists { .. } => Some(DataType::Boolean),
569
570        // ── Boolean predicates ───────────────────────────────────────
571        Expr::Between { .. }
572        | Expr::InList { .. }
573        | Expr::InSubquery { .. }
574        | Expr::IsNull { .. }
575        | Expr::IsBool { .. }
576        | Expr::Like { .. }
577        | Expr::ILike { .. }
578        | Expr::AnyOp { .. }
579        | Expr::AllOp { .. } => Some(DataType::Boolean),
580
581        // ── EXTRACT → numeric ────────────────────────────────────────
582        Expr::Extract { .. } => Some(DataType::Int),
583
584        // ── INTERVAL → Interval ──────────────────────────────────────
585        Expr::Interval { .. } => Some(DataType::Interval),
586
587        // ── Array literal ────────────────────────────────────────────
588        Expr::ArrayLiteral(items) => {
589            let elem_types: Vec<&DataType> = items.iter().filter_map(|e| ann.get_type(e)).collect();
590            let elem = common_type(&elem_types);
591            Some(DataType::Array(elem.map(Box::new)))
592        }
593
594        // ── Tuple ────────────────────────────────────────────────────
595        Expr::Tuple(items) => {
596            let types: Vec<DataType> = items
597                .iter()
598                .map(|e| ann.get_type(e).cloned().unwrap_or(DataType::Null))
599                .collect();
600            Some(DataType::Tuple(types))
601        }
602
603        // ── Array index → element type ───────────────────────────────
604        Expr::ArrayIndex { expr: e, .. } => match ann.get_type(e.as_ref()) {
605            Some(DataType::Array(Some(elem))) => Some(elem.as_ref().clone()),
606            _ => None,
607        },
608
609        // ── JSON access ──────────────────────────────────────────────
610        Expr::JsonAccess { as_text, .. } => {
611            if *as_text {
612                Some(DataType::Text)
613            } else {
614                Some(DataType::Json)
615            }
616        }
617
618        // ── Nested / Alias — pass through ────────────────────────────
619        Expr::Nested(inner) => ann.get_type(inner.as_ref()).cloned(),
620        Expr::Alias { expr: e, .. } => ann.get_type(e.as_ref()).cloned(),
621
622        // ── Collate → Varchar ────────────────────────────────────────
623        Expr::Collate { .. } => Some(DataType::Varchar(None)),
624
625        // ── TypeExpr ─────────────────────────────────────────────────
626        Expr::TypeExpr(dt) => Some(dt.clone()),
627
628        // ── Others — no type ─────────────────────────────────────────
629        Expr::Wildcard
630        | Expr::Star
631        | Expr::QualifiedWildcard { .. }
632        | Expr::Parameter(_)
633        | Expr::Lambda { .. }
634        | Expr::Default
635        | Expr::Cube { .. }
636        | Expr::Rollup { .. }
637        | Expr::GroupingSets { .. } => None,
638    }
639}
640
641// ═══════════════════════════════════════════════════════════════════════
642// Number type inference
643// ═══════════════════════════════════════════════════════════════════════
644
645fn infer_number_type(s: &str) -> DataType {
646    if s.contains('.') || s.contains('e') || s.contains('E') {
647        DataType::Double
648    } else if let Ok(v) = s.parse::<i64>() {
649        if v >= i32::MIN as i64 && v <= i32::MAX as i64 {
650            DataType::Int
651        } else {
652            DataType::BigInt
653        }
654    } else {
655        // Very large numbers or special formats
656        DataType::BigInt
657    }
658}
659
660// ═══════════════════════════════════════════════════════════════════════
661// Binary operator type inference
662// ═══════════════════════════════════════════════════════════════════════
663
664fn infer_binary_op_type(
665    op: &BinaryOperator,
666    left: Option<&DataType>,
667    right: Option<&DataType>,
668) -> Option<DataType> {
669    use BinaryOperator::*;
670    match op {
671        // Comparison operators → Boolean
672        Eq | Neq | Lt | Gt | LtEq | GtEq => Some(DataType::Boolean),
673
674        // Logical operators → Boolean
675        And | Or | Xor => Some(DataType::Boolean),
676
677        // String concatenation → Varchar
678        Concat => Some(DataType::Varchar(None)),
679
680        // Arithmetic → coerce operand types
681        Plus | Minus | Multiply | Divide | Modulo => match (left, right) {
682            (Some(l), Some(r)) => Some(coerce_numeric(l, r)),
683            (Some(l), None) => Some(l.clone()),
684            (None, Some(r)) => Some(r.clone()),
685            (None, None) => None,
686        },
687
688        // Bitwise → integer type
689        BitwiseAnd | BitwiseOr | BitwiseXor | ShiftLeft | ShiftRight => match (left, right) {
690            (Some(l), Some(r)) => Some(coerce_numeric(l, r)),
691            (Some(l), None) => Some(l.clone()),
692            (None, Some(r)) => Some(r.clone()),
693            (None, None) => Some(DataType::Int),
694        },
695
696        // JSON operators
697        Arrow => Some(DataType::Json),
698        DoubleArrow => Some(DataType::Text),
699    }
700}
701
702// ═══════════════════════════════════════════════════════════════════════
703// Generic (untyped) function return type inference
704// ═══════════════════════════════════════════════════════════════════════
705
706fn infer_generic_function_type<S: Schema>(
707    name: &str,
708    args: &[Expr],
709    ctx: &AnnotationContext<S>,
710    ann: &TypeAnnotations,
711) -> Option<DataType> {
712    let upper = name.to_uppercase();
713    match upper.as_str() {
714        // Aggregate functions
715        "COUNT" | "COUNT_BIG" => Some(DataType::BigInt),
716        "SUM" => args
717            .first()
718            .and_then(|a| ann.get_type(a))
719            .map(|t| coerce_sum_type(t)),
720        "AVG" => Some(DataType::Double),
721        "MIN" | "MAX" => args.first().and_then(|a| ann.get_type(a)).cloned(),
722        "VARIANCE" | "VAR_SAMP" | "VAR_POP" | "STDDEV" | "STDDEV_SAMP" | "STDDEV_POP" => {
723            Some(DataType::Double)
724        }
725        "APPROX_COUNT_DISTINCT" | "APPROX_DISTINCT" => Some(DataType::BigInt),
726
727        // String functions
728        "CONCAT" | "UPPER" | "LOWER" | "TRIM" | "LTRIM" | "RTRIM" | "LPAD" | "RPAD" | "REPLACE"
729        | "REVERSE" | "SUBSTRING" | "SUBSTR" | "LEFT" | "RIGHT" | "INITCAP" | "REPEAT"
730        | "TRANSLATE" | "FORMAT" | "CONCAT_WS" | "SPACE" | "REPLICATE" => {
731            Some(DataType::Varchar(None))
732        }
733        "LENGTH" | "LEN" | "CHAR_LENGTH" | "CHARACTER_LENGTH" | "OCTET_LENGTH" | "BIT_LENGTH" => {
734            Some(DataType::Int)
735        }
736        "POSITION" | "STRPOS" | "LOCATE" | "INSTR" | "CHARINDEX" => Some(DataType::Int),
737        "ASCII" => Some(DataType::Int),
738        "CHR" | "CHAR" => Some(DataType::Varchar(Some(1))),
739
740        // Math functions
741        "ABS" | "CEIL" | "CEILING" | "FLOOR" => args.first().and_then(|a| ann.get_type(a)).cloned(),
742        "ROUND" | "TRUNCATE" | "TRUNC" => args.first().and_then(|a| ann.get_type(a)).cloned(),
743        "SQRT" | "LN" | "LOG" | "LOG2" | "LOG10" | "EXP" | "POWER" | "POW" | "ACOS" | "ASIN"
744        | "ATAN" | "ATAN2" | "COS" | "SIN" | "TAN" | "COT" | "DEGREES" | "RADIANS" | "PI"
745        | "SIGN" => Some(DataType::Double),
746        "MOD" => {
747            match (
748                args.first().and_then(|a| ann.get_type(a)),
749                args.get(1).and_then(|a| ann.get_type(a)),
750            ) {
751                (Some(l), Some(r)) => Some(coerce_numeric(l, r)),
752                (Some(l), _) => Some(l.clone()),
753                (_, Some(r)) => Some(r.clone()),
754                _ => Some(DataType::Int),
755            }
756        }
757        "GREATEST" | "LEAST" => {
758            let types: Vec<&DataType> = args.iter().filter_map(|a| ann.get_type(a)).collect();
759            common_type(&types)
760        }
761        "RANDOM" | "RAND" => Some(DataType::Double),
762
763        // Date/Time functions
764        "CURRENT_DATE" | "CURDATE" | "TODAY" => Some(DataType::Date),
765        "CURRENT_TIMESTAMP" | "NOW" | "GETDATE" | "SYSDATE" | "SYSTIMESTAMP" | "LOCALTIMESTAMP" => {
766            Some(DataType::Timestamp {
767                precision: None,
768                with_tz: false,
769            })
770        }
771        "CURRENT_TIME" | "CURTIME" => Some(DataType::Time { precision: None }),
772        "DATE" | "TO_DATE" | "DATE_TRUNC" | "DATE_ADD" | "DATE_SUB" | "DATEADD" | "DATESUB"
773        | "ADDDATE" | "SUBDATE" => Some(DataType::Date),
774        "TIMESTAMP" | "TO_TIMESTAMP" => Some(DataType::Timestamp {
775            precision: None,
776            with_tz: false,
777        }),
778        "YEAR" | "MONTH" | "DAY" | "DAYOFWEEK" | "DAYOFYEAR" | "HOUR" | "MINUTE" | "SECOND"
779        | "QUARTER" | "WEEK" | "EXTRACT" | "DATEDIFF" | "TIMESTAMPDIFF" | "MONTHS_BETWEEN" => {
780            Some(DataType::Int)
781        }
782
783        // Type conversion
784        "CAST" | "TRY_CAST" | "SAFE_CAST" | "CONVERT" => None, // handled by Expr::Cast
785
786        // Boolean functions
787        "COALESCE" => {
788            let types: Vec<&DataType> = args.iter().filter_map(|a| ann.get_type(a)).collect();
789            common_type(&types)
790        }
791        "NULLIF" => args.first().and_then(|a| ann.get_type(a)).cloned(),
792        "IF" | "IIF" => {
793            // IF(cond, true_val, false_val) — type from true_val
794            args.get(1).and_then(|a| ann.get_type(a)).cloned()
795        }
796        "IFNULL" | "NVL" | "ISNULL" => {
797            let types: Vec<&DataType> = args.iter().filter_map(|a| ann.get_type(a)).collect();
798            common_type(&types)
799        }
800
801        // JSON functions
802        "JSON_EXTRACT" | "JSON_QUERY" | "GET_JSON_OBJECT" => Some(DataType::Json),
803        "JSON_EXTRACT_SCALAR" | "JSON_VALUE" | "JSON_EXTRACT_PATH_TEXT" => {
804            Some(DataType::Varchar(None))
805        }
806        "TO_JSON" | "JSON_OBJECT" | "JSON_ARRAY" | "JSON_BUILD_OBJECT" | "JSON_BUILD_ARRAY" => {
807            Some(DataType::Json)
808        }
809        "PARSE_JSON" | "JSON_PARSE" | "JSON" => Some(DataType::Json),
810
811        // Array functions
812        "ARRAY_AGG" | "COLLECT_LIST" | "COLLECT_SET" => {
813            let elem = args.first().and_then(|a| ann.get_type(a)).cloned();
814            Some(DataType::Array(elem.map(Box::new)))
815        }
816        "ARRAY_LENGTH" | "ARRAY_SIZE" | "CARDINALITY" => Some(DataType::Int),
817        "ARRAY" | "ARRAY_CONSTRUCT" => {
818            let types: Vec<&DataType> = args.iter().filter_map(|a| ann.get_type(a)).collect();
819            let elem = common_type(&types);
820            Some(DataType::Array(elem.map(Box::new)))
821        }
822        "ARRAY_CONTAINS" | "ARRAY_POSITION" => Some(DataType::Boolean),
823
824        // Window ranking
825        "ROW_NUMBER" | "RANK" | "DENSE_RANK" | "NTILE" | "CUME_DIST" | "PERCENT_RANK" => {
826            Some(DataType::BigInt)
827        }
828
829        // Hash / crypto
830        "MD5" | "SHA1" | "SHA" | "SHA2" | "SHA256" | "SHA512" => Some(DataType::Varchar(None)),
831        "HEX" | "TO_HEX" => Some(DataType::Varchar(None)),
832        "UNHEX" | "FROM_HEX" => Some(DataType::Varbinary(None)),
833        "CRC32" | "HASH" => Some(DataType::BigInt),
834
835        // Type checking
836        "TYPEOF" | "TYPE_OF" => Some(DataType::Varchar(None)),
837
838        // UDFs — check schema
839        _ => ctx.schema.get_udf_type(&upper).cloned(),
840    }
841}
842
843// ═══════════════════════════════════════════════════════════════════════
844// TypedFunction return type inference
845// ═══════════════════════════════════════════════════════════════════════
846
847fn infer_typed_function_type(func: &TypedFunction, ann: &TypeAnnotations) -> Option<DataType> {
848    match func {
849        // ── Date/Time → Date or Timestamp ────────────────────────────
850        TypedFunction::DateAdd { .. }
851        | TypedFunction::DateSub { .. }
852        | TypedFunction::DateTrunc { .. }
853        | TypedFunction::TsOrDsToDate { .. } => Some(DataType::Date),
854        TypedFunction::DateDiff { .. } => Some(DataType::Int),
855        TypedFunction::CurrentDate => Some(DataType::Date),
856        TypedFunction::CurrentTimestamp => Some(DataType::Timestamp {
857            precision: None,
858            with_tz: false,
859        }),
860        TypedFunction::StrToTime { .. } => Some(DataType::Timestamp {
861            precision: None,
862            with_tz: false,
863        }),
864        TypedFunction::TimeToStr { .. } => Some(DataType::Varchar(None)),
865        TypedFunction::Year { .. } | TypedFunction::Month { .. } | TypedFunction::Day { .. } => {
866            Some(DataType::Int)
867        }
868
869        // ── String → Varchar ─────────────────────────────────────────
870        TypedFunction::Trim { .. }
871        | TypedFunction::Substring { .. }
872        | TypedFunction::Upper { .. }
873        | TypedFunction::Lower { .. }
874        | TypedFunction::Initcap { .. }
875        | TypedFunction::Replace { .. }
876        | TypedFunction::Reverse { .. }
877        | TypedFunction::Left { .. }
878        | TypedFunction::Right { .. }
879        | TypedFunction::Lpad { .. }
880        | TypedFunction::Rpad { .. }
881        | TypedFunction::ConcatWs { .. } => Some(DataType::Varchar(None)),
882        TypedFunction::Length { .. } => Some(DataType::Int),
883        TypedFunction::RegexpLike { .. } => Some(DataType::Boolean),
884        TypedFunction::RegexpExtract { .. } => Some(DataType::Varchar(None)),
885        TypedFunction::RegexpReplace { .. } => Some(DataType::Varchar(None)),
886        TypedFunction::Split { .. } => {
887            Some(DataType::Array(Some(Box::new(DataType::Varchar(None)))))
888        }
889
890        // ── Aggregates ───────────────────────────────────────────────
891        TypedFunction::Count { .. } => Some(DataType::BigInt),
892        TypedFunction::Sum { expr, .. } => ann.get_type(expr.as_ref()).map(|t| coerce_sum_type(t)),
893        TypedFunction::Avg { .. } => Some(DataType::Double),
894        TypedFunction::Min { expr } | TypedFunction::Max { expr } => {
895            ann.get_type(expr.as_ref()).cloned()
896        }
897        TypedFunction::ArrayAgg { expr, .. } => {
898            let elem = ann.get_type(expr.as_ref()).cloned();
899            Some(DataType::Array(elem.map(Box::new)))
900        }
901        TypedFunction::ApproxDistinct { .. } => Some(DataType::BigInt),
902        TypedFunction::Variance { .. } | TypedFunction::Stddev { .. } => Some(DataType::Double),
903
904        // ── Array ────────────────────────────────────────────────────
905        TypedFunction::ArrayConcat { arrays } => {
906            // Type is the same as input arrays
907            arrays.first().and_then(|a| ann.get_type(a)).cloned()
908        }
909        TypedFunction::ArrayContains { .. } => Some(DataType::Boolean),
910        TypedFunction::ArraySize { .. } => Some(DataType::Int),
911        TypedFunction::Explode { expr } => {
912            // Unwrap array element type
913            match ann.get_type(expr.as_ref()) {
914                Some(DataType::Array(Some(elem))) => Some(elem.as_ref().clone()),
915                _ => None,
916            }
917        }
918        TypedFunction::GenerateSeries { .. } => Some(DataType::Int),
919        TypedFunction::Flatten { expr } => ann.get_type(expr.as_ref()).cloned(),
920
921        // ── JSON ─────────────────────────────────────────────────────
922        TypedFunction::JSONExtract { .. } => Some(DataType::Json),
923        TypedFunction::JSONExtractScalar { .. } => Some(DataType::Varchar(None)),
924        TypedFunction::ParseJSON { .. } | TypedFunction::JSONFormat { .. } => Some(DataType::Json),
925
926        // ── Window ───────────────────────────────────────────────────
927        TypedFunction::RowNumber | TypedFunction::Rank | TypedFunction::DenseRank => {
928            Some(DataType::BigInt)
929        }
930        TypedFunction::NTile { .. } => Some(DataType::BigInt),
931        TypedFunction::Lead { expr, .. }
932        | TypedFunction::Lag { expr, .. }
933        | TypedFunction::FirstValue { expr }
934        | TypedFunction::LastValue { expr } => ann.get_type(expr.as_ref()).cloned(),
935
936        // ── Math ─────────────────────────────────────────────────────
937        TypedFunction::Abs { expr }
938        | TypedFunction::Ceil { expr }
939        | TypedFunction::Floor { expr } => ann.get_type(expr.as_ref()).cloned(),
940        TypedFunction::Round { expr, .. } => ann.get_type(expr.as_ref()).cloned(),
941        TypedFunction::Log { .. }
942        | TypedFunction::Ln { .. }
943        | TypedFunction::Pow { .. }
944        | TypedFunction::Sqrt { .. } => Some(DataType::Double),
945        TypedFunction::Greatest { exprs } | TypedFunction::Least { exprs } => {
946            let types: Vec<&DataType> = exprs.iter().filter_map(|e| ann.get_type(e)).collect();
947            common_type(&types)
948        }
949        TypedFunction::Mod { left, right } => {
950            match (ann.get_type(left.as_ref()), ann.get_type(right.as_ref())) {
951                (Some(l), Some(r)) => Some(coerce_numeric(l, r)),
952                (Some(l), _) => Some(l.clone()),
953                (_, Some(r)) => Some(r.clone()),
954                _ => Some(DataType::Int),
955            }
956        }
957
958        // ── Conversion ───────────────────────────────────────────────
959        TypedFunction::Hex { .. } | TypedFunction::Md5 { .. } | TypedFunction::Sha { .. } => {
960            Some(DataType::Varchar(None))
961        }
962        TypedFunction::Sha2 { .. } => Some(DataType::Varchar(None)),
963        TypedFunction::Unhex { .. } => Some(DataType::Varbinary(None)),
964    }
965}
966
967// ═══════════════════════════════════════════════════════════════════════
968// Subquery type inference
969// ═══════════════════════════════════════════════════════════════════════
970
971fn infer_subquery_type(sub: &Statement, ann: &TypeAnnotations) -> Option<DataType> {
972    // The type of a scalar subquery is the type of its single output column
973    if let Statement::Select(sel) = sub {
974        if let Some(SelectItem::Expr { expr, .. }) = sel.columns.first() {
975            return ann.get_type(expr).cloned();
976        }
977    }
978    None
979}
980
981// ═══════════════════════════════════════════════════════════════════════
982// Type coercion helpers
983// ═══════════════════════════════════════════════════════════════════════
984
985/// Numeric type widening precedence (higher = wider).
986fn numeric_precedence(dt: &DataType) -> u8 {
987    match dt {
988        DataType::Boolean => 1,
989        DataType::TinyInt => 2,
990        DataType::SmallInt => 3,
991        DataType::Int | DataType::Serial => 4,
992        DataType::BigInt | DataType::BigSerial => 5,
993        DataType::Real | DataType::Float => 6,
994        DataType::Double => 7,
995        DataType::Decimal { .. } | DataType::Numeric { .. } => 8,
996        _ => 0,
997    }
998}
999
1000/// Coerce two numeric types to their common wider type.
1001fn coerce_numeric(left: &DataType, right: &DataType) -> DataType {
1002    let lp = numeric_precedence(left);
1003    let rp = numeric_precedence(right);
1004    if lp == 0 && rp == 0 {
1005        // Neither is numeric — fall back to left
1006        return left.clone();
1007    }
1008    if lp >= rp {
1009        left.clone()
1010    } else {
1011        right.clone()
1012    }
1013}
1014
1015/// Determine the return type of SUM based on input type.
1016fn coerce_sum_type(input: &DataType) -> DataType {
1017    match input {
1018        DataType::TinyInt | DataType::SmallInt | DataType::Int | DataType::BigInt => {
1019            DataType::BigInt
1020        }
1021        DataType::Float | DataType::Real => DataType::Double,
1022        DataType::Double => DataType::Double,
1023        DataType::Decimal { precision, scale } => DataType::Decimal {
1024            precision: *precision,
1025            scale: *scale,
1026        },
1027        DataType::Numeric { precision, scale } => DataType::Numeric {
1028            precision: *precision,
1029            scale: *scale,
1030        },
1031        _ => DataType::BigInt,
1032    }
1033}
1034
1035/// Find the common (widest) type among a set of types.
1036fn common_type(types: &[&DataType]) -> Option<DataType> {
1037    if types.is_empty() {
1038        return None;
1039    }
1040    let mut result = types[0];
1041    for t in &types[1..] {
1042        // Skip NULL — it doesn't contribute to the common type
1043        if **t == DataType::Null {
1044            continue;
1045        }
1046        if *result == DataType::Null {
1047            result = t;
1048            continue;
1049        }
1050        // If both are numeric, pick the wider one
1051        let lp = numeric_precedence(result);
1052        let rp = numeric_precedence(t);
1053        if lp > 0 && rp > 0 {
1054            if rp > lp {
1055                result = t;
1056            }
1057            continue;
1058        }
1059        // If both are string-like, prefer VARCHAR
1060        if is_string_type(result) && is_string_type(t) {
1061            result = if matches!(result, DataType::Text) || matches!(t, DataType::Text) {
1062                if matches!(result, DataType::Text) {
1063                    result
1064                } else {
1065                    t
1066                }
1067            } else {
1068                result // keep first
1069            };
1070            continue;
1071        }
1072        // Otherwise keep the first non-null type
1073    }
1074    Some(result.clone())
1075}
1076
1077fn is_string_type(dt: &DataType) -> bool {
1078    matches!(
1079        dt,
1080        DataType::Varchar(_) | DataType::Char(_) | DataType::Text | DataType::String
1081    )
1082}
1083
1084// ═══════════════════════════════════════════════════════════════════════
1085// Tests
1086// ═══════════════════════════════════════════════════════════════════════
1087
1088#[cfg(test)]
1089mod tests {
1090    use super::*;
1091    use crate::dialects::Dialect;
1092    use crate::parser::Parser;
1093    use crate::schema::{MappingSchema, Schema};
1094
1095    fn setup_schema() -> MappingSchema {
1096        let mut schema = MappingSchema::new(Dialect::Ansi);
1097        schema
1098            .add_table(
1099                &["users"],
1100                vec![
1101                    ("id".to_string(), DataType::Int),
1102                    ("name".to_string(), DataType::Varchar(Some(255))),
1103                    ("age".to_string(), DataType::Int),
1104                    ("salary".to_string(), DataType::Double),
1105                    ("active".to_string(), DataType::Boolean),
1106                    (
1107                        "created_at".to_string(),
1108                        DataType::Timestamp {
1109                            precision: None,
1110                            with_tz: false,
1111                        },
1112                    ),
1113                ],
1114            )
1115            .unwrap();
1116        schema
1117            .add_table(
1118                &["orders"],
1119                vec![
1120                    ("id".to_string(), DataType::Int),
1121                    ("user_id".to_string(), DataType::Int),
1122                    (
1123                        "amount".to_string(),
1124                        DataType::Decimal {
1125                            precision: Some(10),
1126                            scale: Some(2),
1127                        },
1128                    ),
1129                    ("status".to_string(), DataType::Varchar(Some(50))),
1130                ],
1131            )
1132            .unwrap();
1133        schema
1134    }
1135
1136    fn parse_and_annotate(sql: &str, schema: &MappingSchema) -> (Statement, TypeAnnotations) {
1137        let stmt = Parser::new(sql).unwrap().parse_statement().unwrap();
1138        let ann = annotate_types(&stmt, schema);
1139        (stmt, ann)
1140    }
1141
1142    /// Helper: get the type of the first SELECT column
1143    fn first_col_type(stmt: &Statement, ann: &TypeAnnotations) -> Option<DataType> {
1144        if let Statement::Select(sel) = stmt {
1145            if let Some(SelectItem::Expr { expr, .. }) = sel.columns.first() {
1146                return ann.get_type(expr).cloned();
1147            }
1148        }
1149        None
1150    }
1151
1152    // ── Literal type inference ────────────────────────────────────────
1153
1154    #[test]
1155    fn test_number_literal_int() {
1156        let schema = setup_schema();
1157        let (stmt, ann) = parse_and_annotate("SELECT 42", &schema);
1158        assert_eq!(first_col_type(&stmt, &ann), Some(DataType::Int));
1159    }
1160
1161    #[test]
1162    fn test_number_literal_big_int() {
1163        let schema = setup_schema();
1164        let (stmt, ann) = parse_and_annotate("SELECT 9999999999", &schema);
1165        assert_eq!(first_col_type(&stmt, &ann), Some(DataType::BigInt));
1166    }
1167
1168    #[test]
1169    fn test_number_literal_double() {
1170        let schema = setup_schema();
1171        let (stmt, ann) = parse_and_annotate("SELECT 3.14", &schema);
1172        assert_eq!(first_col_type(&stmt, &ann), Some(DataType::Double));
1173    }
1174
1175    #[test]
1176    fn test_string_literal() {
1177        let schema = setup_schema();
1178        let (stmt, ann) = parse_and_annotate("SELECT 'hello'", &schema);
1179        assert_eq!(first_col_type(&stmt, &ann), Some(DataType::Varchar(None)));
1180    }
1181
1182    #[test]
1183    fn test_boolean_literal() {
1184        let schema = setup_schema();
1185        let (stmt, ann) = parse_and_annotate("SELECT TRUE", &schema);
1186        assert_eq!(first_col_type(&stmt, &ann), Some(DataType::Boolean));
1187    }
1188
1189    #[test]
1190    fn test_null_literal() {
1191        let schema = setup_schema();
1192        let (stmt, ann) = parse_and_annotate("SELECT NULL", &schema);
1193        assert_eq!(first_col_type(&stmt, &ann), Some(DataType::Null));
1194    }
1195
1196    // ── Column reference type lookup ─────────────────────────────────
1197
1198    #[test]
1199    fn test_column_type_from_schema() {
1200        let schema = setup_schema();
1201        let (stmt, ann) = parse_and_annotate("SELECT id FROM users", &schema);
1202        assert_eq!(first_col_type(&stmt, &ann), Some(DataType::Int));
1203    }
1204
1205    #[test]
1206    fn test_qualified_column_type() {
1207        let schema = setup_schema();
1208        let (stmt, ann) = parse_and_annotate("SELECT users.name FROM users", &schema);
1209        assert_eq!(
1210            first_col_type(&stmt, &ann),
1211            Some(DataType::Varchar(Some(255)))
1212        );
1213    }
1214
1215    #[test]
1216    fn test_aliased_table_column_type() {
1217        let schema = setup_schema();
1218        let (stmt, ann) = parse_and_annotate("SELECT u.salary FROM users AS u", &schema);
1219        assert_eq!(first_col_type(&stmt, &ann), Some(DataType::Double));
1220    }
1221
1222    // ── Binary operator type inference ───────────────────────────────
1223
1224    #[test]
1225    fn test_int_plus_int() {
1226        let schema = setup_schema();
1227        let (stmt, ann) = parse_and_annotate("SELECT id + age FROM users", &schema);
1228        assert_eq!(first_col_type(&stmt, &ann), Some(DataType::Int));
1229    }
1230
1231    #[test]
1232    fn test_int_plus_double() {
1233        let schema = setup_schema();
1234        let (stmt, ann) = parse_and_annotate("SELECT id + salary FROM users", &schema);
1235        assert_eq!(first_col_type(&stmt, &ann), Some(DataType::Double));
1236    }
1237
1238    #[test]
1239    fn test_comparison_returns_boolean() {
1240        let schema = setup_schema();
1241        let (stmt, ann) = parse_and_annotate("SELECT id > 5 FROM users", &schema);
1242        assert_eq!(first_col_type(&stmt, &ann), Some(DataType::Boolean));
1243    }
1244
1245    #[test]
1246    fn test_and_returns_boolean() {
1247        let schema = setup_schema();
1248        let (stmt, ann) = parse_and_annotate("SELECT id > 5 AND age < 30 FROM users", &schema);
1249        assert_eq!(first_col_type(&stmt, &ann), Some(DataType::Boolean));
1250    }
1251
1252    // ── CAST type inference ──────────────────────────────────────────
1253
1254    #[test]
1255    fn test_cast_type() {
1256        let schema = setup_schema();
1257        let (stmt, ann) = parse_and_annotate("SELECT CAST(id AS BIGINT) FROM users", &schema);
1258        assert_eq!(first_col_type(&stmt, &ann), Some(DataType::BigInt));
1259    }
1260
1261    #[test]
1262    fn test_cast_to_varchar() {
1263        let schema = setup_schema();
1264        let (stmt, ann) = parse_and_annotate("SELECT CAST(id AS VARCHAR) FROM users", &schema);
1265        assert_eq!(first_col_type(&stmt, &ann), Some(DataType::Varchar(None)));
1266    }
1267
1268    // ── CASE expression ──────────────────────────────────────────────
1269
1270    #[test]
1271    fn test_case_expression_type() {
1272        let schema = setup_schema();
1273        let (stmt, ann) = parse_and_annotate(
1274            "SELECT CASE WHEN id > 1 THEN salary ELSE 0.0 END FROM users",
1275            &schema,
1276        );
1277        let t = first_col_type(&stmt, &ann);
1278        assert!(
1279            matches!(t, Some(DataType::Double)),
1280            "Expected Double, got {t:?}"
1281        );
1282    }
1283
1284    // ── Function return types ────────────────────────────────────────
1285
1286    #[test]
1287    fn test_count_returns_bigint() {
1288        let schema = setup_schema();
1289        let (stmt, ann) = parse_and_annotate("SELECT COUNT(*) FROM users", &schema);
1290        assert_eq!(first_col_type(&stmt, &ann), Some(DataType::BigInt));
1291    }
1292
1293    #[test]
1294    fn test_sum_returns_bigint_for_int() {
1295        let schema = setup_schema();
1296        let (stmt, ann) = parse_and_annotate("SELECT SUM(id) FROM users", &schema);
1297        assert_eq!(first_col_type(&stmt, &ann), Some(DataType::BigInt));
1298    }
1299
1300    #[test]
1301    fn test_avg_returns_double() {
1302        let schema = setup_schema();
1303        let (stmt, ann) = parse_and_annotate("SELECT AVG(age) FROM users", &schema);
1304        assert_eq!(first_col_type(&stmt, &ann), Some(DataType::Double));
1305    }
1306
1307    #[test]
1308    fn test_min_preserves_type() {
1309        let schema = setup_schema();
1310        let (stmt, ann) = parse_and_annotate("SELECT MIN(salary) FROM users", &schema);
1311        assert_eq!(first_col_type(&stmt, &ann), Some(DataType::Double));
1312    }
1313
1314    #[test]
1315    fn test_upper_returns_varchar() {
1316        let schema = setup_schema();
1317        let (stmt, ann) = parse_and_annotate("SELECT UPPER(name) FROM users", &schema);
1318        assert_eq!(first_col_type(&stmt, &ann), Some(DataType::Varchar(None)));
1319    }
1320
1321    #[test]
1322    fn test_length_returns_int() {
1323        let schema = setup_schema();
1324        let (stmt, ann) = parse_and_annotate("SELECT LENGTH(name) FROM users", &schema);
1325        assert_eq!(first_col_type(&stmt, &ann), Some(DataType::Int));
1326    }
1327
1328    // ── Predicate types ──────────────────────────────────────────────
1329
1330    #[test]
1331    fn test_between_returns_boolean() {
1332        let schema = setup_schema();
1333        let (stmt, ann) = parse_and_annotate("SELECT age BETWEEN 18 AND 65 FROM users", &schema);
1334        assert_eq!(first_col_type(&stmt, &ann), Some(DataType::Boolean));
1335    }
1336
1337    #[test]
1338    fn test_in_list_returns_boolean() {
1339        let schema = setup_schema();
1340        let (stmt, ann) = parse_and_annotate("SELECT id IN (1, 2, 3) FROM users", &schema);
1341        assert_eq!(first_col_type(&stmt, &ann), Some(DataType::Boolean));
1342    }
1343
1344    #[test]
1345    fn test_is_null_returns_boolean() {
1346        let schema = setup_schema();
1347        let (stmt, ann) = parse_and_annotate("SELECT name IS NULL FROM users", &schema);
1348        assert_eq!(first_col_type(&stmt, &ann), Some(DataType::Boolean));
1349    }
1350
1351    #[test]
1352    fn test_like_returns_boolean() {
1353        let schema = setup_schema();
1354        let (stmt, ann) = parse_and_annotate("SELECT name LIKE '%test%' FROM users", &schema);
1355        assert_eq!(first_col_type(&stmt, &ann), Some(DataType::Boolean));
1356    }
1357
1358    // ── Exists ───────────────────────────────────────────────────────
1359
1360    #[test]
1361    fn test_exists_returns_boolean() {
1362        let schema = setup_schema();
1363        let (stmt, ann) =
1364            parse_and_annotate("SELECT EXISTS (SELECT 1 FROM orders) FROM users", &schema);
1365        assert_eq!(first_col_type(&stmt, &ann), Some(DataType::Boolean));
1366    }
1367
1368    // ── Nested expressions ───────────────────────────────────────────
1369
1370    #[test]
1371    fn test_nested_expression_propagation() {
1372        let schema = setup_schema();
1373        let (stmt, ann) = parse_and_annotate("SELECT (id + age) * salary FROM users", &schema);
1374        let t = first_col_type(&stmt, &ann);
1375        // INT + INT = INT, INT * DOUBLE = DOUBLE
1376        assert!(
1377            matches!(t, Some(DataType::Double)),
1378            "Expected Double, got {t:?}"
1379        );
1380    }
1381
1382    // ── EXTRACT ──────────────────────────────────────────────────────
1383
1384    #[test]
1385    fn test_extract_returns_int() {
1386        let schema = setup_schema();
1387        let (stmt, ann) =
1388            parse_and_annotate("SELECT EXTRACT(YEAR FROM created_at) FROM users", &schema);
1389        assert_eq!(first_col_type(&stmt, &ann), Some(DataType::Int));
1390    }
1391
1392    // ── Multiple columns ─────────────────────────────────────────────
1393
1394    #[test]
1395    fn test_multiple_columns_annotated() {
1396        let schema = setup_schema();
1397        let (stmt, ann) = parse_and_annotate("SELECT id, name, salary FROM users", &schema);
1398        if let Statement::Select(sel) = &stmt {
1399            assert_eq!(sel.columns.len(), 3);
1400            // id → Int
1401            if let SelectItem::Expr { expr, .. } = &sel.columns[0] {
1402                assert_eq!(ann.get_type(expr), Some(&DataType::Int));
1403            }
1404            // name → Varchar(255)
1405            if let SelectItem::Expr { expr, .. } = &sel.columns[1] {
1406                assert_eq!(ann.get_type(expr), Some(&DataType::Varchar(Some(255))));
1407            }
1408            // salary → Double
1409            if let SelectItem::Expr { expr, .. } = &sel.columns[2] {
1410                assert_eq!(ann.get_type(expr), Some(&DataType::Double));
1411            }
1412        }
1413    }
1414
1415    // ── WHERE clause annotation ──────────────────────────────────────
1416
1417    #[test]
1418    fn test_where_clause_annotated() {
1419        let schema = setup_schema();
1420        // Don't move stmt after annotation — raw pointers for inline fields
1421        // (like where_clause: Option<Expr>) are invalidated on move.
1422        let stmt = Parser::new("SELECT id FROM users WHERE age > 21")
1423            .unwrap()
1424            .parse_statement()
1425            .unwrap();
1426        let ann = annotate_types(&stmt, &schema);
1427        if let Statement::Select(sel) = &stmt {
1428            if let Some(wh) = &sel.where_clause {
1429                assert_eq!(ann.get_type(wh), Some(&DataType::Boolean));
1430            }
1431        }
1432    }
1433
1434    // ── Coercion rules ──────────────────────────────────────────────
1435
1436    #[test]
1437    fn test_int_and_bigint_coercion() {
1438        assert_eq!(
1439            coerce_numeric(&DataType::Int, &DataType::BigInt),
1440            DataType::BigInt
1441        );
1442    }
1443
1444    #[test]
1445    fn test_float_and_double_coercion() {
1446        assert_eq!(
1447            coerce_numeric(&DataType::Float, &DataType::Double),
1448            DataType::Double
1449        );
1450    }
1451
1452    #[test]
1453    fn test_int_and_double_coercion() {
1454        assert_eq!(
1455            coerce_numeric(&DataType::Int, &DataType::Double),
1456            DataType::Double
1457        );
1458    }
1459
1460    // ── Common type ─────────────────────────────────────────────────
1461
1462    #[test]
1463    fn test_common_type_nulls_skipped() {
1464        let types = vec![&DataType::Null, &DataType::Int, &DataType::Null];
1465        assert_eq!(common_type(&types), Some(DataType::Int));
1466    }
1467
1468    #[test]
1469    fn test_common_type_numeric_widening() {
1470        let types = vec![&DataType::Int, &DataType::Double, &DataType::Float];
1471        assert_eq!(common_type(&types), Some(DataType::Double));
1472    }
1473
1474    #[test]
1475    fn test_common_type_empty() {
1476        let types: Vec<&DataType> = vec![];
1477        assert_eq!(common_type(&types), None);
1478    }
1479
1480    // ── UDF type support ─────────────────────────────────────────────
1481
1482    #[test]
1483    fn test_udf_return_type() {
1484        let mut schema = setup_schema();
1485        schema.add_udf("my_func", DataType::Varchar(None));
1486        let (stmt, ann) = parse_and_annotate("SELECT my_func(id) FROM users", &schema);
1487        assert_eq!(first_col_type(&stmt, &ann), Some(DataType::Varchar(None)));
1488    }
1489
1490    // ── Annotation count ─────────────────────────────────────────────
1491
1492    #[test]
1493    fn test_annotations_not_empty() {
1494        let schema = setup_schema();
1495        let (_, ann) = parse_and_annotate("SELECT id, name FROM users WHERE age > 21", &schema);
1496        assert!(!ann.is_empty());
1497        // Should have at least the SELECT columns and WHERE predicate
1498        assert!(ann.len() >= 3);
1499    }
1500
1501    // ── SUM of DECIMAL preserves precision ───────────────────────────
1502
1503    #[test]
1504    fn test_sum_decimal_preserves_type() {
1505        let schema = setup_schema();
1506        let (stmt, ann) = parse_and_annotate("SELECT SUM(amount) FROM orders", &schema);
1507        assert_eq!(
1508            first_col_type(&stmt, &ann),
1509            Some(DataType::Decimal {
1510                precision: Some(10),
1511                scale: Some(2)
1512            })
1513        );
1514    }
1515}