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 UDFs to `MaterializedExprs` operator
271            let mut udf_field_names = BTreeMap::new();
272            let mut udf_expr_indices = HashSet::new();
273            let udf_exprs: Vec<_> = self
274                .exprs()
275                .iter()
276                .enumerate()
277                .filter_map(|(idx, expr)| {
278                    if expr.has_user_defined_function() {
279                        udf_expr_indices.insert(idx);
280                        if let Some(name) = self.core.field_names.get(&idx) {
281                            udf_field_names.insert(idx, name.clone());
282                        }
283                        Some(expr.clone())
284                    } else {
285                        None
286                    }
287                })
288                .collect();
289
290            if !udf_exprs.is_empty() {
291                // Create `MaterializedExprs` for UDFs
292                let mat_exprs_plan: PlanRef =
293                    StreamMaterializedExprs::new(new_input.clone(), udf_exprs, udf_field_names)
294                        .into();
295
296                let input_len = new_input.schema().len();
297                let mut udf_pos = 0;
298
299                // Create final expressions list with UDFs replaced by `InputRef`s
300                let final_exprs = self
301                    .exprs()
302                    .iter()
303                    .enumerate()
304                    .map(|(idx, expr)| {
305                        if udf_expr_indices.contains(&idx) {
306                            let output_idx = input_len + udf_pos;
307                            udf_pos += 1;
308                            InputRef::new(output_idx, expr.return_type()).into()
309                        } else {
310                            expr.clone()
311                        }
312                    })
313                    .collect();
314
315                let core = generic::Project::new(final_exprs, mat_exprs_plan);
316                StreamProject::new(core).into()
317            } else {
318                // No UDFs, create a regular `StreamProject`
319                let core = generic::Project::new(self.exprs().clone(), new_input);
320                StreamProject::new(core).into()
321            }
322        } else {
323            // Materialized expressions feature is not enabled, create a regular `StreamProject`
324            let core = generic::Project::new(self.exprs().clone(), new_input);
325            StreamProject::new(core).into()
326        };
327
328        required_dist.enforce_if_not_satisfies(stream_plan, &Order::any())
329    }
330
331    fn to_stream(&self, ctx: &mut ToStreamContext) -> Result<PlanRef> {
332        self.to_stream_with_dist_required(&RequiredDist::Any, ctx)
333    }
334
335    fn logical_rewrite_for_stream(
336        &self,
337        ctx: &mut RewriteStreamContext,
338    ) -> Result<(PlanRef, ColIndexMapping)> {
339        let (input, input_col_change) = self.input().logical_rewrite_for_stream(ctx)?;
340        let (proj, out_col_change) = self.rewrite_with_input(input.clone(), input_col_change);
341
342        // Add missing columns of `input_pk` into the select list.
343        let input_pk = input.expect_stream_key();
344        let i2o = proj.i2o_col_mapping();
345        let col_need_to_add = input_pk
346            .iter()
347            .cloned()
348            .filter(|i| i2o.try_map(*i).is_none());
349        let input_schema = input.schema();
350        let exprs =
351            proj.exprs()
352                .iter()
353                .cloned()
354                .chain(col_need_to_add.map(|idx| {
355                    InputRef::new(idx, input_schema.fields[idx].data_type.clone()).into()
356                }))
357                .collect();
358        let proj = Self::new(input, exprs);
359        // The added columns is at the end, so it will not change existing column indices.
360        // But the target size of `out_col_change` should be the same as the length of the new
361        // schema.
362        let (map, _) = out_col_change.into_parts();
363        let out_col_change = ColIndexMapping::new(map, proj.base.schema().len());
364        Ok((proj.into(), out_col_change))
365    }
366}
367
368#[cfg(test)]
369mod tests {
370
371    use risingwave_common::catalog::{Field, Schema};
372    use risingwave_common::types::DataType;
373    use risingwave_pb::expr::expr_node::Type;
374
375    use super::*;
376    use crate::expr::{FunctionCall, Literal, assert_eq_input_ref};
377    use crate::optimizer::optimizer_context::OptimizerContext;
378    use crate::optimizer::plan_node::LogicalValues;
379
380    #[tokio::test]
381    /// Pruning
382    /// ```text
383    /// Project(1, input_ref(2), input_ref(0)<5)
384    ///   TableScan(v1, v2, v3)
385    /// ```
386    /// with required columns `[1, 2]` will result in
387    /// ```text
388    /// Project(input_ref(1), input_ref(0)<5)
389    ///   TableScan(v1, v3)
390    /// ```
391    async fn test_prune_project() {
392        let ty = DataType::Int32;
393        let ctx = OptimizerContext::mock().await;
394        let fields: Vec<Field> = vec![
395            Field::with_name(ty.clone(), "v1"),
396            Field::with_name(ty.clone(), "v2"),
397            Field::with_name(ty.clone(), "v3"),
398        ];
399        let values = LogicalValues::new(
400            vec![],
401            Schema {
402                fields: fields.clone(),
403            },
404            ctx,
405        );
406        let project: PlanRef = LogicalProject::new(
407            values.into(),
408            vec![
409                ExprImpl::Literal(Box::new(Literal::new(None, ty.clone()))),
410                InputRef::new(2, ty.clone()).into(),
411                ExprImpl::FunctionCall(Box::new(
412                    FunctionCall::new(
413                        Type::LessThan,
414                        vec![
415                            ExprImpl::InputRef(Box::new(InputRef::new(0, ty.clone()))),
416                            ExprImpl::Literal(Box::new(Literal::new(None, ty))),
417                        ],
418                    )
419                    .unwrap(),
420                )),
421            ],
422        )
423        .into();
424
425        // Perform the prune
426        let required_cols = vec![1, 2];
427        let plan = project.prune_col(
428            &required_cols,
429            &mut ColumnPruningContext::new(project.clone()),
430        );
431
432        // Check the result
433        let project = plan.as_logical_project().unwrap();
434        assert_eq!(project.exprs().len(), 2);
435        assert_eq_input_ref!(&project.exprs()[0], 1);
436
437        let expr = project.exprs()[1].clone();
438        let call = expr.as_function_call().unwrap();
439        assert_eq_input_ref!(&call.inputs()[0], 0);
440
441        let values = project.input();
442        let values = values.as_logical_values().unwrap();
443        assert_eq!(values.schema().fields().len(), 2);
444        assert_eq!(values.schema().fields()[0], fields[0]);
445        assert_eq!(values.schema().fields()[1], fields[2]);
446    }
447}