Skip to main content

risingwave_connector/source/cdc/external/
mod.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
15pub mod mock_external_table;
16pub mod oracle;
17pub mod postgres;
18pub mod sql_server;
19
20pub mod mysql;
21
22use std::collections::{BTreeMap, HashMap};
23
24use anyhow::{Context, anyhow};
25use futures::pin_mut;
26use futures::stream::BoxStream;
27use futures_async_stream::try_stream;
28use risingwave_common::bail;
29use risingwave_common::catalog::{CdcKeyComparison, ColumnDesc, Field, Schema};
30use risingwave_common::row::OwnedRow;
31use risingwave_common::secret::LocalSecretManager;
32use risingwave_pb::catalog::table::CdcTableType as PbCdcTableType;
33use risingwave_pb::secret::PbSecretRef;
34use serde::{Deserialize, Serialize};
35
36use crate::WithPropertiesExt;
37use crate::connector_common::{PgConnectionConfig, PostgresExternalTable, SslMode};
38use crate::error::{ConnectorError, ConnectorResult};
39use crate::source::CdcTableSnapshotSplit;
40use crate::source::cdc::CdcSourceType;
41use crate::source::cdc::external::mock_external_table::MockExternalTableReader;
42use crate::source::cdc::external::mysql::{
43    MysqlExternalTable, MysqlExternalTableReader, MysqlOffset,
44};
45use crate::source::cdc::external::oracle::{
46    OracleExternalTable, OracleExternalTableReader, OracleOffset,
47};
48use crate::source::cdc::external::postgres::{PostgresExternalTableReader, PostgresOffset};
49use crate::source::cdc::external::sql_server::{
50    SqlServerExternalTable, SqlServerExternalTableReader, SqlServerOffset,
51};
52
53#[derive(Debug, Clone, PartialEq, Eq, Hash)]
54pub enum ExternalCdcTableType {
55    Unspecified,
56    Mock,
57    Mysql,
58    Mariadb,
59    Postgres,
60    SqlServer,
61    Mongodb,
62    Oracle,
63}
64
65impl ExternalCdcTableType {
66    pub fn from_properties(with_properties: &impl WithPropertiesExt) -> Self {
67        let connector = with_properties.get_connector().unwrap_or_default();
68        match connector.as_str() {
69            "mysql-cdc" => Self::Mysql,
70            "mariadb-cdc" => Self::Mariadb,
71            "postgres-cdc" => Self::Postgres,
72            "sqlserver-cdc" => Self::SqlServer,
73            "mongodb-cdc" => Self::Mongodb,
74            "oracle-cdc" => Self::Oracle,
75            _ => Self::Unspecified,
76        }
77    }
78
79    pub fn get_cdc_offset_parser(&self) -> ConnectorResult<CdcOffsetParseFunc> {
80        match self {
81            Self::Mysql | Self::Mariadb => Ok(MysqlExternalTableReader::get_cdc_offset_parser()),
82            Self::Postgres => Ok(PostgresExternalTableReader::get_cdc_offset_parser()),
83            Self::SqlServer => Ok(SqlServerExternalTableReader::get_cdc_offset_parser()),
84            Self::Oracle => Ok(OracleExternalTableReader::get_cdc_offset_parser()),
85            Self::Mock => Ok(MockExternalTableReader::get_cdc_offset_parser()),
86            Self::Unspecified | Self::Mongodb => {
87                bail!("invalid external table type: {:?}", *self)
88            }
89        }
90    }
91
92    pub async fn create_table_reader(
93        &self,
94        config: ExternalTableConfig,
95        schema: Schema,
96        pk_indices: Vec<usize>,
97        schema_table_name: SchemaTableName,
98        table_id: u32,
99    ) -> ConnectorResult<ExternalTableReaderImpl> {
100        match self {
101            Self::Mysql | Self::Mariadb => Ok(ExternalTableReaderImpl::Mysql(
102                MysqlExternalTableReader::new(config, schema, pk_indices).await?,
103            )),
104            Self::Postgres => Ok(ExternalTableReaderImpl::Postgres(
105                PostgresExternalTableReader::new(
106                    config,
107                    schema,
108                    pk_indices,
109                    schema_table_name,
110                    table_id,
111                )
112                .await?,
113            )),
114            Self::SqlServer => Ok(ExternalTableReaderImpl::SqlServer(
115                SqlServerExternalTableReader::new(config, schema, pk_indices).await?,
116            )),
117            Self::Oracle => Ok(ExternalTableReaderImpl::Oracle(
118                OracleExternalTableReader::new(config, schema, pk_indices)?,
119            )),
120            Self::Mock => Ok(ExternalTableReaderImpl::Mock(MockExternalTableReader::new())),
121            Self::Unspecified | Self::Mongodb => {
122                bail!("invalid external table type: {:?}", *self)
123            }
124        }
125    }
126}
127
128impl From<ExternalCdcTableType> for PbCdcTableType {
129    fn from(cdc_table_type: ExternalCdcTableType) -> Self {
130        match cdc_table_type {
131            ExternalCdcTableType::Postgres => Self::Postgres,
132            ExternalCdcTableType::Mysql => Self::Mysql,
133            ExternalCdcTableType::Mariadb => Self::Mariadb,
134            ExternalCdcTableType::SqlServer => Self::SqlServer,
135            ExternalCdcTableType::Mongodb => Self::Mongodb,
136            ExternalCdcTableType::Oracle => Self::Oracle,
137            ExternalCdcTableType::Unspecified | ExternalCdcTableType::Mock => Self::Unspecified,
138        }
139    }
140}
141
142impl From<PbCdcTableType> for ExternalCdcTableType {
143    fn from(cdc_table_type: PbCdcTableType) -> Self {
144        match cdc_table_type {
145            PbCdcTableType::Postgres => Self::Postgres,
146            PbCdcTableType::Mysql => Self::Mysql,
147            PbCdcTableType::Mariadb => Self::Mariadb,
148            PbCdcTableType::SqlServer => Self::SqlServer,
149            PbCdcTableType::Mongodb => Self::Mongodb,
150            PbCdcTableType::Oracle => Self::Oracle,
151            PbCdcTableType::Unspecified => Self::Unspecified,
152        }
153    }
154}
155
156#[derive(Debug, Clone, PartialEq)]
157pub struct SchemaTableName {
158    // namespace of the table, e.g. database in mysql, schema in postgres
159    pub schema_name: String,
160    pub table_name: String,
161}
162
163pub const TABLE_NAME_KEY: &str = "table.name";
164pub const SCHEMA_NAME_KEY: &str = "schema.name";
165pub const DATABASE_NAME_KEY: &str = "database.name";
166
167impl SchemaTableName {
168    pub fn from_properties(properties: &BTreeMap<String, String>) -> Self {
169        let table_type = ExternalCdcTableType::from_properties(properties);
170        let table_name = properties.get(TABLE_NAME_KEY).cloned().unwrap_or_default();
171
172        let schema_name = match table_type {
173            ExternalCdcTableType::Mysql | ExternalCdcTableType::Mariadb => properties
174                .get(DATABASE_NAME_KEY)
175                .cloned()
176                .unwrap_or_default(),
177            ExternalCdcTableType::Postgres
178            | ExternalCdcTableType::Oracle
179            | ExternalCdcTableType::SqlServer => {
180                properties.get(SCHEMA_NAME_KEY).cloned().unwrap_or_default()
181            }
182            ExternalCdcTableType::Unspecified
183            | ExternalCdcTableType::Mock
184            | ExternalCdcTableType::Mongodb => {
185                unreachable!("invalid external table type: {:?}", table_type);
186            }
187        };
188
189        Self {
190            schema_name,
191            table_name,
192        }
193    }
194}
195
196#[derive(Debug, Clone, PartialEq, PartialOrd, Serialize, Deserialize)]
197pub enum CdcOffset {
198    // The variant name is the JSON tag persisted in the CDC backfill state table,
199    // so keep the historical spelling for serde.
200    #[serde(rename = "MySql")]
201    Mysql(MysqlOffset),
202    Postgres(PostgresOffset),
203    SqlServer(SqlServerOffset),
204    Oracle(OracleOffset),
205}
206
207// Example debezium offset for Postgres:
208// {
209//     "sourcePartition":
210//     {
211//         "server": "RW_CDC_1004"
212//     },
213//     "sourceOffset":
214//     {
215//         "last_snapshot_record": false,
216//         "lsn": 29973552,
217//         "txId": 1046,
218//         "ts_usec": 1670826189008456,
219//         "snapshot": true
220//     }
221// }
222#[derive(Debug, Clone, Serialize, Deserialize)]
223pub struct DebeziumOffset {
224    #[serde(rename = "sourcePartition")]
225    pub source_partition: HashMap<String, String>,
226    #[serde(rename = "sourceOffset")]
227    pub source_offset: DebeziumSourceOffset,
228    #[serde(rename = "isHeartbeat")]
229    pub is_heartbeat: bool,
230}
231
232#[derive(Debug, Default, Clone, Serialize, Deserialize)]
233pub struct DebeziumSourceOffset {
234    // postgres snapshot progress
235    pub last_snapshot_record: Option<bool>,
236    // mysql snapshot progress
237    pub snapshot: Option<bool>,
238
239    // mysql binlog offset
240    pub file: Option<String>,
241    pub pos: Option<u64>,
242
243    // postgres offset
244    pub lsn: Option<u64>,
245    #[serde(rename = "txId")]
246    pub txid: Option<i64>,
247    pub tx_usec: Option<u64>,
248    pub lsn_commit: Option<u64>,
249    pub lsn_proc: Option<u64>,
250
251    // sql server offset
252    pub commit_lsn: Option<String>,
253    pub change_lsn: Option<String>,
254    // oracle offset
255    // Oracle's sourceOffset can emit a string txId, which conflicts with the
256    // PostgreSQL txid field above using the same serde name. Oracle offsets are
257    // parsed directly with serde_json::Value instead of declaring this field here;
258    // the comparison SCN is read as a string and converted to u64.
259    // pub decoded_commit_scn: Option<u64>
260}
261
262pub type CdcOffsetParseFunc = Box<dyn Fn(&str) -> ConnectorResult<CdcOffset> + Send>;
263
264pub trait ExternalTableReader: Sized {
265    async fn current_cdc_offset(&self) -> ConnectorResult<CdcOffset>;
266
267    // Currently, MySQL cdc uses a connection pool to manage connections to MySQL, and other CDC processes do not require the disconnect step for now.
268
269    async fn disconnect(self) -> ConnectorResult<()> {
270        Ok(())
271    }
272
273    fn snapshot_read(
274        &self,
275        table_name: SchemaTableName,
276        start_pk: Option<OwnedRow>,
277        primary_keys: Vec<String>,
278        limit: u32,
279    ) -> BoxStream<'_, ConnectorResult<OwnedRow>>;
280
281    fn get_parallel_cdc_splits(
282        &self,
283        options: CdcTableSnapshotSplitOption,
284    ) -> BoxStream<'_, ConnectorResult<CdcTableSnapshotSplit>>;
285
286    fn split_snapshot_read(
287        &self,
288        table_name: SchemaTableName,
289        left: OwnedRow,
290        right: OwnedRow,
291        split_columns: Vec<Field>,
292    ) -> BoxStream<'_, ConnectorResult<OwnedRow>>;
293}
294
295pub struct CdcTableSnapshotSplitOption {
296    pub backfill_num_rows_per_split: u64,
297    pub backfill_as_even_splits: bool,
298    pub backfill_split_pk_column_index: u32,
299}
300
301pub enum ExternalTableReaderImpl {
302    Mysql(MysqlExternalTableReader),
303    Postgres(PostgresExternalTableReader),
304    SqlServer(SqlServerExternalTableReader),
305    Oracle(OracleExternalTableReader),
306    Mock(MockExternalTableReader),
307}
308
309#[derive(Debug, Default, Clone, Deserialize)]
310pub struct ExternalTableConfig {
311    pub connector: String,
312
313    #[serde(rename = "hostname")]
314    pub host: String,
315    pub port: String,
316    pub username: String,
317    pub password: String,
318    #[serde(rename = "database.name")]
319    pub database: String,
320    #[serde(rename = "schema.name", default = "Default::default")]
321    pub schema: String,
322    /// The Oracle pluggable database name. This field is only used by the Oracle CDC connector.
323    #[serde(rename = "database.pdb.name")]
324    pub pdb_name: Option<String>,
325    #[serde(rename = "table.name")]
326    pub table: String,
327    /// `ssl.mode` specifies the SSL/TLS encryption level for secure CDC connections.
328    /// Choices include `disabled`, `preferred`, `required`, `verify-ca`, and `verify-full`.
329    /// This field is optional.
330    #[serde(rename = "ssl.mode", default = "postgres_ssl_mode_default")]
331    #[serde(alias = "debezium.database.sslmode")]
332    pub ssl_mode: SslMode,
333
334    /// Optional path to a trusted root CA certificate for verified SSL modes.
335    #[serde(rename = "ssl.root.cert")]
336    #[serde(alias = "debezium.database.sslrootcert")]
337    pub ssl_root_cert: Option<String>,
338
339    /// `encrypt` specifies whether connect to SQL Server using SSL.
340    /// Only "true" means using SSL. All other values are treated as "false".
341    #[serde(rename = "database.encrypt", default = "Default::default")]
342    pub encrypt: String,
343}
344
345fn postgres_ssl_mode_default() -> SslMode {
346    // NOTE(StrikeW): Default to `disabled` for backward compatibility
347    SslMode::Disabled
348}
349
350impl ExternalTableConfig {
351    pub fn try_from_btreemap(
352        connect_properties: BTreeMap<String, String>,
353        secret_refs: BTreeMap<String, PbSecretRef>,
354    ) -> ConnectorResult<Self> {
355        let options_with_secret =
356            LocalSecretManager::global().fill_secrets(connect_properties, secret_refs)?;
357        let json_value = serde_json::to_value(options_with_secret)?;
358        let config = serde_json::from_value::<ExternalTableConfig>(json_value)?;
359        Ok(config)
360    }
361
362    /// Project the Postgres-specific subset of this config so it can drive the
363    /// shared `create_pg_client` / `PostgresExternalTable` helpers. Only meaningful
364    /// for the Postgres CDC connector; other connectors ignore the fields.
365    pub fn pg_connection_config(&self) -> ConnectorResult<PgConnectionConfig> {
366        let port = self
367            .port
368            .parse::<u16>()
369            .with_context(|| format!("invalid postgres port `{}`", self.port))?;
370        Ok(PgConnectionConfig {
371            host: self.host.clone(),
372            port,
373            user: self.username.clone(),
374            password: self.password.clone(),
375            database: self.database.clone(),
376            ssl_mode: self.ssl_mode.clone(),
377            ssl_root_cert: self.ssl_root_cert.clone(),
378        })
379    }
380}
381
382impl ExternalTableReader for ExternalTableReaderImpl {
383    async fn current_cdc_offset(&self) -> ConnectorResult<CdcOffset> {
384        match self {
385            ExternalTableReaderImpl::Mysql(mysql) => mysql.current_cdc_offset().await,
386            ExternalTableReaderImpl::Postgres(postgres) => postgres.current_cdc_offset().await,
387            ExternalTableReaderImpl::SqlServer(sql_server) => sql_server.current_cdc_offset().await,
388            ExternalTableReaderImpl::Oracle(oracle) => oracle.current_cdc_offset().await,
389            ExternalTableReaderImpl::Mock(mock) => mock.current_cdc_offset().await,
390        }
391    }
392
393    fn snapshot_read(
394        &self,
395        table_name: SchemaTableName,
396        start_pk: Option<OwnedRow>,
397        primary_keys: Vec<String>,
398        limit: u32,
399    ) -> BoxStream<'_, ConnectorResult<OwnedRow>> {
400        self.snapshot_read_inner(table_name, start_pk, primary_keys, limit)
401    }
402
403    fn get_parallel_cdc_splits(
404        &self,
405        options: CdcTableSnapshotSplitOption,
406    ) -> BoxStream<'_, ConnectorResult<CdcTableSnapshotSplit>> {
407        self.get_parallel_cdc_splits_inner(options)
408    }
409
410    fn split_snapshot_read(
411        &self,
412        table_name: SchemaTableName,
413        left: OwnedRow,
414        right: OwnedRow,
415        split_columns: Vec<Field>,
416    ) -> BoxStream<'_, ConnectorResult<OwnedRow>> {
417        self.split_snapshot_read_inner(table_name, left, right, split_columns)
418    }
419}
420
421impl ExternalTableReaderImpl {
422    /// Recover comparison semantics for primary-key columns from the live reader.
423    pub fn pk_column_comparisons(
424        &self,
425        pk_names: &[String],
426    ) -> ConnectorResult<Vec<CdcKeyComparison>> {
427        match self {
428            ExternalTableReaderImpl::Mysql(mysql) => mysql.pk_column_comparisons(pk_names),
429            ExternalTableReaderImpl::Postgres(_)
430            | ExternalTableReaderImpl::SqlServer(_)
431            | ExternalTableReaderImpl::Oracle(_)
432            | ExternalTableReaderImpl::Mock(_) => {
433                Ok(vec![CdcKeyComparison::Native; pk_names.len()])
434            }
435        }
436    }
437
438    pub fn get_cdc_offset_parser(&self) -> CdcOffsetParseFunc {
439        match self {
440            ExternalTableReaderImpl::Mysql(_) => MysqlExternalTableReader::get_cdc_offset_parser(),
441            ExternalTableReaderImpl::Postgres(_) => {
442                PostgresExternalTableReader::get_cdc_offset_parser()
443            }
444            ExternalTableReaderImpl::SqlServer(_) => {
445                SqlServerExternalTableReader::get_cdc_offset_parser()
446            }
447            ExternalTableReaderImpl::Oracle(_) => {
448                OracleExternalTableReader::get_cdc_offset_parser()
449            }
450            ExternalTableReaderImpl::Mock(_) => MockExternalTableReader::get_cdc_offset_parser(),
451        }
452    }
453
454    #[try_stream(boxed, ok = OwnedRow, error = ConnectorError)]
455    async fn snapshot_read_inner(
456        &self,
457        table_name: SchemaTableName,
458        start_pk: Option<OwnedRow>,
459        primary_keys: Vec<String>,
460        limit: u32,
461    ) {
462        let stream = match self {
463            ExternalTableReaderImpl::Mysql(mysql) => {
464                mysql.snapshot_read(table_name, start_pk, primary_keys, limit)
465            }
466            ExternalTableReaderImpl::Postgres(postgres) => {
467                postgres.snapshot_read(table_name, start_pk, primary_keys, limit)
468            }
469            ExternalTableReaderImpl::SqlServer(sql_server) => {
470                sql_server.snapshot_read(table_name, start_pk, primary_keys, limit)
471            }
472            ExternalTableReaderImpl::Oracle(oracle) => {
473                oracle.snapshot_read(table_name, start_pk, primary_keys, limit)
474            }
475            ExternalTableReaderImpl::Mock(mock) => {
476                mock.snapshot_read(table_name, start_pk, primary_keys, limit)
477            }
478        };
479
480        pin_mut!(stream);
481        #[for_await]
482        for row in stream {
483            let row = row?;
484            yield row;
485        }
486    }
487
488    #[try_stream(boxed, ok = CdcTableSnapshotSplit, error = ConnectorError)]
489    async fn get_parallel_cdc_splits_inner(&self, options: CdcTableSnapshotSplitOption) {
490        let stream = match self {
491            ExternalTableReaderImpl::Mysql(e) => e.get_parallel_cdc_splits(options),
492            ExternalTableReaderImpl::Postgres(e) => e.get_parallel_cdc_splits(options),
493            ExternalTableReaderImpl::SqlServer(e) => e.get_parallel_cdc_splits(options),
494            ExternalTableReaderImpl::Oracle(e) => e.get_parallel_cdc_splits(options),
495            ExternalTableReaderImpl::Mock(e) => e.get_parallel_cdc_splits(options),
496        };
497        pin_mut!(stream);
498        #[for_await]
499        for row in stream {
500            let row = row?;
501            yield row;
502        }
503    }
504
505    #[try_stream(boxed, ok = OwnedRow, error = ConnectorError)]
506    async fn split_snapshot_read_inner(
507        &self,
508        table_name: SchemaTableName,
509        left: OwnedRow,
510        right: OwnedRow,
511        split_columns: Vec<Field>,
512    ) {
513        let stream = match self {
514            ExternalTableReaderImpl::Mysql(mysql) => {
515                mysql.split_snapshot_read(table_name, left, right, split_columns)
516            }
517            ExternalTableReaderImpl::Postgres(postgres) => {
518                postgres.split_snapshot_read(table_name, left, right, split_columns)
519            }
520            ExternalTableReaderImpl::SqlServer(sql_server) => {
521                sql_server.split_snapshot_read(table_name, left, right, split_columns)
522            }
523            ExternalTableReaderImpl::Oracle(oracle) => {
524                oracle.split_snapshot_read(table_name, left, right, split_columns)
525            }
526            ExternalTableReaderImpl::Mock(mock) => {
527                mock.split_snapshot_read(table_name, left, right, split_columns)
528            }
529        };
530
531        pin_mut!(stream);
532        #[for_await]
533        for row in stream {
534            let row = row?;
535            yield row;
536        }
537    }
538}
539
540pub enum ExternalTableImpl {
541    Mysql(MysqlExternalTable),
542    Postgres(PostgresExternalTable),
543    SqlServer(SqlServerExternalTable),
544    Oracle(OracleExternalTable),
545}
546
547impl ExternalTableImpl {
548    pub async fn connect(config: ExternalTableConfig) -> ConnectorResult<Self> {
549        let cdc_source_type = CdcSourceType::from(config.connector.as_str());
550        match cdc_source_type {
551            CdcSourceType::Mysql | CdcSourceType::Mariadb => Ok(ExternalTableImpl::Mysql(
552                MysqlExternalTable::connect(config).await?,
553            )),
554            CdcSourceType::Postgres => {
555                let pg_conn = config.pg_connection_config()?;
556                Ok(ExternalTableImpl::Postgres(
557                    PostgresExternalTable::connect(
558                        &pg_conn,
559                        &config.schema,
560                        &config.table,
561                        false,
562                        Some("SELECT"),
563                    )
564                    .await?,
565                ))
566            }
567            CdcSourceType::SqlServer => Ok(ExternalTableImpl::SqlServer(
568                SqlServerExternalTable::connect(config).await?,
569            )),
570            CdcSourceType::Oracle => Ok(ExternalTableImpl::Oracle(
571                OracleExternalTable::connect(config).await?,
572            )),
573            CdcSourceType::Mongodb | CdcSourceType::Unspecified => {
574                Err(anyhow!("Unsupported cdc connector type: {}", config.connector).into())
575            }
576        }
577    }
578
579    pub fn column_descs(&self) -> &Vec<ColumnDesc> {
580        match self {
581            ExternalTableImpl::Mysql(mysql) => mysql.column_descs(),
582            ExternalTableImpl::Postgres(postgres) => postgres.column_descs(),
583            ExternalTableImpl::SqlServer(sql_server) => sql_server.column_descs(),
584            ExternalTableImpl::Oracle(oracle) => oracle.column_descs(),
585        }
586    }
587
588    pub fn pk_names(&self) -> &Vec<String> {
589        match self {
590            ExternalTableImpl::Mysql(mysql) => mysql.pk_names(),
591            ExternalTableImpl::Postgres(postgres) => postgres.pk_names(),
592            ExternalTableImpl::SqlServer(sql_server) => sql_server.pk_names(),
593            ExternalTableImpl::Oracle(oracle) => oracle.pk_names(),
594        }
595    }
596
597    /// Return CDC backfill comparison semantics in the requested `pk_names` order.
598    /// Reuses metadata loaded by [`Self::connect`], without querying upstream again.
599    ///
600    /// MySQL `BIGINT UNSIGNED` keys use `UnsignedInt64` to preserve upstream ordering
601    /// when represented as signed `i64` values; other types use `Native`. MySQL names
602    /// are matched case-insensitively, and missing upstream PK names return an error.
603    /// PostgreSQL, SQL Server, and Oracle return `Native` for every requested name.
604    pub fn pk_column_comparisons(
605        &self,
606        pk_names: &[String],
607    ) -> ConnectorResult<Vec<CdcKeyComparison>> {
608        match self {
609            ExternalTableImpl::Mysql(mysql) => mysql.pk_column_comparisons(pk_names),
610            ExternalTableImpl::Postgres(_)
611            | ExternalTableImpl::SqlServer(_)
612            | ExternalTableImpl::Oracle(_) => Ok(vec![CdcKeyComparison::Native; pk_names.len()]),
613        }
614    }
615
616    /// Discover CDC backfill comparison semantics without loading the full table schema.
617    /// Used when SQL defines the columns explicitly, so there is no existing table
618    /// instance whose metadata can be reused via [`Self::pk_column_comparisons`].
619    ///
620    /// For MySQL, queries upstream PK names and types and returns the same comparison
621    /// modes in the requested `pk_names` order, with case-insensitive name matching and
622    /// an error for missing upstream PK names. Other connectors return `Native` for
623    /// every requested name without querying upstream.
624    pub async fn discover_pk_column_comparisons(
625        config: &ExternalTableConfig,
626        pk_names: &[String],
627    ) -> ConnectorResult<Vec<CdcKeyComparison>> {
628        match CdcSourceType::from(config.connector.as_str()) {
629            CdcSourceType::Mysql | CdcSourceType::Mariadb => {
630                MysqlExternalTable::discover_pk_column_comparisons(config, pk_names).await
631            }
632            CdcSourceType::Postgres
633            | CdcSourceType::Mongodb
634            | CdcSourceType::SqlServer
635            | CdcSourceType::Oracle
636            | CdcSourceType::Unspecified => Ok(vec![CdcKeyComparison::Native; pk_names.len()]),
637        }
638    }
639}
640
641pub const CDC_TABLE_SPLIT_ID_START: i64 = 1;
642
643#[cfg(test)]
644mod tests {
645    use super::*;
646
647    #[test]
648    fn test_cdc_offset_persisted_mysql_tag() {
649        let json = r#"{"MySql":{"filename":"binlog.000001","position":4}}"#;
650        let offset = CdcOffset::Mysql(MysqlOffset::new("binlog.000001".to_owned(), 4));
651        assert_eq!(serde_json::to_string(&offset).unwrap(), json);
652        assert_eq!(serde_json::from_str::<CdcOffset>(json).unwrap(), offset);
653    }
654}