Skip to main content

risingwave_connector/parser/unified/
debezium.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::str::FromStr;
16
17use itertools::Itertools;
18use risingwave_common::catalog::{ColumnCatalog, ColumnDesc, ColumnId};
19use risingwave_common::id::SourceId;
20use risingwave_common::types::{
21    DataType, Datum, DatumCow, Int256, ListValue, Scalar, ScalarImpl, ScalarRefImpl, StructValue,
22    Timestamp, Timestamptz, ToDatumRef, ToOwnedDatum,
23};
24use risingwave_connector_codec::decoder::AccessExt;
25use risingwave_pb::plan_common::additional_column::ColumnType;
26use thiserror_ext::AsReport;
27
28use super::{Access, AccessError, AccessResult, ChangeEvent, ChangeEventOperation};
29
30/// JDBC type constants found in Debezium schema change events.
31mod debezium_sql_types {
32    pub const STRUCT: i32 = 2002;
33    pub const ARRAY: i32 = 2003;
34}
35use crate::connector_common::{create_pg_client_from_properties, discover_pgvector_dimensions};
36use crate::parser::TransactionControl;
37use crate::parser::debezium::schema_change::{SchemaChangeEnvelope, TableSchemaChange};
38use crate::parser::schema_change::TableChangeType;
39use crate::source::cdc::build_cdc_table_id;
40use crate::source::cdc::external::mysql::{
41    mysql_type_to_rw_type, timestamp_val_to_timestamptz, type_name_to_mysql_type,
42};
43use crate::source::cdc::external::postgres::{pg_type_to_rw_type, type_name_to_pg_type};
44use crate::source::{ConnectorProperties, SourceColumnDesc};
45
46/// Parse Debezium `tableChanges[].id` into `(schema_name, table_name)`.
47///
48/// Input examples observed in Debezium schema-change events:
49/// - `"public"."orders"` (quoted format)
50/// - `public.orders` (plain dotted format)
51/// - `db.public.orders` (database-prefixed dotted format)
52///
53/// Why two parsing branches:
54/// - Different Debezium versions/connectors may emit quoted or plain identifiers.
55/// - We normalize both forms so downstream lookup can consistently query upstream catalogs.
56///
57/// Output:
58/// - `Some((schema, table))` when both schema and table are successfully extracted.
59/// - `None` when the id is malformed or does not contain enough segments.
60fn parse_schema_table_from_debezium_id(id: &str) -> Option<(String, String)> {
61    let trimmed = id.trim();
62    if trimmed.contains("\".\"") {
63        let parts = trimmed
64            .split("\".\"")
65            .map(|s| s.trim_matches('"').trim())
66            .collect_vec();
67        if parts.len() >= 2 {
68            let schema = parts[parts.len() - 2].to_owned();
69            let table = parts[parts.len() - 1].to_owned();
70            if !schema.is_empty() && !table.is_empty() {
71                return Some((schema, table));
72            }
73        }
74    }
75
76    let cleaned = trimmed.trim_matches('"');
77    let parts = cleaned.split('.').collect_vec();
78    if parts.len() >= 2 {
79        let schema = parts[parts.len() - 2].trim().to_owned();
80        let table = parts[parts.len() - 1].trim().to_owned();
81        if !schema.is_empty() && !table.is_empty() {
82            return Some((schema, table));
83        }
84    }
85    None
86}
87
88async fn fetch_pgvector_dimensions_for_table(
89    connector_props: &ConnectorProperties,
90    schema: &str,
91    table: &str,
92) -> AccessResult<std::collections::HashMap<String, usize>> {
93    let ConnectorProperties::PostgresCdc(cdc_props) = connector_props else {
94        return Ok(std::collections::HashMap::new());
95    };
96
97    let client = create_pg_client_from_properties(&cdc_props.properties, None)
98        .await
99        .map_err(|err| AccessError::Uncategorized {
100            message: format!(
101                "failed to connect upstream postgres for schema change lookup: {}",
102                err.as_report()
103            ),
104        })?;
105
106    discover_pgvector_dimensions(&client, schema, table)
107        .await
108        .map_err(|err| AccessError::Uncategorized {
109            message: format!(
110                "failed to query upstream postgres schema for {schema}.{table}: {}",
111                err.as_report()
112            ),
113        })
114}
115
116/// Decide whether an unknown array column type (one not resolved by
117/// `type_name_to_pg_type`) can be represented as `varchar[]` in RW. This is the
118/// single question this function answers; the criteria behind it may grow over
119/// time.
120///
121/// Right now the answer is "yes iff the array's element type is a user-defined
122/// enum or composite". Debezium does not expose element enum/composite metadata
123/// on the array column (the `enumValues` field is only set for scalar enum
124/// columns, and `jdbcType == STRUCT` is only set for scalar composite columns),
125/// so we ask the upstream catalog directly: follow the array type's `typelem`
126/// to its element type and check `typtype IN ('e', 'c')`. Enum values are plain
127/// text, and composite values are converted to text by our `CustomConverter`,
128/// hence `varchar[]`.
129async fn can_fallback_array_to_varchar(
130    connector_props: &ConnectorProperties,
131    array_type_name: &str,
132) -> AccessResult<bool> {
133    let ConnectorProperties::PostgresCdc(cdc_props) = connector_props else {
134        return Ok(false);
135    };
136
137    let client = create_pg_client_from_properties(&cdc_props.properties, None)
138        .await
139        .map_err(|err| AccessError::Uncategorized {
140            message: format!(
141                "failed to connect upstream postgres for schema change lookup: {}",
142                err.as_report()
143            ),
144        })?;
145
146    let row = client
147        .query_opt(
148            "SELECT t_elem.typtype IN ('e', 'c') \
149             FROM pg_type t \
150             JOIN pg_type t_elem ON t.typelem = t_elem.oid \
151             WHERE t.typname = $1 \
152             LIMIT 1",
153            &[&array_type_name],
154        )
155        .await
156        .map_err(|err| AccessError::Uncategorized {
157            message: format!(
158                "failed to query upstream postgres for array element type of `{array_type_name}`: {}",
159                err.as_report()
160            ),
161        })?;
162
163    Ok(row.map(|r| r.get::<_, bool>(0)).unwrap_or(false))
164}
165
166// Example of Debezium JSON value:
167// {
168//     "payload":
169//     {
170//         "before": null,
171//         "after":
172//         {
173//             "O_ORDERKEY": 5,
174//             "O_CUSTKEY": 44485,
175//             "O_ORDERSTATUS": "F",
176//             "O_TOTALPRICE": "144659.20",
177//             "O_ORDERDATE": "1994-07-30"
178//         },
179//         "source":
180//         {
181//             "version": "1.9.7.Final",
182//             "connector": "mysql",
183//             "name": "RW_CDC_1002",
184//             "ts_ms": 1695277757000,
185//             "db": "mydb",
186//             "sequence": null,
187//             "table": "orders",
188//             "server_id": 0,
189//             "gtid": null,
190//             "file": "binlog.000008",
191//             "pos": 3693,
192//             "row": 0,
193//         },
194//         "op": "r",
195//         "ts_ms": 1695277757017,
196//         "transaction": null
197//     }
198// }
199pub struct DebeziumChangeEvent<A> {
200    value_accessor: Option<A>,
201    key_accessor: Option<A>,
202    is_mongodb: bool,
203}
204
205const BEFORE: &str = "before";
206const AFTER: &str = "after";
207
208const UPSTREAM_DDL: &str = "ddl";
209const SOURCE: &str = "source";
210const SOURCE_TS_MS: &str = "ts_ms";
211const SOURCE_DB: &str = "db";
212const SOURCE_SCHEMA: &str = "schema";
213const SOURCE_TABLE: &str = "table";
214const SOURCE_COLLECTION: &str = "collection";
215
216const OP: &str = "op";
217pub const TRANSACTION_STATUS: &str = "status";
218pub const TRANSACTION_ID: &str = "id";
219
220pub const TABLE_CHANGES: &str = "tableChanges";
221
222pub const DEBEZIUM_READ_OP: &str = "r";
223pub const DEBEZIUM_CREATE_OP: &str = "c";
224pub const DEBEZIUM_UPDATE_OP: &str = "u";
225pub const DEBEZIUM_DELETE_OP: &str = "d";
226
227pub const DEBEZIUM_TRANSACTION_STATUS_BEGIN: &str = "BEGIN";
228pub const DEBEZIUM_TRANSACTION_STATUS_COMMIT: &str = "END";
229
230pub fn parse_transaction_meta(
231    accessor: &impl Access,
232    connector_props: &ConnectorProperties,
233) -> AccessResult<TransactionControl> {
234    if let (Some(ScalarRefImpl::Utf8(status)), Some(ScalarRefImpl::Utf8(id))) = (
235        accessor
236            .access(&[TRANSACTION_STATUS], &DataType::Varchar)?
237            .to_datum_ref(),
238        accessor
239            .access(&[TRANSACTION_ID], &DataType::Varchar)?
240            .to_datum_ref(),
241    ) {
242        // The id field has different meanings for different databases:
243        // PG: txID:LSN
244        // MySQL: source_id:transaction_id (e.g. 3E11FA47-71CA-11E1-9E33-C80AA9429562:23)
245        // SQL Server: commit_lsn (e.g. 00000027:00000ac0:0002)
246        match status {
247            DEBEZIUM_TRANSACTION_STATUS_BEGIN => match *connector_props {
248                ConnectorProperties::PostgresCdc(_) => {
249                    let (tx_id, _) = id.split_once(':').unwrap();
250                    return Ok(TransactionControl::Begin { id: tx_id.into() });
251                }
252                ConnectorProperties::MysqlCdc(_) | ConnectorProperties::MariadbCdc(_) => {
253                    return Ok(TransactionControl::Begin { id: id.into() });
254                }
255                ConnectorProperties::SqlServerCdc(_) => {
256                    return Ok(TransactionControl::Begin { id: id.into() });
257                }
258                _ => {}
259            },
260            DEBEZIUM_TRANSACTION_STATUS_COMMIT => match *connector_props {
261                ConnectorProperties::PostgresCdc(_) => {
262                    let (tx_id, _) = id.split_once(':').unwrap();
263                    return Ok(TransactionControl::Commit { id: tx_id.into() });
264                }
265                ConnectorProperties::MysqlCdc(_) | ConnectorProperties::MariadbCdc(_) => {
266                    return Ok(TransactionControl::Commit { id: id.into() });
267                }
268                ConnectorProperties::SqlServerCdc(_) => {
269                    return Ok(TransactionControl::Commit { id: id.into() });
270                }
271                _ => {}
272            },
273            _ => {}
274        }
275    }
276
277    Err(AccessError::Undefined {
278        name: "transaction status".into(),
279        path: TRANSACTION_STATUS.into(),
280    })
281}
282
283macro_rules! jsonb_access_field {
284    ($col:expr, $field:expr, $as_type:tt) => {
285        $crate::paste! {
286            $col.access_object_field($field).unwrap().[<as_ $as_type>]().unwrap()
287        }
288    };
289}
290
291/// Parse the schema change message from Debezium.
292/// The layout of MySQL schema change message can refer to
293/// <https://debezium.io/documentation/reference/2.6/connectors/mysql.html#mysql-schema-change-topic>
294pub async fn parse_schema_change(
295    accessor: &impl Access,
296    source_id: SourceId,
297    source_name: &str,
298    connector_props: &ConnectorProperties,
299) -> AccessResult<SchemaChangeEnvelope> {
300    let mut schema_changes = vec![];
301    let mut pgvector_dims_cache: std::collections::HashMap<
302        (String, String),
303        std::collections::HashMap<String, usize>,
304    > = std::collections::HashMap::new();
305
306    let upstream_ddl: String = accessor
307        .access(&[UPSTREAM_DDL], &DataType::Varchar)?
308        .to_owned_datum()
309        .unwrap()
310        .as_utf8()
311        .to_string();
312
313    if let Some(ScalarRefImpl::List(table_changes)) = accessor
314        .access(&[TABLE_CHANGES], &DataType::Jsonb.list())?
315        .to_datum_ref()
316    {
317        for datum in table_changes.iter() {
318            let jsonb = match datum {
319                Some(ScalarRefImpl::Jsonb(jsonb)) => jsonb,
320                _ => unreachable!(""),
321            };
322            let id: String = jsonb_access_field!(jsonb, "id", string);
323            let ty = jsonb_access_field!(jsonb, "type", string);
324
325            let table_name = id.trim_matches('"').to_owned();
326            let ddl_type: TableChangeType = ty.as_str().into();
327            if matches!(ddl_type, TableChangeType::Create | TableChangeType::Drop) {
328                tracing::debug!("skip table schema change for create/drop command");
329                continue;
330            }
331
332            let mut column_descs: Vec<ColumnDesc> = vec![];
333            if let Some(table) = jsonb.access_object_field("table")
334                && let Some(columns) = table.access_object_field("columns")
335            {
336                for col in columns.array_elements().unwrap() {
337                    let name = jsonb_access_field!(col, "name", string);
338                    let type_name = jsonb_access_field!(col, "typeName", string);
339                    // User-defined types (enum, composite) are not in the
340                    // `type_name_to_pg_type` whitelist because their type names are
341                    // user-chosen. We detect them via Debezium metadata instead:
342                    //  - Enum: has a non-null `enumValues` field in the column descriptor.
343                    //  - Composite (STRUCT): identified by `jdbcType == 2002`.
344                    // Both are mapped to Varchar — enum values are plain strings, and
345                    // composite values are converted to text by our CustomConverter.
346                    let is_enum = matches!(col.access_object_field("enumValues"), Some(val) if !val.is_jsonb_null());
347                    let jdbc_type = col
348                        .access_object_field("jdbcType")
349                        .and_then(|v| v.as_number().ok())
350                        .map(|n| n.0 as i32);
351                    let is_composite = jdbc_type == Some(debezium_sql_types::STRUCT);
352
353                    let data_type = match *connector_props {
354                        ConnectorProperties::PostgresCdc(_) => {
355                            if is_composite || is_enum {
356                                tracing::debug!(target: "auto_schema_change",
357                                    "Convert PostgreSQL user-defined type '{}' ({}) to VARCHAR",
358                                    type_name,
359                                    if is_composite { "composite" } else { "enum" });
360                                DataType::Varchar
361                            } else if type_name.eq_ignore_ascii_case("vector") {
362                                let Some((schema_name, table_name_only)) =
363                                    parse_schema_table_from_debezium_id(id.as_str())
364                                else {
365                                    return Err(AccessError::CdcAutoSchemaChangeError {
366                                        ty: type_name,
367                                        table_name: format!("{}.{}", source_name, table_name),
368                                    });
369                                };
370
371                                // Cache by normalized `(schema, table)` tuple to avoid split/join churn on id text.
372                                let cache_key = (schema_name, table_name_only);
373                                if !pgvector_dims_cache.contains_key(&cache_key) {
374                                    let fetched = fetch_pgvector_dimensions_for_table(
375                                        connector_props,
376                                        &cache_key.0,
377                                        &cache_key.1,
378                                    )
379                                    .await?;
380                                    pgvector_dims_cache.insert(cache_key.clone(), fetched);
381                                }
382
383                                match pgvector_dims_cache
384                                    .get(&cache_key)
385                                    .and_then(|m| m.get(name.as_str()).copied())
386                                {
387                                    Some(dim) if (1..=DataType::VEC_MAX_SIZE).contains(&dim) => {
388                                        DataType::Vector(dim)
389                                    }
390                                    _ => {
391                                        // No fallback to VARCHAR: a dimension-less vector cannot be mapped to
392                                        // RW's required `vector(n)` type safely.
393                                        return Err(AccessError::CdcAutoSchemaChangeError {
394                                            ty: type_name,
395                                            table_name: format!("{}.{}", source_name, table_name),
396                                        });
397                                    }
398                                }
399                            } else {
400                                // Resolve builtin types first, so arrays of builtin element
401                                // types keep their proper element type (e.g. `_int4` -> int[],
402                                // `_text` -> text[]). `type_name_to_pg_type` only covers PG
403                                // builtins (the `PgType` it returns carries a static OID);
404                                // user-defined and extension types are not representable here
405                                // and fall through to the catalog lookup below.
406                                let ty = type_name_to_pg_type(type_name.as_str());
407                                match ty {
408                                    Some(ty) => match pg_type_to_rw_type(&ty) {
409                                        Ok(data_type) => data_type,
410                                        Err(err) => {
411                                            tracing::warn!(error=%err.as_report(), "unsupported postgres type in schema change message");
412                                            return Err(AccessError::CdcAutoSchemaChangeError {
413                                                ty: type_name,
414                                                table_name: format!(
415                                                    "{}.{}",
416                                                    source_name, table_name
417                                                ),
418                                            });
419                                        }
420                                    },
421                                    // An unrecognized ARRAY type may be an array of a
422                                    // user-defined enum (e.g. `_mood_enum`). Debezium carries
423                                    // no enum metadata on the array column, so ask upstream
424                                    // whether the element is an enum; if so, map to
425                                    // `varchar[]` (enum values are plain text).
426                                    None if jdbc_type == Some(debezium_sql_types::ARRAY)
427                                        && can_fallback_array_to_varchar(
428                                            connector_props,
429                                            type_name.as_str(),
430                                        )
431                                        .await? =>
432                                    {
433                                        tracing::debug!(target: "auto_schema_change",
434                                            "Fall back PostgreSQL array type '{}' to VARCHAR[]",
435                                            type_name);
436                                        DataType::Varchar.list()
437                                    }
438                                    None => {
439                                        return Err(AccessError::CdcAutoSchemaChangeError {
440                                            ty: type_name,
441                                            table_name: format!("{}.{}", source_name, table_name),
442                                        });
443                                    }
444                                }
445                            }
446                        }
447                        ConnectorProperties::MysqlCdc(_) | ConnectorProperties::MariadbCdc(_) => {
448                            let ty = type_name_to_mysql_type(type_name.as_str());
449                            match ty {
450                                Some(ty) => match mysql_type_to_rw_type(&ty) {
451                                    Ok(data_type) => data_type,
452                                    Err(err) => {
453                                        tracing::warn!(error=%err.as_report(), "unsupported mysql type in schema change message");
454                                        return Err(AccessError::CdcAutoSchemaChangeError {
455                                            ty: type_name,
456                                            table_name: format!("{}.{}", source_name, table_name),
457                                        });
458                                    }
459                                },
460                                None => {
461                                    return Err(AccessError::CdcAutoSchemaChangeError {
462                                        ty: type_name,
463                                        table_name: format!("{}.{}", source_name, table_name),
464                                    });
465                                }
466                            }
467                        }
468                        _ => {
469                            unreachable!()
470                        }
471                    };
472
473                    // Handle default value expression. Non-constant defaults (`now()`,
474                    // `gen_random_uuid()`, `nextval('seq'::regclass)` for BIGSERIAL, etc.)
475                    // will fail `ScalarImpl::from_text` and fall through to the fail-open
476                    // branch below — the column is added without a default and a warning is
477                    // logged, rather than aborting the whole auto schema change.
478                    //
479                    // TODO: the schema change event carries the **full** set of columns of
480                    // the table, so here we cannot tell "columns newly added by this ALTER"
481                    // from "columns that already existed". A better approach would be to
482                    // only process the delta columns that actually changed in this event,
483                    // which would let us precisely tell the user: which columns have
484                    // existing rows filled with NULL (needs attention), and which ones are
485                    // pre-existing columns merely surfaced by the event (harmless, can be
486                    // ignored silently).
487                    let column_desc = match col.access_object_field("defaultValueExpression") {
488                        Some(default_val_expr_str) if !default_val_expr_str.is_jsonb_null() => {
489                            let default_val_expr_str = default_val_expr_str.as_str().unwrap();
490                            let value_text: Option<String>;
491                            match *connector_props {
492                                ConnectorProperties::PostgresCdc(_) => {
493                                    // default value of non-number data type will be stored as
494                                    // "'value'::type"
495                                    match default_val_expr_str
496                                        .split("::")
497                                        .map(|s| s.trim_matches('\''))
498                                        .next()
499                                    {
500                                        None => {
501                                            value_text = None;
502                                        }
503                                        Some(val_text) => {
504                                            value_text = Some(val_text.to_owned());
505                                        }
506                                    }
507                                }
508                                ConnectorProperties::MysqlCdc(_)
509                                | ConnectorProperties::MariadbCdc(_) => {
510                                    // mysql timestamp is mapped to timestamptz, we use UTC timezone to
511                                    // interpret its value
512                                    if data_type == DataType::Timestamptz {
513                                        value_text = Some(timestamp_val_to_timestamptz(default_val_expr_str).map_err(|err| {
514                                            tracing::error!(target: "auto_schema_change", error=%err.as_report(), "failed to convert timestamp value to timestamptz");
515                                            AccessError::TypeError {
516                                                expected: "timestamp in YYYY-MM-DD HH:MM:SS".into(),
517                                                got: data_type.to_string(),
518                                                value: default_val_expr_str.to_owned(),
519                                            }
520                                        })?);
521                                    } else {
522                                        value_text = Some(default_val_expr_str.to_owned());
523                                    }
524                                }
525                                _ => {
526                                    unreachable!("connector doesn't support schema change")
527                                }
528                            }
529
530                            let snapshot_value: Datum = value_text.and_then(|value_text| {
531                                ScalarImpl::from_text(value_text.as_str(), &data_type)
532                                    .inspect_err(|err| {
533                                        tracing::warn!(
534                                            target: "auto_schema_change",
535                                            error = %err.as_report(),
536                                            column = %name,
537                                            data_type = %data_type,
538                                            default_value_expression = default_val_expr_str,
539                                            upstream_ddl = %upstream_ddl,
540                                            "non-constant default expression, column added without default. \
541                                             If this column is not newly added by this schema change, it is safe to ignore this warning. \
542                                             If this column is newly added by this schema change, existing rows will be NULL in this column — consider using COALESCE in queries to provide a fallback value."
543                                        );
544                                    })
545                                    .ok()
546                            });
547
548                            if snapshot_value.is_none() {
549                                ColumnDesc::named(name, ColumnId::placeholder(), data_type)
550                            } else {
551                                ColumnDesc::named_with_default_value(
552                                    name,
553                                    ColumnId::placeholder(),
554                                    data_type,
555                                    snapshot_value,
556                                )
557                            }
558                        }
559                        _ => ColumnDesc::named(name, ColumnId::placeholder(), data_type),
560                    };
561                    column_descs.push(column_desc);
562                }
563            }
564
565            // concatenate the source_id to the cdc_table_id
566            let cdc_table_id = build_cdc_table_id(source_id, id.replace('"', "").as_str());
567            schema_changes.push(TableSchemaChange {
568                cdc_table_id,
569                columns: column_descs
570                    .into_iter()
571                    .map(|column_desc| ColumnCatalog {
572                        column_desc,
573                        is_hidden: false,
574                    })
575                    .collect_vec(),
576                change_type: ty.as_str().into(),
577                upstream_ddl: upstream_ddl.clone(),
578            });
579        }
580
581        Ok(SchemaChangeEnvelope {
582            table_changes: schema_changes,
583        })
584    } else {
585        Err(AccessError::Undefined {
586            name: "table schema change".into(),
587            path: TABLE_CHANGES.into(),
588        })
589    }
590}
591
592impl<A> DebeziumChangeEvent<A>
593where
594    A: Access,
595{
596    /// Panic: one of the `key_accessor` or `value_accessor` must be provided.
597    pub fn new(key_accessor: Option<A>, value_accessor: Option<A>) -> Self {
598        assert!(key_accessor.is_some() || value_accessor.is_some());
599        Self {
600            value_accessor,
601            key_accessor,
602            is_mongodb: false,
603        }
604    }
605
606    pub fn new_mongodb_event(key_accessor: Option<A>, value_accessor: Option<A>) -> Self {
607        assert!(key_accessor.is_some() || value_accessor.is_some());
608        Self {
609            value_accessor,
610            key_accessor,
611            is_mongodb: true,
612        }
613    }
614
615    /// Returns the transaction metadata if exists.
616    ///
617    /// See the [doc](https://debezium.io/documentation/reference/2.3/connectors/postgresql.html#postgresql-transaction-metadata) of Debezium for more details.
618    pub(crate) fn transaction_control(
619        &self,
620        connector_props: &ConnectorProperties,
621    ) -> Option<TransactionControl> {
622        // Ignore if `value_accessor` is not provided or there's any error when
623        // trying to parse the transaction metadata.
624        self.value_accessor
625            .as_ref()
626            .and_then(|accessor| parse_transaction_meta(accessor, connector_props).ok())
627    }
628}
629
630impl<A> ChangeEvent for DebeziumChangeEvent<A>
631where
632    A: Access,
633{
634    fn access_field(&self, desc: &SourceColumnDesc) -> super::AccessResult<DatumCow<'_>> {
635        match self.op()? {
636            ChangeEventOperation::Delete => {
637                // For delete events of MongoDB, the "before" and "after" field both are null in the value,
638                // we need to extract the _id field from the key.
639                if self.is_mongodb && desc.name == "_id" {
640                    return self
641                        .key_accessor
642                        .as_ref()
643                        .expect("key_accessor must be provided for delete operation")
644                        .access(&[&desc.name], &desc.data_type);
645                }
646
647                if let Some(va) = self.value_accessor.as_ref() {
648                    va.access(&[BEFORE, &desc.name], &desc.data_type)
649                } else {
650                    self.key_accessor
651                        .as_ref()
652                        .unwrap()
653                        .access(&[&desc.name], &desc.data_type)
654                }
655            }
656
657            // value should not be None.
658            ChangeEventOperation::Upsert => {
659                // For upsert operation, if desc is an additional column, access field in the `SOURCE` field.
660                desc.additional_column.column_type.as_ref().map_or_else(
661                    || {
662                        self.value_accessor
663                            .as_ref()
664                            .expect("value_accessor must be provided for upsert operation")
665                            .access(&[AFTER, &desc.name], &desc.data_type)
666                    },
667                    |additional_column_type| {
668                        match *additional_column_type {
669                            ColumnType::Timestamp(_) => {
670                                // access payload.source.ts_ms
671                                let ts_ms = self
672                                    .value_accessor
673                                    .as_ref()
674                                    .expect("value_accessor must be provided for upsert operation")
675                                    .access_owned(&[SOURCE, SOURCE_TS_MS], &DataType::Int64)?;
676                                Ok(DatumCow::Owned(ts_ms.map(|scalar| {
677                                    Timestamptz::from_millis(scalar.into_int64())
678                                        .expect("source.ts_ms must in millisecond")
679                                        .to_scalar_value()
680                                })))
681                            }
682                            ColumnType::DatabaseName(_) => self
683                                .value_accessor
684                                .as_ref()
685                                .expect("value_accessor must be provided for upsert operation")
686                                .access(&[SOURCE, SOURCE_DB], &desc.data_type),
687                            ColumnType::SchemaName(_) => self
688                                .value_accessor
689                                .as_ref()
690                                .expect("value_accessor must be provided for upsert operation")
691                                .access(&[SOURCE, SOURCE_SCHEMA], &desc.data_type),
692                            ColumnType::TableName(_) => self
693                                .value_accessor
694                                .as_ref()
695                                .expect("value_accessor must be provided for upsert operation")
696                                .access(&[SOURCE, SOURCE_TABLE], &desc.data_type),
697                            ColumnType::CollectionName(_) => self
698                                .value_accessor
699                                .as_ref()
700                                .expect("value_accessor must be provided for upsert operation")
701                                .access(&[SOURCE, SOURCE_COLLECTION], &desc.data_type),
702                            _ => Err(AccessError::UnsupportedAdditionalColumn {
703                                name: desc.name.clone(),
704                            }),
705                        }
706                    },
707                )
708            }
709        }
710    }
711
712    fn op(&self) -> Result<ChangeEventOperation, AccessError> {
713        if let Some(accessor) = &self.value_accessor {
714            if let Some(ScalarRefImpl::Utf8(op)) =
715                accessor.access(&[OP], &DataType::Varchar)?.to_datum_ref()
716            {
717                match op {
718                    DEBEZIUM_READ_OP | DEBEZIUM_CREATE_OP | DEBEZIUM_UPDATE_OP => {
719                        return Ok(ChangeEventOperation::Upsert);
720                    }
721                    DEBEZIUM_DELETE_OP => return Ok(ChangeEventOperation::Delete),
722                    _ => (),
723                }
724            }
725            Err(super::AccessError::Undefined {
726                name: "op".into(),
727                path: Default::default(),
728            })
729        } else {
730            Ok(ChangeEventOperation::Delete)
731        }
732    }
733}
734
735/// Access support for Mongo
736///
737/// For now, we considerate `strong_schema` typed `MongoDB` Debezium event jsons only.
738pub struct MongoJsonAccess<A> {
739    accessor: A,
740    strong_schema: bool,
741}
742
743pub fn extract_bson_id(id_type: &DataType, bson_doc: &serde_json::Value) -> AccessResult {
744    let id_field = if let Some(value) = bson_doc.get("_id") {
745        value
746    } else {
747        bson_doc
748    };
749
750    let type_error = || AccessError::TypeError {
751        expected: id_type.to_string(),
752        got: match id_field {
753            serde_json::Value::Null => "null",
754            serde_json::Value::Bool(_) => "bool",
755            serde_json::Value::Number(_) => "number",
756            serde_json::Value::String(_) => "string",
757            serde_json::Value::Array(_) => "array",
758            serde_json::Value::Object(_) => "object",
759        }
760        .to_owned(),
761        value: id_field.to_string(),
762    };
763
764    let id: Datum = match id_type {
765        DataType::Jsonb => ScalarImpl::Jsonb(id_field.clone().into()).into(),
766        DataType::Varchar => match id_field {
767            serde_json::Value::String(s) => Some(ScalarImpl::Utf8(s.clone().into())),
768            serde_json::Value::Object(obj) if obj.contains_key("$oid") => Some(ScalarImpl::Utf8(
769                obj["$oid"].as_str().unwrap_or_default().into(),
770            )),
771            _ => return Err(type_error()),
772        },
773        DataType::Int32 => {
774            if let serde_json::Value::Object(obj) = id_field
775                && obj.contains_key("$numberInt")
776            {
777                let int_str = obj["$numberInt"].as_str().unwrap_or_default();
778                Some(ScalarImpl::Int32(int_str.parse().unwrap_or_default()))
779            } else {
780                return Err(type_error());
781            }
782        }
783        DataType::Int64 => {
784            if let serde_json::Value::Object(obj) = id_field
785                && obj.contains_key("$numberLong")
786            {
787                let int_str = obj["$numberLong"].as_str().unwrap_or_default();
788                Some(ScalarImpl::Int64(int_str.parse().unwrap_or_default()))
789            } else {
790                return Err(type_error());
791            }
792        }
793        _ => unreachable!("DebeziumMongoJsonParser::new must ensure _id column datatypes."),
794    };
795    Ok(id)
796}
797
798/// Extract the field data from the bson document
799///
800/// BSON document is a JSON object with some special fields, such as:
801/// long integer: {"$numberLong": "1630454400000"}
802/// date time: {"$date": {"$numberLong": "1630454400000"}}
803///
804/// For now, we support only the Canonical format of the date and timestamp.
805///
806/// # NOTE:
807///
808/// - `field` indicates the field name in the bson document, if it is None, the `bson_doc` is the field itself.
809// similar to extract the "_id" field from the message payload
810pub fn extract_bson_field(
811    type_expected: &DataType,
812    bson_doc: &serde_json::Value,
813    field: Option<&str>,
814) -> AccessResult {
815    let type_error = |datum: &serde_json::Value| AccessError::TypeError {
816        expected: type_expected.to_string(),
817        got: match bson_doc {
818            serde_json::Value::Null => "null",
819            serde_json::Value::Bool(_) => "bool",
820            serde_json::Value::Number(_) => "number",
821            serde_json::Value::String(_) => "string",
822            serde_json::Value::Array(_) => "array",
823            serde_json::Value::Object(_) => "object",
824        }
825        .to_owned(),
826        value: datum.to_string(),
827    };
828
829    let datum = if let Some(field) = field {
830        let Some(bson_doc) = bson_doc.get(field) else {
831            return Err(type_error(bson_doc));
832        };
833        bson_doc
834    } else {
835        bson_doc
836    };
837
838    if datum.is_null() {
839        return Ok(None);
840    }
841
842    let field_datum: Datum = match type_expected {
843        DataType::Boolean => {
844            if datum.is_boolean() {
845                Some(ScalarImpl::Bool(datum.as_bool().unwrap()))
846            } else {
847                return Err(type_error(datum));
848            }
849        }
850        DataType::Jsonb => ScalarImpl::Jsonb(datum.clone().into()).into(),
851        DataType::Varchar => match datum {
852            serde_json::Value::String(s) => Some(ScalarImpl::Utf8(s.clone().into())),
853            serde_json::Value::Object(obj) if obj.contains_key("$oid") && field == Some("_id") => {
854                obj["oid"].as_str().map(|s| ScalarImpl::Utf8(s.into()))
855            }
856            _ => return Err(type_error(datum)),
857        },
858        DataType::Int16
859        | DataType::Int32
860        | DataType::Int64
861        | DataType::Int256
862        | DataType::Float32
863        | DataType::Float64 => {
864            if !datum.is_object() {
865                return Err(type_error(datum));
866            };
867
868            bson_extract_number(datum, type_expected)?
869        }
870
871        DataType::Date | DataType::Timestamp | DataType::Timestamptz => {
872            if let serde_json::Value::Object(mp) = datum {
873                if mp.contains_key("$timestamp") && mp["$timestamp"].is_object() {
874                    bson_extract_timestamp(datum, type_expected)?
875                } else if mp.contains_key("$date") {
876                    bson_extract_date(datum, type_expected)?
877                } else {
878                    return Err(type_error(datum));
879                }
880            } else {
881                return Err(type_error(datum));
882            }
883        }
884        DataType::Decimal => {
885            if let serde_json::Value::Object(obj) = datum
886                && obj.contains_key("$numberDecimal")
887                && obj["$numberDecimal"].is_string()
888            {
889                let number = obj["$numberDecimal"].as_str().unwrap();
890
891                let dec = risingwave_common::types::Decimal::from_str(number).map_err(|_| {
892                    AccessError::TypeError {
893                        expected: type_expected.to_string(),
894                        got: "unparsable string".into(),
895                        value: number.to_owned(),
896                    }
897                })?;
898                Some(ScalarImpl::Decimal(dec))
899            } else {
900                return Err(type_error(datum));
901            }
902        }
903
904        DataType::Bytea => {
905            if let serde_json::Value::Object(obj) = datum
906                && obj.contains_key("$binary")
907                && obj["$binary"].is_object()
908            {
909                use base64::Engine;
910
911                let binary = obj["$binary"].as_object().unwrap();
912
913                if !binary.contains_key("$base64")
914                    || !binary["$base64"].is_string()
915                    || !binary.contains_key("$subType")
916                    || !binary["$subType"].is_string()
917                {
918                    return Err(AccessError::TypeError {
919                        expected: type_expected.to_string(),
920                        got: "object".into(),
921                        value: datum.to_string(),
922                    });
923                }
924
925                let b64_str = binary["$base64"]
926                    .as_str()
927                    .ok_or_else(|| AccessError::TypeError {
928                        expected: type_expected.to_string(),
929                        got: "object".into(),
930                        value: datum.to_string(),
931                    })?;
932
933                // type is not used for now
934                let _type_str =
935                    binary["$subType"]
936                        .as_str()
937                        .ok_or_else(|| AccessError::TypeError {
938                            expected: type_expected.to_string(),
939                            got: "object".into(),
940                            value: datum.to_string(),
941                        })?;
942
943                let bytes = base64::prelude::BASE64_STANDARD
944                    .decode(b64_str)
945                    .map_err(|_| AccessError::TypeError {
946                        expected: "$binary object with $base64 string and $subType string field"
947                            .to_owned(),
948                        got: "string".to_owned(),
949                        value: bson_doc.to_string(),
950                    })?;
951                let bytea = ScalarImpl::Bytea(bytes.into());
952                Some(bytea)
953            } else {
954                return Err(type_error(datum));
955            }
956        }
957
958        DataType::Struct(struct_fields) => {
959            let mut datums = vec![];
960            for (field_name, field_type) in struct_fields.iter() {
961                let field_datum = extract_bson_field(field_type, datum, Some(field_name))?;
962                datums.push(field_datum);
963            }
964            let value = StructValue::new(datums);
965
966            Some(ScalarImpl::Struct(value))
967        }
968
969        DataType::List(list_type) => {
970            let elem_type = list_type.elem();
971            let Some(d_array) = datum.as_array() else {
972                return Err(type_error(datum));
973            };
974
975            let mut builder = elem_type.create_array_builder(d_array.len());
976            for item in d_array {
977                builder.append(extract_bson_field(elem_type, item, None)?);
978            }
979            Some(ScalarImpl::from(ListValue::new(builder.finish())))
980        }
981
982        _ => {
983            if let Some(field_name) = field {
984                unreachable!(
985                    "DebeziumMongoJsonParser::new must ensure {field_name} column datatypes."
986                )
987            } else {
988                let type_expected = type_expected.to_string();
989                unreachable!(
990                    "DebeziumMongoJsonParser::new must ensure type of `{type_expected}` matches datum `{datum}`"
991                )
992            }
993        }
994    };
995    Ok(field_datum)
996}
997
998fn bson_extract_number(bson_doc: &serde_json::Value, type_expected: &DataType) -> AccessResult {
999    let field_name = match type_expected {
1000        DataType::Int16 => "$numberInt",
1001        DataType::Int32 => "$numberInt",
1002        DataType::Int64 => "$numberLong",
1003        DataType::Int256 => "$numberLong",
1004        DataType::Float32 => "$numberDouble",
1005        DataType::Float64 => "$numberDouble",
1006        _ => unreachable!("DebeziumMongoJsonParser::new must ensure column datatypes."),
1007    };
1008
1009    let datum = bson_doc.get(field_name);
1010    if datum.is_none() {
1011        return Err(AccessError::TypeError {
1012            expected: type_expected.to_string(),
1013            got: "object".into(),
1014            value: bson_doc.to_string(),
1015        });
1016    }
1017
1018    let datum = datum.unwrap();
1019
1020    if datum.is_string() {
1021        let Some(num_str) = datum.as_str() else {
1022            return Err(AccessError::TypeError {
1023                expected: type_expected.to_string(),
1024                got: "string".into(),
1025                value: datum.to_string(),
1026            });
1027        };
1028        // parse to float
1029        if [DataType::Float32, DataType::Float64].contains(type_expected) {
1030            match (num_str, type_expected) {
1031                ("Infinity", DataType::Float64) => {
1032                    return Ok(Some(ScalarImpl::Float64(f64::INFINITY.into())));
1033                }
1034                ("Infinity", DataType::Float32) => {
1035                    return Ok(Some(ScalarImpl::Float32(f32::INFINITY.into())));
1036                }
1037                ("-Infinity", DataType::Float64) => {
1038                    return Ok(Some(ScalarImpl::Float64(f64::NEG_INFINITY.into())));
1039                }
1040                ("-Infinity", DataType::Float32) => {
1041                    return Ok(Some(ScalarImpl::Float32(f32::NEG_INFINITY.into())));
1042                }
1043                ("NaN", DataType::Float64) => {
1044                    return Ok(Some(ScalarImpl::Float64(f64::NAN.into())));
1045                }
1046                ("NaN", DataType::Float32) => {
1047                    return Ok(Some(ScalarImpl::Float32(f32::NAN.into())));
1048                }
1049                _ => {}
1050            }
1051
1052            let parsed_num: f64 = match num_str.parse() {
1053                Ok(n) => n,
1054                Err(_e) => {
1055                    return Err(AccessError::TypeError {
1056                        expected: type_expected.to_string(),
1057                        got: "string".into(),
1058                        value: num_str.to_owned(),
1059                    });
1060                }
1061            };
1062            if *type_expected == DataType::Float64 {
1063                return Ok(Some(ScalarImpl::Float64(parsed_num.into())));
1064            } else {
1065                let parsed_num = parsed_num as f32;
1066                return Ok(Some(ScalarImpl::Float32(parsed_num.into())));
1067            }
1068        }
1069        // parse to large int
1070        if *type_expected == DataType::Int256 {
1071            let parsed_num = match Int256::from_str(num_str) {
1072                Ok(n) => n,
1073                Err(_) => {
1074                    return Err(AccessError::TypeError {
1075                        expected: type_expected.to_string(),
1076                        got: "string".into(),
1077                        value: num_str.to_owned(),
1078                    });
1079                }
1080            };
1081            return Ok(Some(ScalarImpl::Int256(parsed_num)));
1082        }
1083
1084        // parse to integer
1085        let parsed_num: i64 = match num_str.parse() {
1086            Ok(n) => n,
1087            Err(_e) => {
1088                return Err(AccessError::TypeError {
1089                    expected: type_expected.to_string(),
1090                    got: "string".into(),
1091                    value: num_str.to_owned(),
1092                });
1093            }
1094        };
1095        match type_expected {
1096            DataType::Int16 => {
1097                if parsed_num < i16::MIN as i64 || parsed_num > i16::MAX as i64 {
1098                    return Err(AccessError::TypeError {
1099                        expected: type_expected.to_string(),
1100                        got: "string".into(),
1101                        value: num_str.to_owned(),
1102                    });
1103                }
1104                return Ok(Some(ScalarImpl::Int16(parsed_num as i16)));
1105            }
1106            DataType::Int32 => {
1107                if parsed_num < i32::MIN as i64 || parsed_num > i32::MAX as i64 {
1108                    return Err(AccessError::TypeError {
1109                        expected: type_expected.to_string(),
1110                        got: "string".into(),
1111                        value: num_str.to_owned(),
1112                    });
1113                }
1114                return Ok(Some(ScalarImpl::Int32(parsed_num as i32)));
1115            }
1116            DataType::Int64 => {
1117                return Ok(Some(ScalarImpl::Int64(parsed_num)));
1118            }
1119            _ => unreachable!("DebeziumMongoJsonParser::new must ensure column datatypes."),
1120        }
1121    }
1122    if datum.is_null() {
1123        return Err(AccessError::TypeError {
1124            expected: type_expected.to_string(),
1125            got: "null".into(),
1126            value: bson_doc.to_string(),
1127        });
1128    }
1129
1130    if datum.is_array() {
1131        return Err(AccessError::TypeError {
1132            expected: type_expected.to_string(),
1133            got: "array".to_owned(),
1134            value: datum.to_string(),
1135        });
1136    }
1137
1138    if datum.is_object() {
1139        return Err(AccessError::TypeError {
1140            expected: type_expected.to_string(),
1141            got: "object".to_owned(),
1142            value: datum.to_string(),
1143        });
1144    }
1145
1146    if datum.is_boolean() {
1147        return Err(AccessError::TypeError {
1148            expected: type_expected.to_string(),
1149            got: "boolean".into(),
1150            value: bson_doc.to_string(),
1151        });
1152    }
1153
1154    if datum.is_number() {
1155        let got_type = if datum.is_f64() { "f64" } else { "i64" };
1156        return Err(AccessError::TypeError {
1157            expected: type_expected.to_string(),
1158            got: got_type.into(),
1159            value: bson_doc.to_string(),
1160        });
1161    }
1162
1163    Err(AccessError::TypeError {
1164        expected: type_expected.to_string(),
1165        got: "unknown".into(),
1166        value: bson_doc.to_string(),
1167    })
1168}
1169
1170fn bson_extract_date(bson_doc: &serde_json::Value, type_expected: &DataType) -> AccessResult {
1171    // according to mongodb extended json v2
1172    // the date could be:
1173    //
1174    // the timestamp type could be:
1175    //
1176    // both Canonical and Relaxed format:
1177    // {"$timestamp": {"t": 1630454400, "i": 1}}
1178    //
1179    // Canonical: {"$date": {"$numberLong": "1630454400000"}}
1180    // date is encoded as number of milliseconds since the Unix epoch
1181    //
1182    // Relaxed: {"$date": "2021-09-01T00:00:00.000Z"}
1183    // date is encoded as ISO8601 string
1184
1185    let datum = &bson_doc["$date"];
1186
1187    let type_error = || AccessError::TypeError {
1188        expected: type_expected.to_string(),
1189        got: match bson_doc {
1190            serde_json::Value::Null => "null",
1191            serde_json::Value::Bool(_) => "bool",
1192            serde_json::Value::Number(_) => "number",
1193            serde_json::Value::String(_) => "string",
1194            serde_json::Value::Array(_) => "array",
1195            serde_json::Value::Object(_) => "object",
1196        }
1197        .to_owned(),
1198        value: datum.to_string(),
1199    };
1200
1201    // deal with the Canonical format only
1202    let millis = match datum {
1203        // Canonical format {"$date": {"$numberLong": "1630454400000"}}
1204        serde_json::Value::Object(obj)
1205            if obj.contains_key("$numberLong") && obj["$numberLong"].is_string() =>
1206        {
1207            obj["$numberLong"]
1208                .as_str()
1209                .unwrap()
1210                .parse::<i64>()
1211                .map_err(|_| AccessError::TypeError {
1212                    expected: "timestamp".into(),
1213                    got: "object".into(),
1214                    value: datum.to_string(),
1215                })?
1216        }
1217        // Relaxed format {"$date": "2021-09-01T00:00:00.000Z"}
1218        serde_json::Value::String(s) => {
1219            let dt =
1220                chrono::DateTime::parse_from_rfc3339(s).map_err(|_| AccessError::TypeError {
1221                    expected: "valid ISO-8601 date string".into(),
1222                    got: "string".into(),
1223                    value: datum.to_string(),
1224                })?;
1225            dt.timestamp_millis()
1226        }
1227
1228        // jsonv1 format
1229        // {"$date": 1630454400000}
1230        serde_json::Value::Number(num) => num.as_i64().ok_or_else(|| AccessError::TypeError {
1231            expected: "timestamp".into(),
1232            got: "number".into(),
1233            value: datum.to_string(),
1234        })?,
1235
1236        _ => return Err(type_error()),
1237    };
1238
1239    let datetime =
1240        chrono::DateTime::from_timestamp_millis(millis).ok_or_else(|| AccessError::TypeError {
1241            expected: "timestamp".into(),
1242            got: "object".into(),
1243            value: datum.to_string(),
1244        })?;
1245
1246    let res = match type_expected {
1247        DataType::Date => {
1248            let naive = datetime.naive_local();
1249            let dt = naive.date();
1250            Some(ScalarImpl::Date(dt.into()))
1251        }
1252        DataType::Time => {
1253            let naive = datetime.naive_local();
1254            let dt = naive.time();
1255            Some(ScalarImpl::Time(dt.into()))
1256        }
1257        DataType::Timestamp => {
1258            let naive = datetime.naive_local();
1259            let dt = Timestamp::from(naive);
1260            Some(ScalarImpl::Timestamp(dt))
1261        }
1262        DataType::Timestamptz => {
1263            let dt = datetime.into();
1264            Some(ScalarImpl::Timestamptz(dt))
1265        }
1266        _ => unreachable!("DebeziumMongoJsonParser::new must ensure column datatypes."),
1267    };
1268    Ok(res)
1269}
1270
1271fn bson_extract_timestamp(bson_doc: &serde_json::Value, type_expected: &DataType) -> AccessResult {
1272    // according to mongodb extended json v2
1273    // the date could be:
1274    //
1275    // the timestamp type could be:
1276    //
1277    // both Canonical and Relaxed format:
1278    // {"$timestamp": {"t": 1630454400, "i": 1}}
1279    // t is the number of seconds since the Unix epoch
1280    //
1281    // Canonical: {"$date": {"$numberLong": "1630454400000"}}
1282    // date is encoded as number of milliseconds since the Unix epoch
1283    //
1284    // Relaxed: {"$date": "2021-09-01T00:00:00.000Z"}
1285    // date is encoded as ISO8601 string
1286    //
1287    // *For now, we support the Canonical format only.*
1288
1289    let Some(obj) = bson_doc["$timestamp"].as_object() else {
1290        return Err(AccessError::TypeError {
1291            expected: "timestamp".into(),
1292            got: "object".into(),
1293            value: bson_doc.to_string(),
1294        });
1295    };
1296
1297    if !obj.contains_key("t") || !obj["t"].is_u64() || !obj.contains_key("i") || !obj["i"].is_u64()
1298    {
1299        return Err(AccessError::TypeError {
1300            expected: "timestamp with valid seconds since epoch".into(),
1301            got: "object".into(),
1302            value: bson_doc.to_string(),
1303        });
1304    }
1305
1306    let since_epoch = obj["t"].as_i64().ok_or_else(|| AccessError::TypeError {
1307        expected: "timestamp with valid seconds since epoch".into(),
1308        got: "object".into(),
1309        value: bson_doc.to_string(),
1310    })?;
1311
1312    let chrono_datetime =
1313        chrono::DateTime::from_timestamp(since_epoch, 0).ok_or_else(|| AccessError::TypeError {
1314            expected: type_expected.to_string(),
1315            got: "object".to_owned(),
1316            value: bson_doc.to_string(),
1317        })?;
1318
1319    let res = match type_expected {
1320        DataType::Date => {
1321            let naive = chrono_datetime.naive_local();
1322            let dt = naive.date();
1323            Some(ScalarImpl::Date(dt.into()))
1324        }
1325        DataType::Time => {
1326            let naive = chrono_datetime.naive_local();
1327            let dt = naive.time();
1328            Some(ScalarImpl::Time(dt.into()))
1329        }
1330        DataType::Timestamp => {
1331            let naive = chrono_datetime.naive_local();
1332            let dt = Timestamp::from(naive);
1333            Some(ScalarImpl::Timestamp(dt))
1334        }
1335        DataType::Timestamptz => {
1336            let dt = chrono_datetime.into();
1337            Some(ScalarImpl::Timestamptz(dt))
1338        }
1339        _ => unreachable!("DebeziumMongoJsonParser::new must ensure column datatypes."),
1340    };
1341
1342    Ok(res)
1343}
1344
1345impl<A> MongoJsonAccess<A> {
1346    pub fn new(accessor: A, strong_schema: bool) -> Self {
1347        Self {
1348            accessor,
1349            strong_schema,
1350        }
1351    }
1352}
1353
1354impl<A> Access for MongoJsonAccess<A>
1355where
1356    A: Access,
1357{
1358    fn access<'a>(&'a self, path: &[&str], type_expected: &DataType) -> AccessResult<DatumCow<'a>> {
1359        match path {
1360            ["after" | "before", "_id"] => {
1361                let payload = self.access_owned(&[path[0]], &DataType::Jsonb)?;
1362                if let Some(ScalarImpl::Jsonb(bson_doc)) = payload {
1363                    Ok(extract_bson_id(type_expected, &bson_doc.take())?.into())
1364                } else {
1365                    // fail to extract the "_id" field from the message payload
1366                    Err(AccessError::Undefined {
1367                        name: "_id".to_owned(),
1368                        path: path[0].to_owned(),
1369                    })?
1370                }
1371            }
1372
1373            ["after" | "before", "payload"] if !self.strong_schema => {
1374                self.access(&[path[0]], &DataType::Jsonb)
1375            }
1376
1377            ["after" | "before", field] if self.strong_schema => {
1378                let payload = self.access_owned(&[path[0]], &DataType::Jsonb)?;
1379                if let Some(ScalarImpl::Jsonb(bson_doc)) = payload {
1380                    Ok(extract_bson_field(type_expected, &bson_doc.take(), Some(field))?.into())
1381                } else {
1382                    // fail to extract the expected field from the message payload
1383                    Err(AccessError::Undefined {
1384                        name: field.to_string(),
1385                        path: path[0].to_owned(),
1386                    })?
1387                }
1388            }
1389
1390            // To handle a DELETE message, we need to extract the "_id" field from the message key, because it is not in the payload.
1391            // In addition, the "_id" field is named as "id" in the key. An example of message key:
1392            // {"schema":null,"payload":{"id":"{\"$oid\": \"65bc9fb6c485f419a7a877fe\"}"}}
1393            ["_id"] => {
1394                let ret = self.accessor.access(path, type_expected);
1395                if matches!(ret, Err(AccessError::Undefined { .. })) {
1396                    let id_bson = self.accessor.access_owned(&["id"], &DataType::Jsonb)?;
1397                    if let Some(ScalarImpl::Jsonb(bson_doc)) = id_bson {
1398                        Ok(extract_bson_id(type_expected, &bson_doc.take())?.into())
1399                    } else {
1400                        // fail to extract the "_id" field from the message key
1401                        Err(AccessError::Undefined {
1402                            name: "_id".to_owned(),
1403                            path: "id".to_owned(),
1404                        })?
1405                    }
1406                } else {
1407                    ret
1408                }
1409            }
1410            _ => self.accessor.access(path, type_expected),
1411        }
1412    }
1413}