Repository: tobymao/sqlglot
Issue category: Bug Report

Issue:
getting UnboundLocalError: cannot access local variable 'aggregate' where it is not associated with a value when running sqlglot.planner.Plan
**Before you file an issue**
- Make sure you specify the "read" dialect eg. `parse_one(sql, read="spark")`
- Make sure you specify the "write" dialect eg. `ast.sql(dialect="duckdb")`
- Check if the issue still exists on main

**Fully reproducible code snippet**
```
import sqlglot
import sqlglot.planner

r = 'select suma from ( select sum(a) as suma from table1) order by suma'
parsed = sqlglot.parse_one(r, dialect='snowflake')
p = sqlglot.planner.Plan(parsed)
```
Throws:
```
File venv/lib/python3.11/site-packages/sqlglot/planner.py:14, in Plan.__init__(self, expression)
     12 def __init__(self, expression: exp.Expression) -> None:
     13     self.expression = expression.copy()
---> 14     self.root = Step.from_expression(self.expression)
     15     self._dag: t.Dict[Step, t.Set[Step]] = {}

File venv/lib/python3.11/site-packages/sqlglot/planner.py:213, in Step.from_expression(cls, expression, ctes)
    210         if extract_agg_operands(exp.alias_(ordered.this, f"_o_{i}", quoted=True)):
    211             ordered.this.replace(exp.column(f"_o_{i}", step.name, quoted=True))
--> 213     set_ops_and_aggs(aggregate)
    215 sort = Sort()
    216 sort.name = step.name

UnboundLocalError: cannot access local variable 'aggregate' where it is not associated with a value
```

On sqlglot 25.33.0

dialect seems to be irrelevant, same error with Athena

**Official Documentation**
Please include links to official SQL documentation related to your issue.



Hints:
You need to run the optimizer first:

```python
>>> import sqlglot
>>> import sqlglot.planner
>>>
>>> r = 'select suma from ( select sum(a) as suma from table1) order by suma'
>>> parsed = sqlglot.parse_one(r, dialect='snowflake')
>>> p = sqlglot.planner.Plan(parsed)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/georgesittas/Code/tobiko/sqlglot/sqlglot/planner.py", line 14, in __init__
    self.root = Step.from_expression(self.expression)
                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/georgesittas/Code/tobiko/sqlglot/sqlglot/planner.py", line 213, in from_expression
    set_ops_and_aggs(aggregate)
                     ^^^^^^^^^
UnboundLocalError: cannot access local variable 'aggregate' where it is not associated with a value
>>> from sqlglot.optimizer import optimize
>>> optimized = optimize(parsed)
>>> optimized.sql()
'WITH "_q_0" AS (SELECT SUM("table1"."a") AS "suma" FROM "table1" AS "table1") SELECT "_q_0"."suma" AS "suma" FROM "_q_0" AS "_q_0" ORDER BY "suma" NULLS LAST'
>>>
>>> p = sqlglot.planner.Plan(optimized)
>>> p
Plan
----
- Sort: _q_0 (4376798720)
    Context:
      Key:
        - "suma" NULLS LAST
    Projections:
      - "_q_0"."suma" AS "suma"
    Dependencies:
    - Scan: _q_0 (4343324816)
      Context:
        Source: "_q_0" AS "_q_0"
      Projections:
      Dependencies:
      - Aggregate: _q_0 (4376798672)
        Context:
          Aggregations:
            - SUM("table1"."a") AS "suma"
        Projections:
          - "table1"."suma"
        Dependencies:
        - Scan: table1 (4376798816)
          Context:
            Source: "table1" AS "table1"
          Projections:
```


Looks like there's a code path where this _can_ happen, I think I may have made an incorrect assumption on needing the optimizer. Will double check and re-close if needed.

Patch:
diff --git a/sqlglot/planner.py b/sqlglot/planner.py
index 2e42b32c4..687bffb9f 100644
--- a/sqlglot/planner.py
+++ b/sqlglot/planner.py
@@ -201,11 +201,13 @@ def set_ops_and_aggs(step):
 
             aggregate.add_dependency(step)
             step = aggregate
+        else:
+            aggregate = None
 
         order = expression.args.get("order")
 
         if order:
-            if isinstance(step, Aggregate):
+            if aggregate and isinstance(step, Aggregate):
                 for i, ordered in enumerate(order.expressions):
                     if extract_agg_operands(exp.alias_(ordered.this, f"_o_{i}", quoted=True)):
                         ordered.this.replace(exp.column(f"_o_{i}", step.name, quoted=True))


Test patch: