Expand description
Type annotation pass for SQL expressions.
Infers and propagates SQL data types across AST nodes using schema metadata.
Inspired by Python sqlglot’s annotate_types optimizer pass.
§Overview
The pass walks the AST bottom-up, resolving types for:
- Literals:
42→Int,'hello'→Varchar,TRUE→Boolean - Column references: looked up from the provided
Schema - Binary operators: result type from operand coercion (e.g.
INT + FLOAT → FLOAT) - CAST / TRY_CAST: the target data type
- Functions: return type based on function signature and argument types
- CASE: common type across all THEN / ELSE branches
- Aggregates:
COUNT → BigInt,SUMdepends on input, etc. - Subqueries: type of the single output column
§Example
use sqlglot_rust::optimizer::annotate_types::annotate_types;
use sqlglot_rust::schema::{MappingSchema, Schema};
use sqlglot_rust::ast::DataType;
use sqlglot_rust::{parse, Dialect};
let mut schema = MappingSchema::new(Dialect::Ansi);
schema.add_table(&["t"], vec![
("id".to_string(), DataType::Int),
("name".to_string(), DataType::Varchar(Some(255))),
]).unwrap();
let stmt = parse("SELECT id, name FROM t WHERE id > 1", Dialect::Ansi).unwrap();
let annotations = annotate_types(&stmt, &schema);
// annotations now contains inferred types for every expression nodeStructs§
- Type
Annotations - Stores inferred
DataTypeannotations for expression nodes in an AST.
Functions§
- annotate_
types - Annotate all expression nodes in a statement with inferred SQL types.