Expand description
The NormalizingVisitor for traversing SQL AST and applying name transformations.
This module contains the NormalizingVisitor struct which transforms object
names in SQL statements using a configurable strategy (via the NameTransformer
trait). Query-level traversal is delegated to mz-sql-parser’s auto-generated
VisitMut trait — the visitor overrides visit_query_mut (for CTE scope
management) and visit_table_factor_mut (for name transformation and implicit
aliasing). All other AST nodes (expressions, set operations, etc.) are handled
by the default traversal.
§CTE Scoping
Common Table Expressions (CTEs) introduce names that shadow real database
objects. The visitor uses CteScope
to track which names are currently in scope:
- Simple CTE names are introduced incrementally: each CTE body is visited
with only its earlier siblings in scope, then its own name is added.
Mutually-recursive blocks push all names up front. This mirrors
Materialize’s resolver (
fold_queryinsrc/sql/src/names.rs), so a simple CTE whose name shadows a catalog object can still reference that object inside its own body. - Unqualified single-identifier references are checked against the scope stack — if a match is found, the reference is not transformed (it refers to a CTE, not a database object).
- When leaving a
WITHclause, the scope is popped.
Key Insight: CTE names can only be referenced by their unqualified
name. Any multi-part reference (e.g., schema.name) is always a database
object reference and is always transformed.
§Implicit Aliasing
When a table reference in a FROM clause is transformed (e.g., sales →
materialize.public.sales), an implicit alias preserving the original
table name is attached. This ensures that column references like
sales.column continue to resolve correctly after transformation.
Structs§
- Normalizing
Visitor - Visitor that traverses SQL AST and transforms names using a given strategy.