Skip to main content

risingwave_connector/parser/debezium/
debezium_parser.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::collections::BTreeMap;
16
17use risingwave_common::bail;
18
19use super::simd_json_parser::DebeziumJsonAccessBuilder;
20use super::{DebeziumAvroAccessBuilder, DebeziumAvroParserConfig};
21use crate::error::ConnectorResult;
22use crate::parser::unified::debezium::DebeziumChangeEvent;
23use crate::parser::unified::json::{
24    BigintUnsignedHandlingMode, NumericHandling, TimeHandling, TimestampHandling,
25    TimestamptzHandling,
26};
27use crate::parser::unified::util::apply_row_operation_on_stream_chunk_writer;
28use crate::parser::{
29    AccessBuilderImpl, ByteStreamSourceParser, EncodingProperties, EncodingType, ParseResult,
30    ParserFormat, ProtocolProperties, SourceStreamChunkRowWriter, SpecificParserConfig,
31};
32use crate::source::{SourceColumnDesc, SourceContext, SourceContextRef};
33
34#[derive(Debug)]
35pub struct DebeziumParser {
36    key_builder: AccessBuilderImpl,
37    payload_builder: AccessBuilderImpl,
38    pub(crate) rw_columns: Vec<SourceColumnDesc>,
39    source_ctx: SourceContextRef,
40
41    props: DebeziumProps,
42}
43
44pub const DEBEZIUM_IGNORE_KEY: &str = "ignore_key";
45
46#[derive(Debug, Clone, Default)]
47pub struct DebeziumProps {
48    // Ignore the key part of the message.
49    // If enabled, we don't take the key part into message accessor.
50    pub ignore_key: bool,
51}
52
53impl DebeziumProps {
54    pub fn from(props: &BTreeMap<String, String>) -> Self {
55        let ignore_key = props
56            .get(DEBEZIUM_IGNORE_KEY)
57            .map(|v| v.eq_ignore_ascii_case("true"))
58            .unwrap_or(false);
59        Self { ignore_key }
60    }
61}
62
63async fn build_accessor_builder(
64    config: EncodingProperties,
65    encoding_type: EncodingType,
66    numeric_handling: NumericHandling,
67) -> ConnectorResult<AccessBuilderImpl> {
68    match config {
69        EncodingProperties::Avro(_) => {
70            let config = DebeziumAvroParserConfig::new(config).await?;
71            Ok(AccessBuilderImpl::DebeziumAvro(
72                DebeziumAvroAccessBuilder::new(config, encoding_type)?,
73            ))
74        }
75        EncodingProperties::Json(json_config) => Ok(AccessBuilderImpl::DebeziumJson(
76            DebeziumJsonAccessBuilder::new(
77                json_config
78                    .timestamptz_handling
79                    .unwrap_or(TimestamptzHandling::GuessNumberUnit),
80                json_config
81                    .timestamp_handling
82                    .unwrap_or(TimestampHandling::GuessNumberUnit),
83                json_config.time_handling.unwrap_or(TimeHandling::Micro),
84                numeric_handling,
85                json_config
86                    .bigint_unsigned_handling
87                    .unwrap_or(BigintUnsignedHandlingMode::Long),
88                json_config.handle_postgres_toast_columns,
89            )?,
90        )),
91        _ => bail!("unsupported encoding for Debezium"),
92    }
93}
94
95impl DebeziumParser {
96    pub async fn new(
97        props: SpecificParserConfig,
98        rw_columns: Vec<SourceColumnDesc>,
99        source_ctx: SourceContextRef,
100        numeric_handling: NumericHandling,
101    ) -> ConnectorResult<Self> {
102        let key_builder = build_accessor_builder(
103            props.encoding_config.clone(),
104            EncodingType::Key,
105            numeric_handling.clone(),
106        )
107        .await?;
108        let payload_builder =
109            build_accessor_builder(props.encoding_config, EncodingType::Value, numeric_handling)
110                .await?;
111        let debezium_props = if let ProtocolProperties::Debezium(props) = props.protocol_config {
112            props
113        } else {
114            unreachable!(
115                "expecting Debezium protocol properties but got {:?}",
116                props.protocol_config
117            )
118        };
119        Ok(Self {
120            key_builder,
121            payload_builder,
122            rw_columns,
123            source_ctx,
124            props: debezium_props,
125        })
126    }
127
128    pub async fn new_for_test(rw_columns: Vec<SourceColumnDesc>) -> ConnectorResult<Self> {
129        use crate::parser::JsonProperties;
130
131        let props = SpecificParserConfig {
132            encoding_config: EncodingProperties::Json(JsonProperties {
133                use_schema_registry: false,
134                timestamptz_handling: None,
135                timestamp_handling: None,
136                time_handling: None,
137                bigint_unsigned_handling: None,
138                handle_postgres_toast_columns: false,
139            }),
140            protocol_config: ProtocolProperties::Debezium(DebeziumProps::default()),
141        };
142        Self::new(
143            props,
144            rw_columns,
145            SourceContext::dummy().into(),
146            NumericHandling::Relax {
147                string_parsing: false,
148            },
149        )
150        .await
151    }
152
153    pub async fn parse_inner(
154        &mut self,
155        key: Option<Vec<u8>>,
156        payload: Option<Vec<u8>>,
157        mut writer: SourceStreamChunkRowWriter<'_>,
158    ) -> ConnectorResult<ParseResult> {
159        let meta = writer.source_meta();
160        // tombetone messages are handled implicitly by these accessors
161        let key_accessor = match (key, self.props.ignore_key) {
162            (None, false) => None,
163            (Some(data), false) => Some(self.key_builder.generate_accessor(data, meta).await?),
164            (_, true) => None,
165        };
166        let payload_accessor = match payload {
167            None => None,
168            Some(data) => Some(self.payload_builder.generate_accessor(data, meta).await?),
169        };
170        let row_op = DebeziumChangeEvent::new(key_accessor, payload_accessor);
171
172        match apply_row_operation_on_stream_chunk_writer(&row_op, &mut writer) {
173            Ok(_) => Ok(ParseResult::Rows),
174            Err(err) => {
175                // Only try to access transaction control message if the row operation access failed
176                // to make it a fast path.
177                if let Some(transaction_control) =
178                    row_op.transaction_control(&self.source_ctx.connector_props)
179                {
180                    Ok(ParseResult::TransactionControl(transaction_control))
181                } else {
182                    Err(err)?
183                }
184            }
185        }
186    }
187}
188
189impl ByteStreamSourceParser for DebeziumParser {
190    fn columns(&self) -> &[SourceColumnDesc] {
191        &self.rw_columns
192    }
193
194    fn source_ctx(&self) -> &SourceContext {
195        &self.source_ctx
196    }
197
198    fn parser_format(&self) -> ParserFormat {
199        ParserFormat::Debezium
200    }
201
202    async fn parse_one<'a>(
203        &'a mut self,
204        _key: Option<Vec<u8>>,
205        _payload: Option<Vec<u8>>,
206        _writer: SourceStreamChunkRowWriter<'a>,
207    ) -> ConnectorResult<()> {
208        unreachable!("should call `parse_one_with_txn` instead")
209    }
210
211    async fn parse_one_with_txn<'a>(
212        &'a mut self,
213        key: Option<Vec<u8>>,
214        payload: Option<Vec<u8>>,
215        writer: SourceStreamChunkRowWriter<'a>,
216    ) -> ConnectorResult<ParseResult> {
217        self.parse_inner(key, payload, writer).await
218    }
219}
220
221#[cfg(test)]
222mod tests {
223    use std::ops::Deref;
224    use std::sync::Arc;
225
226    use risingwave_common::array::Op;
227    use risingwave_common::catalog::{CDC_SOURCE_COLUMN_NUM, ColumnCatalog, ColumnDesc, ColumnId};
228    use risingwave_common::row::Row;
229    use risingwave_common::types::{DataType, ScalarImpl, Timestamptz};
230    use risingwave_pb::plan_common::{
231        AdditionalColumn, AdditionalColumnTimestamp, additional_column,
232    };
233
234    use super::*;
235    use crate::parser::{JsonProperties, SourceStreamChunkBuilder, TransactionControl};
236    use crate::source::cdc::CdcSourceType;
237    use crate::source::{ConnectorProperties, SourceCtrlOpts};
238
239    #[tokio::test]
240    async fn test_parse_transaction_metadata() {
241        let schema = ColumnCatalog::debezium_cdc_source_cols();
242
243        let columns = schema
244            .iter()
245            .map(|c| SourceColumnDesc::from(&c.column_desc))
246            .collect::<Vec<_>>();
247
248        let props = SpecificParserConfig {
249            encoding_config: EncodingProperties::Json(JsonProperties {
250                use_schema_registry: false,
251                timestamptz_handling: None,
252                timestamp_handling: None,
253                time_handling: None,
254                bigint_unsigned_handling: None,
255                handle_postgres_toast_columns: false,
256            }),
257            protocol_config: ProtocolProperties::Debezium(DebeziumProps::default()),
258        };
259        let source_ctx = SourceContext {
260            connector_props: ConnectorProperties::PostgresCdc(Box::default()),
261            ..SourceContext::dummy()
262        };
263        let mut parser = DebeziumParser::new(
264            props,
265            columns.clone(),
266            Arc::new(source_ctx),
267            CdcSourceType::Postgres.debezium_numeric_handling(),
268        )
269        .await
270        .unwrap();
271        let mut dummy_builder = SourceStreamChunkBuilder::new(columns, SourceCtrlOpts::for_test());
272
273        // "id":"35352:3962948040" Postgres transaction ID itself and LSN of given operation separated by colon, i.e. the format is txID:LSN
274        let begin_msg = r#"{"schema":null,"payload":{"status":"BEGIN","id":"35352:3962948040","event_count":null,"data_collections":null,"ts_ms":1704269323180}}"#;
275        let commit_msg = r#"{"schema":null,"payload":{"status":"END","id":"35352:3962950064","event_count":11,"data_collections":[{"data_collection":"public.orders_tx","event_count":5},{"data_collection":"public.person","event_count":6}],"ts_ms":1704269323180}}"#;
276        let res = parser
277            .parse_one_with_txn(
278                None,
279                Some(begin_msg.as_bytes().to_vec()),
280                dummy_builder.row_writer(),
281            )
282            .await;
283        match res {
284            Ok(ParseResult::TransactionControl(TransactionControl::Begin { id })) => {
285                assert_eq!(id.deref(), "35352");
286            }
287            _ => panic!("unexpected parse result: {:?}", res),
288        }
289        let res = parser
290            .parse_one_with_txn(
291                None,
292                Some(commit_msg.as_bytes().to_vec()),
293                dummy_builder.row_writer(),
294            )
295            .await;
296        match res {
297            Ok(ParseResult::TransactionControl(TransactionControl::Commit { id })) => {
298                assert_eq!(id.deref(), "35352");
299            }
300            _ => panic!("unexpected parse result: {:?}", res),
301        }
302    }
303
304    /// Verifies that committed Oracle create, update, and delete events decode `NUMBER` values
305    /// emitted as JSON strings into RisingWave integer and decimal types while preserving the
306    /// accompanying `RAW` and `VARCHAR2` values.
307    #[tokio::test]
308    async fn test_parse_oracle_row_changes_with_numeric_strings() {
309        let columns = [
310            ColumnDesc::named("ID", ColumnId::new(1), DataType::Int64),
311            ColumnDesc::named("QUANTITY", ColumnId::new(2), DataType::Int32),
312            ColumnDesc::named("AMOUNT", ColumnId::new(3), DataType::Decimal),
313            ColumnDesc::named("PAYLOAD", ColumnId::new(4), DataType::Bytea),
314            ColumnDesc::named("NAME", ColumnId::new(5), DataType::Varchar),
315        ];
316        let columns = columns
317            .iter()
318            .map(SourceColumnDesc::from)
319            .collect::<Vec<_>>();
320        let props = SpecificParserConfig {
321            encoding_config: EncodingProperties::Json(JsonProperties {
322                use_schema_registry: false,
323                timestamptz_handling: None,
324                timestamp_handling: None,
325                time_handling: None,
326                bigint_unsigned_handling: None,
327                handle_postgres_toast_columns: false,
328            }),
329            protocol_config: ProtocolProperties::Debezium(DebeziumProps::default()),
330        };
331        let source_ctx = SourceContext {
332            connector_props: ConnectorProperties::OracleCdc(Box::default()),
333            ..SourceContext::dummy()
334        };
335        let mut parser = DebeziumParser::new(
336            props,
337            columns.clone(),
338            Arc::new(source_ctx),
339            CdcSourceType::Oracle.debezium_numeric_handling(),
340        )
341        .await
342        .unwrap();
343        let mut builder = SourceStreamChunkBuilder::new(columns, SourceCtrlOpts::for_test());
344        let events = [
345            // INSERT INTO APP.CUSTOMERS (ID, QUANTITY, AMOUNT, PAYLOAD, NAME)
346            // VALUES (1, 7, 123.45, HEXTORAW('010203'), 'before');
347            // COMMIT;
348            r#"{"payload":{"before":null,"after":{"ID":"1","QUANTITY":"7","AMOUNT":"123.45","PAYLOAD":"AQID","NAME":"before"},"source":{"connector":"oracle","ts_ms":1788480000000,"schema":"APP","table":"CUSTOMERS"},"op":"c","ts_ms":1788480000010}}"#,
349            // UPDATE APP.CUSTOMERS
350            // SET QUANTITY = 8, AMOUNT = 456.78, PAYLOAD = HEXTORAW('040506'), NAME = 'after'
351            // WHERE ID = 1;
352            // COMMIT;
353            r#"{"payload":{"before":{"ID":"1","QUANTITY":"7","AMOUNT":"123.45","PAYLOAD":"AQID","NAME":"before"},"after":{"ID":"1","QUANTITY":"8","AMOUNT":"456.78","PAYLOAD":"BAUG","NAME":"after"},"source":{"connector":"oracle","ts_ms":1788480001000,"schema":"APP","table":"CUSTOMERS"},"op":"u","ts_ms":1788480001010}}"#,
354            // DELETE FROM APP.CUSTOMERS WHERE ID = 1;
355            // COMMIT;
356            r#"{"payload":{"before":{"ID":"1","QUANTITY":"8","AMOUNT":"456.78","PAYLOAD":"BAUG","NAME":"after"},"after":null,"source":{"connector":"oracle","ts_ms":1788480002000,"schema":"APP","table":"CUSTOMERS"},"op":"d","ts_ms":1788480002010}}"#,
357        ];
358
359        for event in events {
360            let result = parser
361                .parse_one_with_txn(None, Some(event.as_bytes().to_vec()), builder.row_writer())
362                .await
363                .unwrap();
364            assert!(matches!(result, ParseResult::Rows));
365        }
366
367        builder.finish_current_chunk();
368        let chunk = builder.consume_ready_chunks().next().unwrap();
369        assert_eq!(chunk.ops(), &[Op::Insert, Op::Insert, Op::Delete]);
370        let rows = chunk
371            .rows()
372            .map(|(_, row)| row.to_owned_row())
373            .collect::<Vec<_>>();
374        assert_eq!(rows[0][0], Some(ScalarImpl::Int64(1)));
375        assert_eq!(rows[0][1], Some(ScalarImpl::Int32(7)));
376        assert_eq!(
377            rows[0][2],
378            Some(ScalarImpl::Decimal("123.45".parse().unwrap()))
379        );
380        assert_eq!(rows[0][3], Some(ScalarImpl::Bytea(vec![1, 2, 3].into())));
381        assert_eq!(rows[1][1], Some(ScalarImpl::Int32(8)));
382        assert_eq!(
383            rows[1][2],
384            Some(ScalarImpl::Decimal("456.78".parse().unwrap()))
385        );
386        assert_eq!(rows[2], rows[1]);
387    }
388
389    #[tokio::test]
390    async fn test_parse_additional_columns() {
391        let columns = [
392            ColumnDesc::named("O_ORDERKEY", ColumnId::new(1), DataType::Int64),
393            ColumnDesc::named("O_CUSTKEY", ColumnId::new(2), DataType::Int64),
394            ColumnDesc::named("O_ORDERSTATUS", ColumnId::new(3), DataType::Varchar),
395            ColumnDesc::named("O_TOTALPRICE", ColumnId::new(4), DataType::Decimal),
396            ColumnDesc::named("O_ORDERDATE", ColumnId::new(5), DataType::Date),
397            ColumnDesc::named_with_additional_column(
398                "commit_ts",
399                ColumnId::new(6),
400                DataType::Timestamptz,
401                AdditionalColumn {
402                    column_type: Some(additional_column::ColumnType::Timestamp(
403                        AdditionalColumnTimestamp {},
404                    )),
405                },
406            ),
407        ];
408
409        let columns = columns
410            .iter()
411            .map(SourceColumnDesc::from)
412            .collect::<Vec<_>>();
413
414        let props = SpecificParserConfig {
415            encoding_config: EncodingProperties::Json(JsonProperties {
416                use_schema_registry: false,
417                timestamptz_handling: None,
418                timestamp_handling: None,
419                time_handling: None,
420                bigint_unsigned_handling: None,
421                handle_postgres_toast_columns: false,
422            }),
423            protocol_config: ProtocolProperties::Debezium(DebeziumProps::default()),
424        };
425        let source_ctx = SourceContext {
426            connector_props: ConnectorProperties::PostgresCdc(Box::default()),
427            ..SourceContext::dummy()
428        };
429        let mut parser = DebeziumParser::new(
430            props,
431            columns.clone(),
432            Arc::new(source_ctx),
433            CdcSourceType::Postgres.debezium_numeric_handling(),
434        )
435        .await
436        .unwrap();
437        let mut builder = SourceStreamChunkBuilder::new(columns, SourceCtrlOpts::for_test());
438
439        let payload = r#"{ "payload": { "before": null, "after": { "O_ORDERKEY": 5, "O_CUSTKEY": 44485, "O_ORDERSTATUS": "F", "O_TOTALPRICE": "144659.20", "O_ORDERDATE": "1994-07-30" }, "source": { "version": "1.9.7.Final", "connector": "mysql", "name": "RW_CDC_1002", "ts_ms": 1695277757000, "snapshot": "last", "db": "mydb", "sequence": null, "table": "orders_new", "server_id": 0, "gtid": null, "file": "binlog.000008", "pos": 3693, "row": 0, "thread": null, "query": null }, "op": "c", "ts_ms": 1695277757017, "transaction": null } }"#;
440
441        let res = parser
442            .parse_one_with_txn(
443                None,
444                Some(payload.as_bytes().to_vec()),
445                builder.row_writer(),
446            )
447            .await;
448        match res {
449            Ok(ParseResult::Rows) => {
450                builder.finish_current_chunk();
451                let chunk = builder.consume_ready_chunks().next().unwrap();
452                for (_, row) in chunk.rows() {
453                    let commit_ts = row.datum_at(5).unwrap().into_timestamptz();
454                    assert_eq!(commit_ts, Timestamptz::from_millis(1695277757000).unwrap());
455                }
456            }
457            _ => panic!("unexpected parse result: {:?}", res),
458        }
459    }
460
461    #[tokio::test]
462    async fn test_cdc_source_job_schema() {
463        let columns = ColumnCatalog::debezium_cdc_source_cols();
464        // make sure it doesn't broken by future PRs
465        assert_eq!(CDC_SOURCE_COLUMN_NUM, columns.len() as u32);
466    }
467}