vlorql-core 0.5.0

A high-performance SQL query optimizer with constant folding, predicate pushdown, column pruning, and cost-based join reordering
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
//! Recursive expression and predicate type validation.

use crate::errors::{ValidationErrorKind, VlorQLError};
use crate::query::QuerySource;
use crate::schema::{
    BinaryOperator, ComparisonOperator, DataType, Expression, InTarget, Predicate, Projection,
    QueryPlan, SchemaSnapshot, WindowFrameBound,
};
use serde_json::{Value, json};
use std::collections::HashSet;

/// Validates expression operand types against a schema snapshot.
pub struct OperandValidator<'a> {
    schema: &'a SchemaSnapshot,
}

impl<'a> OperandValidator<'a> {
    /// Creates an operand validator borrowing a schema snapshot.
    pub fn new(schema: &'a SchemaSnapshot) -> Self {
        Self { schema }
    }

    /// Convenience entry point equivalent to `OperandValidator::new(schema).validate_plan(plan)`.
    pub fn validate(plan: &QueryPlan, schema: &'a SchemaSnapshot) -> Result<(), Vec<VlorQLError>> {
        Self::new(schema).validate_plan(plan)
    }

    /// Validates every expression and predicate in a plan, including nested CTEs.
    pub fn validate_plan(&self, plan: &QueryPlan) -> Result<(), Vec<VlorQLError>> {
        let mut errors = Vec::new();
        self.validate_plan_inner(plan, &mut errors);
        if errors.is_empty() {
            Ok(())
        } else {
            Err(errors)
        }
    }

    /// Resolves and validates one expression outside a query-plan context.
    pub fn validate_expression(
        &self,
        expression: &Expression,
    ) -> Result<DataType, Vec<VlorQLError>> {
        let scope = OperandScope::from_schema(self.schema);
        let mut errors = Vec::new();
        let data_type = self
            .validate_expression_inner(expression, &scope, &mut errors)
            .unwrap_or(DataType::Null);
        if errors.is_empty() {
            Ok(data_type)
        } else {
            Err(errors)
        }
    }

    /// Validates one predicate outside a query-plan context.
    pub fn validate_predicate(&self, predicate: &Predicate) -> Result<(), Vec<VlorQLError>> {
        let scope = OperandScope::from_schema(self.schema);
        let mut errors = Vec::new();
        self.validate_predicate_inner(predicate, &scope, &mut errors);
        if errors.is_empty() {
            Ok(())
        } else {
            Err(errors)
        }
    }

