1use std::collections::HashMap;
38
39use crate::ast::*;
40use crate::schema::Schema;
41
42pub struct TypeAnnotations {
52 types: HashMap<*const Expr, DataType>,
53}
54
55unsafe 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 #[must_use]
73 pub fn get_type(&self, expr: &Expr) -> Option<&DataType> {
74 self.types.get(&(expr as *const Expr))
75 }
76
77 #[must_use]
79 pub fn len(&self) -> usize {
80 self.types.len()
81 }
82
83 #[must_use]
85 pub fn is_empty(&self) -> bool {
86 self.types.is_empty()
87 }
88}
89
90#[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
109struct AnnotationContext<'s, S: Schema> {
115 schema: &'s S,
116 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 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 fn resolve_column_type(&self, table: Option<&str>, column: &str) -> Option<DataType> {
141 if let Some(tbl) = table {
142 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 return self.schema.get_column_type(&[tbl], column).ok();
149 }
150 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
161fn 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 _ => {}
210 }
211}
212
213fn annotate_select<S: Schema>(
214 sel: &SelectStatement,
215 ctx: &mut AnnotationContext<S>,
216 ann: &mut TypeAnnotations,
217) {
218 for cte in &sel.ctes {
220 annotate_statement(&cte.query, ctx, ann);
221 }
222
223 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 if let Some(wh) = &sel.where_clause {
233 annotate_expr(wh, ctx, ann);
234 }
235
236 for item in &sel.columns {
238 if let SelectItem::Expr { expr, .. } = item {
239 annotate_expr(expr, ctx, ann);
240 }
241 }
242
243 for expr in &sel.group_by {
245 annotate_expr(expr, ctx, ann);
246 }
247
248 if let Some(having) = &sel.having {
250 annotate_expr(having, ctx, ann);
251 }
252
253 for ob in &sel.order_by {
255 annotate_expr(&ob.expr, ctx, ann);
256 }
257
258 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 if let Some(qualify) = &sel.qualify {
271 annotate_expr(qualify, ctx, ann);
272 }
273
274 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 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
298fn annotate_expr<S: Schema>(expr: &Expr, ctx: &AnnotationContext<S>, ann: &mut TypeAnnotations) {
303 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
312fn 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 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
464fn annotate_typed_function_children<S: Schema>(
466 func: &TypedFunction,
467 ctx: &AnnotationContext<S>,
468 ann: &mut TypeAnnotations,
469) {
470 func.walk_children(&mut |child| {
472 annotate_expr(child, ctx, ann);
473 true
474 });
475}
476
477fn infer_type<S: Schema>(
482 expr: &Expr,
483 ctx: &AnnotationContext<S>,
484 ann: &TypeAnnotations,
485) -> Option<DataType> {
486 match expr {
487 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 Expr::Column { table, name, .. } => ctx.resolve_column_type(table.as_deref(), name),
495
496 Expr::BinaryOp { left, op, right } => {
498 infer_binary_op_type(op, ann.get_type(left), ann.get_type(right))
499 }
500
501 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 Expr::Cast { data_type, .. } | Expr::TryCast { data_type, .. } => Some(data_type.clone()),
510
511 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 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 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 Expr::NullIf { expr: e, .. } => ann.get_type(e.as_ref()).cloned(),
557
558 Expr::Function { name, args, .. } => infer_generic_function_type(name, args, ctx, ann),
560
561 Expr::TypedFunction { func, .. } => infer_typed_function_type(func, ann),
563
564 Expr::Subquery(sub) => infer_subquery_type(sub, ann),
566
567 Expr::Exists { .. } => Some(DataType::Boolean),
569
570 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 Expr::Extract { .. } => Some(DataType::Int),
583
584 Expr::Interval { .. } => Some(DataType::Interval),
586
587 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 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 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 Expr::JsonAccess { as_text, .. } => {
611 if *as_text {
612 Some(DataType::Text)
613 } else {
614 Some(DataType::Json)
615 }
616 }
617
618 Expr::Nested(inner) => ann.get_type(inner.as_ref()).cloned(),
620 Expr::Alias { expr: e, .. } => ann.get_type(e.as_ref()).cloned(),
621
622 Expr::Collate { .. } => Some(DataType::Varchar(None)),
624
625 Expr::TypeExpr(dt) => Some(dt.clone()),
627
628 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
641fn 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 DataType::BigInt
657 }
658}
659
660fn 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 Eq | Neq | Lt | Gt | LtEq | GtEq => Some(DataType::Boolean),
673
674 And | Or | Xor => Some(DataType::Boolean),
676
677 Concat => Some(DataType::Varchar(None)),
679
680 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 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 Arrow => Some(DataType::Json),
698 DoubleArrow => Some(DataType::Text),
699 }
700}
701
702fn 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 "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 "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 "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 "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 "CAST" | "TRY_CAST" | "SAFE_CAST" | "CONVERT" => None, "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 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_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_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 "ROW_NUMBER" | "RANK" | "DENSE_RANK" | "NTILE" | "CUME_DIST" | "PERCENT_RANK" => {
826 Some(DataType::BigInt)
827 }
828
829 "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 "TYPEOF" | "TYPE_OF" => Some(DataType::Varchar(None)),
837
838 _ => ctx.schema.get_udf_type(&upper).cloned(),
840 }
841}
842
843fn infer_typed_function_type(func: &TypedFunction, ann: &TypeAnnotations) -> Option<DataType> {
848 match func {
849 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 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 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 TypedFunction::ArrayConcat { arrays } => {
906 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 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 TypedFunction::JSONExtract { .. } => Some(DataType::Json),
923 TypedFunction::JSONExtractScalar { .. } => Some(DataType::Varchar(None)),
924 TypedFunction::ParseJSON { .. } | TypedFunction::JSONFormat { .. } => Some(DataType::Json),
925
926 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 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 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
967fn infer_subquery_type(sub: &Statement, ann: &TypeAnnotations) -> Option<DataType> {
972 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
981fn 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
1000fn 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 return left.clone();
1007 }
1008 if lp >= rp {
1009 left.clone()
1010 } else {
1011 right.clone()
1012 }
1013}
1014
1015fn 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
1035fn 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 if **t == DataType::Null {
1044 continue;
1045 }
1046 if *result == DataType::Null {
1047 result = t;
1048 continue;
1049 }
1050 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 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 };
1070 continue;
1071 }
1072 }
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#[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 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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 assert!(
1377 matches!(t, Some(DataType::Double)),
1378 "Expected Double, got {t:?}"
1379 );
1380 }
1381
1382 #[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 #[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 if let SelectItem::Expr { expr, .. } = &sel.columns[0] {
1402 assert_eq!(ann.get_type(expr), Some(&DataType::Int));
1403 }
1404 if let SelectItem::Expr { expr, .. } = &sel.columns[1] {
1406 assert_eq!(ann.get_type(expr), Some(&DataType::Varchar(Some(255))));
1407 }
1408 if let SelectItem::Expr { expr, .. } = &sel.columns[2] {
1410 assert_eq!(ann.get_type(expr), Some(&DataType::Double));
1411 }
1412 }
1413 }
1414
1415 #[test]
1418 fn test_where_clause_annotated() {
1419 let schema = setup_schema();
1420 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 #[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 #[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 #[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 #[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 assert!(ann.len() >= 3);
1499 }
1500
1501 #[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}