Skip to main content

vlorql_core/optimizer/
prune.rs

1//! Column pruning: drop CTE output columns nobody reads.
2//!
3//! A [`CommonTableExpression`](crate::schema::CommonTableExpression) may
4//! project more columns than the outer query actually consumes. Each
5//! unused column forces the CTE to compute and materialize a value that
6//! is thrown away. [`ColumnPruning`] removes those columns from a CTE's
7//! `SELECT` list when it can prove they are unreferenced.
8//!
9//! Because the plan model's [`FromClause`](crate::schema::FromClause) is
10//! a bare table name (no inline subquery), CTEs are the only relations
11//! with a prunable projection, so this rule targets them.
12//!
13//! # What counts as "used"
14//!
15//! A CTE column is kept when any of the following holds:
16//!
17//! * the outer query (its `SELECT`, `WHERE`, `GROUP BY`, `HAVING`,
18//!   `ORDER BY`, or join `ON` clauses) references it by the CTE's
19//!   name/alias,
20//! * some relation qualifies the column with a `None` table (an
21//!   unqualified reference the rule cannot attribute), in which case the
22//!   rule keeps *every* column of every CTE to stay safe,
23//! * a downstream CTE references it, or
24//! * it is a primary-key or foreign-key column of the CTE's own base
25//!   table — these are preserved so join and policy checks stay correct
26//!   even if the current query happens not to select them.
27//! * it appears in a `GROUP BY` expression, an aggregation function
28//!   argument, or a `HAVING` predicate.
29//!
30//! # Safety
31//!
32//! The rule never prunes a CTE whose projection it cannot fully reason
33//! about (a `SELECT *`, or an aliased expression that renames a column).
34//! When in doubt it keeps the column, so pruning can only ever remove
35//! provably-dead outputs.
36
37use std::collections::HashSet;
38
39use crate::errors::VlorQLError;
40use crate::schema::{ArcSchemaSnapshot, CommonTableExpression, Expression, Projection, QueryPlan};
41
42use super::analyze::{
43    ColumnRef, columns_in_expression, columns_in_order_by, columns_in_predicate,
44    columns_in_projection,
45};
46use super::rules::PlanRewriter;
47use super::visitor::ExpressionFold;
48
49/// Removes CTE `SELECT` columns that no consumer references.
50///
51/// Construct with [`ColumnPruning::new`] for structural pruning, or
52/// [`ColumnPruning::with_schema`] to additionally preserve primary- and
53/// foreign-key columns of each CTE's base table.
54#[derive(Debug, Clone, Default)]
55pub struct ColumnPruning {
56    /// Optional schema snapshot used to identify primary/foreign keys.
57    schema: Option<ArcSchemaSnapshot>,
58}
59
60impl ColumnPruning {
61    /// Creates a pruner with no schema.
62    pub fn new() -> Self {
63        Self { schema: None }
64    }
65
66    /// Creates a pruner that consults `schema` to preserve primary-key
67    /// and foreign-key columns of each CTE's base table.
68    pub fn with_schema(schema: ArcSchemaSnapshot) -> Self {
69        Self {
70            schema: Some(schema),
71        }
72    }
73}
74
75impl PlanRewriter for ColumnPruning {
76    fn rewrite(&self, plan: &QueryPlan) -> Result<QueryPlan, VlorQLError> {
77        Ok(self.prune_plan(plan))
78    }
79}
80
81impl ColumnPruning {
82    fn prune_plan(&self, plan: &QueryPlan) -> QueryPlan {
83        let Some(ctes) = plan.ctes.as_ref() else {
84            return plan.clone();
85        };
86        if ctes.is_empty() {
87            return plan.clone();
88        }
89
90        // Collect every column the outer query reads, keyed by qualifier.
91        let used = self.used_columns(plan);
92
93        // A single unqualified reference anywhere means we cannot know
94        // which CTE it targets; keep all columns to preserve semantics.
95        if used.iter().any(|(table, _)| table.is_none()) {
96            return plan.clone();
97        }
98
99        // Recurse first so a CTE defined over other CTEs is pruned using
100        // its own body's demands, then prune this level.
101        let pruned: Vec<CommonTableExpression> = ctes
102            .iter()
103            .map(|cte| {
104                let inner = self.prune_plan(&cte.query);
105                self.prune_cte(cte, &inner, &used)
106            })
107            .collect();
108
109        QueryPlan {
110            ctes: Some(pruned),
111            ..plan.clone()
112        }
113    }
114
115    /// Prunes a single CTE's projection against the set of columns its
116    /// consumers reference. `inner` is the already-pruned CTE body.
117    fn prune_cte(
118        &self,
119        cte: &CommonTableExpression,
120        inner: &QueryPlan,
121        used: &HashSet<ColumnRef>,
122    ) -> CommonTableExpression {
123        let keep_all = || CommonTableExpression {
124            name: cte.name.clone(),
125            query: Box::new(inner.clone()), recursive: false
126        };
127
128        // A consumer that reads `<this cte>.*` needs every column.
129        if used.contains(&(Some(cte.name.clone()), "*".to_owned())) {
130            return keep_all();
131        }
132
133        // Build a map from output column name to the projection that
134        // produces it, and check whether every projection is a simple
135        // column reference (either bare or aliased).  If a projection
136        // renames a column with an alias, the output name is the alias;
137        // otherwise it is the table column name.
138        let mut output_map: Vec<(String, &Projection)> = Vec::with_capacity(inner.select.len());
139        let mut all_simple = true;
140        for projection in &inner.select {
141            match projection {
142                Projection::Column {
143                    column,
144                    alias: None,
145                    ..
146                } => {
147                    output_map.push((column.clone(), projection));
148                }
149                Projection::Column {
150                    column: _,
151                    alias: Some(alias),
152                    ..
153                } => {
154                    output_map.push((alias.clone(), projection));
155                }
156                Projection::Expr { alias: None, .. } => {
157                    all_simple = false;
158                }
159                Projection::Expr {
160                    alias: Some(alias), ..
161                } => {
162                    output_map.push((alias.clone(), projection));
163                }
164                Projection::Star { .. } => {
165                    return keep_all();
166                }
167            }
168        }
169        if !all_simple {
170            return keep_all();
171        }
172
173        // Columns of this CTE that a consumer references, by output name.
174        let referenced: HashSet<&str> = used
175            .iter()
176            .filter(|(table, _)| table.as_deref() == Some(cte.name.as_str()))
177            .map(|(_, column)| column.as_str())
178            .collect();
179
180        // If the CTE has GROUP BY or HAVING, determine which columns
181        // must be preserved (group keys + aggregation arguments from
182        // referenced projections + HAVING-referenced). Aggregate args
183        // from projections that are not referenced by any consumer are
184        // not included, allowing those projections to be pruned.
185        let group_required: HashSet<String> = if inner.group_by.is_some() || inner.having.is_some()
186        {
187            self.group_required_columns(inner, &output_map, &referenced)
188        } else {
189            HashSet::new()
190        };
191
192        // Primary/foreign-key columns of the CTE's base table are always
193        // preserved when a schema is available.
194        let protected = self.protected_columns(inner);
195
196        let kept: Vec<Projection> = output_map
197            .iter()
198            .filter(|(name, _)| {
199                referenced.contains(name.as_str())
200                    || protected.contains(name.as_str())
201                    || group_required.contains(name.as_str())
202            })
203            .map(|(_, projection)| (*projection).clone())
204            .collect();
205
206        // Never produce an empty projection; if nothing survived, keep the
207        // original list rather than emit invalid SQL.
208        if kept.is_empty() || kept.len() == inner.select.len() {
209            return keep_all();
210        }
211
212        let mut body = inner.clone();
213        body.select = kept;
214        CommonTableExpression {
215            name: cte.name.clone(),
216            query: Box::new(body), recursive: false
217        }
218    }
219
220    /// Determines the set of column names that must be preserved when
221    /// the CTE has GROUP BY or HAVING.
222    ///
223    /// Aggregate-function arguments are only collected from projections
224    /// that are actually referenced by a consumer — an unreferenced
225    /// aggregation (e.g. `SUM(b) AS s` where `s` is never read) does
226    /// not force its arguments to be preserved.
227    fn group_required_columns(
228        &self,
229        cte_body: &QueryPlan,
230        output_map: &[(String, &Projection)],
231        referenced: &HashSet<&str>,
232    ) -> HashSet<String> {
233        let mut required = HashSet::new();
234
235        // GROUP BY expressions: the columns they reference are group keys
236        // and must be preserved.
237        if let Some(exprs) = &cte_body.group_by {
238            for expr in exprs {
239                for (_, col) in columns_in_expression(expr) {
240                    required.insert(col);
241                }
242            }
243        }
244
245        // HAVING predicate columns.
246        if let Some(pred) = &cte_body.having {
247            for (_, col) in columns_in_predicate(pred) {
248                required.insert(col);
249            }
250        }
251
252        // Aggregate-function arguments: only collect them from
253        // projections that consumers actually reference. An unreferenced
254        // aggregate's argument columns do not need to be preserved.
255        for (name, projection) in output_map {
256            if referenced.contains(name.as_str())
257                && let Projection::Expr { expression, .. } = projection
258            {
259                required.extend(self.aggregate_args(expression));
260            }
261        }
262
263        // ORDER BY columns must also be preserved when grouping.
264        if let Some(terms) = &cte_body.order_by {
265            for term in terms {
266                for (_, col) in columns_in_expression(&term.expr) {
267                    required.insert(col);
268                }
269            }
270        }
271
272        required
273    }
274
275    /// Collects column names referenced inside aggregate-function
276    /// arguments within an expression.
277    fn aggregate_args(&self, expr: &Expression) -> HashSet<String> {
278        struct ArgCollector(HashSet<String>);
279        impl ExpressionFold for ArgCollector {
280            fn fold_expression(&mut self, expr: &Expression) -> Expression {
281                if let Expression::FunctionCall { args, .. } = expr {
282                    for arg in args {
283                        for (_, col) in crate::optimizer::analyze::columns_in_expression(arg) {
284                            self.0.insert(col);
285                        }
286                    }
287                }
288                super::visitor::default_fold_expression(self, expr)
289            }
290        }
291        let mut collector = ArgCollector(HashSet::new());
292        collector.fold_expression(expr);
293        collector.0
294    }
295
296    /// Returns the primary-key and foreign-key column names of the CTE
297    /// body's base table, or an empty set when no schema is configured or
298    /// the base table is unknown.
299    fn protected_columns(&self, cte_body: &QueryPlan) -> HashSet<String> {
300        let mut protected = HashSet::new();
301        let Some(schema) = self.schema.as_ref() else {
302            return protected;
303        };
304        let Some(table) = schema.get_table(&cte_body.from.table) else {
305            return protected;
306        };
307        for column in &table.columns {
308            if column.is_primary_key || column.foreign_key.is_some() {
309                protected.insert(column.name.clone());
310            }
311        }
312        protected
313    }
314
315    /// Collects every column referenced by the outer query itself (not by
316    /// the CTE bodies). A `SELECT *` short-circuits to a sentinel
317    /// unqualified entry so the caller keeps every CTE column.
318    fn used_columns(&self, plan: &QueryPlan) -> HashSet<ColumnRef> {
319        let mut used = HashSet::new();
320
321        for projection in &plan.select {
322            match columns_in_projection(projection) {
323                Some(columns) => used.extend(columns),
324                None => {
325                    used.insert((None, "*".to_owned()));
326                }
327            }
328        }
329
330        if let Some(pred) = plan.r#where.as_ref() {
331            used.extend(columns_in_predicate(pred));
332        }
333        if let Some(exprs) = plan.group_by.as_ref() {
334            for expr in exprs {
335                used.extend(columns_in_expression(expr));
336            }
337        }
338        if let Some(pred) = plan.having.as_ref() {
339            used.extend(columns_in_predicate(pred));
340        }
341        if let Some(terms) = plan.order_by.as_ref() {
342            used.extend(columns_in_order_by(terms));
343        }
344        if let Some(joins) = plan.joins.as_ref() {
345            for join in joins {
346                used.extend(columns_in_predicate(&join.on));
347            }
348        }
349
350        // Downstream CTEs may reference an earlier CTE's columns.
351        if let Some(ctes) = plan.ctes.as_ref() {
352            for cte in ctes {
353                used.extend(self.columns_used_by_cte_body(&cte.query));
354            }
355        }
356
357        used
358    }
359
360    /// Columns a CTE body reads from a *sibling* relation, i.e. references
361    /// qualified by another CTE's name.
362    ///
363    /// Only qualified references are returned: an *unqualified* column in a
364    /// CTE body binds to that body's own `FROM` table, never to a sibling
365    /// CTE's output, so it says nothing about which of this level's CTE
366    /// outputs are consumed.
367    fn columns_used_by_cte_body(&self, body: &QueryPlan) -> HashSet<ColumnRef> {
368        let mut used = HashSet::new();
369        for projection in &body.select {
370            match projection {
371                Projection::Star { table: Some(table) } => {
372                    used.insert((Some(table.clone()), "*".to_owned()));
373                }
374                Projection::Star { table: None } => {}
375                other => {
376                    if let Some(columns) = columns_in_projection(other) {
377                        used.extend(columns);
378                    }
379                }
380            }
381        }
382        if let Some(pred) = body.r#where.as_ref() {
383            used.extend(columns_in_predicate(pred));
384        }
385        if let Some(exprs) = body.group_by.as_ref() {
386            for expr in exprs {
387                used.extend(columns_in_expression(expr));
388            }
389        }
390        if let Some(pred) = body.having.as_ref() {
391            used.extend(columns_in_predicate(pred));
392        }
393        if let Some(terms) = body.order_by.as_ref() {
394            used.extend(columns_in_order_by(terms));
395        }
396        if let Some(joins) = body.joins.as_ref() {
397            for join in joins {
398                used.extend(columns_in_predicate(&join.on));
399            }
400        }
401        used.retain(|(table, _)| table.is_some());
402        used
403    }
404}
405
406#[cfg(test)]
407mod tests {
408    use super::*;
409    use crate::schema::{
410        BinaryOperator, ColumnSchema, ComparisonOperator, DataType, Expression, ForeignKey,
411        FromClause, Predicate, Projection, SchemaMetadata, SchemaSnapshot, TableSchema,
412    };
413    use std::sync::Arc;
414
415    fn col(table: Option<&str>, column: &str) -> Expression {
416        Expression::ColumnRef {
417            table: table.map(str::to_owned),
418            column: column.to_owned(),
419        }
420    }
421
422    fn int(value: i64) -> Expression {
423        Expression::Literal {
424            value: value.into(),
425            data_type: DataType::Int,
426        }
427    }
428
429    fn lit_int(value: i64) -> Expression {
430        int(value)
431    }
432
433    fn column_projection(table: Option<&str>, column: &str) -> Projection {
434        Projection::Column {
435            table: table.map(str::to_owned),
436            column: column.to_owned(),
437            alias: None,
438        }
439    }
440
441    fn compare(left: Expression, op: ComparisonOperator, right: Expression) -> Predicate {
442        Predicate::Comparison { left, op, right }
443    }
444
445    fn eq(left: Expression, right: Expression) -> Predicate {
446        compare(left, ComparisonOperator::Eq, right)
447    }
448
449    fn plan_with_cte(
450        outer_select: Vec<Projection>,
451        cte_name: &str,
452        cte_projection: Vec<Projection>,
453        cte_gb: Option<Vec<Expression>>,
454        cte_having: Option<Predicate>,
455        outer_where: Option<Predicate>,
456    ) -> QueryPlan {
457        let cte = CommonTableExpression {
458            name: cte_name.to_owned(),
459            recursive: false,
460            query: Box::new(QueryPlan {
461                select: cte_projection,
462                from: FromClause {
463                    table: "orders".to_owned(),
464                    alias: None,
465                },
466                r#where: None,
467                group_by: cte_gb,
468                having: cte_having,
469                order_by: None,
470                limit: None,
471                offset: None,
472                joins: None,
473                ctes: None,
474            distinct: false,
475            distinct_on: None,
476            set_operation: None,            }),
477        };
478        QueryPlan {
479            select: outer_select,
480            from: FromClause {
481                table: cte_name.to_owned(),
482                alias: None,
483            },
484            r#where: outer_where,
485            group_by: None,
486            having: None,
487            order_by: None,
488            limit: None,
489            offset: None,
490            joins: None,
491            ctes: Some(vec![cte]),
492            distinct: false,
493            distinct_on: None,
494            set_operation: None,
495        }
496    }
497
498    #[test]
499    fn prunes_unreferenced_cte_columns() {
500        let plan = plan_with_cte(
501            vec![column_projection(Some("recent"), "id")],
502            "recent",
503            vec![
504                column_projection(Some("orders"), "id"),
505                column_projection(Some("orders"), "user_id"),
506                column_projection(Some("orders"), "status"),
507            ],
508            None,
509            None,
510            Some(eq(col(Some("recent"), "id"), lit_int(1))),
511        );
512        let rewritten = ColumnPruning::new().rewrite(&plan).unwrap();
513        let cte_select = &rewritten.ctes.as_ref().unwrap()[0].query.select;
514        assert_eq!(cte_select.len(), 1);
515        assert_eq!(cte_select[0], column_projection(Some("orders"), "id"));
516    }
517
518    #[test]
519    fn preserves_primary_and_foreign_keys() {
520        let schema = Arc::new(SchemaSnapshot::new(
521            vec![TableSchema {
522                name: "orders".to_owned(),
523                columns: vec![
524                    ColumnSchema {
525                        name: "id".to_owned(),
526                        data_type: DataType::Int,
527                        nullable: false,
528                        description: None,
529                        is_primary_key: true,
530                        foreign_key: None,
531                    },
532                    ColumnSchema {
533                        name: "user_id".to_owned(),
534                        data_type: DataType::Int,
535                        nullable: false,
536                        description: None,
537                        is_primary_key: false,
538                        foreign_key: Some(ForeignKey {
539                            foreign_table: "users".to_owned(),
540                            foreign_column: "id".to_owned(),
541                        }),
542                    },
543                    ColumnSchema {
544                        name: "status".to_owned(),
545                        data_type: DataType::Int,
546                        nullable: false,
547                        description: None,
548                        is_primary_key: false,
549                        foreign_key: None,
550                    },
551                ],
552                description: None,
553                primary_key: Some(vec!["id".to_owned()]),
554            }],
555            SchemaMetadata::default(),
556        ));
557
558        let plan = plan_with_cte(
559            vec![column_projection(Some("recent"), "status")],
560            "recent",
561            vec![
562                column_projection(Some("orders"), "id"),
563                column_projection(Some("orders"), "user_id"),
564                column_projection(Some("orders"), "status"),
565            ],
566            None,
567            None,
568            Some(eq(col(Some("recent"), "status"), lit_int(1))),
569        );
570
571        let rewritten = ColumnPruning::with_schema(schema).rewrite(&plan).unwrap();
572        let cte_select = &rewritten.ctes.as_ref().unwrap()[0].query.select;
573        let kept: Vec<&str> = cte_select
574            .iter()
575            .filter_map(|p| match p {
576                Projection::Column { column, .. } => Some(column.as_str()),
577                _ => None,
578            })
579            .collect();
580
581        assert!(kept.contains(&"status"), "referenced column kept");
582        assert!(kept.contains(&"id"), "primary key preserved");
583        assert!(kept.contains(&"user_id"), "foreign key preserved");
584    }
585
586    #[test]
587    fn keeps_all_columns_under_unqualified_reference() {
588        let mut plan = plan_with_cte(
589            vec![column_projection(None, "id")],
590            "recent",
591            vec![
592                column_projection(Some("orders"), "id"),
593                column_projection(Some("orders"), "user_id"),
594                column_projection(Some("orders"), "status"),
595            ],
596            None,
597            None,
598            Some(eq(col(None, "status"), lit_int(1))),
599        );
600        plan.select = vec![column_projection(None, "id")];
601
602        let rewritten = ColumnPruning::new().rewrite(&plan).unwrap();
603        assert_eq!(rewritten.ctes.as_ref().unwrap()[0].query.select.len(), 3);
604    }
605
606    // --- GROUP BY pruning tests ------------------------------------------
607
608    #[test]
609    fn prunes_unused_columns_from_group_by_cte() {
610        // CTE: SELECT a, b, c FROM t GROUP BY a, b
611        // The outer query only references `a` and `b` (group keys).
612        // `c` is neither a group key nor used in an aggregate → prunable.
613        let plan = plan_with_cte(
614            vec![
615                column_projection(Some("recent"), "a"),
616                column_projection(Some("recent"), "b"),
617            ],
618            "recent",
619            vec![
620                column_projection(Some("t"), "a"),
621                column_projection(Some("t"), "b"),
622                column_projection(Some("t"), "c"),
623            ],
624            Some(vec![col(None, "a"), col(None, "b")]),
625            None,
626            None,
627        );
628
629        let rewritten = ColumnPruning::new().rewrite(&plan).unwrap();
630        let cte_select = &rewritten.ctes.as_ref().unwrap()[0].query.select;
631        let kept: Vec<&str> = cte_select
632            .iter()
633            .filter_map(|p| match p {
634                Projection::Column { column, .. } => Some(column.as_str()),
635                _ => None,
636            })
637            .collect();
638
639        assert!(kept.contains(&"a"), "group key `a` kept");
640        assert!(kept.contains(&"b"), "group key `b` kept");
641        assert!(
642            !kept.contains(&"c"),
643            "`c` is neither key nor aggregate → pruned"
644        );
645    }
646
647    #[test]
648    fn keeps_only_referenced_columns_from_group_by_cte() {
649        // CTE: SELECT a, SUM(b) AS total FROM t GROUP BY a
650        // The outer query only reads `a`, so `total` (aggregate) is
651        // unreferenced and can be pruned — the GROUP BY is unaffected.
652        let plan = plan_with_cte(
653            vec![column_projection(Some("recent"), "a")],
654            "recent",
655            vec![
656                column_projection(Some("t"), "a"),
657                Projection::Expr {
658                    expression: Expression::FunctionCall {
659                        name: "SUM".to_owned(),
660                        args: vec![col(None, "b")],
661                        distinct: false,
662                    },
663                    alias: Some("total".to_owned()),
664                },
665            ],
666            Some(vec![col(None, "a")]),
667            None,
668            None,
669        );
670
671        let rewritten = ColumnPruning::new().rewrite(&plan).unwrap();
672        let cte_select = &rewritten.ctes.as_ref().unwrap()[0].query.select;
673        let kept: Vec<&str> = cte_select
674            .iter()
675            .filter_map(|p| match p {
676                Projection::Column { column, .. } => Some(column.as_str()),
677                Projection::Expr { alias, .. } => alias.as_deref(),
678                _ => None,
679            })
680            .collect();
681
682        assert!(kept.contains(&"a"), "group key `a` kept");
683        assert!(
684            !kept.contains(&"total"),
685            "unreferenced aggregate `total` pruned"
686        );
687    }
688
689    #[test]
690    fn prunes_expression_projection_not_referenced_by_alias() {
691        // CTE: SELECT id, col + 1 AS plus_one FROM t
692        // Outer query references only `id`.
693        // `plus_one` can be pruned because no consumer uses it by alias.
694        let plan = plan_with_cte(
695            vec![column_projection(Some("recent"), "id")],
696            "recent",
697            vec![
698                column_projection(Some("t"), "id"),
699                Projection::Expr {
700                    expression: Expression::BinaryOp {
701                        left: Box::new(col(None, "col")),
702                        op: BinaryOperator::Add,
703                        right: Box::new(lit_int(1)),
704                    },
705                    alias: Some("plus_one".to_owned()),
706                },
707            ],
708            None,
709            None,
710            None,
711        );
712
713        let rewritten = ColumnPruning::new().rewrite(&plan).unwrap();
714        let cte_select = &rewritten.ctes.as_ref().unwrap()[0].query.select;
715        let kept: Vec<&str> = cte_select
716            .iter()
717            .filter_map(|p| match p {
718                Projection::Column { column, .. } => Some(column.as_str()),
719                Projection::Expr { alias, .. } => alias.as_deref(),
720                _ => None,
721            })
722            .collect();
723
724        assert!(kept.contains(&"id"), "referenced column `id` kept");
725        assert!(
726            !kept.contains(&"plus_one"),
727            "unreferenced expression `plus_one` pruned"
728        );
729    }
730
731    #[test]
732    fn keeps_expression_projection_when_referenced_by_alias() {
733        let plan = plan_with_cte(
734            vec![column_projection(Some("recent"), "plus_one")],
735            "recent",
736            vec![
737                column_projection(Some("t"), "id"),
738                Projection::Expr {
739                    expression: Expression::BinaryOp {
740                        left: Box::new(col(None, "col")),
741                        op: BinaryOperator::Add,
742                        right: Box::new(lit_int(1)),
743                    },
744                    alias: Some("plus_one".to_owned()),
745                },
746            ],
747            None,
748            None,
749            None,
750        );
751
752        let rewritten = ColumnPruning::new().rewrite(&plan).unwrap();
753        let cte_select = &rewritten.ctes.as_ref().unwrap()[0].query.select;
754        let kept: Vec<&str> = cte_select
755            .iter()
756            .filter_map(|p| match p {
757                Projection::Column { column, .. } => Some(column.as_str()),
758                Projection::Expr { alias, .. } => alias.as_deref(),
759                _ => None,
760            })
761            .collect();
762
763        assert!(kept.contains(&"plus_one"), "referenced expression kept");
764        // `id` is not referenced → should be pruned.
765        assert!(!kept.contains(&"id"), "unreferenced column `id` pruned");
766    }
767
768    #[test]
769    fn keeps_having_referenced_columns_in_group_by_cte() {
770        // CTE: SELECT a, b FROM t GROUP BY a, b HAVING b > 0
771        // The outer query only reads `a`, but `b` must be kept because
772        // it appears in HAVING.
773        let plan = plan_with_cte(
774            vec![column_projection(Some("recent"), "a")],
775            "recent",
776            vec![
777                column_projection(Some("t"), "a"),
778                column_projection(Some("t"), "b"),
779            ],
780            Some(vec![col(None, "a"), col(None, "b")]),
781            Some(compare(col(None, "b"), ComparisonOperator::Gt, lit_int(0))),
782            None,
783        );
784
785        let rewritten = ColumnPruning::new().rewrite(&plan).unwrap();
786        let cte_select = &rewritten.ctes.as_ref().unwrap()[0].query.select;
787        let kept: Vec<&str> = cte_select
788            .iter()
789            .filter_map(|p| match p {
790                Projection::Column { column, .. } => Some(column.as_str()),
791                _ => None,
792            })
793            .collect();
794
795        assert!(kept.contains(&"a"), "group key `a` kept");
796        assert!(kept.contains(&"b"), "HAVING-referenced `b` kept");
797    }
798}