    fn validate_plan_inner(&self, plan: &QueryPlan, errors: &mut Vec<VlorQLError>) {
        if let Some(ctes) = &plan.ctes {
            for cte in ctes {
                self.validate_plan_inner(&cte.query, errors);
            }
        }

        let scope = OperandScope::from_plan(plan, self.schema);
        for projection in &plan.select {
            if let Projection::Expr { expression, .. } = projection {
                self.validate_expression_inner(expression, &scope, errors);
            }
        }
        if let Some(predicate) = &plan.r#where {
            self.validate_predicate_inner(predicate, &scope, errors);
        }
        if let Some(expressions) = &plan.group_by {
            for expression in expressions {
                self.validate_expression_inner(expression, &scope, errors);
            }
            // Reject aggregate functions in GROUP BY (e.g. GROUP BY array_agg(...)).
            for expression in expressions {
                if is_aggregate_call(expression) {
                    errors.push(VlorQLError::validation(
                        ValidationErrorKind::AggregationMismatch {
                            message: format!(
                                "aggregate function `{}` is not allowed in GROUP BY",
                                aggregate_name(expression).unwrap_or("<unknown>"),
                            ),
                        },
                        json!({"expression": expression, "clause": "group_by"}),
                    ));
                }
            }
        }
        if let Some(predicate) = &plan.having {
            self.validate_predicate_inner(predicate, &scope, errors);
        }
        if let Some(terms) = &plan.order_by {
            for term in terms {
                self.validate_expression_inner(&term.expr, &scope, errors);
            }
        }
        if let Some(joins) = &plan.joins {
            for join in joins {
                self.validate_predicate_inner(&join.on, &scope, errors);
            }
        }
    }

    fn validate_expression_inner(
        &self,
        expression: &Expression,
        scope: &OperandScope,
        errors: &mut Vec<VlorQLError>,
    ) -> Option<DataType> {
        match expression {
            Expression::Literal { value, data_type } => {
                if !literal_matches_type(value, *data_type) {
                    // Small local LLMs frequently set data_type to Null with a non-null
                    // value (e.g. {"value":"done","data_type":"null"}).  Infer the
                    // correct data type from the JSON value and treat it as a warning-free
                    // auto-fix so the plan can proceed.
                    if *data_type == DataType::Null && !value.is_null() {
                        let inferred = match value {
                            Value::String(_) => DataType::String,
                            Value::Bool(_) => DataType::Boolean,
                            Value::Number(n) if n.is_f64() => DataType::Float,
                            Value::Number(_) => DataType::Int,
                            _ => DataType::Null,
                        };
                        tracing::debug!(
                            "Literal with declared data_type=null and non-null value; inferred {inferred:?}"
                        );
                        return Some(inferred);
                    }
                    errors.push(type_mismatch_error(
                        data_type.type_name(),
                        json_value_type(value),
                        "literal",
                        json!({"value": value, "declared_type": data_type}),
                    ));
                }
                Some(*data_type)
            }
            Expression::ColumnRef { table, column } => {
                scope.resolve_column_type(table.as_deref(), column, self.schema)
            }
            Expression::FunctionCall { name, args, .. } => {
                let argument_types = args
                    .iter()
                    .map(|argument| self.validate_expression_inner(argument, scope, errors))
                    .collect::<Vec<_>>();
                Some(self.validate_function(name, &argument_types, errors))
            }
            Expression::BinaryOp { left, op, right } => {
                let left_type = self.validate_expression_inner(left, scope, errors);
                let right_type = self.validate_expression_inner(right, scope, errors);
                match (left_type, right_type) {
                    (Some(left_type), Some(right_type)) => Some(validate_binary_operation(
                        *op, left_type, right_type, errors,
                    )),
                    _ => None,
                }
            }
            Expression::Star => None,
            Expression::SubQuery { query } => {
                self.validate_plan_inner(query, errors);
                None
            }
            Expression::Case {
                operand,
                when_thens,
                else_result,
            } => {
                if let Some(op) = operand {
                    self.validate_expression_inner(op, scope, errors);
                }
                for wt in when_thens.iter() {
                    self.validate_expression_inner(&wt.when, scope, errors);
                    self.validate_expression_inner(&wt.then, scope, errors);
                }
                if let Some(el) = else_result {
                    self.validate_expression_inner(el, scope, errors);
                }
                // CASE type = common type of all THEN and ELSE branches
                let then_types: Vec<DataType> = when_thens
                    .iter()
                    .filter_map(|wt| self.validate_expression_inner(&wt.then, scope, errors))
                    .collect();
                let else_type = else_result
                    .as_ref()
                    .and_then(|el| self.validate_expression_inner(el, scope, errors));
                then_types
                    .into_iter()
                    .chain(else_type)
                    .reduce(|a, b| if a == b { a } else { DataType::String })
            }
            Expression::WindowFunction {
                name, args, over, ..
            } => {
                let argument_types = args
                    .iter()
                    .map(|argument| self.validate_expression_inner(argument, scope, errors))
                    .collect::<Vec<_>>();
                // Validate expressions inside the window spec.
                if let Some(partition_by) = &over.partition_by {
                    for expr in partition_by {
                        self.validate_expression_inner(expr, scope, errors);
                    }
                }
                if let Some(order_by) = &over.order_by {
                    for term in order_by {
                        self.validate_expression_inner(&term.expr, scope, errors);
                    }
                }
                if let Some(frame) = &over.frame {
                    if let Some(start) = frame_bound_expr(&frame.start) {
                        self.validate_expression_inner(start, scope, errors);
                    }
                    if let Some(end) = &frame.end
                        && let Some(expr) = frame_bound_expr(end)
                    {
                        self.validate_expression_inner(expr, scope, errors);
                    }
                }
                Some(self.validate_function(name, &argument_types, errors))
            }
        }
    }

    fn validate_predicate_inner(
        &self,
        predicate: &Predicate,
        scope: &OperandScope,
        errors: &mut Vec<VlorQLError>,
    ) {
        match predicate {
            Predicate::Comparison { left, op, right } => {
                let left_type = self.validate_expression_inner(left, scope, errors);
                let right_type = self.validate_expression_inner(right, scope, errors);
                if let (Some(left_type), Some(right_type)) = (left_type, right_type) {
                    validate_comparison(*op, left_type, right_type, errors);
                }
            }
            Predicate::And { left, right } | Predicate::Or { left, right } => {
                self.validate_predicate_inner(left, scope, errors);
                self.validate_predicate_inner(right, scope, errors);
            }
            Predicate::Not { child } => self.validate_predicate_inner(child, scope, errors),
            Predicate::Between { expr, low, high } => {
                let expr_type = self.validate_expression_inner(expr, scope, errors);
                let low_type = self.validate_expression_inner(low, scope, errors);
                let high_type = self.validate_expression_inner(high, scope, errors);
                if let (Some(expr_type), Some(low_type)) = (expr_type, low_type) {
                    validate_compatible_types("BETWEEN lower bound", expr_type, low_type, errors);
                }
                if let (Some(expr_type), Some(high_type)) = (expr_type, high_type) {
                    validate_compatible_types("BETWEEN upper bound", expr_type, high_type, errors);
                }
            }
            Predicate::In { expr, target } => {
                let expr_type = self.validate_expression_inner(expr, scope, errors);
                match target {
                    InTarget::Values(values) => {
                        for value in values {
                            let value_type = self.validate_expression_inner(value, scope, errors);
                            if let (Some(expr_type), Some(value_type)) = (expr_type, value_type) {
                                validate_compatible_types(
                                    "IN value", expr_type, value_type, errors,
                                );
                            }
                        }
                    }
                    InTarget::SubQuery(query) => {
                        self.validate_plan_inner(query, errors);
                    }
                }
            }
            Predicate::Exists { query } => {
                self.validate_plan_inner(query, errors);
            }
            Predicate::Like { expr, .. } => {
                if let Some(data_type) = self.validate_expression_inner(expr, scope, errors) {
                    require_string("LIKE expression", data_type, errors);
                }
            }
            Predicate::IsNull { expr } => {
                self.validate_expression_inner(expr, scope, errors);
            }
            Predicate::True | Predicate::False => {}
        }
    }

    fn validate_function(
        &self,
        name: &str,
        argument_types: &[Option<DataType>],
        errors: &mut Vec<VlorQLError>,
    ) -> DataType {
        // Match case-insensitively without allocating a lowercased copy.
        if name.eq_ignore_ascii_case("count") {
            require_arity_range(name, argument_types.len(), 0, 1, errors);
            DataType::Int
        } else if is_any_of_ignore_case(name, &["sum", "avg", "abs"]) {
            require_arity(name, argument_types.len(), 1, errors);
            if let Some(Some(argument_type)) = argument_types.first() {
                require_numeric(
                    &format!("function `{name}` argument"),
                    *argument_type,
                    errors,
                );
            }
            if name.eq_ignore_ascii_case("avg") {
                DataType::Float
            } else {
                argument_types
                    .first()
                    .copied()
                    .flatten()
                    .unwrap_or(DataType::Null)
            }
        } else if is_any_of_ignore_case(name, &["min", "max"]) {
            require_arity(name, argument_types.len(), 1, errors);
            argument_types
                .first()
                .copied()
                .flatten()
                .unwrap_or(DataType::Null)
        } else if is_any_of_ignore_case(name, &["lower", "upper"]) {
            require_arity(name, argument_types.len(), 1, errors);
            if let Some(Some(argument_type)) = argument_types.first() {
                require_string(
                    &format!("function `{name}` argument"),
                    *argument_type,
                    errors,
                );
            }
            DataType::String
        } else if name.eq_ignore_ascii_case("length") {
            require_arity(name, argument_types.len(), 1, errors);
            if let Some(Some(argument_type)) = argument_types.first() {
                require_string(
                    &format!("function `{name}` argument"),
                    *argument_type,
                    errors,
                );
            }
            DataType::Int
        } else if name.eq_ignore_ascii_case("concat") {
            require_min_arity(name, argument_types.len(), 1, errors);
            for argument_type in argument_types.iter().flatten() {
                require_string(
                    &format!("function `{name}` argument"),
                    *argument_type,
                    errors,
                );
            }
            DataType::String
        } else if name.eq_ignore_ascii_case("coalesce") {
            require_min_arity(name, argument_types.len(), 1, errors);
            let result = argument_types
                .iter()
                .flatten()
                .copied()
                .find(|data_type| *data_type != DataType::Null)
                .unwrap_or(DataType::Null);
            for argument_type in argument_types.iter().flatten() {
                validate_compatible_types(
                    &format!("function `{name}` argument"),
                    result,
                    *argument_type,
                    errors,
                );
            }
            result
        } else {
            DataType::Null
        }
    }
}

