Skip to main content

risingwave_stream/from_proto/
stream_cdc_scan.rs

1// Copyright 2023 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::sync::Arc;
16
17use anyhow::Context;
18use risingwave_common::catalog::{CdcKeyComparison, Schema};
19use risingwave_common::hash::VnodeBitmapExt;
20use risingwave_common::util::sort_util::OrderType;
21use risingwave_connector::source::cdc::CdcScanOptions;
22use risingwave_connector::source::cdc::external::{
23    ExternalCdcTableType, ExternalTableConfig, SchemaTableName,
24};
25use risingwave_pb::data::data_type::TypeName;
26use risingwave_pb::plan_common::ExternalTableDesc;
27use risingwave_pb::stream_plan::StreamCdcScanNode;
28
29use super::*;
30use crate::common::table::state_table::StateTableBuilder;
31use crate::executor::{CdcBackfillExecutor, ExternalStorageTable, ParallelizedCdcBackfillExecutor};
32use crate::task::cdc_progress::CdcProgressReporter;
33
34pub struct StreamCdcScanExecutorBuilder;
35
36impl_stream_node_body!(StreamCdcScan(StreamCdcScanNode) => StreamCdcScanExecutorBuilder);
37
38type DecodedTablePk = (Vec<OrderType>, Option<Vec<CdcKeyComparison>>, Vec<usize>);
39
40fn decode_table_pk(
41    table_desc: &ExternalTableDesc,
42    table_type: &ExternalCdcTableType,
43) -> StreamResult<DecodedTablePk> {
44    if let Some(table_pk) = &table_desc.pk_ordering {
45        let order_types = table_pk
46            .columns
47            .iter()
48            .map(|_| OrderType::ascending())
49            .collect_vec();
50        let comparisons = table_pk
51            .columns
52            .iter()
53            .map(|column| column.get_comparison().map(CdcKeyComparison::from_protobuf))
54            .try_collect()?;
55        let indices = table_pk
56            .columns
57            .iter()
58            .map(|column| column.pk_col_idx as usize)
59            .collect_vec();
60        Ok((order_types, Some(comparisons), indices))
61    } else {
62        let order_types = table_desc
63            .pk
64            .iter()
65            .map(|column| OrderType::from_protobuf(column.get_order_type().unwrap()))
66            .collect_vec();
67        let indices = table_desc
68            .pk
69            .iter()
70            .map(|column| column.column_index as usize)
71            .collect_vec();
72        // Legacy graphs do not retain MySQL signedness: signed and unsigned BIGINT stored as
73        // Int64 are indistinguishable until the reader checks upstream. Only Int64 PK columns
74        // can need unsigned reinterpretation; other types (including Decimal) use native ordering.
75        let mut needs_reader_comparisons = false;
76        if matches!(
77            table_type,
78            ExternalCdcTableType::Mysql | ExternalCdcTableType::Mariadb
79        ) {
80            for &idx in &indices {
81                if table_desc.columns[idx].get_column_type()?.get_type_name()? == TypeName::Int64 {
82                    needs_reader_comparisons = true;
83                    break;
84                }
85            }
86        }
87        let comparisons = (!needs_reader_comparisons)
88            .then(|| vec![CdcKeyComparison::Native; table_desc.pk.len()]);
89        Ok((order_types, comparisons, indices))
90    }
91}
92
93impl ExecutorBuilder for StreamCdcScanExecutorBuilder {
94    type Node = StreamCdcScanNode;
95
96    async fn new_boxed_executor(
97        params: ExecutorParams,
98        node: &Self::Node,
99        state_store: impl StateStore,
100    ) -> StreamResult<Executor> {
101        let [upstream]: [_; 1] = params.input.try_into().unwrap();
102
103        let output_indices = node
104            .output_indices
105            .iter()
106            .map(|&i| i as usize)
107            .collect_vec();
108
109        let table_desc: &ExternalTableDesc = node.get_cdc_table_desc()?;
110
111        let output_schema: Schema = table_desc.columns.iter().map(Into::into).collect();
112        assert_eq!(output_indices, (0..output_schema.len()).collect_vec());
113        assert_eq!(output_schema.data_types(), params.info.schema.data_types());
114
115        let properties = table_desc.connect_properties.clone();
116        let table_type = ExternalCdcTableType::from_properties(&properties);
117        let (table_pk_order_types, table_pk_comparisons, table_pk_indices) =
118            decode_table_pk(table_desc, &table_type)?;
119
120        let scan_options = node
121            .options
122            .as_ref()
123            .map(CdcScanOptions::from_proto)
124            .unwrap_or(CdcScanOptions {
125                disable_backfill: node.disable_backfill,
126                ..Default::default()
127            });
128        // Filter out additional columns to construct the external table schema
129        let table_schema: Schema = table_desc
130            .columns
131            .iter()
132            .filter(|col| {
133                col.additional_column
134                    .as_ref()
135                    .is_none_or(|a_col| a_col.column_type.is_none())
136            })
137            .map(Into::into)
138            .collect();
139
140        let schema_table_name = SchemaTableName::from_properties(&properties);
141        let table_config = ExternalTableConfig::try_from_btreemap(
142            properties.clone(),
143            table_desc.secret_refs.clone(),
144        )
145        .context("failed to parse external table config")?;
146
147        let database_name = table_config.database.clone();
148
149        let external_table = ExternalStorageTable::new(
150            table_desc.table_id,
151            schema_table_name,
152            database_name,
153            table_config,
154            table_type,
155            table_schema,
156            table_pk_order_types,
157            table_pk_comparisons,
158            table_pk_indices,
159        );
160
161        let output_columns = table_desc.columns.iter().map(Into::into).collect_vec();
162        if scan_options.is_parallelized_backfill() {
163            // Set state table's vnodes to None to allow splits to be assigned to any actors, without following vnode constraints.
164            let vnodes = None;
165            let state_table = StateTableBuilder::new(node.get_state_table()?, state_store, vnodes)
166                .enable_preload_all_rows_by_config(&params.config)
167                .build()
168                .await;
169            let progress = CdcProgressReporter::new(params.local_barrier_manager.clone());
170            let exec = ParallelizedCdcBackfillExecutor::new(
171                params.actor_context.clone(),
172                external_table,
173                upstream,
174                output_indices,
175                output_columns,
176                params.executor_stats,
177                state_table,
178                node.rate_limit,
179                scan_options,
180                properties,
181                Some(progress),
182            );
183            Ok((params.info, exec).into())
184        } else {
185            assert!(
186                params.vnode_bitmap.is_singleton(),
187                "cdc backfill should be singleton"
188            );
189            let vnodes = Some(Arc::new(params.vnode_bitmap));
190            let state_table = StateTableBuilder::new(node.get_state_table()?, state_store, vnodes)
191                .enable_preload_all_rows_by_config(&params.config)
192                .build()
193                .await;
194            let exec = CdcBackfillExecutor::new(
195                params.actor_context.clone(),
196                external_table,
197                upstream,
198                output_indices,
199                output_columns,
200                None,
201                params.executor_stats,
202                state_table,
203                node.rate_limit,
204                scan_options,
205                properties,
206            );
207            Ok((params.info, exec).into())
208        }
209    }
210}
211
212#[cfg(test)]
213mod tests {
214    use risingwave_common::catalog::{CdcKeyComparison, ColumnDesc};
215    use risingwave_common::types::DataType;
216    use risingwave_common::util::sort_util::{ColumnOrder, OrderType};
217    use risingwave_connector::source::cdc::external::ExternalCdcTableType;
218    use risingwave_pb::plan_common::cdc_key_ordering::{Column, Comparison};
219    use risingwave_pb::plan_common::{CdcKeyOrdering, ExternalTableDesc};
220
221    use super::decode_table_pk;
222
223    fn legacy_desc(pk_type: DataType) -> ExternalTableDesc {
224        ExternalTableDesc {
225            columns: vec![
226                ColumnDesc::unnamed(0.into(), DataType::Varchar).to_protobuf(),
227                ColumnDesc::unnamed(1.into(), DataType::Int64).to_protobuf(),
228                ColumnDesc::unnamed(2.into(), pk_type).to_protobuf(),
229            ],
230            pk: vec![
231                ColumnOrder::new(2, OrderType::descending()).to_protobuf(),
232                ColumnOrder::new(0, OrderType::ascending()).to_protobuf(),
233            ],
234            ..Default::default()
235        }
236    }
237
238    #[test]
239    fn test_decode_legacy_mysql_int64_pk_comparisons_as_unknown() {
240        let (order_types, comparisons, indices) =
241            decode_table_pk(&legacy_desc(DataType::Int64), &ExternalCdcTableType::Mysql).unwrap();
242
243        assert_eq!(
244            order_types,
245            vec![OrderType::descending(), OrderType::ascending()]
246        );
247        assert_eq!(comparisons, None);
248        assert_eq!(indices, vec![2, 0]);
249    }
250
251    #[test]
252    fn test_decode_legacy_mysql_non_int64_pk_comparisons_as_native() {
253        // An Int64 non-PK column must not require recovering comparison metadata.
254        for pk_type in [
255            DataType::Int16,
256            DataType::Int32,
257            DataType::Decimal,
258            DataType::Float32,
259            DataType::Float64,
260            DataType::Varchar,
261        ] {
262            let (order_types, comparisons, indices) =
263                decode_table_pk(&legacy_desc(pk_type), &ExternalCdcTableType::Mysql).unwrap();
264            assert_eq!(
265                order_types,
266                vec![OrderType::descending(), OrderType::ascending()]
267            );
268            assert_eq!(
269                comparisons,
270                Some(vec![CdcKeyComparison::Native, CdcKeyComparison::Native])
271            );
272            assert_eq!(indices, vec![2, 0]);
273        }
274    }
275
276    #[test]
277    fn test_decode_legacy_non_mysql_pk_comparisons_as_native() {
278        for table_type in [
279            ExternalCdcTableType::Postgres,
280            ExternalCdcTableType::SqlServer,
281            ExternalCdcTableType::Mock,
282        ] {
283            let (_, comparisons, _) =
284                decode_table_pk(&legacy_desc(DataType::Int64), &table_type).unwrap();
285            assert_eq!(
286                comparisons,
287                Some(vec![CdcKeyComparison::Native, CdcKeyComparison::Native])
288            );
289        }
290    }
291
292    #[test]
293    fn test_decode_new_pk_comparisons_and_column_order() {
294        let desc = ExternalTableDesc {
295            pk_ordering: Some(CdcKeyOrdering {
296                columns: vec![
297                    Column {
298                        pk_col_idx: 3,
299                        comparison: Comparison::UnsignedInt64 as i32,
300                    },
301                    Column {
302                        pk_col_idx: 1,
303                        comparison: Comparison::Native as i32,
304                    },
305                ],
306            }),
307            ..Default::default()
308        };
309
310        let (order_types, comparisons, indices) =
311            decode_table_pk(&desc, &ExternalCdcTableType::Mysql).unwrap();
312        assert_eq!(
313            order_types,
314            vec![OrderType::ascending(), OrderType::ascending()]
315        );
316        assert_eq!(
317            comparisons,
318            Some(vec![
319                CdcKeyComparison::UnsignedInt64,
320                CdcKeyComparison::Native,
321            ])
322        );
323        assert_eq!(indices, vec![3, 1]);
324    }
325}