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