#[derive(Debug)]
struct OperandScope {
    sources: Vec<QuerySource>,
    cte_names: HashSet<String>,
}

impl OperandScope {
    fn from_plan(plan: &QueryPlan, schema: &SchemaSnapshot) -> Self {
        let scope = crate::query::QueryScope::from_plan(plan);
        let mut sources = scope.sources;
        sources.retain(|source| {
            scope.cte_names.contains(&source.table) || schema.get_table(&source.table).is_some()
        });
        Self {
            sources,
            cte_names: scope.cte_names,
        }
    }

    fn from_schema(schema: &SchemaSnapshot) -> Self {
        Self {
            sources: schema
                .tables
                .iter()
                .map(|table| QuerySource {
                    table: table.name.clone(),
                    alias: None,
                })
                .collect(),
            cte_names: HashSet::new(),
        }
    }

    fn resolve_column_type(
        &self,
        qualifier: Option<&str>,
        column: &str,
        schema: &SchemaSnapshot,
    ) -> Option<DataType> {
        if let Some(qualifier) = qualifier {
            let source = self.sources.iter().find(|source| {
                source.table == qualifier || source.alias.as_deref() == Some(qualifier)
            })?;
            if self.cte_names.contains(&source.table) {
                return None;
            }
            return schema
                .get_column(&source.table, column)
                .map(|column| column.data_type);
        }

        self.sources
            .iter()
            .filter(|source| !self.cte_names.contains(&source.table))
            .filter_map(|source| schema.get_column(&source.table, column))
            .map(|column| column.data_type)
            .next()
    }
}

