# Traversal

This module is responsible for traversing the Abstract Syntax Tree (AST) generated by the query builder. It provides mechanisms to visit each node in the AST, allowing for analysis, modification, and processing of the query structure.

**Dialect Notes**: Traversal is dialect-agnostic and used by PostgreSQL, SQLite, and MySQL compilers.

## Core Concepts: The Visitor Pattern

The traversal logic is built upon the **Visitor Design Pattern**, which separates the data structure (AST nodes) from the algorithms that operate on them (compilers, validators, etc.).

### `Visitor` Class (The "Reader")
The base `Visitor` class is used to traverse the tree to extract information or generate output without modifying the original AST.

-   **Dynamic Dispatch:** The `visit(node)` method automatically dispatches to type-specific methods (e.g., `visit_ColumnNode`) using Python's `getattr`.
-   **Decoupling:** Keeps `models.py` clean by moving logic like SQL generation or validation into separate visitor implementations.
-   **Flexible Returns:** The `visit` method is hinted to return `Any`, allowing visitors to produce strings (for compilation), booleans (for validation), or any other data type.

### `Transformer` Class (The "Modifier")
The `Transformer` is a specialized `Visitor` intended for AST-to-AST transformations.

-   **Identity by Default:** If a specific `visit_` method isn't overridden, it returns the original node. You only need to implement the methods for the nodes you wish to change.
-   **Use Cases:** Ideal for query optimization (e.g., constant folding), normalization (e.g., case conversion), or dialect-specific structural adjustments.
-   **AST-to-AST:** Strictly hinted to return an `ASTNode`, ensuring the result is always a valid tree.

## Implementation Details

The traversal infrastructure is located in `visitor_pattern.py`. To create a new operation, inherit from `Visitor` or `Transformer` and implement the relevant `visit_<NodeName>` methods.

### Example: A Simple Logger Visitor

```python
from buildaquery.traversal.visitor_pattern import Visitor

class NodeLogger(Visitor):
    def visit_TableNode(self, node):
        print(f"Visiting table: {node.name}")

    def visit_ColumnNode(self, node):
        print(f"Visiting column: {node.name}")

---

## Future Enhancements (TODO)

*   **Automatic Child Traversal:** Enhance `generic_visit` to automatically identify and visit all child `ASTNode` instances within a node using reflection (e.g., iterating over dataclass fields).
*   **Breadth-First Walker:** Implement a non-recursive `walk()` utility function that yields every node in the tree level-by-level using a queue.

```
