Skip to main content

risingwave_connector/source/cdc/
mod.rs

1// Copyright 2022 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
15pub mod enumerator;
16pub mod external;
17pub mod jni_source;
18pub mod mariadb;
19pub mod mongodb;
20pub mod mysql;
21pub mod oracle;
22pub mod postgres;
23pub mod source;
24pub mod split;
25pub mod sql_server;
26
27use std::collections::{BTreeMap, HashMap, HashSet};
28use std::marker::PhantomData;
29
30use anyhow::anyhow;
31pub use enumerator::*;
32use itertools::Itertools;
33use risingwave_common::bail;
34use risingwave_common::id::{ActorId, SourceId};
35use risingwave_common::license::FeatureNotAvailable;
36use risingwave_common::secret::LocalSecretManager;
37use risingwave_pb::catalog::PbSource;
38use risingwave_pb::connector_service::{PbSourceType, PbTableSchema, SourceType, TableSchema};
39use risingwave_pb::plan_common::column_desc::GeneratedOrDefaultColumn;
40use risingwave_pb::plan_common::{ExternalTableDesc, PbEncodeType, PbFormatType};
41use risingwave_pb::secret::PbSecretRef;
42use risingwave_pb::source::{PbCdcTableSnapshotSplit, PbCdcTableSnapshotSplitsWithGeneration};
43use risingwave_pb::stream_plan::StreamCdcScanOptions;
44use simd_json::prelude::ArrayTrait;
45pub use source::*;
46
47use crate::enforce_secret::EnforceSecret;
48use crate::error::ConnectorResult;
49use crate::parser::NumericHandling;
50use crate::source::cdc::external::SchemaTableName;
51use crate::source::{CdcTableSnapshotSplitRaw, SourceProperties, SplitImpl, TryFromBTreeMap};
52use crate::{dispatch_cdc_source_type, for_all_classified_sources, impl_cdc_source_type};
53
54pub const CDC_CONNECTOR_NAME_SUFFIX: &str = "-cdc";
55pub const CDC_SNAPSHOT_MODE_KEY: &str = "debezium.snapshot.mode";
56pub const CDC_SNAPSHOT_BACKFILL: &str = "rw_cdc_backfill";
57pub const CDC_SHARING_MODE_KEY: &str = "rw.sharing.mode.enable";
58// User can set snapshot='false' to disable cdc backfill
59pub const CDC_BACKFILL_ENABLE_KEY: &str = "snapshot";
60pub const CDC_BACKFILL_SNAPSHOT_INTERVAL_KEY: &str = "snapshot.interval";
61pub const CDC_BACKFILL_SNAPSHOT_BATCH_SIZE_KEY: &str = "snapshot.batch_size";
62pub const CDC_BACKFILL_PARALLELISM: &str = "backfill.parallelism";
63pub const CDC_BACKFILL_NUM_ROWS_PER_SPLIT: &str = "backfill.num_rows_per_split";
64pub const CDC_BACKFILL_AS_EVEN_SPLITS: &str = "backfill.as_even_splits";
65pub const CDC_BACKFILL_SPLIT_PK_COLUMN_INDEX: &str = "backfill.split_pk_column_index";
66// We enable transaction for shared cdc source by default
67pub const CDC_TRANSACTIONAL_KEY: &str = "transactional";
68/// Comma-separated upstream columns to leave out of a CDC table created with `(*)`.
69pub const CDC_COLUMN_EXCLUDE_LIST: &str = "column.exclude.list";
70pub const CDC_WAIT_FOR_STREAMING_START_TIMEOUT: &str = "cdc.source.wait.streaming.start.timeout";
71pub const CDC_NEEDS_OFFSET_COMMIT_ON_CHECKPOINT_KEY: &str =
72    "cdc.source.needs.offset.commit.on.checkpoint";
73pub const CDC_BACKFILL_MAX_PARALLELISM: u32 = 256;
74
75// User can set strong-schema='true' to enable strong schema for mongo cdc source
76pub const CDC_MONGODB_STRONG_SCHEMA_KEY: &str = "strong_schema";
77
78pub const MYSQL_CDC_CONNECTOR: &str = Mysql::CDC_CONNECTOR_NAME;
79pub const MARIADB_CDC_CONNECTOR: &str = Mariadb::CDC_CONNECTOR_NAME;
80pub const POSTGRES_CDC_CONNECTOR: &str = Postgres::CDC_CONNECTOR_NAME;
81pub const MONGODB_CDC_CONNECTOR: &str = Mongodb::CDC_CONNECTOR_NAME;
82pub const SQL_SERVER_CDC_CONNECTOR: &str = SqlServer::CDC_CONNECTOR_NAME;
83pub const ORACLE_CDC_CONNECTOR: &str = Oracle::CDC_CONNECTOR_NAME;
84
85/// Build a unique CDC table identifier from a source ID and external table name
86pub fn build_cdc_table_id(source_id: SourceId, external_table_name: &str) -> String {
87    format!("{}.{}", source_id, external_table_name)
88}
89
90/// Parse the value of `column.exclude.list`, e.g. `'a, b'`.
91pub fn parse_cdc_column_exclude_list(list: &str) -> HashSet<String> {
92    list.split(',')
93        .map(|c| c.trim().to_owned())
94        .filter(|c| !c.is_empty())
95        .collect()
96}
97
98pub trait CdcSourceTypeTrait: Send + Sync + Clone + std::fmt::Debug + 'static {
99    const CDC_CONNECTOR_NAME: &'static str;
100    fn source_type() -> CdcSourceType;
101}
102
103/// Behavior switches.
104pub trait CdcSourceRuntimeFlags: CdcSourceTypeTrait {
105    /// When true, only shared sources are supported; otherwise only direct sources are supported.
106    const CAN_BACKFILL: bool = false;
107    /// When true, the planner may choose parallelized backfill.
108    const CAN_BACKFILL_IN_PARALLEL: bool = false;
109    /// When true, a shared source sets Debezium's `provide.transaction.metadata`, so that all rows
110    /// of one upstream transaction go into a single chunk.
111    const CAN_USE_TRANSACTION_METADATA: bool = false;
112    /// When true, the connector accepts `auto.schema.change = true`, which makes Debezium emit
113    /// schema change events that RisingWave applies to the CDC tables of the source. Set it only
114    /// when Debezium consumes the option for the connector and RisingWave can apply the resulting
115    /// DDL events.
116    const CAN_AUTO_SCHEMA_CHANGE: bool = false;
117    /// When true, the connector accepts `heartbeat.table.auto.initialize = true`, which makes
118    /// source validation create the heartbeat table named by `heartbeat.table.name` in the
119    /// upstream database if it does not exist yet.
120    const CAN_AUTO_INITIALIZE_HEARTBEAT_TABLE: bool = false;
121    /// When true, the source executor waits for a non-empty split offset before reporting the
122    /// initial CDC offset.
123    const NEEDS_NON_EMPTY_INITIAL_OFFSET: bool = false;
124    /// When true, the consumed offset is committed back to the upstream database on each
125    /// checkpoint via a JNI call. The CDC reader passes the flag to the Java engine, which then
126    /// holds back Debezium's acknowledgement of each record until that commit.
127    const NEEDS_OFFSET_COMMIT_ON_CHECKPOINT: bool = false;
128    /// When true, the Debezium JSON parser accepts a numeric value that arrives as a JSON string,
129    /// such as `"42"` for an integer column or `"123.45"` for a decimal column, and converts it to
130    /// the column type instead of rejecting it.
131    const NEEDS_PARSING_NUMBER_IN_DEBEZIUM_EVENT_AS_STRING: bool = false;
132}
133
134/// Checks the `CREATE` and `ALTER` statements of a CDC source connector.
135pub trait CdcSourceDdlValidator: CdcSourceRuntimeFlags {
136    /// Checks the `FORMAT ... ENCODE ...` clause of a `CREATE` statement.
137    fn check_format_encode(format: PbFormatType, encode: PbEncodeType) -> ConnectorResult<()> {
138        check_format_encode_inner(
139            Self::CDC_CONNECTOR_NAME,
140            format,
141            encode,
142            &[
143                (PbFormatType::Debezium, &[PbEncodeType::Json]),
144                // support source stream job
145                (PbFormatType::Plain, &[PbEncodeType::Json]),
146            ],
147        )
148    }
149
150    /// Checks an additional column type in the `INCLUDE` clause of a `CREATE` statement, such as
151    /// `timestamp` in `INCLUDE timestamp AS ts`.
152    fn check_include_column(additional_column_type: &str) -> ConnectorResult<()> {
153        bail!(
154            "additional column type {} is not supported for connector {}, which accepts no additional column",
155            additional_column_type,
156            Self::CDC_CONNECTOR_NAME
157        )
158    }
159
160    /// Checks the `WITH (...)` options of a `CREATE` statement, and fills in the options that the
161    /// CDC source generates when they are omitted, such as a random `slot.name` for Postgres.
162    /// The connector node later renders the filled options into the Debezium config through the
163    /// `.properties` template of the CDC source. An override calls [`check_common_with_options`]
164    /// first.
165    fn check_and_fill_create_with_options(
166        props: &mut BTreeMap<String, String>,
167        secret_refs: &BTreeMap<String, PbSecretRef>,
168    ) -> ConnectorResult<()> {
169        check_common_with_options::<Self>(props, secret_refs)
170    }
171
172    /// Checks that the license allows the CDC source.
173    fn check_license() -> Result<(), FeatureNotAvailable> {
174        Ok(())
175    }
176
177    /// Checks that `ALTER SOURCE ... CONNECTOR WITH (...)` only changes options that a running
178    /// CDC source can apply. An override calls [`check_common_with_options`] first.
179    fn check_alter_with_options(
180        props: &BTreeMap<String, String>,
181        secret_refs: &BTreeMap<String, PbSecretRef>,
182    ) -> ConnectorResult<()> {
183        check_common_with_options::<Self>(props, secret_refs)
184    }
185}
186
187/// Handles the identifiers of upstream objects of a CDC source connector, such as tables and
188/// columns: how the connector spells them, quotes them, and how Debezium names them.
189// TODO(#27225): move the remaining per-connector identifier handling in as trait methods.
190pub trait CdcSourceExternalTableIdentifier: CdcSourceTypeTrait {
191    /// Returns the canonical identifier of the external table that the connect properties of a
192    /// CDC table point to: the part of the Debezium topic name of the table's change events that
193    /// the source reader keeps as `_rw_table_name`. A CDC table filters the change events of its
194    /// source by this identifier, and its `cdc_table_id` is built from it.
195    fn canonical_name(connect_properties: &BTreeMap<String, String>) -> String {
196        let SchemaTableName {
197            schema_name,
198            table_name,
199        } = SchemaTableName::from_properties(connect_properties);
200        format!("{schema_name}.{table_name}")
201    }
202
203    /// Splits a `.`-separated name, such as the one in the `TABLE '...'` clause of a CDC table,
204    /// into its identifiers, following the connector's quoting syntax. Returns `None` if the name
205    /// is malformed.
206    fn split_quoted_identifier(name: &str) -> Option<Vec<String>> {
207        split_quoted_identifier_inner(name, '"', '"')
208    }
209}
210
211/// Splits a `.`-separated name into its identifiers. An identifier wrapped in `open` and `close`
212/// may contain `.`, and a doubled `close` inside it stands for one `close`, e.g. `"a.b"` and
213/// `"a""b"` for Postgres, `[a.b]` and `[a]]b]` for SQL Server. Returns `None` if the name is
214/// malformed.
215pub fn split_quoted_identifier_inner(name: &str, open: char, close: char) -> Option<Vec<String>> {
216    let mut parts = vec![];
217    let mut current = String::new();
218    let mut chars = name.chars().peekable();
219    let mut in_quote = false;
220    let mut just_closed_quote = false;
221
222    while let Some(ch) = chars.next() {
223        if in_quote {
224            if ch == close {
225                if chars.peek() == Some(&close) {
226                    current.push(close);
227                    chars.next();
228                } else {
229                    in_quote = false;
230                    just_closed_quote = true;
231                }
232            } else {
233                current.push(ch);
234            }
235        } else {
236            match ch {
237                '.' => {
238                    if current.is_empty() {
239                        return None;
240                    }
241                    parts.push(std::mem::take(&mut current));
242                    just_closed_quote = false;
243                }
244                _ if ch == open && current.is_empty() => in_quote = true,
245                _ if ch == open || ch == close || just_closed_quote => return None,
246                _ => current.push(ch),
247            }
248        }
249    }
250
251    if in_quote || current.is_empty() {
252        return None;
253    }
254    parts.push(current);
255    Some(parts)
256}
257
258const HEARTBEAT_TABLE_AUTO_INITIALIZE_KEY: &str = "heartbeat.table.auto.initialize";
259
260/// Checks the `WITH (...)` options that every CDC source accepts, on both `CREATE` and `ALTER`.
261/// Options that only some connectors support are checked against the runtime flags of `T`. An
262/// option given as a `SECRET` in `secret_refs` is checked by its resolved value, which an error
263/// never shows.
264pub fn check_common_with_options<T: CdcSourceRuntimeFlags>(
265    props: &BTreeMap<String, String>,
266    secret_refs: &BTreeMap<String, PbSecretRef>,
267) -> ConnectorResult<()> {
268    let value_of = |key: &str| -> ConnectorResult<Option<String>> {
269        Ok(match secret_refs.get(key) {
270            Some(secret_ref) => Some(LocalSecretManager::global().fill_secret(*secret_ref)?),
271            None => props.get(key).cloned(),
272        })
273    };
274    let shown = |key: &str, value: String| {
275        if secret_refs.contains_key(key) {
276            "<secret>".to_owned()
277        } else {
278            value
279        }
280    };
281    // RisingWave consumes schema-less JSON from Debezium and cannot reconstruct the scale of
282    // binary logical decimals emitted by `precise`. `double` can lose precision, so an explicit
283    // override must retain the common `string` default from `debezium.properties`.
284    if let Some(mode) = value_of("debezium.decimal.handling.mode")?
285        && mode != "string"
286    {
287        bail!(
288            "'debezium.decimal.handling.mode' must be 'string', got: '{}'",
289            shown("debezium.decimal.handling.mode", mode)
290        );
291    }
292    for key in [
293        CDC_WAIT_FOR_STREAMING_START_TIMEOUT,
294        "debezium.max.queue.size",
295    ] {
296        if let Some(value) = value_of(key)?
297            && value.parse::<u32>().is_err()
298        {
299            bail!("Invalid value `{}` for `{key}`", shown(key, value));
300        }
301    }
302    // Debezium reads the interval as a signed 32-bit integer.
303    if let Some(value) = value_of("debezium.heartbeat.interval.ms")?
304        && !value.parse::<i32>().is_ok_and(|interval| interval > 0)
305    {
306        bail!(
307            "'debezium.heartbeat.interval.ms' must be a positive integer, got: '{}'",
308            shown("debezium.heartbeat.interval.ms", value)
309        );
310    }
311    if let Some(value) = value_of(HEARTBEAT_TABLE_AUTO_INITIALIZE_KEY)?
312        && value.parse::<bool>().map_err(|_| {
313            anyhow!("'{HEARTBEAT_TABLE_AUTO_INITIALIZE_KEY}' must be 'true' or 'false'")
314        })?
315        && !T::CAN_AUTO_INITIALIZE_HEARTBEAT_TABLE
316    {
317        bail!(
318            "'{HEARTBEAT_TABLE_AUTO_INITIALIZE_KEY}=true' is not supported for connector {}",
319            T::CDC_CONNECTOR_NAME
320        );
321    }
322    Ok(())
323}
324
325pub fn check_format_encode_inner(
326    connector_name: &str,
327    format: PbFormatType,
328    encode: PbEncodeType,
329    compatible_formats: &[(PbFormatType, &[PbEncodeType])],
330) -> ConnectorResult<()> {
331    let Some((_, compatible_encodes)) = compatible_formats.iter().find(|(f, _)| *f == format)
332    else {
333        bail!(
334            "connector {} does not support format {:?}",
335            connector_name,
336            format
337        );
338    };
339    if !compatible_encodes.contains(&encode) {
340        bail!(
341            "connector {} does not support format {:?} with encode {:?}",
342            connector_name,
343            format,
344            encode
345        );
346    }
347    Ok(())
348}
349
350pub fn check_include_column_inner(
351    connector_name: &str,
352    additional_column_type: &str,
353    compatible_additional_column_types: &[&str],
354) -> ConnectorResult<()> {
355    if !compatible_additional_column_types.contains(&additional_column_type) {
356        bail!(
357            "additional column type {} is not supported for connector {}, acceptable column types: {:?}",
358            additional_column_type,
359            connector_name,
360            compatible_additional_column_types
361        );
362    }
363    Ok(())
364}
365
366pub fn check_alter_with_options_inner(
367    connector_name: &str,
368    props: &BTreeMap<String, String>,
369    secret_refs: &BTreeMap<String, PbSecretRef>,
370    allowed_keys: &[&str],
371) -> ConnectorResult<()> {
372    if let Some(key) = props
373        .keys()
374        .chain(secret_refs.keys())
375        .find(|key| !allowed_keys.contains(&key.as_str()))
376    {
377        bail!(
378            "Field '{}' is not allowed to be altered on the fly for connector: {}",
379            key,
380            connector_name
381        );
382    }
383    Ok(())
384}
385
386for_all_classified_sources!(impl_cdc_source_type);
387
388impl<'a> From<&'a str> for CdcSourceType {
389    fn from(name: &'a str) -> Self {
390        match name {
391            MYSQL_CDC_CONNECTOR => CdcSourceType::Mysql,
392            MARIADB_CDC_CONNECTOR => CdcSourceType::Mariadb,
393            POSTGRES_CDC_CONNECTOR => CdcSourceType::Postgres,
394            MONGODB_CDC_CONNECTOR => CdcSourceType::Mongodb,
395            SQL_SERVER_CDC_CONNECTOR => CdcSourceType::SqlServer,
396            ORACLE_CDC_CONNECTOR => CdcSourceType::Oracle,
397            _ => CdcSourceType::Unspecified,
398        }
399    }
400}
401
402impl CdcSourceType {
403    pub fn as_str_name(&self) -> &str {
404        match self {
405            CdcSourceType::Mysql => "MySQL",
406            CdcSourceType::Mariadb => "MariaDB",
407            CdcSourceType::Postgres => "Postgres",
408            CdcSourceType::Mongodb => "MongoDB",
409            CdcSourceType::SqlServer => "SQL Server",
410            CdcSourceType::Oracle => "Oracle",
411            CdcSourceType::Unspecified => "Unspecified",
412        }
413    }
414
415    /// Returns how the Debezium JSON parser handles the numeric values in the change events of
416    /// this connector.
417    pub fn debezium_numeric_handling(&self) -> NumericHandling {
418        NumericHandling::Relax {
419            string_parsing: dispatch_cdc_source_type!(
420                self,
421                T,
422                T::NEEDS_PARSING_NUMBER_IN_DEBEZIUM_EVENT_AS_STRING,
423                false
424            ),
425        }
426    }
427}
428
429#[derive(Clone, Debug, Default)]
430pub struct CdcProperties<T: CdcSourceTypeTrait> {
431    /// Properties specified in the WITH clause by user
432    pub properties: BTreeMap<String, String>,
433
434    /// Schema of the source specified by users
435    pub table_schema: TableSchema,
436
437    /// Whether it is created by a cdc source job
438    pub is_cdc_source_job: bool,
439
440    /// For validation purpose, mark if the table is a backfill cdc table
441    pub is_backfill_table: bool,
442
443    pub _phantom: PhantomData<T>,
444}
445
446pub fn table_schema_exclude_additional_columns(table_schema: &TableSchema) -> TableSchema {
447    TableSchema {
448        columns: table_schema
449            .columns
450            .iter()
451            .filter(|col| {
452                col.additional_column
453                    .as_ref()
454                    .is_some_and(|val| val.column_type.is_none())
455            })
456            .cloned()
457            .collect(),
458        pk_indices: table_schema.pk_indices.clone(),
459    }
460}
461
462impl<T: CdcSourceTypeTrait> TryFromBTreeMap for CdcProperties<T> {
463    fn try_from_btreemap(
464        properties: BTreeMap<String, String>,
465        _deny_unknown_fields: bool,
466    ) -> ConnectorResult<Self> {
467        let is_share_source: bool = properties
468            .get(CDC_SHARING_MODE_KEY)
469            .is_some_and(|v| v == "true");
470        Ok(CdcProperties {
471            properties,
472            table_schema: Default::default(),
473            // TODO(siyuan): use serde to deserialize input hashmap
474            is_cdc_source_job: is_share_source,
475            is_backfill_table: false,
476            _phantom: PhantomData,
477        })
478    }
479}
480
481impl<T: CdcSourceTypeTrait> EnforceSecret for CdcProperties<T> {} // todo: enforce jdbc like properties
482
483impl<T: CdcSourceTypeTrait> SourceProperties for CdcProperties<T>
484where
485    DebeziumCdcSplit<T>: TryFrom<SplitImpl, Error = crate::error::ConnectorError> + Into<SplitImpl>,
486    DebeziumSplitEnumerator<T>: ListCdcSplits<CdcSourceType = T> + enumerator::CdcMonitor,
487{
488    type Split = DebeziumCdcSplit<T>;
489    type SplitEnumerator = DebeziumSplitEnumerator<T>;
490    type SplitReader = CdcSplitReader<T>;
491
492    const SOURCE_NAME: &'static str = T::CDC_CONNECTOR_NAME;
493
494    fn init_from_pb_source(&mut self, source: &PbSource) {
495        let pk_indices = source
496            .pk_column_ids
497            .iter()
498            .map(|&id| {
499                source
500                    .columns
501                    .iter()
502                    .position(|col| col.column_desc.as_ref().unwrap().column_id == id)
503                    .unwrap() as u32
504            })
505            .collect_vec();
506
507        let table_schema = PbTableSchema {
508            columns: source
509                .columns
510                .iter()
511                .flat_map(|col| &col.column_desc)
512                .filter(|col| {
513                    !matches!(
514                        col.generated_or_default_column,
515                        Some(GeneratedOrDefaultColumn::GeneratedColumn(_))
516                    )
517                })
518                .cloned()
519                .collect(),
520            pk_indices,
521        };
522        self.table_schema = table_schema;
523        if let Some(info) = source.info.as_ref() {
524            self.is_cdc_source_job = info.is_shared();
525        }
526    }
527
528    fn init_from_pb_cdc_table_desc(&mut self, table_desc: &ExternalTableDesc) {
529        let table_schema = TableSchema {
530            columns: table_desc
531                .columns
532                .iter()
533                .filter(|col| {
534                    !matches!(
535                        col.generated_or_default_column,
536                        Some(GeneratedOrDefaultColumn::GeneratedColumn(_))
537                    )
538                })
539                .cloned()
540                .collect(),
541            pk_indices: table_desc.stream_key.clone(),
542        };
543
544        self.table_schema = table_schema;
545        self.is_cdc_source_job = false;
546        self.is_backfill_table = true;
547    }
548}
549
550impl<T: CdcSourceTypeTrait> crate::source::UnknownFields for CdcProperties<T> {
551    fn unknown_fields(&self) -> HashMap<String, String> {
552        // FIXME: CDC does not handle unknown fields yet
553        HashMap::new()
554    }
555}
556
557impl<T: CdcSourceTypeTrait> CdcProperties<T> {
558    pub fn get_source_type_pb(&self) -> SourceType {
559        SourceType::from(T::source_type())
560    }
561}
562
563pub const INVALID_CDC_SPLIT_ASSIGNMENT_GENERATION_ID: u64 = 0;
564pub const INITIAL_CDC_SPLIT_ASSIGNMENT_GENERATION_ID: u64 = 1;
565
566#[derive(Clone, Debug, PartialEq, Default)]
567pub struct CdcTableSnapshotSplitAssignmentWithGeneration {
568    pub splits: HashMap<ActorId, (Vec<CdcTableSnapshotSplitRaw>, u64)>,
569}
570
571impl CdcTableSnapshotSplitAssignmentWithGeneration {
572    pub fn new(splits: HashMap<ActorId, (Vec<CdcTableSnapshotSplitRaw>, u64)>) -> Self {
573        Self { splits }
574    }
575
576    pub fn empty() -> Self {
577        Self {
578            splits: HashMap::default(),
579        }
580    }
581}
582
583pub fn build_cdc_table_snapshot_split(s: &CdcTableSnapshotSplitRaw) -> PbCdcTableSnapshotSplit {
584    PbCdcTableSnapshotSplit {
585        split_id: s.split_id,
586        left_bound_inclusive: s.left_bound_inclusive.clone(),
587        right_bound_exclusive: s.right_bound_exclusive.clone(),
588    }
589}
590
591pub fn build_actor_cdc_table_snapshot_splits_with_generation(
592    pb_cdc_table_snapshot_split_assignment: PbCdcTableSnapshotSplitsWithGeneration,
593) -> CdcTableSnapshotSplitAssignmentWithGeneration {
594    let splits = pb_cdc_table_snapshot_split_assignment
595        .splits
596        .into_iter()
597        .map(|(actor_id, splits)| {
598            let generation = splits.generation;
599            let splits = splits
600                .splits
601                .into_iter()
602                .map(|s| CdcTableSnapshotSplitRaw {
603                    split_id: s.split_id,
604                    left_bound_inclusive: s.left_bound_inclusive,
605                    right_bound_exclusive: s.right_bound_exclusive,
606                })
607                .collect();
608            (actor_id, (splits, generation))
609        })
610        .collect();
611    CdcTableSnapshotSplitAssignmentWithGeneration { splits }
612}
613
614#[derive(Debug, Clone, Hash, PartialEq)]
615pub struct CdcScanOptions {
616    /// Used by Used in non-parallel backfill, i.e. backfill V1.
617    pub disable_backfill: bool,
618    /// Used by non-parallelized backfill. The frequency of snapshot read resets for consuming the WAL backlog.
619    pub snapshot_barrier_interval: u32,
620    /// Used by non-parallelized backfill. The number of rows to fetch in a single batch when reading from an external table.
621    pub snapshot_batch_size: u32,
622    /// Used by parallelized backfill, i.e. backfill V2. The initial parallelism of parallel backfill.
623    pub backfill_parallelism: u32,
624    /// Used by parallelized backfill. The estimated number of rows per split used in splits generation.
625    pub backfill_num_rows_per_split: u64,
626    /// Used by parallelized backfill. For supported split column data type, assume an uniform distribution and adopt a much faster splits generation method.
627    pub backfill_as_even_splits: bool,
628    /// Used by parallelized backfill. Specify the index of primary key column to use as split column.
629    pub backfill_split_pk_column_index: u32,
630}
631
632impl Default for CdcScanOptions {
633    fn default() -> Self {
634        Self {
635            disable_backfill: false,
636            snapshot_barrier_interval: 10,
637            snapshot_batch_size: 1000,
638            // 0 means disable backfill v2.
639            backfill_parallelism: 0,
640            backfill_num_rows_per_split: 100_000,
641            backfill_as_even_splits: true,
642            backfill_split_pk_column_index: 0,
643        }
644    }
645}
646
647impl CdcScanOptions {
648    pub fn to_proto(&self) -> StreamCdcScanOptions {
649        StreamCdcScanOptions {
650            disable_backfill: self.disable_backfill,
651            snapshot_barrier_interval: self.snapshot_barrier_interval,
652            snapshot_batch_size: self.snapshot_batch_size,
653            backfill_parallelism: self.backfill_parallelism,
654            backfill_num_rows_per_split: self.backfill_num_rows_per_split,
655            backfill_as_even_splits: self.backfill_as_even_splits,
656            backfill_split_pk_column_index: self.backfill_split_pk_column_index,
657        }
658    }
659
660    pub fn from_proto(proto: &StreamCdcScanOptions) -> Self {
661        Self {
662            disable_backfill: proto.disable_backfill,
663            snapshot_barrier_interval: proto.snapshot_barrier_interval,
664            snapshot_batch_size: proto.snapshot_batch_size,
665            backfill_parallelism: proto.backfill_parallelism,
666            backfill_num_rows_per_split: proto.backfill_num_rows_per_split,
667            backfill_as_even_splits: proto.backfill_as_even_splits,
668            backfill_split_pk_column_index: proto.backfill_split_pk_column_index,
669        }
670    }
671
672    pub fn is_parallelized_backfill(&self) -> bool {
673        !self.disable_backfill
674            && self.backfill_num_rows_per_split > 0
675            && self.backfill_parallelism > 0
676    }
677}
678
679#[cfg(test)]
680mod tests {
681    use super::*;
682
683    fn connect_properties(pairs: &[(&str, &str)]) -> BTreeMap<String, String> {
684        pairs
685            .iter()
686            .map(|(k, v)| ((*k).to_owned(), (*v).to_owned()))
687            .collect()
688    }
689
690    #[test]
691    fn test_canonical_name() {
692        assert_eq!(
693            Mysql::canonical_name(&connect_properties(&[
694                ("connector", MYSQL_CDC_CONNECTOR),
695                ("database.name", "mydb"),
696                ("table.name", "orders"),
697            ])),
698            "mydb.orders"
699        );
700        assert_eq!(
701            Postgres::canonical_name(&connect_properties(&[
702                ("connector", POSTGRES_CDC_CONNECTOR),
703                ("database.name", "postgres"),
704                ("schema.name", "public"),
705                ("table.name", "a.b"),
706            ])),
707            "public.a.b"
708        );
709        assert_eq!(
710            SqlServer::canonical_name(&connect_properties(&[
711                ("connector", SQL_SERVER_CDC_CONNECTOR),
712                ("database.name", "my.db"),
713                ("schema.name", "dbo"),
714                ("table.name", "a.b"),
715            ])),
716            "my.db.dbo.a.b"
717        );
718    }
719
720    #[test]
721    fn test_split_quoted_identifier() {
722        let parts = |parts: &[&str]| Some(parts.iter().map(|p| (*p).to_owned()).collect_vec());
723
724        assert_eq!(
725            Postgres::split_quoted_identifier("public.orders"),
726            parts(&["public", "orders"])
727        );
728        assert_eq!(
729            Postgres::split_quoted_identifier(r#""My.Schema"."a""b.c""#),
730            parts(&["My.Schema", r#"a"b.c"#])
731        );
732        assert_eq!(
733            SqlServer::split_quoted_identifier("[my.db].dbo.[a]]b.c]"),
734            parts(&["my.db", "dbo", "a]b.c"])
735        );
736        assert_eq!(
737            SqlServer::split_quoted_identifier("dbo.a[b"),
738            None,
739            "`[` opens a quote only at the start of a part"
740        );
741
742        for name in ["", "a..b", ".a", "a.", r#"public."a"#, r#"public."a"b"#] {
743            assert_eq!(Postgres::split_quoted_identifier(name), None, "{name}");
744        }
745        for name in ["[a", "dbo.[a]b]", "dbo.a]b", "[a]].b"] {
746            assert_eq!(SqlServer::split_quoted_identifier(name), None, "{name}");
747        }
748    }
749}