fn validate_binary_operation(
    operator: BinaryOperator,
    left: DataType,
    right: DataType,
    errors: &mut Vec<VlorQLError>,
) -> DataType {
    match operator {
        BinaryOperator::Add
        | BinaryOperator::Sub
        | BinaryOperator::Mul
        | BinaryOperator::Div
        | BinaryOperator::Mod => {
            if !are_numeric(left, right) {
                errors.push(type_mismatch_error(
                    "compatible numeric operands",
                    format!("{} and {}", left.type_name(), right.type_name()),
                    format!("binary operator {operator:?}"),
                    json!({"left": left, "right": right, "operator": operator}),
                ));
            }
            numeric_result_type(left, right)
        }
        BinaryOperator::And | BinaryOperator::Or => {
            if left != DataType::Boolean || right != DataType::Boolean {
                errors.push(type_mismatch_error(
                    "boolean operands",
                    format!("{} and {}", left.type_name(), right.type_name()),
                    format!("binary operator {operator:?}"),
                    json!({"left": left, "right": right, "operator": operator}),
                ));
            }
            DataType::Boolean
        }
        BinaryOperator::Eq
        | BinaryOperator::Neq
        | BinaryOperator::Gt
        | BinaryOperator::Lt
        | BinaryOperator::Gte
        | BinaryOperator::Lte => {
            validate_compatible_types(
                &format!("binary operator {operator:?}"),
                left,
                right,
                errors,
            );
            DataType::Boolean
        }
        BinaryOperator::Like | BinaryOperator::ILike => {
            if !is_string_compatible(left) || !is_string_compatible(right) {
                errors.push(type_mismatch_error(
                    "string operands",
                    format!("{} and {}", left.type_name(), right.type_name()),
                    format!("binary operator {operator:?}"),
                    json!({"left": left, "right": right, "operator": operator}),
                ));
            }
            DataType::Boolean
        }
    }
}

