Skip to main content

risingwave_frontend/optimizer/plan_node/generic/
changelog.rs

1// Copyright 2024 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 pretty_xmlish::{Pretty, Str, XmlNode};
16use risingwave_common::catalog::{Field, FieldDisplay, Schema};
17use risingwave_common::util::column_index_mapping::ColIndexMapping;
18
19use super::{DistillUnit, GenericPlanNode};
20use crate::OptimizerContextRef;
21use crate::optimizer::plan_node::stream::prelude::GenericPlanRef;
22use crate::optimizer::plan_node::utils::childless_record;
23use crate::optimizer::property::FunctionalDependencySet;
24use crate::utils::ColIndexMappingRewriteExt;
25
26pub const CHANGELOG_OP: &str = "changelog_op";
27pub const _CHANGELOG_ROW_ID: &str = "_changelog_row_id";
28#[derive(Debug, Clone, PartialEq, Eq, Hash)]
29pub struct ChangeLog<PlanRef> {
30    pub input: PlanRef,
31    /// Declared key column indices in the input schema. Changes sharing this key are
32    /// co-located, with deletes emitted before inserts within each epoch. Distinct stream
33    /// keys remain separate changes; this does not compact to one final change per declared key.
34    /// For upsert input, these columns must be a subset of the input stream key.
35    pub key_indices: Option<Vec<usize>>,
36    /// Explicit vnode distribution columns, independent of keyed changelog processing.
37    pub distribution_key_indices: Option<Vec<usize>>,
38    // If there is no op in the output result, it is false, example 'create materialized view mv1 as with sub as changelog from t1 select v1 from sub;'
39    pub need_op: bool,
40    // Before rewrite. If there is no changelog_row_id in the output result, it is false.
41    // After rewrite. It is always true.
42    pub need_changelog_row_id: bool,
43}
44impl<PlanRef: GenericPlanRef> DistillUnit for ChangeLog<PlanRef> {
45    fn distill_with_name<'a>(&self, name: impl Into<Str<'a>>) -> XmlNode<'a> {
46        let mut fields = Vec::with_capacity(1);
47
48        if let Some(key_indices) = &self.key_indices {
49            let key = Pretty::Array(
50                key_indices
51                    .iter()
52                    .map(|&index| {
53                        let field = &self.input.schema()[index];
54
55                        Pretty::display(&FieldDisplay(field))
56                    })
57                    .collect(),
58            );
59
60            fields.push(("key", key));
61        }
62
63        if let Some(indices) = &self.distribution_key_indices {
64            fields.push((
65                "distribution_key",
66                Pretty::Array(
67                    indices
68                        .iter()
69                        .map(|&index| Pretty::display(&FieldDisplay(&self.input.schema()[index])))
70                        .collect(),
71                ),
72            ));
73        }
74
75        childless_record(name, fields)
76    }
77}
78impl<PlanRef: GenericPlanRef> ChangeLog<PlanRef> {
79    pub fn new(
80        input: PlanRef,
81        key_indices: Option<Vec<usize>>,
82        distribution_key_indices: Option<Vec<usize>>,
83        need_op: bool,
84        need_changelog_row_id: bool,
85    ) -> Self {
86        ChangeLog {
87            input,
88            key_indices,
89            distribution_key_indices,
90            need_op,
91            need_changelog_row_id,
92        }
93    }
94
95    pub fn clone_with_input<OtherPlanRef>(&self, input: OtherPlanRef) -> ChangeLog<OtherPlanRef> {
96        ChangeLog {
97            input,
98            key_indices: self.key_indices.clone(),
99            distribution_key_indices: self.distribution_key_indices.clone(),
100            need_op: self.need_op,
101            need_changelog_row_id: self.need_changelog_row_id,
102        }
103    }
104
105    pub fn i2o_col_mapping(&self) -> ColIndexMapping {
106        let mut map = vec![None; self.input.schema().len()];
107        (0..self.input.schema().len()).for_each(|i| map[i] = Some(i));
108        ColIndexMapping::new(map, self.schema().len())
109    }
110}
111impl<PlanRef: GenericPlanRef> GenericPlanNode for ChangeLog<PlanRef> {
112    fn schema(&self) -> Schema {
113        let mut fields = self.input.schema().fields.clone();
114        if self.need_op {
115            fields.push(Field::with_name(
116                risingwave_common::types::DataType::Int16,
117                CHANGELOG_OP,
118            ));
119        }
120        if self.need_changelog_row_id {
121            fields.push(Field::with_name(
122                risingwave_common::types::DataType::Serial,
123                _CHANGELOG_ROW_ID,
124            ));
125        }
126        Schema::new(fields)
127    }
128
129    fn stream_key(&self) -> Option<Vec<usize>> {
130        if self.need_changelog_row_id {
131            let keys = vec![self.schema().len() - 1];
132            Some(keys)
133        } else {
134            None
135        }
136    }
137
138    fn ctx(&self) -> OptimizerContextRef {
139        self.input.ctx()
140    }
141
142    fn functional_dependency(&self) -> FunctionalDependencySet {
143        let i2o = self.i2o_col_mapping();
144        i2o.rewrite_functional_dependency_set(self.input.functional_dependency().clone())
145    }
146}