Skip to main content

risingwave_connector/parser/unified/
json.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;
16use std::sync::LazyLock;
17
18use base64::Engine;
19use itertools::Itertools;
20use num_bigint::BigInt;
21use risingwave_common::array::{Finite32, ListValue, StructValue};
22use risingwave_common::cast::{i64_to_timestamp, i64_to_timestamptz, str_to_bytea};
23use risingwave_common::log::LogSuppressor;
24use risingwave_common::types::{
25    DEBEZIUM_UNAVAILABLE_VALUE, DataType, Date, Decimal, Int256, Interval, JsonbVal, ScalarImpl,
26    Time, Timestamp, Timestamptz, ToOwnedDatum, VectorVal, debezium_unavailable_vector,
27};
28use risingwave_connector_codec::decoder::utils::scaled_bigint_to_rust_decimal;
29use simd_json::base::ValueAsObject;
30use simd_json::prelude::{
31    TypedValue, ValueAsArray, ValueAsScalar, ValueObjectAccess, ValueTryAsScalar,
32};
33use simd_json::{BorrowedValue, ValueType};
34use thiserror_ext::AsReport;
35
36use super::{Access, AccessError, AccessResult};
37use crate::parser::DatumCow;
38use crate::schema::{InvalidOptionError, bail_invalid_option_error};
39
40/// Try to parse a Debezium `PostGIS` spatial object.
41///
42/// Debezium represents `PostGIS` `geometry` and `geography` values as an object:
43/// `{"srid": <int>, "wkb": <base64_string>}`.
44/// For our current Postgres CDC ingestion, the `wkb` field is expected to be EWKB bytes (base64-encoded),
45/// and `srid` is redundant. We decode `wkb` into raw bytes and store it as `bytea`.
46///
47/// Note: Debezium provides an SMT to convert between `WKB` and `EWKB`, which may be useful for future
48/// unification across connectors (e.g., MySQL): see `GeometryFormatTransformer`.
49///
50/// Return semantics:
51/// - `Ok(Some(bytes))`: The input matches the Debezium spatial shape (`srid` is numeric AND `wkb` is string),
52///   and we successfully decoded `wkb` into bytes.
53/// - `Ok(None)`: The input does NOT look like a Debezium spatial object. This allows the caller to keep the
54///   match arm focused on dispatching, and avoids misclassifying other JSON objects that might map to `bytea`
55///   in the future.
56/// - `Err(...)`: The input looks like a Debezium spatial object, but decoding/parsing failed (e.g. invalid
57///   base64). This indicates a real data/format error and should not be silently ignored.
58fn try_parse_debezium_postgis_spatial_as_bytea(
59    value: &BorrowedValue<'_>,
60    create_error: impl Fn() -> AccessError,
61) -> AccessResult<Option<Box<[u8]>>> {
62    let obj = match value.as_object() {
63        Some(obj) => obj,
64        None => return Ok(None),
65    };
66
67    // Strictly identify the spatial object by checking both fields and their types.
68    // There may be other objects that map to bytea in the future.
69    let srid = obj.get("srid").and_then(|v| v.as_i64());
70    let wkb = obj.get("wkb").and_then(|v| v.as_str());
71
72    let (Some(_srid), Some(wkb)) = (srid, wkb) else {
73        return Ok(None);
74    };
75
76    let bytes = base64::engine::general_purpose::STANDARD
77        .decode(wkb)
78        .map_err(|_| create_error())?
79        .into_boxed_slice();
80
81    Ok(Some(bytes))
82}
83
84#[derive(Clone, Debug)]
85pub enum ByteaHandling {
86    Standard,
87    // debezium converts postgres bytea to base64 format
88    Base64,
89}
90#[derive(Clone, Debug)]
91pub enum TimeHandling {
92    Milli,
93    Micro,
94}
95
96#[derive(Clone, Copy, Debug)]
97pub enum BigintUnsignedHandlingMode {
98    /// Convert unsigned bigint to signed bigint (default)
99    Long,
100    /// Use base64-encoded decimal for unsigned bigint (Debezium precise mode)
101    Precise,
102}
103
104#[derive(Clone, Debug)]
105pub enum TimestamptzHandling {
106    /// `"2024-04-11T02:00:00.123456Z"`
107    UtcString,
108    /// `"2024-04-11 02:00:00.123456"`
109    UtcWithoutSuffix,
110    /// `1712800800123`
111    Milli,
112    /// `1712800800123456`
113    Micro,
114    /// Both `1712800800123` (ms) and `1712800800123456` (us) maps to `2024-04-11`.
115    ///
116    /// Only works for `[1973-03-03 09:46:40, 5138-11-16 09:46:40)`.
117    ///
118    /// This option is backward compatible.
119    GuessNumberUnit,
120}
121
122impl TimestamptzHandling {
123    pub const OPTION_KEY: &'static str = "timestamptz.handling.mode";
124
125    pub fn from_options(value: &str) -> Result<Self, InvalidOptionError> {
126        let mode = match value {
127            "utc_string" => Self::UtcString,
128            "utc_without_suffix" => Self::UtcWithoutSuffix,
129            "micro" => Self::Micro,
130            "milli" => Self::Milli,
131            "guess_number_unit" => Self::GuessNumberUnit,
132            v => bail_invalid_option_error!("unrecognized {} value {}", Self::OPTION_KEY, v),
133        };
134        Ok(mode)
135    }
136}
137
138#[derive(Clone, Debug)]
139pub enum TimestampHandling {
140    Milli,
141    Micro,
142    GuessNumberUnit,
143}
144
145#[derive(Clone, Debug)]
146pub enum JsonValueHandling {
147    AsValue,
148    AsString,
149}
150#[derive(Clone, Debug)]
151pub enum NumericHandling {
152    Strict,
153    // should integer be parsed to float
154    Relax {
155        // should "3.14" be parsed to 3.14 in float
156        string_parsing: bool,
157    },
158}
159#[derive(Clone, Debug)]
160pub enum BooleanHandling {
161    Strict,
162    // should integer 1,0 be parsed to boolean (debezium)
163    Relax {
164        // should "True" "False" be parsed to true or false in boolean
165        string_parsing: bool,
166        // should string "1" "0" be paesed to boolean (cannal + mysql)
167        string_integer_parsing: bool,
168    },
169}
170
171#[derive(Clone, Debug)]
172pub enum VarcharHandling {
173    // do not allow other types cast to varchar
174    Strict,
175    // allow Json Value (Null, Bool, I64, I128, U64, U128, F64) cast to varchar
176    OnlyPrimaryTypes,
177    // allow all type cast to varchar (inc. Array, Object)
178    AllTypes,
179}
180
181#[derive(Clone, Debug)]
182pub enum StructHandling {
183    // only allow object parsed to struct
184    Strict,
185    // allow string containing a serialized json object (like "{\"a\": 1, \"b\": 2}") parsed to
186    // struct
187    AllowJsonString,
188}
189
190#[derive(Clone, Debug)]
191pub struct JsonParseOptions {
192    pub bytea_handling: ByteaHandling,
193    pub time_handling: TimeHandling,
194    pub timestamp_handling: TimestampHandling,
195    pub timestamptz_handling: TimestamptzHandling,
196    pub json_value_handling: JsonValueHandling,
197    pub numeric_handling: NumericHandling,
198    pub boolean_handling: BooleanHandling,
199    pub varchar_handling: VarcharHandling,
200    pub struct_handling: StructHandling,
201    pub bigint_unsigned_handling: BigintUnsignedHandlingMode,
202    pub ignoring_keycase: bool,
203    /// Convert Debezium's placeholder for an unchanged TOAST value into a sentinel of the column
204    /// type, which the materialize executor replaces with the stored value.
205    ///
206    /// PostgreSQL CDC only: the placeholder is a string, and `jsonb` and pgvector `vector`
207    /// columns cannot hold it as is, so the parser must convert it. Placeholders in `varchar`
208    /// and `bytea` columns need no conversion.
209    pub handle_postgres_toast_columns: bool,
210}
211
212impl Default for JsonParseOptions {
213    fn default() -> Self {
214        Self::DEFAULT.clone()
215    }
216}
217
218impl JsonParseOptions {
219    pub const CANAL: JsonParseOptions = JsonParseOptions {
220        bytea_handling: ByteaHandling::Standard,
221        time_handling: TimeHandling::Micro,
222        timestamp_handling: TimestampHandling::GuessNumberUnit, // backward-compatible
223        timestamptz_handling: TimestamptzHandling::GuessNumberUnit, // backward-compatible
224        json_value_handling: JsonValueHandling::AsValue,
225        numeric_handling: NumericHandling::Relax {
226            string_parsing: true,
227        },
228        boolean_handling: BooleanHandling::Relax {
229            string_parsing: true,
230            string_integer_parsing: true,
231        },
232        varchar_handling: VarcharHandling::Strict,
233        struct_handling: StructHandling::Strict,
234        bigint_unsigned_handling: BigintUnsignedHandlingMode::Long, // default to long mode
235        ignoring_keycase: true,
236        handle_postgres_toast_columns: false,
237    };
238    pub const DEFAULT: JsonParseOptions = JsonParseOptions {
239        bytea_handling: ByteaHandling::Standard,
240        time_handling: TimeHandling::Micro,
241        timestamp_handling: TimestampHandling::GuessNumberUnit, // backward-compatible
242        timestamptz_handling: TimestamptzHandling::GuessNumberUnit, // backward-compatible
243        json_value_handling: JsonValueHandling::AsValue,
244        numeric_handling: NumericHandling::Relax {
245            string_parsing: true,
246        },
247        boolean_handling: BooleanHandling::Strict,
248        varchar_handling: VarcharHandling::OnlyPrimaryTypes,
249        struct_handling: StructHandling::AllowJsonString,
250        bigint_unsigned_handling: BigintUnsignedHandlingMode::Long, // default to long mode
251        ignoring_keycase: true,
252        handle_postgres_toast_columns: false,
253    };
254
255    pub fn new_for_debezium(
256        timestamptz_handling: TimestamptzHandling,
257        timestamp_handling: TimestampHandling,
258        time_handling: TimeHandling,
259        numeric_handling: NumericHandling,
260        bigint_unsigned_handling: BigintUnsignedHandlingMode,
261        handle_postgres_toast_columns: bool,
262    ) -> Self {
263        Self {
264            bytea_handling: ByteaHandling::Base64,
265            time_handling,
266            timestamp_handling,
267            timestamptz_handling,
268            json_value_handling: JsonValueHandling::AsString,
269            numeric_handling,
270            boolean_handling: BooleanHandling::Relax {
271                string_parsing: false,
272                string_integer_parsing: false,
273            },
274            varchar_handling: VarcharHandling::Strict,
275            struct_handling: StructHandling::Strict,
276            bigint_unsigned_handling,
277            ignoring_keycase: true,
278            handle_postgres_toast_columns,
279        }
280    }
281
282    pub fn parse<'a>(
283        &self,
284        value: &'a BorrowedValue<'a>,
285        type_expected: &DataType,
286    ) -> AccessResult<DatumCow<'a>> {
287        let create_error = || AccessError::TypeError {
288            expected: format!("{:?}", type_expected),
289            got: value.value_type().to_string(),
290            value: value.to_string(),
291        };
292        let v: ScalarImpl = match (type_expected, value.value_type()) {
293            (_, ValueType::Null) => return Ok(DatumCow::NULL),
294            // ---- Boolean -----
295            (DataType::Boolean, ValueType::Bool) => value.as_bool().unwrap().into(),
296
297            (
298                DataType::Boolean,
299                ValueType::I64 | ValueType::I128 | ValueType::U64 | ValueType::U128,
300            ) if matches!(self.boolean_handling, BooleanHandling::Relax { .. })
301                && matches!(value.as_i64(), Some(0i64) | Some(1i64)) =>
302            {
303                (value.as_i64() == Some(1i64)).into()
304            }
305
306            (DataType::Boolean, ValueType::String)
307                if matches!(
308                    self.boolean_handling,
309                    BooleanHandling::Relax {
310                        string_parsing: true,
311                        ..
312                    }
313                ) =>
314            {
315                match value.as_str().unwrap().to_lowercase().as_str() {
316                    "true" => true.into(),
317                    "false" => false.into(),
318                    c @ ("1" | "0")
319                        if matches!(
320                            self.boolean_handling,
321                            BooleanHandling::Relax {
322                                string_parsing: true,
323                                string_integer_parsing: true
324                            }
325                        ) =>
326                    {
327                        if c == "1" {
328                            true.into()
329                        } else {
330                            false.into()
331                        }
332                    }
333                    _ => Err(create_error())?,
334                }
335            }
336            // ---- Int16 -----
337            (
338                DataType::Int16,
339                ValueType::I64 | ValueType::I128 | ValueType::U64 | ValueType::U128,
340            ) => value.try_as_i16().map_err(|_| create_error())?.into(),
341
342            (DataType::Int16, ValueType::String)
343                if matches!(
344                    self.numeric_handling,
345                    NumericHandling::Relax {
346                        string_parsing: true
347                    }
348                ) =>
349            {
350                value
351                    .as_str()
352                    .unwrap()
353                    .parse::<i16>()
354                    .map_err(|_| create_error())?
355                    .into()
356            }
357            // ---- Int32 -----
358            (
359                DataType::Int32,
360                ValueType::I64 | ValueType::I128 | ValueType::U64 | ValueType::U128,
361            ) => value.try_as_i32().map_err(|_| create_error())?.into(),
362
363            (DataType::Int32, ValueType::String)
364                if matches!(
365                    self.numeric_handling,
366                    NumericHandling::Relax {
367                        string_parsing: true
368                    }
369                ) =>
370            {
371                value
372                    .as_str()
373                    .unwrap()
374                    .parse::<i32>()
375                    .map_err(|_| create_error())?
376                    .into()
377            }
378            // ---- Int64 -----
379            (
380                DataType::Int64,
381                ValueType::I64 | ValueType::I128 | ValueType::U64 | ValueType::U128,
382            ) => value.try_as_i64().map_err(|_| create_error())?.into(),
383
384            (DataType::Int64, ValueType::String)
385                if matches!(
386                    self.numeric_handling,
387                    NumericHandling::Relax {
388                        string_parsing: true
389                    }
390                ) =>
391            {
392                value
393                    .as_str()
394                    .unwrap()
395                    .parse::<i64>()
396                    .map_err(|_| create_error())?
397                    .into()
398            }
399            // ---- Float32 -----
400            (
401                DataType::Float32,
402                ValueType::I64 | ValueType::I128 | ValueType::U64 | ValueType::U128,
403            ) if matches!(self.numeric_handling, NumericHandling::Relax { .. }) => {
404                (value.try_as_i64().map_err(|_| create_error())? as f32).into()
405            }
406            (DataType::Float32, ValueType::String)
407                if matches!(
408                    self.numeric_handling,
409                    NumericHandling::Relax {
410                        string_parsing: true
411                    }
412                ) =>
413            {
414                value
415                    .as_str()
416                    .unwrap()
417                    .parse::<f32>()
418                    .map_err(|_| create_error())?
419                    .into()
420            }
421            (DataType::Float32, ValueType::F64) => {
422                value.try_as_f32().map_err(|_| create_error())?.into()
423            }
424            // ---- Float64 -----
425            (
426                DataType::Float64,
427                ValueType::I64 | ValueType::I128 | ValueType::U64 | ValueType::U128,
428            ) if matches!(self.numeric_handling, NumericHandling::Relax { .. }) => {
429                (value.try_as_i64().map_err(|_| create_error())? as f64).into()
430            }
431            (DataType::Float64, ValueType::String)
432                if matches!(
433                    self.numeric_handling,
434                    NumericHandling::Relax {
435                        string_parsing: true
436                    }
437                ) =>
438            {
439                value
440                    .as_str()
441                    .unwrap()
442                    .parse::<f64>()
443                    .map_err(|_| create_error())?
444                    .into()
445            }
446            (DataType::Float64, ValueType::F64) => {
447                value.try_as_f64().map_err(|_| create_error())?.into()
448            }
449            // ---- Decimal -----
450            (DataType::Decimal, ValueType::I128 | ValueType::U128) => {
451                Decimal::from_str(&value.try_as_i128().map_err(|_| create_error())?.to_string())
452                    .map_err(|_| create_error())?
453                    .into()
454            }
455            (DataType::Decimal, ValueType::I64 | ValueType::U64) => {
456                let i64_val = value.try_as_i64().map_err(|_| create_error())?;
457                Decimal::from(i64_val).into()
458            }
459            (DataType::Decimal, ValueType::String) => {
460                let str_val = value.as_str().unwrap();
461                // the following values are special string generated by Debezium and should be handled separately
462                match str_val {
463                    "NAN" => return Ok(DatumCow::Owned(Some(ScalarImpl::Decimal(Decimal::NaN)))),
464                    "POSITIVE_INFINITY" => {
465                        return Ok(DatumCow::Owned(Some(ScalarImpl::Decimal(
466                            Decimal::PositiveInf,
467                        ))));
468                    }
469                    "NEGATIVE_INFINITY" => {
470                        return Ok(DatumCow::Owned(Some(ScalarImpl::Decimal(
471                            Decimal::NegativeInf,
472                        ))));
473                    }
474                    _ => {}
475                }
476
477                Decimal::from_str(str_val)
478                    .or_else(|_err| {
479                        try_base64_decode_decimal(
480                            str_val,
481                            self.bigint_unsigned_handling,
482                            create_error,
483                        )
484                    })?
485                    .into()
486            }
487
488            (DataType::Decimal, ValueType::F64) => {
489                Decimal::try_from(value.try_as_f64().map_err(|_| create_error())?)
490                    .map_err(|_| create_error())?
491                    .into()
492            }
493            (DataType::Decimal, ValueType::Object) => {
494                // ref https://github.com/risingwavelabs/risingwave/issues/10628
495                // handle debezium json (variable scale): {"scale": int, "value": bytes}
496                let scale = value
497                    .get("scale")
498                    .ok_or_else(create_error)?
499                    .as_i32()
500                    .unwrap();
501                let value = value
502                    .get("value")
503                    .ok_or_else(create_error)?
504                    .as_str()
505                    .unwrap()
506                    .as_bytes();
507                let unscaled = BigInt::from_signed_bytes_be(value);
508                let decimal = scaled_bigint_to_rust_decimal(unscaled, scale as _)?;
509                ScalarImpl::Decimal(Decimal::Normalized(decimal))
510            }
511            // ---- Date -----
512            (
513                DataType::Date,
514                ValueType::I64 | ValueType::I128 | ValueType::U64 | ValueType::U128,
515            ) => Date::with_days_since_unix_epoch(value.try_as_i32().map_err(|_| create_error())?)
516                .map_err(|_| create_error())?
517                .into(),
518            (DataType::Date, ValueType::String) => value
519                .as_str()
520                .unwrap()
521                .parse::<Date>()
522                .map_err(|_| create_error())?
523                .into(),
524            // ---- Varchar -----
525            (DataType::Varchar, ValueType::String) => {
526                return Ok(DatumCow::Borrowed(Some(value.as_str().unwrap().into())));
527            }
528            (
529                DataType::Varchar,
530                ValueType::Bool
531                | ValueType::I64
532                | ValueType::I128
533                | ValueType::U64
534                | ValueType::U128
535                | ValueType::F64,
536            ) if matches!(self.varchar_handling, VarcharHandling::OnlyPrimaryTypes) => {
537                value.to_string().into()
538            }
539            (
540                DataType::Varchar,
541                ValueType::Bool
542                | ValueType::I64
543                | ValueType::I128
544                | ValueType::U64
545                | ValueType::U128
546                | ValueType::F64
547                | ValueType::Array
548                | ValueType::Object,
549            ) if matches!(self.varchar_handling, VarcharHandling::AllTypes) => {
550                value.to_string().into()
551            }
552            // ---- Time -----
553            (DataType::Time, ValueType::String) => value
554                .as_str()
555                .unwrap()
556                .parse::<Time>()
557                .map_err(|_| create_error())?
558                .into(),
559            (
560                DataType::Time,
561                ValueType::I64 | ValueType::I128 | ValueType::U64 | ValueType::U128,
562            ) => value
563                .as_i64()
564                .map(|i| match self.time_handling {
565                    TimeHandling::Milli => Time::with_milli(i as u32),
566                    TimeHandling::Micro => Time::with_micro(i as u64),
567                })
568                .unwrap()
569                .map_err(|_| create_error())?
570                .into(),
571            // ---- Timestamp -----
572            (DataType::Timestamp, ValueType::String) => value
573                .as_str()
574                .unwrap()
575                .parse::<Timestamp>()
576                .map_err(|_| create_error())?
577                .into(),
578            (
579                DataType::Timestamp,
580                ValueType::I64 | ValueType::I128 | ValueType::U64 | ValueType::U128,
581            ) => value
582                .as_i64()
583                .map(|num| match self.timestamp_handling {
584                    // Only when user configures debezium.time.precision.mode = 'connect',
585                    // the Milli branch will be executed
586                    TimestampHandling::Milli => {
587                        Timestamp::with_millis(num).map_err(|_| create_error())
588                    }
589                    TimestampHandling::Micro => {
590                        Timestamp::with_micros(num).map_err(|_| create_error())
591                    }
592                    TimestampHandling::GuessNumberUnit => {
593                        i64_to_timestamp(num).map_err(|_| create_error())
594                    }
595                })
596                .ok_or_else(create_error)??
597                .into(),
598            // ---- Timestamptz -----
599            (DataType::Timestamptz, ValueType::String) => match self.timestamptz_handling {
600                TimestamptzHandling::UtcWithoutSuffix => value
601                    .as_str()
602                    .unwrap()
603                    .parse::<Timestamp>()
604                    .map(|naive_utc| {
605                        Timestamptz::from_micros_uncheck(naive_utc.0.and_utc().timestamp_micros())
606                    })
607                    .map_err(|_| create_error())?
608                    .into(),
609                // Unless explicitly requested `utc_without_utc`, we parse string with `YYYY-MM-DDTHH:MM:SSZ`.
610                _ => value
611                    .as_str()
612                    .unwrap()
613                    .parse::<Timestamptz>()
614                    .map_err(|_| create_error())?
615                    .into(),
616            },
617            (
618                DataType::Timestamptz,
619                ValueType::I64 | ValueType::I128 | ValueType::U64 | ValueType::U128,
620            ) => value
621                .as_i64()
622                .and_then(|num| match self.timestamptz_handling {
623                    TimestamptzHandling::GuessNumberUnit => i64_to_timestamptz(num).ok(),
624                    TimestamptzHandling::Micro => Timestamptz::from_micros(num),
625                    TimestamptzHandling::Milli => Timestamptz::from_millis(num),
626                    // When explicitly requested string format, number without units are rejected.
627                    TimestamptzHandling::UtcString | TimestamptzHandling::UtcWithoutSuffix => None,
628                })
629                .ok_or_else(create_error)?
630                .into(),
631            // ---- Interval -----
632            (DataType::Interval, ValueType::String) => value
633                .as_str()
634                .unwrap()
635                .parse::<Interval>()
636                .map_err(|_| create_error())?
637                .into(),
638            // ---- Struct -----
639            (DataType::Struct(struct_type_info), ValueType::Object) => {
640                // Collecting into a Result<Vec<_>> doesn't reserve the capacity in advance, so we `Vec::with_capacity` instead.
641                // https://github.com/rust-lang/rust/issues/48994
642                let mut fields = Vec::with_capacity(struct_type_info.len());
643                for (field_name, field_type) in struct_type_info.iter() {
644                    let field_value = json_object_get_case_insensitive(value, field_name)
645                            .unwrap_or_else(|| {
646                                let error = AccessError::Undefined {
647                                    name: field_name.to_owned(),
648                                    path: struct_type_info.to_string(), // TODO: this is not good, we should maintain a path stack
649                                };
650                                // TODO: is it possible to unify the logging with the one in `do_action`?
651                                static LOG_SUPPRESSOR: LazyLock<LogSuppressor> =  LazyLock::new(LogSuppressor::default);
652                                if let Ok(suppressed_count) = LOG_SUPPRESSOR.check() {
653                                    tracing::warn!(error = %error.as_report(), suppressed_count, "undefined nested field, padding with `NULL`");
654                                }
655                                &BorrowedValue::Static(simd_json::StaticNode::Null)
656                            });
657                    fields.push(
658                        self.parse(field_value, field_type)
659                            .map(|d| d.to_owned_datum())?,
660                    );
661                }
662                StructValue::new(fields).into()
663            }
664
665            // String containing json object, e.g. "{\"a\": 1, \"b\": 2}"
666            // Try to parse it as json object.
667            (DataType::Struct(_), ValueType::String)
668                if matches!(self.struct_handling, StructHandling::AllowJsonString) =>
669            {
670                // TODO: avoid copy by accepting `&mut BorrowedValue` in `parse` method.
671                let mut value = value.as_str().unwrap().as_bytes().to_vec();
672                let value =
673                    simd_json::to_borrowed_value(&mut value[..]).map_err(|_| create_error())?;
674                return self
675                    .parse(&value, type_expected)
676                    .map(|d| d.to_owned_datum().into());
677            }
678
679            // ---- List -----
680            (DataType::List(list_type), ValueType::Array) => ListValue::new({
681                let item_type = list_type.elem();
682                let array = value.as_array().unwrap();
683                let mut builder = item_type.create_array_builder(array.len());
684                for v in array {
685                    let value = self.parse(v, item_type)?;
686                    builder.append(value);
687                }
688                builder.finish()
689            })
690            .into(),
691            // ---- Vector -----
692            (DataType::Vector(size), ValueType::Array) => {
693                let array = value.as_array().unwrap();
694                if array.len() != *size {
695                    Err(create_error())?
696                }
697                let mut elems = Vec::with_capacity(array.len());
698                for v in array {
699                    let value = match v.value_type() {
700                        ValueType::I64 | ValueType::I128 => {
701                            let i128_value = v.try_as_i128().map_err(|_| create_error())?;
702                            i128_value
703                                .to_string()
704                                .parse::<f32>()
705                                .map_err(|_| create_error())?
706                        }
707                        ValueType::U64 | ValueType::U128 => {
708                            let u128_value = v.try_as_u128().map_err(|_| create_error())?;
709                            u128_value
710                                .to_string()
711                                .parse::<f32>()
712                                .map_err(|_| create_error())?
713                        }
714                        ValueType::F64 => {
715                            let f64_value = v.try_as_f64().map_err(|_| create_error())?;
716                            if !f64_value.is_finite() {
717                                Err(create_error())?
718                            }
719                            f64_value
720                                .to_string()
721                                .parse::<f32>()
722                                .map_err(|_| create_error())?
723                        }
724                        _ => Err(create_error())?,
725                    };
726                    let finite = Finite32::try_from(value).map_err(|_| create_error())?;
727                    elems.push(finite);
728                }
729                VectorVal::from(elems).into()
730            }
731            // Vector emitted as a string. Reached via the Java `PgVectorToStringConverter`,
732            // which downgrades the pgvector column from `DoubleVector` (ARRAY) to STRING so
733            // that the Debezium unchanged-TOAST placeholder can flow through without tripping
734            // Connect's schema validation. The value is either the pgvector text form
735            // `"[a,b,...]"` or the placeholder; the latter is mapped to a sentinel `VectorVal`
736            // that the materialize executor recognises and replaces with the old row value.
737            (DataType::Vector(size), ValueType::String) => {
738                let s = value.as_str().unwrap();
739                if self.handle_postgres_toast_columns
740                    && s.len() == DEBEZIUM_UNAVAILABLE_VALUE.len()
741                    && s == DEBEZIUM_UNAVAILABLE_VALUE
742                {
743                    // Build the sentinel at the declared dimension so it passes
744                    // `check_datum_type` in the chunk builder; the materialize
745                    // executor recognises it by checking that every element
746                    // equals `DEBEZIUM_UNAVAILABLE_VECTOR_ELEM`.
747                    debezium_unavailable_vector(*size).into()
748                } else {
749                    VectorVal::from_text(s, *size)
750                        .map_err(|_| create_error())?
751                        .into()
752                }
753            }
754
755            // ---- Bytea -----
756            (DataType::Bytea, ValueType::String) => {
757                let value_str = value.as_str().unwrap();
758
759                match self.bytea_handling {
760                    ByteaHandling::Standard => {
761                        let mut buf = Vec::new();
762                        str_to_bytea(value_str, &mut buf).map_err(|_| create_error())?;
763                        buf.into()
764                    }
765                    ByteaHandling::Base64 => base64::engine::general_purpose::STANDARD
766                        .decode(value_str)
767                        .map_err(|_| create_error())?
768                        .into_boxed_slice()
769                        .into(),
770                }
771            }
772            // Handle Debezium PostGIS geometry and geography types:
773            // {"srid": <int>, "wkb": <base64_string>}. We extract the wkb field and
774            // decode it as EWKB bytes.
775            (DataType::Bytea, ValueType::Object) => {
776                match try_parse_debezium_postgis_spatial_as_bytea(value, create_error)? {
777                    Some(bytes) => bytes.into(),
778                    None => Err(create_error())?,
779                }
780            }
781            // ---- Jsonb -----
782            (DataType::Jsonb, ValueType::String)
783                if matches!(self.json_value_handling, JsonValueHandling::AsString) =>
784            {
785                // Check if this value is the Debezium unavailable value (TOAST handling for postgres-cdc).
786                // Debezium will base64 encode the bytea type placeholder.
787                // When a placeholder is encountered, it is converted into a jsonb format placeholder to match the original type.
788                match self.handle_postgres_toast_columns {
789                    true => JsonbVal::from_debezium_unavailable_value(value.as_str().unwrap())
790                        .map_err(|_| create_error())?
791                        .into(),
792                    false => JsonbVal::from_str(value.as_str().unwrap())
793                        .map_err(|_| create_error())?
794                        .into(),
795                }
796            }
797            (DataType::Jsonb, _)
798                if matches!(self.json_value_handling, JsonValueHandling::AsValue) =>
799            {
800                let value: serde_json::Value =
801                    value.clone().try_into().map_err(|_| create_error())?;
802                JsonbVal::from(value).into()
803            }
804            // ---- Int256 -----
805            (
806                DataType::Int256,
807                ValueType::I64 | ValueType::I128 | ValueType::U64 | ValueType::U128,
808            ) => Int256::from(value.try_as_i64().map_err(|_| create_error())?).into(),
809
810            (DataType::Int256, ValueType::String) => Int256::from_str(value.as_str().unwrap())
811                .map_err(|_| create_error())?
812                .into(),
813
814            (_expected, _got) => Err(create_error())?,
815        };
816        Ok(DatumCow::Owned(Some(v)))
817    }
818}
819
820/// Try to decode a base64-encoded decimal string for unsigned bigint handling in Precise mode.
821///
822/// This is used when processing CDC data from upstream systems with unsigned bigint (e.g., MySQL CDC).
823/// When users configure `debezium.bigint.unsigned.handling.mode='precise'`, Debezium converts
824/// unsigned bigint to base64-encoded decimal.
825///
826/// Reference: <https://debezium.io/documentation/reference/stable/connectors/mysql.html#mysql-property-bigint-unsigned-handling-mode>.
827fn try_base64_decode_decimal(
828    str_val: &str,
829    bigint_unsigned_handling: BigintUnsignedHandlingMode,
830    create_error: impl Fn() -> AccessError,
831) -> Result<Decimal, AccessError> {
832    match bigint_unsigned_handling {
833        BigintUnsignedHandlingMode::Precise => {
834            // A better approach would be to get bytes + org.apache.kafka.connect.data.Decimal from schema
835            // instead of string, as described in <https://github.com/risingwavelabs/risingwave/issues/16852>.
836            // However, Rust doesn't have a library to parse Kafka Connect metadata, so we'll refactor this
837            // after implementing that functionality.
838            let value = base64::engine::general_purpose::STANDARD
839                .decode(str_val)
840                .map_err(|_| create_error())?;
841            let unscaled = num_bigint::BigInt::from_signed_bytes_be(&value);
842            Decimal::from_str(&unscaled.to_string()).map_err(|_| create_error())
843        }
844        BigintUnsignedHandlingMode::Long => {
845            // In Long mode, don't attempt base64 decoding
846            Err(create_error())
847        }
848    }
849}
850
851pub struct JsonAccess<'a> {
852    value: BorrowedValue<'a>,
853    options: &'a JsonParseOptions,
854}
855
856impl<'a> JsonAccess<'a> {
857    pub fn new_with_options(value: BorrowedValue<'a>, options: &'a JsonParseOptions) -> Self {
858        Self { value, options }
859    }
860
861    pub fn new(value: BorrowedValue<'a>) -> Self {
862        Self::new_with_options(value, &JsonParseOptions::DEFAULT)
863    }
864}
865
866impl Access for JsonAccess<'_> {
867    fn access<'a>(&'a self, path: &[&str], type_expected: &DataType) -> AccessResult<DatumCow<'a>> {
868        let mut value = &self.value;
869
870        for (idx, &key) in path.iter().enumerate() {
871            if let Some(sub_value) = if self.options.ignoring_keycase {
872                json_object_get_case_insensitive(value, key)
873            } else {
874                value.get(key)
875            } {
876                value = sub_value;
877            } else {
878                Err(AccessError::Undefined {
879                    name: key.to_owned(),
880                    path: path.iter().take(idx).join("."),
881                })?;
882            }
883        }
884
885        self.options.parse(value, type_expected)
886    }
887}
888
889/// Get a value from a json object by key, case insensitive.
890///
891/// Returns `None` if the given json value is not an object, or the key is not found.
892fn json_object_get_case_insensitive<'b>(
893    v: &'b simd_json::BorrowedValue<'b>,
894    key: &str,
895) -> Option<&'b simd_json::BorrowedValue<'b>> {
896    let obj = v.as_object()?;
897    let value = obj.get(key);
898    if value.is_some() {
899        return value; // fast path
900    }
901    for (k, v) in obj {
902        if k.eq_ignore_ascii_case(key) {
903            return Some(v);
904        }
905    }
906    None
907}