fn validate_comparison(
    operator: ComparisonOperator,
    left: DataType,
    right: DataType,
    errors: &mut Vec<VlorQLError>,
) {
    match operator {
        ComparisonOperator::Like | ComparisonOperator::ILike => {
            if !is_string_compatible(left) || !is_string_compatible(right) {
                errors.push(type_mismatch_error(
                    "string operands",
                    format!("{} and {}", left.type_name(), right.type_name()),
                    format!("comparison {operator:?}"),
                    json!({"left": left, "right": right, "operator": operator}),
                ));
            }
        }
        _ => validate_compatible_types(&format!("comparison {operator:?}"), left, right, errors),
    }
}

fn validate_compatible_types(
    expression: &str,
    left: DataType,
    right: DataType,
    errors: &mut Vec<VlorQLError>,
) {
    if !types_compatible(left, right) {
        errors.push(type_mismatch_error(
            // Clear "side A vs side B" format so the LLM retry feedback
            // correctly identifies which side of the comparison has the
            // wrong type, instead of assuming one side is "correct".
            format!("{} (left)", left.type_name()),
            format!("{} (right)", right.type_name()),
            expression,
            json!({"left": left, "right": right}),
        ));
    }
}

fn require_numeric(expression: &str, actual: DataType, errors: &mut Vec<VlorQLError>) {
    if !is_numeric(actual) && actual != DataType::Null {
        errors.push(type_mismatch_error(
            "numeric",
            actual.type_name(),
            expression,
            json!({"actual": actual}),
        ));
    }
}

fn require_string(expression: &str, actual: DataType, errors: &mut Vec<VlorQLError>) {
    if !is_string_compatible(actual) {
        errors.push(type_mismatch_error(
            "string",
            actual.type_name(),
            expression,
            json!({"actual": actual}),
        ));
    }
}

fn require_arity(name: &str, actual: usize, expected: usize, errors: &mut Vec<VlorQLError>) {
    if actual != expected {
        errors.push(type_mismatch_error(
            format!("{expected} argument(s)"),
            format!("{actual} argument(s)"),
            format!("function `{name}`"),
            json!({"function": name, "expected_arguments": expected, "actual_arguments": actual}),
        ));
    }
}

fn require_min_arity(name: &str, actual: usize, min: usize, errors: &mut Vec<VlorQLError>) {
    if actual < min {
        errors.push(type_mismatch_error(
            format!("at least {min} argument(s)"),
            format!("{actual} argument(s)"),
            format!("function `{name}`"),
            json!({"function": name, "minimum_arguments": min, "actual_arguments": actual}),
        ));
    }
}

fn require_arity_range(
    name: &str,
    actual: usize,
    min: usize,
    max: usize,
    errors: &mut Vec<VlorQLError>,
) {
    if !(min..=max).contains(&actual) {
        errors.push(type_mismatch_error(
            format!("between {min} and {max} argument(s)"),
            format!("{actual} argument(s)"),
            format!("function `{name}`"),
            json!({
                "function": name,
                "minimum_arguments": min,
                "maximum_arguments": max,
                "actual_arguments": actual,
            }),
        ));
    }
}

fn type_mismatch_error(
    expected: impl Into<String>,
    found: impl Into<String>,
    expression: impl Into<String>,
    details: Value,
) -> VlorQLError {
    VlorQLError::validation(
        ValidationErrorKind::TypeMismatch {
            expected: expected.into(),
            found: found.into(),
            expr: expression.into(),
        },
        details,
    )
}

fn literal_matches_type(value: &Value, data_type: DataType) -> bool {
    match data_type {
        DataType::Int => value.as_i64().is_some() || value.as_u64().is_some(),
        DataType::Float => value.is_number(),
        DataType::String | DataType::Date | DataType::Timestamp | DataType::Uuid => {
            value.is_string()
        }
        DataType::Boolean => value.is_boolean(),
        DataType::Json => true,
        DataType::Null => value.is_null(),
        DataType::Decimal => value.is_number() || value.is_string(),
        DataType::Array => value.is_array(),
        DataType::Jsonb => true,
        DataType::Blob => value.is_string(),
    }
}

