Skip to main content

vlorql_core/optimizer/
mod.rs

1//! Logical rewrite rules applied to a validated [`QueryPlan`].
2//!
3//! Once a plan has passed validation and policy checks, the optimizer
4//! applies semantics-preserving rewrites that reduce the work the SQL
5//! backend has to do:
6//!
7//! * [`ConstantFolding`] statically evaluates constant sub-expressions
8//!   (`20 + 5` becomes `25`).
9//! * [`PredicatePushdown`] moves single-relation `WHERE` conjuncts down
10//!   into the CTE they filter, so rows are discarded earlier.
11//! * [`ColumnPruning`] removes CTE output columns that no consumer reads.
12//!
13//! Every rule implements [`PlanRewriter`]; [`RewriterPipeline`] chains
14//! them in a chosen order.
15//!
16//! Cost-based [`JoinReorderer`] is a separate, `async` optimizer (it
17//! consults a statistics provider) rather than a [`PlanRewriter`]: it
18//! reorders an inner-join chain to minimize estimated cost.
19//!
20//! # Model limitations
21//!
22//! The plan model's [`FromClause`](crate::schema::FromClause) is a bare
23//! table name — there is no inline-subquery relation. The only nestable
24//! relation is a [`CommonTableExpression`](crate::schema::CommonTableExpression).
25//! Pushdown and pruning therefore operate on **CTEs**, not on synthetic
26//! FROM subqueries. Every rule is conservative: when it cannot prove a
27//! rewrite is safe it leaves that part of the plan untouched, so the
28//! output is always semantically equivalent to the input.
29
30mod analyze;
31mod fold;
32mod join_reorder;
33mod prune;
34mod pushdown;
35mod rules;
36pub(crate) mod visitor;
37
38pub use fold::ConstantFolding;
39pub use join_reorder::{JoinGraph, JoinReorderer, MAX_DP_RELATIONS};
40pub use prune::ColumnPruning;
41pub use pushdown::PredicatePushdown;
42pub use rules::{PlanRewriter, RewriterPipeline};
43
44use crate::errors::VlorQLError;
45use crate::schema::QueryPlan;
46use crate::statistics::Cost;
47use crate::statistics::StatisticsProvider;
48use std::sync::Arc;
49
50/// Orchestrates all optimisation passes over a validated [`QueryPlan`].
51///
52/// The optimizer applies a fixed sequence of logical rewrites (constant
53/// folding, predicate pushdown, column pruning) and, when a statistics
54/// provider is available, cost-based join reordering.
55///
56/// # Examples
57///
58/// ```
59/// use vlorql_core::optimizer::QueryOptimizer;
60/// use vlorql_core::statistics::DummyStatisticsProvider;
61/// use std::sync::Arc;
62///
63/// let stats = Arc::new(DummyStatisticsProvider::default());
64/// let optimizer = QueryOptimizer::new(stats);
65/// ```
66#[derive(Debug, Clone)]
67pub struct QueryOptimizer {
68    /// The synchronous rewrite pipeline (folding, pushdown, pruning).
69    pipeline: Arc<RewriterPipeline>,
70    /// Optional async join reorderer, available when statistics are present.
71    join_reorderer: Option<JoinReorderer>,
72    /// Flag to enable/disable join reordering at runtime.
73    enable_join_reorder: bool,
74}
75
76impl QueryOptimizer {
77    /// Creates a new optimizer with all rewrite rules enabled.
78    ///
79    /// When `stats_provider` is a non-empty provider, join reordering is
80    /// also enabled. Pass `DummyStatisticsProvider::default()` to skip
81    /// join reordering.
82    pub fn new(stats_provider: Arc<dyn StatisticsProvider>) -> Self {
83        let join_reorderer = Some(JoinReorderer::new(Arc::clone(&stats_provider)));
84        Self {
85            pipeline: Arc::new(
86                RewriterPipeline::new()
87                    .with(ConstantFolding)
88                    .with(PredicatePushdown)
89                    .with(ColumnPruning::new()),
90            ),
91            join_reorderer,
92            enable_join_reorder: true,
93        }
94    }
95
96    /// Creates an optimizer with only the logical rewrite rules (no join
97    /// reordering), regardless of whether statistics are available.
98    pub fn rewrites_only() -> Self {
99        Self {
100            pipeline: Arc::new(
101                RewriterPipeline::new()
102                    .with(ConstantFolding)
103                    .with(PredicatePushdown)
104                    .with(ColumnPruning::new()),
105            ),
106            join_reorderer: None,
107            enable_join_reorder: false,
108        }
109    }
110
111    /// Enables or disables join reordering at runtime.
112    #[must_use]
113    pub fn with_join_reorder(mut self, enabled: bool) -> Self {
114        self.enable_join_reorder = enabled;
115        self
116    }
117
118    /// Returns the estimated cost of executing `plan`'s join chain.
119    ///
120    /// Returns `None` when no join reorderer is configured.
121    pub async fn estimated_cost(&self, plan: &QueryPlan) -> Option<Cost> {
122        match self.join_reorderer {
123            Some(ref jr) => Some(jr.estimate_plan_cost(plan).await.unwrap_or_default()),
124            None => None,
125        }
126    }
127
128    /// Applies synchronous rewrite rules (constant folding, predicate
129    /// pushdown, column pruning) to the plan.
130    pub fn optimize(&self, plan: &QueryPlan) -> Result<QueryPlan, VlorQLError> {
131        self.pipeline.rewrite(plan)
132    }
133
134    /// Applies the rewrite pipeline in fixed-point iteration (up to
135    /// `max_rounds`) until the plan stabilizes. See
136    /// [`RewriterPipeline::repeat_until_stable`].
137    pub fn optimize_repeat(
138        &self,
139        plan: &QueryPlan,
140        max_rounds: usize,
141    ) -> Result<QueryPlan, VlorQLError> {
142        self.pipeline.repeat_until_stable(plan, max_rounds)
143    }
144
145    /// Applies all rewrite rules **and**, if enabled, cost-based join
146    /// reordering. This is the async entry point because join reordering
147    /// consults the statistics provider.
148    pub async fn optimize_async(&self, plan: &QueryPlan) -> Result<QueryPlan, VlorQLError> {
149        let plan = self.pipeline.rewrite(plan)?;
150        if self.enable_join_reorder
151            && let Some(ref reorderer) = self.join_reorderer
152        {
153            return reorderer.reorder(&plan).await;
154        }
155        Ok(plan)
156    }
157}
158
159#[cfg(test)]
160mod tests {
161    use super::*;
162    use crate::schema::{
163        BinaryOperator, ColumnSchema, CommonTableExpression, ComparisonOperator, DataType,
164        Expression, ForeignKey, FromClause, JoinClause, JoinType, Predicate, Projection, QueryPlan,
165        SchemaMetadata, SchemaSnapshot, TableSchema,
166    };
167    use std::sync::Arc;
168
169    // --- builders -------------------------------------------------------
170
171    fn col(table: Option<&str>, column: &str) -> Expression {
172        Expression::ColumnRef {
173            table: table.map(str::to_owned),
174            column: column.to_owned(),
175        }
176    }
177
178    fn int(value: i64) -> Expression {
179        Expression::Literal {
180            value: value.into(),
181            data_type: DataType::Int,
182        }
183    }
184
185    fn column_projection(table: Option<&str>, column: &str) -> Projection {
186        Projection::Column {
187            table: table.map(str::to_owned),
188            column: column.to_owned(),
189            alias: None,
190        }
191    }
192
193    fn compare(left: Expression, op: ComparisonOperator, right: Expression) -> Predicate {
194        Predicate::Comparison { left, op, right }
195    }
196
197    fn and(left: Predicate, right: Predicate) -> Predicate {
198        Predicate::And {
199            left: Box::new(left),
200            right: Box::new(right),
201        }
202    }
203
204    /// Counts the comparison leaves in a predicate tree.
205    fn conjunct_count(pred: &Predicate) -> usize {
206        match pred {
207            Predicate::And { left, right } => conjunct_count(left) + conjunct_count(right),
208            _ => 1,
209        }
210    }
211
212    // --- constant folding ----------------------------------------------
213
214    #[test]
215    fn constant_folding_evaluates_arithmetic_in_projection() {
216        let plan = QueryPlan {
217            select: vec![Projection::Expr {
218                expression: Expression::BinaryOp {
219                    left: Box::new(int(1)),
220                    op: BinaryOperator::Add,
221                    right: Box::new(int(2)),
222                },
223                alias: Some("three".to_owned()),
224            }],
225            from: FromClause {
226                table: "t".to_owned(),
227                alias: None,
228            },
229            r#where: None,
230            group_by: None,
231            having: None,
232            order_by: None,
233            limit: None,
234            offset: None,
235            joins: None,
236            ctes: None,
237            distinct: false,
238            distinct_on: None,
239            set_operation: None,
240        };
241
242        let folded = ConstantFolding.rewrite(&plan).unwrap();
243        assert_eq!(
244            folded.select[0],
245            Projection::Expr {
246                expression: int(3),
247                alias: Some("three".to_owned()),
248            }
249        );
250    }
251
252    #[test]
253    fn constant_folding_simplifies_constant_side_of_comparison() {
254        // age > 20 + 5   -->   age > 25
255        let plan = QueryPlan {
256            select: vec![column_projection(Some("users"), "age")],
257            from: FromClause {
258                table: "users".to_owned(),
259                alias: None,
260            },
261            r#where: Some(compare(
262                col(Some("users"), "age"),
263                ComparisonOperator::Gt,
264                Expression::BinaryOp {
265                    left: Box::new(int(20)),
266                    op: BinaryOperator::Add,
267                    right: Box::new(int(5)),
268                },
269            )),
270            group_by: None,
271            having: None,
272            order_by: None,
273            limit: None,
274            offset: None,
275            joins: None,
276            ctes: None,
277            distinct: false,
278            distinct_on: None,
279            set_operation: None,
280        };
281
282        let folded = ConstantFolding.rewrite(&plan).unwrap();
283        assert_eq!(
284            folded.r#where,
285            Some(compare(
286                col(Some("users"), "age"),
287                ComparisonOperator::Gt,
288                int(25),
289            ))
290        );
291    }
292
293    #[test]
294    fn constant_folding_leaves_column_expressions_untouched() {
295        // age + 1 has a column operand and must not be folded.
296        let expr = Expression::BinaryOp {
297            left: Box::new(col(Some("users"), "age")),
298            op: BinaryOperator::Add,
299            right: Box::new(int(1)),
300        };
301        let plan = QueryPlan {
302            select: vec![Projection::Expr {
303                expression: expr.clone(),
304                alias: None,
305            }],
306            from: FromClause {
307                table: "users".to_owned(),
308                alias: None,
309            },
310            r#where: None,
311            group_by: None,
312            having: None,
313            order_by: None,
314            limit: None,
315            offset: None,
316            joins: None,
317            ctes: None,
318            distinct: false,
319            distinct_on: None,
320            set_operation: None,
321        };
322
323        let folded = ConstantFolding.rewrite(&plan).unwrap();
324        assert_eq!(
325            folded.select[0],
326            Projection::Expr {
327                expression: expr,
328                alias: None
329            }
330        );
331    }
332
333    // --- predicate pushdown --------------------------------------------
334
335    /// A CTE named `recent` selecting `id`, `user_id`, `status` from a
336    /// base table, wrapped by an outer query that filters on it.
337    fn plan_with_cte(outer_where: Predicate) -> QueryPlan {
338        let cte = CommonTableExpression {
339            name: "recent".to_owned(),
340            recursive: false,
341            query: Box::new(QueryPlan {
342                select: vec![
343                    column_projection(Some("orders"), "id"),
344                    column_projection(Some("orders"), "user_id"),
345                    column_projection(Some("orders"), "status"),
346                ],
347                from: FromClause {
348                    table: "orders".to_owned(),
349                    alias: None,
350                },
351                r#where: None,
352                group_by: None,
353                having: None,
354                order_by: None,
355                limit: None,
356                offset: None,
357                joins: None,
358                ctes: None,
359            distinct: false,
360            distinct_on: None,
361            set_operation: None,            }),
362        };
363        QueryPlan {
364            select: vec![column_projection(Some("recent"), "id")],
365            from: FromClause {
366                table: "recent".to_owned(),
367                alias: None,
368            },
369            r#where: Some(outer_where),
370            group_by: None,
371            having: None,
372            order_by: None,
373            limit: None,
374            offset: None,
375            joins: None,
376            ctes: Some(vec![cte]),
377            distinct: false,
378            distinct_on: None,
379            set_operation: None,
380        }
381    }
382
383    #[test]
384    fn pushdown_moves_single_cte_conjunct_into_the_cte() {
385        // WHERE recent.status = 1 AND recent.id > 100
386        // both reference only `recent`, so both push down.
387        let outer = and(
388            compare(
389                col(Some("recent"), "status"),
390                ComparisonOperator::Eq,
391                int(1),
392            ),
393            compare(col(Some("recent"), "id"), ComparisonOperator::Gt, int(100)),
394        );
395        let plan = plan_with_cte(outer);
396
397        let rewritten = PredicatePushdown.rewrite(&plan).unwrap();
398
399        // The outer WHERE is now empty; both conjuncts moved into the CTE.
400        assert!(rewritten.r#where.is_none());
401        let cte_where = rewritten.ctes.as_ref().unwrap()[0]
402            .query
403            .r#where
404            .as_ref()
405            .expect("CTE should have received the pushed conjuncts");
406        assert_eq!(conjunct_count(cte_where), 2);
407        // Qualifiers are stripped so the CTE body re-resolves them.
408        let pushed = super::analyze::split_conjuncts(cte_where);
409        for conjunct in &pushed {
410            for (table, _) in super::analyze::columns_in_predicate(conjunct) {
411                assert!(table.is_none(), "qualifier should be stripped inside CTE");
412            }
413        }
414    }
415
416    #[test]
417    fn pushdown_keeps_conjuncts_over_base_tables() {
418        // The outer FROM is a base table, not a CTE: nothing to push.
419        let plan = QueryPlan {
420            select: vec![column_projection(Some("users"), "id")],
421            from: FromClause {
422                table: "users".to_owned(),
423                alias: None,
424            },
425            r#where: Some(compare(
426                col(Some("users"), "active"),
427                ComparisonOperator::Eq,
428                int(1),
429            )),
430            group_by: None,
431            having: None,
432            order_by: None,
433            limit: None,
434            offset: None,
435            joins: None,
436            ctes: None,
437            distinct: false,
438            distinct_on: None,
439            set_operation: None,
440        };
441
442        let rewritten = PredicatePushdown.rewrite(&plan).unwrap();
443        assert_eq!(rewritten, plan, "no CTE means the plan is unchanged");
444    }
445
446    #[test]
447    fn pushdown_reduces_outer_conjunct_count() {
448        // WHERE recent.status = 1 AND some_base.flag = 1
449        // Only the first conjunct references the CTE.
450        let outer = and(
451            compare(
452                col(Some("recent"), "status"),
453                ComparisonOperator::Eq,
454                int(1),
455            ),
456            compare(col(Some("other"), "flag"), ComparisonOperator::Eq, int(1)),
457        );
458        let mut plan = plan_with_cte(outer);
459        // Add a joined base table `other` so the second conjunct is valid
460        // but not attributable to the CTE.
461        plan.joins = Some(vec![JoinClause {
462            join_type: JoinType::Inner,
463            right_table: FromClause {
464                table: "other".to_owned(),
465                alias: None,
466            },
467            on: compare(
468                col(Some("recent"), "user_id"),
469                ComparisonOperator::Eq,
470                col(Some("other"), "user_id"),
471            ),
472        }]);
473
474        let before = conjunct_count(plan.r#where.as_ref().unwrap());
475        let rewritten = PredicatePushdown.rewrite(&plan).unwrap();
476        let after = conjunct_count(rewritten.r#where.as_ref().unwrap());
477
478        assert_eq!(before, 2);
479        assert_eq!(after, 1, "the CTE conjunct should have moved out");
480        assert!(rewritten.ctes.as_ref().unwrap()[0].query.r#where.is_some());
481    }
482
483    // --- column pruning ------------------------------------------------
484
485    #[test]
486    fn pruning_drops_unreferenced_cte_columns() {
487        // The outer query only reads `recent.id`, so `user_id` and
488        // `status` can be pruned from the CTE.
489        let plan = plan_with_cte(compare(
490            col(Some("recent"), "id"),
491            ComparisonOperator::Gt,
492            int(0),
493        ));
494
495        let rewritten = ColumnPruning::new().rewrite(&plan).unwrap();
496        let cte_select = &rewritten.ctes.as_ref().unwrap()[0].query.select;
497        assert_eq!(cte_select.len(), 1);
498        assert_eq!(cte_select[0], column_projection(Some("orders"), "id"));
499    }
500
501    #[test]
502    fn pruning_preserves_primary_and_foreign_keys() {
503        // With a schema, the CTE's PK (`id`) and FK (`user_id`) survive
504        // even though the outer query only reads `status`.
505        let schema = Arc::new(SchemaSnapshot::new(
506            vec![TableSchema {
507                name: "orders".to_owned(),
508                columns: vec![
509                    ColumnSchema {
510                        name: "id".to_owned(),
511                        data_type: DataType::Int,
512                        nullable: false,
513                        description: None,
514                        is_primary_key: true,
515                        foreign_key: None,
516                    },
517                    ColumnSchema {
518                        name: "user_id".to_owned(),
519                        data_type: DataType::Int,
520                        nullable: false,
521                        description: None,
522                        is_primary_key: false,
523                        foreign_key: Some(ForeignKey {
524                            foreign_table: "users".to_owned(),
525                            foreign_column: "id".to_owned(),
526                        }),
527                    },
528                    ColumnSchema {
529                        name: "status".to_owned(),
530                        data_type: DataType::Int,
531                        nullable: false,
532                        description: None,
533                        is_primary_key: false,
534                        foreign_key: None,
535                    },
536                ],
537                description: None,
538                primary_key: Some(vec!["id".to_owned()]),
539            }],
540            SchemaMetadata::default(),
541        ));
542
543        let plan = plan_with_cte(compare(
544            col(Some("recent"), "status"),
545            ComparisonOperator::Eq,
546            int(1),
547        ));
548        // Outer query reads only `status`.
549        let mut plan = plan;
550        plan.select = vec![column_projection(Some("recent"), "status")];
551
552        let rewritten = ColumnPruning::with_schema(schema).rewrite(&plan).unwrap();
553        let cte_select = &rewritten.ctes.as_ref().unwrap()[0].query.select;
554        let kept: Vec<&str> = cte_select
555            .iter()
556            .filter_map(|projection| match projection {
557                Projection::Column { column, .. } => Some(column.as_str()),
558                _ => None,
559            })
560            .collect();
561
562        assert!(kept.contains(&"status"), "referenced column kept");
563        assert!(kept.contains(&"id"), "primary key preserved");
564        assert!(kept.contains(&"user_id"), "foreign key preserved");
565    }
566
567    #[test]
568    fn pruning_keeps_all_columns_under_unqualified_reference() {
569        // An unqualified column in the outer query is unattributable, so
570        // the pruner conservatively keeps every CTE column.
571        let mut plan = plan_with_cte(compare(col(None, "status"), ComparisonOperator::Eq, int(1)));
572        plan.select = vec![column_projection(None, "id")];
573
574        let rewritten = ColumnPruning::new().rewrite(&plan).unwrap();
575        assert_eq!(rewritten.ctes.as_ref().unwrap()[0].query.select.len(), 3);
576    }
577
578    // --- pipeline ------------------------------------------------------
579
580    #[test]
581    fn pipeline_applies_rules_in_order() {
582        // Fold `100 + 0` in the outer filter, push the CTE conjunct down,
583        // then prune unread CTE columns — all in one pass.
584        let outer = and(
585            compare(
586                col(Some("recent"), "id"),
587                ComparisonOperator::Gt,
588                Expression::BinaryOp {
589                    left: Box::new(int(100)),
590                    op: BinaryOperator::Add,
591                    right: Box::new(int(0)),
592                },
593            ),
594            compare(
595                col(Some("recent"), "status"),
596                ComparisonOperator::Eq,
597                int(1),
598            ),
599        );
600        let plan = plan_with_cte(outer);
601
602        let pipeline = RewriterPipeline::new()
603            .with(ConstantFolding)
604            .with(PredicatePushdown)
605            .with(ColumnPruning::new());
606        let rewritten = pipeline.rewrite(&plan).unwrap();
607
608        // Pushdown emptied the outer WHERE.
609        assert!(rewritten.r#where.is_none());
610
611        let cte = &rewritten.ctes.as_ref().unwrap()[0].query;
612        // Folding turned `100 + 0` into `100` before pushdown moved it in.
613        let cte_where = cte.r#where.as_ref().expect("conjuncts pushed into CTE");
614        assert_eq!(conjunct_count(cte_where), 2);
615        assert!(super::analyze::split_conjuncts(cte_where).iter().any(|p| {
616            matches!(
617                p,
618                Predicate::Comparison { right, .. } if *right == int(100)
619            )
620        }));
621
622        // Pruning kept only the columns the CTE now needs: `id` (outer
623        // select) and `status`/`id` (pushed filters).
624        assert!(cte.select.len() < 3, "at least one column pruned");
625    }
626
627    #[test]
628    fn empty_pipeline_is_identity() {
629        let plan = plan_with_cte(compare(
630            col(Some("recent"), "id"),
631            ComparisonOperator::Gt,
632            int(0),
633        ));
634        let pipeline = RewriterPipeline::new();
635        assert!(pipeline.is_empty());
636        assert_eq!(pipeline.rewrite(&plan).unwrap(), plan);
637    }
638
639    // --- QueryOptimizer orchestrator -------------------------------------
640
641    #[test]
642    fn query_optimizer_folds_constants() {
643        let plan = QueryPlan {
644            select: vec![Projection::Expr {
645                expression: Expression::BinaryOp {
646                    left: Box::new(Expression::Literal {
647                        value: serde_json::json!(20),
648                        data_type: DataType::Int,
649                    }),
650                    op: BinaryOperator::Add,
651                    right: Box::new(Expression::Literal {
652                        value: serde_json::json!(5),
653                        data_type: DataType::Int,
654                    }),
655                },
656                alias: Some("total".to_owned()),
657            }],
658            from: FromClause {
659                table: "t".to_owned(),
660                alias: None,
661            },
662            r#where: None,
663            group_by: None,
664            having: None,
665            order_by: None,
666            limit: None,
667            offset: None,
668            joins: None,
669            ctes: None,
670            distinct: false,
671            distinct_on: None,
672            set_operation: None,
673        };
674
675        let optimizer = QueryOptimizer::rewrites_only();
676        let rewritten = optimizer.optimize(&plan).unwrap();
677
678        assert_eq!(
679            rewritten.select[0],
680            Projection::Expr {
681                expression: Expression::Literal {
682                    value: serde_json::json!(25),
683                    data_type: DataType::Int,
684                },
685                alias: Some("total".to_owned()),
686            },
687        );
688    }
689
690    #[tokio::test]
691    async fn query_optimizer_async_runs_pipeline() {
692        let plan = plan_with_cte(compare(
693            col(Some("recent"), "id"),
694            ComparisonOperator::Gt,
695            int(0),
696        ));
697
698        let optimizer = QueryOptimizer::rewrites_only();
699        let rewritten = optimizer.optimize_async(&plan).await.unwrap();
700
701        // The pipeline should have folded nothing here (no constant
702        // expressions), but pushdown and pruning should still run.
703        assert!(!rewritten.select.is_empty());
704    }
705
706    #[tokio::test]
707    async fn query_optimizer_with_stats_creates_join_reorderer() {
708        use crate::statistics::DummyStatisticsProvider;
709
710        let stats = Arc::new(DummyStatisticsProvider::default());
711        let optimizer = QueryOptimizer::new(stats);
712
713        // A simple plan with no joins — the reorderer is a no-op, but the
714        // pipeline should still run without error.
715        let plan = QueryPlan {
716            select: vec![Projection::Column {
717                table: None,
718                column: "id".to_owned(),
719                alias: None,
720            }],
721            from: FromClause {
722                table: "users".to_owned(),
723                alias: None,
724            },
725            r#where: None,
726            group_by: None,
727            having: None,
728            order_by: None,
729            limit: None,
730            offset: None,
731            joins: None,
732            ctes: None,
733            distinct: false,
734            distinct_on: None,
735            set_operation: None,
736        };
737        let rewritten = optimizer.optimize_async(&plan).await.unwrap();
738        // The pipeline may rewrite constants or reorder, but the FROM
739        // table should be preserved.
740        assert_eq!(rewritten.from.table, "users");
741    }
742
743    // ------------------------------------------------------------------
744    // Security: pushdown must not push policy row filters into CTEs
745    // ------------------------------------------------------------------
746
747    #[test]
748    fn pushdown_does_not_push_policy_row_filter_into_cte() {
749        // A row filter predicate is a policy-enforced condition that the
750        // policy engine appends to the outer WHERE clause.  The optimizer
751        // must NOT push it into a CTE because that would duplicate the
752        // filter (once by the engine, once by the CTE body) and could
753        // change the semantics of outer joins.
754        //
755        // Simulate a policy filter: `tenant_id = 42` on the outer query.
756        let policy_filter = compare(col(None, "tenant_id"), ComparisonOperator::Eq, int(42));
757
758        // Build a plan with a CTE and an outer WHERE that contains both
759        // a user conjunct and the policy conjunct.
760        let plan = plan_with_cte(and(
761            policy_filter.clone(),
762            compare(col(Some("recent"), "id"), ComparisonOperator::Gt, int(0)),
763        ));
764
765        // Apply pushdown only.
766        let rewritten = PredicatePushdown.rewrite(&plan).unwrap();
767
768        // The user conjunct (`recent.id > 0`) may be pushed into the CTE,
769        // but the policy conjunct (`tenant_id = 42`) must stay in the
770        // outer WHERE because it references a column of the outer table,
771        // not the CTE.
772        let outer_where = rewritten.r#where.as_ref().unwrap();
773        let conjuncts = crate::optimizer::analyze::split_conjuncts(outer_where);
774        let has_policy_filter = conjuncts
775            .iter()
776            .any(|c| matches!(c, Predicate::Comparison { right, .. } if *right == int(42)));
777        assert!(
778            has_policy_filter,
779            "policy filter `tenant_id = 42` must remain in the outer WHERE"
780        );
781    }
782
783    // ------------------------------------------------------------------
784    // Security: column pruning must preserve PK/FK columns
785    // ------------------------------------------------------------------
786
787    #[test]
788    fn column_pruning_preserves_primary_and_foreign_keys() {
789        use crate::schema::ForeignKey;
790
791        // Build a schema snapshot where `orders` has a PK (`id`) and two
792        // FKs (`user_id` → `users.id`, `product_id` → `products.id`).
793        let schema = Arc::new(SchemaSnapshot::new(
794            vec![TableSchema {
795                name: "orders".to_owned(),
796                columns: vec![
797                    ColumnSchema {
798                        name: "id".to_owned(),
799                        data_type: DataType::Int,
800                        nullable: false,
801                        description: None,
802                        is_primary_key: true,
803                        foreign_key: None,
804                    },
805                    ColumnSchema {
806                        name: "user_id".to_owned(),
807                        data_type: DataType::Int,
808                        nullable: false,
809                        description: None,
810                        is_primary_key: false,
811                        foreign_key: Some(ForeignKey {
812                            foreign_table: "users".to_owned(),
813                            foreign_column: "id".to_owned(),
814                        }),
815                    },
816                    ColumnSchema {
817                        name: "product_id".to_owned(),
818                        data_type: DataType::Int,
819                        nullable: false,
820                        description: None,
821                        is_primary_key: false,
822                        foreign_key: Some(ForeignKey {
823                            foreign_table: "products".to_owned(),
824                            foreign_column: "id".to_owned(),
825                        }),
826                    },
827                    ColumnSchema {
828                        name: "status".to_owned(),
829                        data_type: DataType::String,
830                        nullable: false,
831                        description: None,
832                        is_primary_key: false,
833                        foreign_key: None,
834                    },
835                ],
836                description: None,
837                primary_key: Some(vec!["id".to_owned()]),
838            }],
839            SchemaMetadata::default(),
840        ));
841
842        // CTE that selects * from orders. The outer query only reads
843        // `status`.
844        let cte = CommonTableExpression {
845            name: "recent".to_owned(),
846            recursive: false,
847            query: Box::new(QueryPlan {
848                select: vec![
849                    Projection::Column {
850                        table: Some("orders".to_owned()),
851                        column: "id".to_owned(),
852                        alias: None,
853                    },
854                    Projection::Column {
855                        table: Some("orders".to_owned()),
856                        column: "user_id".to_owned(),
857                        alias: None,
858                    },
859                    Projection::Column {
860                        table: Some("orders".to_owned()),
861                        column: "product_id".to_owned(),
862                        alias: None,
863                    },
864                    Projection::Column {
865                        table: Some("orders".to_owned()),
866                        column: "status".to_owned(),
867                        alias: None,
868                    },
869                ],
870                from: FromClause {
871                    table: "orders".to_owned(),
872                    alias: None,
873                },
874                r#where: None,
875                group_by: None,
876                having: None,
877                order_by: None,
878                limit: None,
879                offset: None,
880                joins: None,
881                ctes: None,
882            distinct: false,
883            distinct_on: None,
884            set_operation: None,            }),
885        };
886
887        let plan = QueryPlan {
888            select: vec![Projection::Column {
889                table: Some("recent".to_owned()),
890                column: "status".to_owned(),
891                alias: None,
892            }],
893            from: FromClause {
894                table: "recent".to_owned(),
895                alias: None,
896            },
897            r#where: None,
898            group_by: None,
899            having: None,
900            order_by: None,
901            limit: None,
902            offset: None,
903            joins: None,
904            ctes: Some(vec![cte]),
905            distinct: false,
906            distinct_on: None,
907            set_operation: None,
908        };
909
910        let pruner = ColumnPruning::with_schema(schema);
911        let rewritten = pruner.rewrite(&plan).unwrap();
912
913        let cte_select = &rewritten.ctes.as_ref().unwrap()[0].query.select;
914        let cte_cols: Vec<&str> = cte_select
915            .iter()
916            .filter_map(|p| match p {
917                Projection::Column { column, .. } => Some(column.as_str()),
918                _ => None,
919            })
920            .collect();
921
922        // The CTE must still contain `id` (PK) and `user_id` + `product_id` (FKs),
923        // even though the outer query only reads `status`.
924        assert!(
925            cte_cols.contains(&"id"),
926            "PK column `id` must be preserved: got {cte_cols:?}"
927        );
928        assert!(
929            cte_cols.contains(&"user_id"),
930            "FK column `user_id` must be preserved: got {cte_cols:?}"
931        );
932        assert!(
933            cte_cols.contains(&"product_id"),
934            "FK column `product_id` must be preserved: got {cte_cols:?}"
935        );
936        // `status` should also be present since it's the only column
937        // the outer query explicitly selects.
938        assert!(
939            cte_cols.contains(&"status"),
940            "selected column `status` must be preserved: got {cte_cols:?}"
941        );
942    }
943
944    #[test]
945    fn repeat_until_stable_converges_in_one_round_when_already_stable() {
946        // A plan with no CTEs and no foldable expressions reaches fixpoint
947        // immediately.
948        let plan = QueryPlan {
949            select: vec![column_projection(None, "id")],
950            from: FromClause {
951                table: "t".to_owned(),
952                alias: None,
953            },
954            r#where: None,
955            group_by: None,
956            having: None,
957            order_by: None,
958            limit: None,
959            offset: None,
960            joins: None,
961            ctes: None,
962            distinct: false,
963            distinct_on: None,
964            set_operation: None,
965        };
966        let pipeline = RewriterPipeline::new()
967            .with(ConstantFolding)
968            .with(PredicatePushdown)
969            .with(ColumnPruning::new());
970        let result = pipeline.repeat_until_stable(&plan, 5).unwrap();
971        assert_eq!(result.select.len(), 1);
972    }
973
974    #[test]
975    fn repeat_until_stable_preserves_equivalence() {
976        // A plan with a foldable expression should still fold correctly
977        // under repeat_until_stable.
978        let plan = QueryPlan {
979            select: vec![Projection::Expr {
980                expression: Expression::BinaryOp {
981                    left: Box::new(Expression::Literal {
982                        value: 10.into(),
983                        data_type: DataType::Int,
984                    }),
985                    op: BinaryOperator::Add,
986                    right: Box::new(Expression::Literal {
987                        value: 20.into(),
988                        data_type: DataType::Int,
989                    }),
990                },
991                alias: Some("total".to_owned()),
992            }],
993            from: FromClause {
994                table: "t".to_owned(),
995                alias: None,
996            },
997            r#where: None,
998            group_by: None,
999            having: None,
1000            order_by: None,
1001            limit: None,
1002            offset: None,
1003            joins: None,
1004            ctes: None,
1005            distinct: false,
1006            distinct_on: None,
1007            set_operation: None,
1008        };
1009        let pipeline = RewriterPipeline::new().with(ConstantFolding);
1010        let result = pipeline.repeat_until_stable(&plan, 3).unwrap();
1011        assert_eq!(
1012            result.select[0],
1013            Projection::Expr {
1014                expression: Expression::Literal {
1015                    value: 30.into(),
1016                    data_type: DataType::Int
1017                },
1018                alias: Some("total".to_owned()),
1019            },
1020        );
1021    }
1022
1023    #[test]
1024    fn optimize_repeat_exposes_fixpoint_method() {
1025        let plan = QueryPlan {
1026            select: vec![column_projection(None, "id")],
1027            from: FromClause {
1028                table: "t".to_owned(),
1029                alias: None,
1030            },
1031            r#where: None,
1032            group_by: None,
1033            having: None,
1034            order_by: None,
1035            limit: None,
1036            offset: None,
1037            joins: None,
1038            ctes: None,
1039            distinct: false,
1040            distinct_on: None,
1041            set_operation: None,
1042        };
1043        let optimizer = QueryOptimizer::rewrites_only();
1044        let result = optimizer.optimize_repeat(&plan, 3).unwrap();
1045        assert_eq!(result.select.len(), 1);
1046    }
1047
1048    #[test]
1049    fn multi_layer_cte_pushdown_cascades_through_nested_ctes() {
1050        // Two CTEs where the outer one references the inner one:
1051        //   WITH
1052        //     cte2 AS (SELECT id, val FROM t2),
1053        //     cte1 AS (SELECT * FROM cte2)
1054        //   SELECT * FROM cte1 WHERE cte1.val > 10
1055        // The condition `cte1.val > 10` should be pushed into cte2.
1056        let cte2_body = QueryPlan {
1057            select: vec![
1058                column_projection(None, "id"),
1059                column_projection(None, "val"),
1060            ],
1061            from: FromClause {
1062                table: "t2".to_owned(),
1063                alias: None,
1064            },
1065            r#where: None,
1066            group_by: None,
1067            having: None,
1068            order_by: None,
1069            limit: None,
1070            offset: None,
1071            joins: None,
1072            ctes: None,
1073            distinct: false,
1074            distinct_on: None,
1075            set_operation: None,
1076        };
1077        let cte1_body = QueryPlan {
1078            select: vec![Projection::Star { table: None }],
1079            from: FromClause {
1080                table: "cte2".to_owned(),
1081                alias: None,
1082            },
1083            r#where: None,
1084            group_by: None,
1085            having: None,
1086            order_by: None,
1087            limit: None,
1088            offset: None,
1089            joins: None,
1090            ctes: None,
1091            distinct: false,
1092            distinct_on: None,
1093            set_operation: None,
1094        };
1095        let plan = QueryPlan {
1096            select: vec![Projection::Star { table: None }],
1097            from: FromClause {
1098                table: "cte1".to_owned(),
1099                alias: None,
1100            },
1101            r#where: Some(compare(
1102                col(Some("cte1"), "val"),
1103                ComparisonOperator::Gt,
1104                int(10),
1105            )),
1106            group_by: None,
1107            having: None,
1108            order_by: None,
1109            limit: None,
1110            offset: None,
1111            joins: None,
1112            ctes: Some(vec![
1113                CommonTableExpression {
1114                    name: "cte2".to_owned(),
1115                    recursive: false,
1116                    query: Box::new(cte2_body)
1117                },
1118                CommonTableExpression {
1119                    name: "cte1".to_owned(),
1120                    recursive: false,
1121                    query: Box::new(cte1_body)
1122                },
1123            ]),
1124            distinct: false,
1125            distinct_on: None,
1126            set_operation: None,
1127        };
1128
1129        let pipeline = RewriterPipeline::new().with(PredicatePushdown);
1130        let result = pipeline.rewrite(&plan).unwrap();
1131
1132        // The outer WHERE should be empty (condition was pushed down).
1133        assert!(
1134            result.r#where.is_none(),
1135            "outer WHERE should be empty after pushdown"
1136        );
1137
1138        // cte1's WHERE should be empty (condition was further pushed into cte2).
1139        let cte1 = result
1140            .ctes
1141            .as_ref()
1142            .unwrap()
1143            .iter()
1144            .find(|cte| cte.name == "cte1")
1145            .expect("cte1 should exist");
1146        assert!(
1147            cte1.query.r#where.is_none(),
1148            "cte1 WHERE should be empty after cascade pushdown: {:?}",
1149            cte1.query.r#where
1150        );
1151
1152        // cte2 should have the condition in its WHERE.
1153        let cte2 = result
1154            .ctes
1155            .as_ref()
1156            .unwrap()
1157            .iter()
1158            .find(|cte| cte.name == "cte2")
1159            .expect("cte2 should exist");
1160        assert!(
1161            cte2.query.r#where.is_some(),
1162            "cte2 should have the pushed condition: {:?}",
1163            cte2.query.r#where
1164        );
1165    }
1166
1167    #[test]
1168    fn multi_layer_cte_pushdown_with_alias() {
1169        // Same as above but cte1 uses an alias for cte2:
1170        //   WITH
1171        //     cte2 AS (SELECT id, val FROM t2),
1172        //     cte1 AS (SELECT * FROM cte2 AS inner_c)
1173        //   SELECT * FROM cte1 WHERE cte1.val > 10
1174        let cte2_body = QueryPlan {
1175            select: vec![
1176                column_projection(None, "id"),
1177                column_projection(None, "val"),
1178            ],
1179            from: FromClause {
1180                table: "t2".to_owned(),
1181                alias: None,
1182            },
1183            r#where: None,
1184            group_by: None,
1185            having: None,
1186            order_by: None,
1187            limit: None,
1188            offset: None,
1189            joins: None,
1190            ctes: None,
1191            distinct: false,
1192            distinct_on: None,
1193            set_operation: None,
1194        };
1195        let cte1_body = QueryPlan {
1196            select: vec![Projection::Star { table: None }],
1197            from: FromClause {
1198                table: "cte2".to_owned(),
1199                alias: Some("inner_c".to_owned()),
1200            },
1201            r#where: None,
1202            group_by: None,
1203            having: None,
1204            order_by: None,
1205            limit: None,
1206            offset: None,
1207            joins: None,
1208            ctes: None,
1209            distinct: false,
1210            distinct_on: None,
1211            set_operation: None,
1212        };
1213        let plan = QueryPlan {
1214            select: vec![Projection::Star { table: None }],
1215            from: FromClause {
1216                table: "cte1".to_owned(),
1217                alias: None,
1218            },
1219            r#where: Some(compare(
1220                col(Some("cte1"), "val"),
1221                ComparisonOperator::Gt,
1222                int(10),
1223            )),
1224            group_by: None,
1225            having: None,
1226            order_by: None,
1227            limit: None,
1228            offset: None,
1229            joins: None,
1230            ctes: Some(vec![
1231                CommonTableExpression {
1232                    name: "cte2".to_owned(),
1233                    recursive: false,
1234                    query: Box::new(cte2_body)
1235                },
1236                CommonTableExpression {
1237                    name: "cte1".to_owned(),
1238                    recursive: false,
1239                    query: Box::new(cte1_body)
1240                },
1241            ]),
1242            distinct: false,
1243            distinct_on: None,
1244            set_operation: None,
1245        };
1246
1247        let pipeline = RewriterPipeline::new().with(PredicatePushdown);
1248        let result = pipeline.rewrite(&plan).unwrap();
1249
1250        // The outer WHERE should be empty.
1251        assert!(result.r#where.is_none(), "outer WHERE should be empty");
1252
1253        // cte1's WHERE should be empty.
1254        let cte1 = result
1255            .ctes
1256            .as_ref()
1257            .unwrap()
1258            .iter()
1259            .find(|cte| cte.name == "cte1")
1260            .expect("cte1 should exist");
1261        assert!(
1262            cte1.query.r#where.is_none(),
1263            "cte1 WHERE should be empty after cascade: {:?}",
1264            cte1.query.r#where
1265        );
1266
1267        // cte2 should have the condition.
1268        let cte2 = result
1269            .ctes
1270            .as_ref()
1271            .unwrap()
1272            .iter()
1273            .find(|cte| cte.name == "cte2")
1274            .expect("cte2 should exist");
1275        assert!(
1276            cte2.query.r#where.is_some(),
1277            "cte2 should have the pushed condition: {:?}",
1278            cte2.query.r#where
1279        );
1280    }
1281}