risingwave_frontend/optimizer/plan_node/
logical_project.rs

1// Copyright 2025 RisingWave Labs
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::collections::{BTreeMap, HashSet};
16
17use fixedbitset::FixedBitSet;
18use itertools::Itertools;
19use pretty_xmlish::XmlNode;
20
21use super::generic::GenericPlanNode;
22use super::utils::{Distill, childless_record};
23use super::{
24    BatchProject, ColPrunable, ExprRewritable, Logical, PlanBase, PlanRef, PlanTreeNodeUnary,
25    PredicatePushdown, StreamMaterializedExprs, StreamProject, ToBatch, ToStream,
26    gen_filter_and_pushdown, generic,
27};
28use crate::error::Result;
29use crate::expr::{Expr, ExprImpl, ExprRewriter, ExprVisitor, InputRef, collect_input_refs};
30use crate::optimizer::plan_node::expr_visitable::ExprVisitable;
31use crate::optimizer::plan_node::generic::GenericPlanRef;
32use crate::optimizer::plan_node::{
33    ColumnPruningContext, PredicatePushdownContext, RewriteStreamContext, ToStreamContext,
34};
35use crate::optimizer::property::{Distribution, Order, RequiredDist};
36use crate::utils::{ColIndexMapping, ColIndexMappingRewriteExt, Condition, Substitute};
37
38/// `LogicalProject` computes a set of expressions from its input relation.
39#[derive(Debug, Clone, PartialEq, Eq, Hash)]
40pub struct LogicalProject {
41    pub base: PlanBase<Logical>,
42    core: generic::Project<PlanRef>,
43}
44
45impl LogicalProject {
46    pub fn create(input: PlanRef, exprs: Vec<ExprImpl>) -> PlanRef {
47        Self::new(input, exprs).into()
48    }
49
50    // TODO(kwannoel): We only need create/new don't keep both.
51    pub fn new(input: PlanRef, exprs: Vec<ExprImpl>) -> Self {
52        let core = generic::Project::new(exprs, input);
53        Self::with_core(core)
54    }
55
56    pub fn with_core(core: generic::Project<PlanRef>) -> Self {
57        let base = PlanBase::new_logical_with_core(&core);
58        LogicalProject { base, core }
59    }
60
61    pub fn o2i_col_mapping(&self) -> ColIndexMapping {
62        self.core.o2i_col_mapping()
63    }
64
65    pub fn i2o_col_mapping(&self) -> ColIndexMapping {
66        self.core.i2o_col_mapping()
67    }
68
69    /// Creates a `LogicalProject` which select some columns from the input.
70    ///
71    /// `mapping` should maps from `(0..input_fields.len())` to a consecutive range starting from 0.
72    ///
73    /// This is useful in column pruning when we want to add a project to ensure the output schema
74    /// is correct.
75    pub fn with_mapping(input: PlanRef, mapping: ColIndexMapping) -> Self {
76        Self::with_core(generic::Project::with_mapping(input, mapping))
77    }
78
79    /// Creates a `LogicalProject` which select some columns from the input.
80    pub fn with_out_fields(input: PlanRef, out_fields: &FixedBitSet) -> Self {
81        Self::with_core(generic::Project::with_out_fields(input, out_fields))
82    }
83
84    /// Creates a `LogicalProject` which select some columns from the input.
85    pub fn with_out_col_idx(input: PlanRef, out_fields: impl Iterator<Item = usize>) -> Self {
86        Self::with_core(generic::Project::with_out_col_idx(input, out_fields))
87    }
88
89    pub fn exprs(&self) -> &Vec<ExprImpl> {
90        &self.core.exprs
91    }
92
93    pub fn is_identity(&self) -> bool {
94        self.core.is_identity()
95    }
96
97    pub fn try_as_projection(&self) -> Option<Vec<usize>> {
98        self.core.try_as_projection()
99    }
100
101    pub fn decompose(self) -> (Vec<ExprImpl>, PlanRef) {
102        self.core.decompose()
103    }
104
105    pub fn is_all_inputref(&self) -> bool {
106        self.core.is_all_inputref()
107    }
108}
109
110impl PlanTreeNodeUnary for LogicalProject {
111    fn input(&self) -> PlanRef {
112        self.core.input.clone()
113    }
114
115    fn clone_with_input(&self, input: PlanRef) -> Self {
116        Self::new(input, self.exprs().clone())
117    }
118
119    fn rewrite_with_input(
120        &self,
121        input: PlanRef,
122        mut input_col_change: ColIndexMapping,
123    ) -> (Self, ColIndexMapping) {
124        let exprs = self
125            .exprs()
126            .clone()
127            .into_iter()
128            .map(|expr| input_col_change.rewrite_expr(expr))
129            .collect();
130        let proj = Self::new(input, exprs);
131        // change the input columns index will not change the output column index
132        let out_col_change = ColIndexMapping::identity(self.schema().len());
133        (proj, out_col_change)
134    }
135}
136
137impl_plan_tree_node_for_unary! {LogicalProject}
138
139impl Distill for LogicalProject {
140    fn distill<'a>(&self) -> XmlNode<'a> {
141        childless_record(
142            "LogicalProject",
143            self.core.fields_pretty(self.base.schema()),
144        )
145    }
146}
147
148impl ColPrunable for LogicalProject {
149    fn prune_col(&self, required_cols: &[usize], ctx: &mut ColumnPruningContext) -> PlanRef {
150        let input_col_num: usize = self.input().schema().len();
151        let input_required_cols = collect_input_refs(
152            input_col_num,
153            required_cols.iter().map(|i| &self.exprs()[*i]),
154        )
155        .ones()
156        .collect_vec();
157        let new_input = self.input().prune_col(&input_required_cols, ctx);
158        let mut mapping = ColIndexMapping::with_remaining_columns(
159            &input_required_cols,
160            self.input().schema().len(),
161        );
162        // Rewrite each InputRef with new index.
163        let exprs = required_cols
164            .iter()
165            .map(|&id| mapping.rewrite_expr(self.exprs()[id].clone()))
166            .collect();
167
168        // Reconstruct the LogicalProject.
169        LogicalProject::new(new_input, exprs).into()
170    }
171}
172
173impl ExprRewritable for LogicalProject {
174    fn has_rewritable_expr(&self) -> bool {
175        true
176    }
177
178    fn rewrite_exprs(&self, r: &mut dyn ExprRewriter) -> PlanRef {
179        let mut core = self.core.clone();
180        core.rewrite_exprs(r);
181        Self {
182            base: self.base.clone_with_new_plan_id(),
183            core,
184        }
185        .into()
186    }
187}
188
189impl ExprVisitable for LogicalProject {
190    fn visit_exprs(&self, v: &mut dyn ExprVisitor) {
191        self.core.visit_exprs(v);
192    }
193}
194
195impl PredicatePushdown for LogicalProject {
196    fn predicate_pushdown(
197        &self,
198        predicate: Condition,
199        ctx: &mut PredicatePushdownContext,
200    ) -> PlanRef {
201        // convert the predicate to one that references the child of the project
202        let mut subst = Substitute {
203            mapping: self.exprs().clone(),
204        };
205
206        let impure_mask = {
207            let mut impure_mask = FixedBitSet::with_capacity(self.exprs().len());
208            for (i, e) in self.exprs().iter().enumerate() {
209                impure_mask.set(i, e.is_impure())
210            }
211            impure_mask
212        };
213        // (with impure input, with pure input)
214        let (remained_cond, pushed_cond) = predicate.split_disjoint(&impure_mask);
215        let pushed_cond = pushed_cond.rewrite_expr(&mut subst);
216
217        gen_filter_and_pushdown(self, remained_cond, pushed_cond, ctx)
218    }
219}
220
221impl ToBatch for LogicalProject {
222    fn to_batch(&self) -> Result<PlanRef> {
223        self.to_batch_with_order_required(&Order::any())
224    }
225
226    fn to_batch_with_order_required(&self, required_order: &Order) -> Result<PlanRef> {
227        let input_order = self
228            .o2i_col_mapping()
229            .rewrite_provided_order(required_order);
230        let new_input = self.input().to_batch_with_order_required(&input_order)?;
231        let mut new_logical = self.core.clone();
232        new_logical.input = new_input;
233        let batch_project = BatchProject::new(new_logical);
234        required_order.enforce_if_not_satisfies(batch_project.into())
235    }
236}
237
238impl ToStream for LogicalProject {
239    fn to_stream_with_dist_required(
240        &self,
241        required_dist: &RequiredDist,
242        ctx: &mut ToStreamContext,
243    ) -> Result<PlanRef> {
244        let input_required = if required_dist.satisfies(&RequiredDist::AnyShard) {
245            RequiredDist::Any
246        } else {
247            let input_required = self
248                .o2i_col_mapping()
249                .rewrite_required_distribution(required_dist);
250            match input_required {
251                RequiredDist::PhysicalDist(dist) => match dist {
252                    Distribution::Single => RequiredDist::Any,
253                    _ => RequiredDist::PhysicalDist(dist),
254                },
255                _ => input_required,
256            }
257        };
258        let new_input = self
259            .input()
260            .to_stream_with_dist_required(&input_required, ctx)?;
261
262        let enable_materialized_exprs = self
263            .core
264            .ctx()
265            .session_ctx()
266            .config()
267            .streaming_enable_materialized_expressions();
268
269        let stream_plan = if enable_materialized_exprs {
270            // Extract impure functions to `MaterializedExprs` operator
271            let mut impure_field_names = BTreeMap::new();
272            let mut impure_expr_indices = HashSet::new();
273            let impure_exprs: Vec<_> = self
274                .exprs()
275                .iter()
276                .enumerate()
277                .filter_map(|(idx, expr)| {
278                    // Extract impure expressions
279                    if expr.is_impure() {
280                        impure_expr_indices.insert(idx);
281                        if let Some(name) = self.core.field_names.get(&idx) {
282                            impure_field_names.insert(idx, name.clone());
283                        }
284                        Some(expr.clone())
285                    } else {
286                        None
287                    }
288                })
289                .collect();
290
291            if !impure_exprs.is_empty() {
292                // Create `MaterializedExprs` for impure expressions
293                let mat_exprs_plan: PlanRef = StreamMaterializedExprs::new(
294                    new_input.clone(),
295                    impure_exprs,
296                    impure_field_names,
297                )
298                .into();
299
300                let input_len = new_input.schema().len();
301                let mut materialized_pos = 0;
302
303                // Create final expressions list with impure expressions replaced by `InputRef`s
304                let final_exprs = self
305                    .exprs()
306                    .iter()
307                    .enumerate()
308                    .map(|(idx, expr)| {
309                        if impure_expr_indices.contains(&idx) {
310                            let output_idx = input_len + materialized_pos;
311                            materialized_pos += 1;
312                            InputRef::new(output_idx, expr.return_type()).into()
313                        } else {
314                            expr.clone()
315                        }
316                    })
317                    .collect();
318
319                let core = generic::Project::new(final_exprs, mat_exprs_plan);
320                StreamProject::new(core).into()
321            } else {
322                // No impure expressions, create a regular `StreamProject`
323                let core = generic::Project::new(self.exprs().clone(), new_input);
324                StreamProject::new(core).into()
325            }
326        } else {
327            // Materialized expressions feature is not enabled, create a regular `StreamProject`
328            let core = generic::Project::new(self.exprs().clone(), new_input);
329            StreamProject::new(core).into()
330        };
331
332        required_dist.enforce_if_not_satisfies(stream_plan, &Order::any())
333    }
334
335    fn to_stream(&self, ctx: &mut ToStreamContext) -> Result<PlanRef> {
336        self.to_stream_with_dist_required(&RequiredDist::Any, ctx)
337    }
338
339    fn logical_rewrite_for_stream(
340        &self,
341        ctx: &mut RewriteStreamContext,
342    ) -> Result<(PlanRef, ColIndexMapping)> {
343        let (input, input_col_change) = self.input().logical_rewrite_for_stream(ctx)?;
344        let (proj, out_col_change) = self.rewrite_with_input(input.clone(), input_col_change);
345
346        // Add missing columns of `input_pk` into the select list.
347        let input_pk = input.expect_stream_key();
348        let i2o = proj.i2o_col_mapping();
349        let col_need_to_add = input_pk
350            .iter()
351            .cloned()
352            .filter(|i| i2o.try_map(*i).is_none());
353        let input_schema = input.schema();
354        let exprs =
355            proj.exprs()
356                .iter()
357                .cloned()
358                .chain(col_need_to_add.map(|idx| {
359                    InputRef::new(idx, input_schema.fields[idx].data_type.clone()).into()
360                }))
361                .collect();
362        let proj = Self::new(input, exprs);
363        // The added columns is at the end, so it will not change existing column indices.
364        // But the target size of `out_col_change` should be the same as the length of the new
365        // schema.
366        let (map, _) = out_col_change.into_parts();
367        let out_col_change = ColIndexMapping::new(map, proj.base.schema().len());
368        Ok((proj.into(), out_col_change))
369    }
370}
371
372#[cfg(test)]
373mod tests {
374
375    use risingwave_common::catalog::{Field, Schema};
376    use risingwave_common::types::DataType;
377    use risingwave_pb::expr::expr_node::Type;
378
379    use super::*;
380    use crate::expr::{FunctionCall, Literal, assert_eq_input_ref};
381    use crate::optimizer::optimizer_context::OptimizerContext;
382    use crate::optimizer::plan_node::LogicalValues;
383
384    #[tokio::test]
385    /// Pruning
386    /// ```text
387    /// Project(1, input_ref(2), input_ref(0)<5)
388    ///   TableScan(v1, v2, v3)
389    /// ```
390    /// with required columns `[1, 2]` will result in
391    /// ```text
392    /// Project(input_ref(1), input_ref(0)<5)
393    ///   TableScan(v1, v3)
394    /// ```
395    async fn test_prune_project() {
396        let ty = DataType::Int32;
397        let ctx = OptimizerContext::mock().await;
398        let fields: Vec<Field> = vec![
399            Field::with_name(ty.clone(), "v1"),
400            Field::with_name(ty.clone(), "v2"),
401            Field::with_name(ty.clone(), "v3"),
402        ];
403        let values = LogicalValues::new(
404            vec![],
405            Schema {
406                fields: fields.clone(),
407            },
408            ctx,
409        );
410        let project: PlanRef = LogicalProject::new(
411            values.into(),
412            vec![
413                ExprImpl::Literal(Box::new(Literal::new(None, ty.clone()))),
414                InputRef::new(2, ty.clone()).into(),
415                ExprImpl::FunctionCall(Box::new(
416                    FunctionCall::new(
417                        Type::LessThan,
418                        vec![
419                            ExprImpl::InputRef(Box::new(InputRef::new(0, ty.clone()))),
420                            ExprImpl::Literal(Box::new(Literal::new(None, ty))),
421                        ],
422                    )
423                    .unwrap(),
424                )),
425            ],
426        )
427        .into();
428
429        // Perform the prune
430        let required_cols = vec![1, 2];
431        let plan = project.prune_col(
432            &required_cols,
433            &mut ColumnPruningContext::new(project.clone()),
434        );
435
436        // Check the result
437        let project = plan.as_logical_project().unwrap();
438        assert_eq!(project.exprs().len(), 2);
439        assert_eq_input_ref!(&project.exprs()[0], 1);
440
441        let expr = project.exprs()[1].clone();
442        let call = expr.as_function_call().unwrap();
443        assert_eq_input_ref!(&call.inputs()[0], 0);
444
445        let values = project.input();
446        let values = values.as_logical_values().unwrap();
447        assert_eq!(values.schema().fields().len(), 2);
448        assert_eq!(values.schema().fields()[0], fields[0]);
449        assert_eq!(values.schema().fields()[1], fields[2]);
450    }
451}