fn json_value_type(value: &Value) -> &'static str {
    match value {
        Value::Null => "null",
        Value::Bool(_) => "boolean",
        Value::Number(number) if number.is_i64() || number.is_u64() => "integer",
        Value::Number(_) => "float",
        Value::String(_) => "string",
        Value::Array(_) => "array",
        Value::Object(_) => "object",
    }
}
fn is_numeric(data_type: DataType) -> bool {
    matches!(
        data_type,
        DataType::Int | DataType::Float | DataType::Decimal
    )
}

fn are_numeric(left: DataType, right: DataType) -> bool {
    (is_numeric(left) || left == DataType::Null) && (is_numeric(right) || right == DataType::Null)
}

fn is_string_compatible(data_type: DataType) -> bool {
    matches!(data_type, DataType::String | DataType::Null)
}

fn types_compatible(left: DataType, right: DataType) -> bool {
    left == right || left == DataType::Null || right == DataType::Null || are_numeric(left, right)
}

fn numeric_result_type(left: DataType, right: DataType) -> DataType {
    if left == DataType::Float || right == DataType::Float {
        DataType::Float
    } else if left == DataType::Decimal || right == DataType::Decimal {
        DataType::Decimal
    } else if left == DataType::Int || right == DataType::Int {
        DataType::Int
    } else {
        DataType::Null
    }
}

/// Returns `true` when `name` matches any candidate case-insensitively.
fn is_any_of_ignore_case(name: &str, candidates: &[&str]) -> bool {
    candidates
        .iter()
        .any(|candidate| candidate.eq_ignore_ascii_case(name))
}

/// Extracts the inner expression from a window frame bound, if any.
fn frame_bound_expr(bound: &WindowFrameBound) -> Option<&Expression> {
    match bound {
        WindowFrameBound::Preceding(expr) | WindowFrameBound::Following(expr) => Some(expr),
        _ => None,
    }
}

/// Known aggregate function names that are invalid in GROUP BY expressions.
const AGGREGATE_FUNCTIONS: &[&str] = &[
    "count",
    "sum",
    "avg",
    "min",
    "max",
    "array_agg",
    "string_agg",
    "json_agg",
    "jsonb_agg",
    "bool_and",
    "bool_or",
    "every",
];

/// Returns `true` if `expr` is a function call with an aggregate name.
fn is_aggregate_call(expr: &Expression) -> bool {
    match expr {
        Expression::FunctionCall { name, .. } => AGGREGATE_FUNCTIONS
            .iter()
            .any(|agg| agg.eq_ignore_ascii_case(name)),
        _ => false,
    }
}

/// Returns the function name if `expr` is an aggregate call.
fn aggregate_name(expr: &Expression) -> Option<&str> {
    match expr {
        Expression::FunctionCall { name, .. } => Some(name.as_str()),
        _ => None,
    }
}

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

    #[test]
    fn decimal_is_numeric_and_promotes() {
        assert!(is_numeric(DataType::Decimal));
        // Float > Decimal > Int
        assert_eq!(
            numeric_result_type(DataType::Int, DataType::Decimal),
            DataType::Decimal
        );
        assert_eq!(
            numeric_result_type(DataType::Decimal, DataType::Float),
            DataType::Float
        );
    }

    #[test]
    fn container_literal_matching() {
        assert!(literal_matches_type(
            &serde_json::json!([1, 2]),
            DataType::Array
        ));
        assert!(literal_matches_type(
            &serde_json::json!({"a":1}),
            DataType::Jsonb
        ));
        assert!(literal_matches_type(
            &serde_json::json!("YWJj"),
            DataType::Blob
        ));
        assert!(literal_matches_type(
            &serde_json::json!(12.34),
            DataType::Decimal
        ));
        assert!(!literal_matches_type(
            &serde_json::json!(3),
            DataType::Array
        ));
    }
}