risingwave_frontend/optimizer/plan_node/
logical_changelog.rs1use itertools::Itertools;
16
17use super::expr_visitable::ExprVisitable;
18use super::generic::{_CHANGELOG_ROW_ID, CHANGELOG_OP, GenericPlanRef};
19use super::stream::StreamPlanNodeMetadata;
20use super::utils::impl_distill_by_unit;
21use super::{
22 BatchPlanRef, ColPrunable, ColumnPruningContext, ExprRewritable, Logical,
23 LogicalPlanRef as PlanRef, LogicalProject, PlanBase, PlanTreeNodeUnary, PredicatePushdown,
24 RewriteStreamContext, StreamChangeLog, StreamPlanRef, ToBatch, ToStream, ToStreamContext,
25 gen_filter_and_pushdown, generic,
26};
27use crate::error::ErrorCode::BindError;
28use crate::error::Result;
29use crate::optimizer::plan_node::generic::PhysicalPlanRef;
30use crate::optimizer::property::{Distribution, RequiredDist};
31use crate::utils::{ColIndexMapping, Condition};
32
33#[derive(Debug, Clone, PartialEq, Eq, Hash)]
34pub struct LogicalChangeLog {
35 pub base: PlanBase<Logical>,
36 core: generic::ChangeLog<PlanRef>,
37}
38
39impl LogicalChangeLog {
40 pub fn create(
41 input: PlanRef,
42 key_indices: Option<Vec<usize>>,
43 distribution_key_indices: Option<Vec<usize>>,
44 ) -> PlanRef {
45 Self::new(input, key_indices, distribution_key_indices, true, true).into()
46 }
47
48 pub fn new(
49 input: PlanRef,
50 key_indices: Option<Vec<usize>>,
51 distribution_key_indices: Option<Vec<usize>>,
52 need_op: bool,
53 need_changelog_row_id: bool,
54 ) -> Self {
55 let core = generic::ChangeLog::new(
56 input,
57 key_indices,
58 distribution_key_indices,
59 need_op,
60 need_changelog_row_id,
61 );
62 Self::with_core(core)
63 }
64
65 pub fn with_core(core: generic::ChangeLog<PlanRef>) -> Self {
66 let base = PlanBase::new_logical_with_core(&core);
67 LogicalChangeLog { base, core }
68 }
69}
70
71impl PlanTreeNodeUnary<Logical> for LogicalChangeLog {
72 fn input(&self) -> PlanRef {
73 self.core.input.clone()
74 }
75
76 fn clone_with_input(&self, input: PlanRef) -> Self {
77 let core = self.core.clone_with_input(input);
78
79 Self::with_core(core)
80 }
81
82 fn rewrite_with_input(
83 &self,
84 input: PlanRef,
85 input_col_change: ColIndexMapping,
86 ) -> (Self, ColIndexMapping) {
87 let key_indices = self
88 .core
89 .key_indices
90 .as_ref()
91 .map(|key| input_col_change.map_all(key));
92 let distribution_key_indices = self
93 .core
94 .distribution_key_indices
95 .as_ref()
96 .map(|key| input_col_change.map_all(key));
97 let changelog = Self::new(
98 input,
99 key_indices,
100 distribution_key_indices,
101 self.core.need_op,
102 true,
103 );
104
105 let out_col_change = if self.core.need_op {
106 let (mut output_vec, len) = input_col_change.into_parts();
107 output_vec.push(Some(len));
108 ColIndexMapping::new(output_vec, len + 1)
109 } else {
110 input_col_change
111 };
112
113 let (mut output_vec, len) = out_col_change.into_parts();
114 let out_col_change = if self.core.need_changelog_row_id {
115 output_vec.push(Some(len));
116 ColIndexMapping::new(output_vec, len + 1)
117 } else {
118 ColIndexMapping::new(output_vec, len + 1)
119 };
120
121 (changelog, out_col_change)
122 }
123}
124
125impl_plan_tree_node_for_unary! { Logical, LogicalChangeLog}
126impl_distill_by_unit!(LogicalChangeLog, core, "LogicalChangeLog");
127
128impl ExprRewritable<Logical> for LogicalChangeLog {}
129
130impl ExprVisitable for LogicalChangeLog {}
131
132impl PredicatePushdown for LogicalChangeLog {
133 fn predicate_pushdown(
134 &self,
135 predicate: Condition,
136 ctx: &mut super::PredicatePushdownContext,
137 ) -> PlanRef {
138 gen_filter_and_pushdown(self, predicate, Condition::true_cond(), ctx)
139 }
140}
141
142impl ColPrunable for LogicalChangeLog {
143 fn prune_col(&self, required_cols: &[usize], ctx: &mut ColumnPruningContext) -> PlanRef {
144 let fields = self.schema().fields();
145 let mut need_op = false;
146 let mut need_changelog_row_id = false;
147 let mut input_required_cols = required_cols
150 .iter()
151 .filter_map(|a| {
152 if let Some(f) = fields.get(*a) {
153 if f.name == CHANGELOG_OP {
154 need_op = true;
155 None
156 } else if f.name == _CHANGELOG_ROW_ID {
157 need_changelog_row_id = true;
158 None
159 } else {
160 Some(*a)
161 }
162 } else {
163 Some(*a)
164 }
165 })
166 .collect_vec();
167
168 if let Some(stream_key) = self.input().stream_key() {
172 for &key in stream_key {
173 if !input_required_cols.contains(&key) {
174 input_required_cols.push(key);
175 }
176 }
177 }
178
179 if let Some(key) = &self.core.key_indices {
181 for &index in key {
182 if !input_required_cols.contains(&index) {
183 input_required_cols.push(index);
184 }
185 }
186 }
187
188 if let Some(key) = &self.core.distribution_key_indices {
190 for &index in key {
191 if !input_required_cols.contains(&index) {
192 input_required_cols.push(index);
193 }
194 }
195 }
196
197 let new_input = self.input().prune_col(&input_required_cols, ctx);
198 let input_mapping = ColIndexMapping::with_remaining_columns(
199 &input_required_cols,
200 self.input().schema().len(),
201 );
202 let key_indices = self
203 .core
204 .key_indices
205 .as_ref()
206 .map(|key| input_mapping.map_all(key));
207
208 let distribution_key_indices = self
209 .core
210 .distribution_key_indices
211 .as_ref()
212 .map(|key| input_mapping.map_all(key));
213
214 let changelog: PlanRef = Self::new(
216 new_input,
217 key_indices,
218 distribution_key_indices,
219 need_op,
220 need_changelog_row_id,
221 )
222 .into();
223
224 let (mut output_mapping, new_output_len) = input_mapping.into_parts();
226
227 if self.core.need_op {
228 output_mapping.push(need_op.then_some(new_output_len));
229 }
230
231 if self.core.need_changelog_row_id {
232 output_mapping
233 .push(need_changelog_row_id.then_some(new_output_len + usize::from(need_op)));
234 }
235
236 let output_len = changelog.schema().len();
237 let output_mapping = ColIndexMapping::new(output_mapping, output_len);
238 let output_required_cols = output_mapping.map_all(required_cols);
239
240 if output_required_cols.iter().copied().eq(0..output_len) {
241 changelog
242 } else {
243 let output_mapping =
244 ColIndexMapping::with_remaining_columns(&output_required_cols, output_len);
245
246 LogicalProject::with_mapping(changelog, output_mapping).into()
247 }
248 }
249}
250
251impl ToBatch for LogicalChangeLog {
252 fn to_batch(&self) -> Result<BatchPlanRef> {
253 Err(BindError("With changelog cte only support with create mv/sink".to_owned()).into())
254 }
255}
256
257impl ToStream for LogicalChangeLog {
258 fn to_stream(&self, ctx: &mut ToStreamContext) -> Result<StreamPlanRef> {
259 let input = self.input().to_stream(ctx)?;
260
261 if let Some(key) = &self.core.key_indices {
262 if input.stream_kind().is_upsert()
265 && !key.iter().all(|i| input.expect_stream_key().contains(i))
266 {
267 return Err(BindError(
268 "When producing a changelog from an upsert stream, KEY must be the same as \
269 or a subset of the stream key. Materialize the input first to use other key columns."
270 .to_owned(),
271 )
272 .into());
273 }
274 }
275
276 let input = if let Some(key) = &self.core.distribution_key_indices {
277 RequiredDist::hash_shard(key).streaming_enforce_if_not_satisfies(input)?
278 } else if let Some(key) = &self.core.key_indices {
279 RequiredDist::hash_shard(key).streaming_enforce_if_not_satisfies(input)?
280 } else if matches!(input.distribution(), Distribution::SomeShard) {
281 RequiredDist::hash_shard(input.expect_stream_key())
282 .streaming_enforce_if_not_satisfies(input)?
283 } else {
284 input
285 };
286
287 let row_id_index = self.schema().fields().len() - 1;
288 let (distribution_keys, dist) = match input.distribution() {
292 Distribution::HashShard(distribution_keys)
293 | Distribution::UpstreamHashShard(distribution_keys, _) => (
294 distribution_keys.clone(),
295 Distribution::HashShard(vec![row_id_index]),
296 ),
297 Distribution::Single => (vec![], Distribution::Single),
298 dist => {
299 return Err(BindError(format!(
300 "ChangeLog requires input to be hash distributed, single, but got {:?}",
301 dist
302 ))
303 .into());
304 }
305 };
306 let core = self.core.clone_with_input(input);
307 let plan = StreamChangeLog::new_with_dist(
308 core,
309 dist,
310 distribution_keys.into_iter().map(|k| k as u32).collect(),
311 )
312 .into();
313
314 Ok(plan)
315 }
316
317 fn logical_rewrite_for_stream(
318 &self,
319 ctx: &mut RewriteStreamContext,
320 ) -> Result<(PlanRef, ColIndexMapping)> {
321 let (input, input_col_change) = self.input().logical_rewrite_for_stream(ctx)?;
322 let (changelog, out_col_change) = self.rewrite_with_input(input, input_col_change);
323 Ok((changelog.into(), out_col_change))
324 }
325}
326
327#[cfg(test)]
328mod tests {
329 use std::rc::Rc;
330
331 use risingwave_common::catalog::{CdcTableDesc, ColumnDesc, ColumnId, TableId};
332 use risingwave_common::id::SourceId;
333 use risingwave_common::types::DataType;
334 use risingwave_common::util::sort_util::{ColumnOrder, OrderType};
335 use risingwave_connector::source::cdc::CdcScanOptions;
336
337 use super::*;
338 use crate::optimizer::optimizer_context::OptimizerContext;
339 use crate::optimizer::plan_node::{BackfillType, LogicalCdcScan, PlanTreeNodeUnary};
340
341 #[test]
342 fn test_changelog_on_cdc_scan_enforces_hash_distribution() {
343 let desc = CdcTableDesc {
344 table_id: TableId::new(1),
345 source_id: SourceId::new(2),
346 external_table_name: "mydb.orders".to_owned(),
347 pk: vec![ColumnOrder::new(0, OrderType::ascending())],
348 pk_comparisons: vec![risingwave_common::catalog::CdcKeyComparison::Native],
349 columns: vec![
350 ColumnDesc::named("id", ColumnId::new(1), DataType::Int32),
351 ColumnDesc::named("payload", ColumnId::new(2), DataType::Varchar),
352 ],
353 stream_key: vec![0],
354 ..Default::default()
355 };
356 let scan = LogicalCdcScan::create(
357 "orders".to_owned(),
358 Rc::new(desc),
359 OptimizerContext::mock(),
360 CdcScanOptions {
361 disable_backfill: true,
362 ..Default::default()
363 },
364 );
365 let changelog = LogicalChangeLog::create(scan.clone().into(), None, None);
366 let stream = changelog
367 .to_stream(&mut ToStreamContext::new_with_backfill_type(
368 false,
369 BackfillType::Replicated,
370 ))
371 .unwrap();
372
373 let input = stream.as_stream_change_log().unwrap().input();
374 assert!(input.as_stream_exchange().is_some());
375 assert_eq!(input.distribution(), &Distribution::HashShard(vec![0]));
376
377 let changelog = LogicalChangeLog::create(scan.into(), None, None);
379 let pruned = changelog.prune_col(
380 &[1, 2, 3],
381 &mut ColumnPruningContext::new(changelog.clone()),
382 );
383 let stream = pruned
384 .to_stream(&mut ToStreamContext::new_with_backfill_type(
385 false,
386 BackfillType::Replicated,
387 ))
388 .unwrap();
389 let changelog = stream.as_stream_project().unwrap().input();
390 let input = changelog.as_stream_change_log().unwrap().input();
391 assert!(input.as_stream_exchange().is_some());
392 assert_eq!(input.distribution(), &Distribution::HashShard(vec![1]));
393 }
394}