Skip to main content

datatypes/types/
json_type.rs

1// Copyright 2023 Greptime Team
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;
16use std::fmt::{Debug, Display, Formatter};
17use std::sync::Arc;
18
19use arrow::datatypes::DataType as ArrowDataType;
20use arrow_schema::{Field, Fields};
21use common_base::bytes::Bytes;
22use serde::{Deserialize, Serialize};
23
24use crate::Error;
25use crate::data_type::DataType;
26use crate::error::{InvalidJsonSnafu, InvalidJsonbSnafu, Result, UnsupportedArrowTypeSnafu};
27use crate::prelude::ConcreteDataType;
28use crate::scalars::ScalarVectorBuilder;
29use crate::type_id::LogicalTypeId;
30use crate::value::Value;
31use crate::vectors::json::builder::JsonVectorBuilder;
32use crate::vectors::{BinaryVectorBuilder, MutableVector};
33
34pub const JSON_TYPE_NAME: &str = "Json";
35const JSON2_TYPE_NAME: &str = "Json2";
36
37pub type JsonObjectType = BTreeMap<String, JsonNativeType>;
38
39#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
40pub enum JsonNumberType {
41    U64,
42    I64,
43    F64,
44}
45
46#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize, Default)]
47pub enum JsonNativeType {
48    /// JSON null value type.
49    ///
50    /// This variant may also appear as the initial state while merging inferred
51    /// types, but it does not represent an empty object. Empty objects are
52    /// represented as `Object({})`.
53    #[default]
54    Null,
55    Bool,
56    Number(JsonNumberType),
57    String,
58    Array(Box<JsonNativeType>),
59    Object(JsonObjectType),
60    /// A special (not in the JSON official specification) JSON type to indicate the "resolved" or
61    /// "lifted" type of two conflicting JSON types. For example, when merging JSON types of "Bool"
62    /// and "Number".
63    Variant,
64}
65
66impl JsonNativeType {
67    pub fn is_null(&self) -> bool {
68        matches!(self, JsonNativeType::Null)
69    }
70
71    pub fn u64() -> Self {
72        Self::Number(JsonNumberType::U64)
73    }
74
75    pub fn i64() -> Self {
76        Self::Number(JsonNumberType::I64)
77    }
78
79    pub fn f64() -> Self {
80        Self::Number(JsonNumberType::F64)
81    }
82
83    pub fn object() -> Self {
84        Self::Object(JsonObjectType::new())
85    }
86
87    /// Merge other [JsonNativeType] into this.
88    /// Conflicting fields will be resolved to the "Variant" type.
89    pub fn merge(&mut self, other: &JsonNativeType) {
90        if self == other {
91            return;
92        }
93
94        fn merge_object(this: &mut JsonObjectType, that: &JsonObjectType) {
95            // merge "that" into "this" directly:
96            for (type_name, that_type) in that {
97                if let Some(this_type) = this.get_mut(type_name) {
98                    this_type.merge(that_type);
99                } else {
100                    this.insert(type_name.clone(), that_type.clone());
101                }
102            }
103        }
104
105        let zelf = std::mem::take(self);
106        *self = match (zelf, other) {
107            (JsonNativeType::Object(mut this), JsonNativeType::Object(that)) => {
108                merge_object(&mut this, that);
109                JsonNativeType::Object(this)
110            }
111            (JsonNativeType::Array(mut this), JsonNativeType::Array(that)) => {
112                this.merge(that);
113                JsonNativeType::Array(this)
114            }
115            (JsonNativeType::Null, that) => that.clone(),
116            (this, JsonNativeType::Null) => this,
117            (this, that) if this == *that => this,
118
119            _ => JsonNativeType::Variant,
120        };
121    }
122
123    pub fn as_arrow_type(&self) -> ArrowDataType {
124        match self {
125            JsonNativeType::Null => ArrowDataType::Null,
126            JsonNativeType::Bool => ArrowDataType::Boolean,
127            JsonNativeType::Number(n) => match n {
128                JsonNumberType::U64 => ArrowDataType::UInt64,
129                JsonNumberType::I64 => ArrowDataType::Int64,
130                JsonNumberType::F64 => ArrowDataType::Float64,
131            },
132            JsonNativeType::String => ArrowDataType::Utf8View,
133            JsonNativeType::Array(array) => {
134                ArrowDataType::List(Arc::new(Field::new("item", array.as_arrow_type(), true)))
135            }
136            JsonNativeType::Object(object) => {
137                let fields = object
138                    .iter()
139                    .map(|(k, v)| Arc::new(Field::new(k, v.as_arrow_type(), true)))
140                    .collect::<Vec<_>>();
141                ArrowDataType::Struct(Fields::from(fields))
142            }
143            JsonNativeType::Variant => ArrowDataType::Binary,
144        }
145    }
146
147    /// Returns whether this type is a boolean, number, or string scalar.
148    pub fn is_primitive(&self) -> bool {
149        matches!(
150            self,
151            JsonNativeType::Bool | JsonNativeType::Number(_) | JsonNativeType::String
152        )
153    }
154}
155
156impl From<&ConcreteDataType> for JsonNativeType {
157    fn from(value: &ConcreteDataType) -> Self {
158        match value {
159            ConcreteDataType::Null(_) => JsonNativeType::Null,
160            ConcreteDataType::Boolean(_) => JsonNativeType::Bool,
161            ConcreteDataType::UInt64(_)
162            | ConcreteDataType::UInt32(_)
163            | ConcreteDataType::UInt16(_)
164            | ConcreteDataType::UInt8(_) => JsonNativeType::u64(),
165            ConcreteDataType::Int64(_)
166            | ConcreteDataType::Int32(_)
167            | ConcreteDataType::Int16(_)
168            | ConcreteDataType::Int8(_) => JsonNativeType::i64(),
169            ConcreteDataType::Float64(_) | ConcreteDataType::Float32(_) => JsonNativeType::f64(),
170            ConcreteDataType::String(_) => JsonNativeType::String,
171            ConcreteDataType::List(list_type) => {
172                JsonNativeType::Array(Box::new(JsonNativeType::from(list_type.item_type())))
173            }
174            ConcreteDataType::Struct(struct_type) => JsonNativeType::Object(
175                struct_type
176                    .fields()
177                    .iter()
178                    .map(|field| (field.name().to_string(), field.data_type().into()))
179                    .collect(),
180            ),
181            ConcreteDataType::Json(json_type) => json_type.native_type().clone(),
182            ConcreteDataType::Binary(_) => JsonNativeType::Variant,
183            _ => unreachable!(),
184        }
185    }
186}
187
188impl TryFrom<&ArrowDataType> for JsonNativeType {
189    type Error = Error;
190
191    fn try_from(t: &ArrowDataType) -> Result<Self> {
192        let t = match t {
193            ArrowDataType::Null => JsonNativeType::Null,
194            ArrowDataType::Boolean => JsonNativeType::Bool,
195            ArrowDataType::Int8
196            | ArrowDataType::Int16
197            | ArrowDataType::Int32
198            | ArrowDataType::Int64 => JsonNativeType::i64(),
199            ArrowDataType::UInt8
200            | ArrowDataType::UInt16
201            | ArrowDataType::UInt32
202            | ArrowDataType::UInt64 => JsonNativeType::u64(),
203            ArrowDataType::Float16 | ArrowDataType::Float32 | ArrowDataType::Float64 => {
204                JsonNativeType::f64()
205            }
206            ArrowDataType::Binary
207            | ArrowDataType::FixedSizeBinary(_)
208            | ArrowDataType::LargeBinary
209            | ArrowDataType::BinaryView => JsonNativeType::Variant,
210            ArrowDataType::Utf8 | ArrowDataType::LargeUtf8 | ArrowDataType::Utf8View => {
211                JsonNativeType::String
212            }
213            ArrowDataType::List(field)
214            | ArrowDataType::ListView(field)
215            | ArrowDataType::FixedSizeList(field, _)
216            | ArrowDataType::LargeList(field)
217            | ArrowDataType::LargeListView(field) => {
218                JsonNativeType::Array(Box::new(Self::try_from(field.data_type())?))
219            }
220            ArrowDataType::Struct(fields) => {
221                let mut object = JsonObjectType::new();
222                for field in fields {
223                    object.insert(field.name().clone(), Self::try_from(field.data_type())?);
224                }
225                JsonNativeType::Object(object)
226            }
227            t => {
228                return UnsupportedArrowTypeSnafu {
229                    arrow_type: t.clone(),
230                }
231                .fail();
232            }
233        };
234        Ok(t)
235    }
236}
237
238impl Display for JsonNativeType {
239    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
240        match self {
241            JsonNativeType::Null => write!(f, r#""<Null>""#),
242            JsonNativeType::Bool => write!(f, r#""<Bool>""#),
243            JsonNativeType::Number(_) => {
244                write!(f, r#""<Number>""#)
245            }
246            JsonNativeType::String => write!(f, r#""<String>""#),
247            JsonNativeType::Array(item_type) => write!(f, "[{}]", item_type),
248            JsonNativeType::Object(object) => {
249                write!(
250                    f,
251                    "{{{}}}",
252                    object
253                        .iter()
254                        .map(|(k, v)| format!(r#""{k}":{v}"#))
255                        .collect::<Vec<_>>()
256                        .join(",")
257                )
258            }
259            JsonNativeType::Variant => write!(f, r#""<Variant>""#),
260        }
261    }
262}
263
264#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize, Default)]
265pub enum JsonFormat {
266    #[default]
267    Jsonb,
268    Json2(Arc<JsonNativeType>),
269}
270
271/// JsonType is a data type for JSON data. It is stored as binary data of jsonb format.
272/// It utilizes current binary value and vector implementation.
273#[derive(Debug, Default, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
274pub struct JsonType {
275    pub format: JsonFormat,
276}
277
278impl JsonType {
279    pub fn new(format: JsonFormat) -> Self {
280        Self { format }
281    }
282
283    pub(crate) fn json2(json_type: Arc<JsonNativeType>) -> Self {
284        Self {
285            format: JsonFormat::Json2(json_type),
286        }
287    }
288
289    pub fn is_json2(&self) -> bool {
290        matches!(self.format, JsonFormat::Json2(_))
291    }
292
293    /// Returns the native JSON type represented by this data type.
294    pub fn native_type(&self) -> &JsonNativeType {
295        match &self.format {
296            JsonFormat::Jsonb => &JsonNativeType::String,
297            JsonFormat::Json2(x) => x.as_ref(),
298        }
299    }
300
301    pub fn null() -> Self {
302        Self::json2(Arc::new(JsonNativeType::Null))
303    }
304
305    /// Check if it includes all fields in `other` json type.
306    pub fn is_include(&self, other: &JsonType) -> bool {
307        match (&self.format, &other.format) {
308            (JsonFormat::Jsonb, JsonFormat::Jsonb) => true,
309            (JsonFormat::Json2(this), JsonFormat::Json2(that)) => is_include(this, that),
310            _ => false,
311        }
312    }
313}
314
315pub(crate) fn is_include(this: &JsonNativeType, that: &JsonNativeType) -> bool {
316    fn is_include_object(this: &JsonObjectType, that: &JsonObjectType) -> bool {
317        for (type_name, that_type) in that {
318            let Some(this_type) = this.get(type_name) else {
319                return false;
320            };
321            if !is_include(this_type, that_type) {
322                return false;
323            }
324        }
325        true
326    }
327
328    match (this, that) {
329        (this, that) if this == that => true,
330        (JsonNativeType::Array(this), JsonNativeType::Array(that)) => is_include(this, that),
331        (JsonNativeType::Object(this), JsonNativeType::Object(that)) => {
332            is_include_object(this, that)
333        }
334        (_, JsonNativeType::Null) => true,
335        _ => false,
336    }
337}
338
339impl DataType for JsonType {
340    fn name(&self) -> String {
341        match &self.format {
342            JsonFormat::Jsonb => JSON_TYPE_NAME.to_string(),
343            JsonFormat::Json2(ty) => {
344                format!("{JSON2_TYPE_NAME}{}", ty)
345            }
346        }
347    }
348
349    fn logical_type_id(&self) -> LogicalTypeId {
350        LogicalTypeId::Json
351    }
352
353    fn default_value(&self) -> Value {
354        Bytes::default().into()
355    }
356
357    fn as_arrow_type(&self) -> ArrowDataType {
358        match &self.format {
359            JsonFormat::Jsonb => ArrowDataType::Binary,
360            JsonFormat::Json2(x) => {
361                let mut object = JsonNativeType::object();
362                object.merge(x.as_ref());
363                object.as_arrow_type()
364            }
365        }
366    }
367
368    fn create_mutable_vector(&self, capacity: usize) -> Box<dyn MutableVector> {
369        match &self.format {
370            JsonFormat::Jsonb => Box::new(BinaryVectorBuilder::with_capacity(capacity)),
371            JsonFormat::Json2(x) => Box::new(JsonVectorBuilder::new(x.as_ref().clone(), capacity)),
372        }
373    }
374
375    fn try_cast(&self, from: Value) -> Option<Value> {
376        match from {
377            Value::Binary(v) => Some(Value::Binary(v)),
378            _ => None,
379        }
380    }
381}
382
383impl Display for JsonType {
384    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
385        write!(f, "{}", self.name())
386    }
387}
388
389/// Converts a json type value to string
390///
391/// The binary jsonb is serialized directly with `serde_json`, so object keys and string
392/// values are escaped by `serde_json`. `RawJsonb::to_string()` is avoided, since it falls
393/// back to the lossy raw bytes when serialization fails.
394///
395/// Some write paths (e.g. `COPY FROM` files, or a JSON parameter bound as text through
396/// the MySQL protocol) store JSON text in place of binary jsonb. Bytes that fail to
397/// serialize are parsed as text with the extended parser, as `jsonb::from_slice` does.
398pub fn jsonb_to_string(val: &[u8]) -> Result<String> {
399    if val.is_empty() {
400        return Ok("".to_string());
401    }
402    match serde_json::to_string(&jsonb::RawJsonb::new(val)) {
403        Ok(s) => Ok(s),
404        Err(jsonb_err) => {
405            let value = jsonb::parse_value(val).map_err(|text_err| {
406                InvalidJsonSnafu {
407                    value: format!("neither jsonb ({jsonb_err}) nor JSON text ({text_err})"),
408                }
409                .build()
410            })?;
411            serde_json::to_string(&jsonb::RawJsonb::new(&value.to_vec())).map_err(|e| {
412                InvalidJsonSnafu {
413                    value: e.to_string(),
414                }
415                .build()
416            })
417        }
418    }
419}
420
421/// Converts a json type value to serde_json::Value
422pub fn jsonb_to_serde_json(val: &[u8]) -> Result<serde_json::Value> {
423    jsonb::from_slice(val)
424        .map(Into::into)
425        .map_err(|error| InvalidJsonbSnafu { error }.build())
426}
427
428/// Parses a string to a json type value
429pub fn parse_string_to_jsonb(s: &str) -> Result<Vec<u8>> {
430    jsonb::parse_value_standard_mode(s.as_bytes())
431        .map_err(|_| InvalidJsonSnafu { value: s }.build())
432        .map(|json| json.to_vec())
433}
434
435#[cfg(test)]
436mod tests {
437    #[test]
438    fn test_parse_json_rejects_extended_syntax() {
439        for input in ["+1", "01", ".5", "[1,,2]", "{'a':1}"] {
440            assert!(parse_string_to_jsonb(input).is_err(), "{input}");
441        }
442    }
443
444    #[test]
445    fn test_parse_json_rejects_integers_out_of_range() {
446        for input in [
447            "18446744073709551616",
448            "-9223372036854775809",
449            r#"{"n": 123456789012345678901234567890}"#,
450        ] {
451            assert!(parse_string_to_jsonb(input).is_err(), "{input}");
452        }
453        for input in ["18446744073709551615", "-9223372036854775808"] {
454            let jsonb = parse_string_to_jsonb(input).unwrap();
455            assert_eq!(jsonb_to_string(&jsonb).unwrap(), input);
456        }
457    }
458
459    #[test]
460    fn test_v2_jsonb_to_serde_json_escaped_keys()
461    -> std::result::Result<(), Box<dyn std::error::Error>> {
462        let expected = serde_json::json!({"": 9, "a\"b": {"a\\b": "\u{1f600}\n"}});
463        let input = expected.to_string();
464        let value = jsonb::parse_value(input.as_bytes()).map_err(|e| e.to_string())?;
465        assert_eq!(jsonb_to_serde_json(&value.to_vec())?, expected);
466        Ok(())
467    }
468
469    #[test]
470    fn test_jsonb_to_serde_json_scalars() {
471        for input in [r#""2026-11-05""#, "1730800000000", "false", "null"] {
472            let expected: serde_json::Value = serde_json::from_str(input).unwrap();
473            let jsonb = parse_string_to_jsonb(input).unwrap();
474            assert_eq!(jsonb_to_serde_json(&jsonb).unwrap(), expected, "{input}");
475            // Stored as JSON text, the first two used to decode as `false`.
476            assert_eq!(
477                jsonb_to_serde_json(input.as_bytes()).unwrap(),
478                expected,
479                "{input}"
480            );
481        }
482    }
483
484    #[test]
485    fn test_jsonb_to_string_escapes_object_keys()
486    -> std::result::Result<(), Box<dyn std::error::Error>> {
487        let expected = serde_json::json!({
488            "": 1,
489            "a\"b": {"c\\d": ["x", {"e\nf\tg\u{1}": true}], "h": null},
490            "plain": "v\"q",
491        });
492        let input = expected.to_string();
493        let value = jsonb::parse_value(input.as_bytes()).map_err(|e| e.to_string())?;
494        let text = jsonb_to_string(&value.to_vec())?;
495        assert_eq!(serde_json::from_str::<serde_json::Value>(&text)?, expected);
496        assert!(text.contains(r#""a\"b":"#), "{text}");
497        Ok(())
498    }
499
500    #[test]
501    fn test_jsonb_to_string_preserves_literal_unicode_escape_key() {
502        let input = r#"{"\\u{1f600}":"value"}"#;
503        let bytes = parse_string_to_jsonb(input).unwrap();
504        let text = jsonb_to_string(&bytes).unwrap();
505        assert_eq!(
506            serde_json::from_str::<serde_json::Value>(&text).unwrap(),
507            serde_json::from_str::<serde_json::Value>(input).unwrap(),
508        );
509
510        // A BMP literal key round-trips unchanged as well.
511        let input = r#"{"\\u{41}":"value"}"#;
512        let bytes = parse_string_to_jsonb(input).unwrap();
513        let text = jsonb_to_string(&bytes).unwrap();
514        assert_eq!(text, input);
515    }
516
517    #[test]
518    fn test_jsonb_to_string_escapes_string_values() {
519        // Literal `\u{...}` text and a NUL in a value must still render as valid JSON
520        // that round-trips to the same value.
521        for input in [
522            r#"{"k":"\\u{1f600}"}"#,
523            r#"{"k":"\\u{41}"}"#,
524            r#"{"k":"a\u0000b"}"#,
525            r#"["\\u{1f600}","\u0000"]"#,
526        ] {
527            let bytes = parse_string_to_jsonb(input).unwrap();
528            let text = jsonb_to_string(&bytes).unwrap();
529            assert_eq!(
530                serde_json::from_str::<serde_json::Value>(&text).unwrap(),
531                serde_json::from_str::<serde_json::Value>(input).unwrap(),
532                "{input} -> {text}"
533            );
534        }
535
536        // U+2028 is emitted as-is, which is still valid JSON.
537        let bytes = parse_string_to_jsonb("{\"k\":\"a\\u2028b\"}").unwrap();
538        assert_eq!(jsonb_to_string(&bytes).unwrap(), "{\"k\":\"a\u{2028}b\"}");
539    }
540
541    #[test]
542    fn test_jsonb_to_string_rejects_invalid_jsonb() {
543        assert!(jsonb_to_string(&[1, 2, 3, 4]).is_err());
544        assert_eq!(jsonb_to_string(&[]).unwrap(), "");
545
546        let mut truncated = parse_string_to_jsonb(r#"{"k":"value"}"#).unwrap();
547        truncated.pop();
548        assert!(jsonb_to_string(&truncated).is_err());
549    }
550
551    #[test]
552    fn test_jsonb_to_string_accepts_json_text_bytes() {
553        // Bytes written as JSON text rather than binary jsonb (e.g. by `COPY FROM`).
554        assert_eq!(
555            jsonb_to_string(br#"{"foo":"bar"}"#).unwrap(),
556            r#"{"foo":"bar"}"#
557        );
558        assert_eq!(
559            jsonb_to_string(br#"{"a":null, "foo":"bar"}"#).unwrap(),
560            r#"{"a":null,"foo":"bar"}"#
561        );
562        // Keys and values coming from text are still escaped by serde_json.
563        assert_eq!(
564            jsonb_to_string(br#"{"a\"b":"c\u0000d"}"#).unwrap(),
565            r#"{"a\"b":"c\u0000d"}"#
566        );
567        // These start with bytes that also read as a jsonb scalar header.
568        assert_eq!(
569            jsonb_to_string(br#""hello world""#).unwrap(),
570            r#""hello world""#
571        );
572        assert_eq!(jsonb_to_string(b"        null").unwrap(), "null");
573        // Without the bounds check, these read back as `false`.
574        assert_eq!(
575            jsonb_to_string(br#""2026-11-05""#).unwrap(),
576            r#""2026-11-05""#
577        );
578        assert_eq!(jsonb_to_string(b"1730800000000").unwrap(), "1730800000000");
579        // Extended syntax is accepted, as text was read before.
580        assert_eq!(jsonb_to_string(b"[+1,,2]").unwrap(), "[1,null,2]");
581        assert!(jsonb_to_string(b"{not json").is_err());
582    }
583
584    #[test]
585    fn test_jsonb_to_string_keeps_compact_format() -> Result<()> {
586        let value = jsonb::parse_value(br#"{"b": [1, 2.5, "x"], "a": {"c": false}}"#).unwrap();
587        assert_eq!(
588            jsonb_to_string(&value.to_vec())?,
589            r#"{"a":{"c":false},"b":[1,2.5,"x"]}"#
590        );
591        Ok(())
592    }
593
594    use super::*;
595
596    #[test]
597    fn test_json_type_include() {
598        fn test(this: &JsonNativeType, that: &JsonNativeType, expected: bool) {
599            assert_eq!(is_include(this, that), expected, "this={this}, that={that}");
600        }
601
602        test(&JsonNativeType::Null, &JsonNativeType::Null, true);
603        test(&JsonNativeType::Null, &JsonNativeType::Bool, false);
604        test(&JsonNativeType::Bool, &JsonNativeType::Null, true);
605
606        test(&JsonNativeType::Bool, &JsonNativeType::Bool, true);
607        test(&JsonNativeType::Bool, &JsonNativeType::u64(), false);
608
609        test(&JsonNativeType::u64(), &JsonNativeType::Null, true);
610        test(&JsonNativeType::u64(), &JsonNativeType::u64(), true);
611        test(&JsonNativeType::u64(), &JsonNativeType::String, false);
612
613        test(&JsonNativeType::String, &JsonNativeType::Null, true);
614        test(&JsonNativeType::String, &JsonNativeType::String, true);
615        test(
616            &JsonNativeType::String,
617            &JsonNativeType::Array(Box::new(JsonNativeType::f64())),
618            false,
619        );
620
621        test(
622            &JsonNativeType::Array(Box::new(JsonNativeType::f64())),
623            &JsonNativeType::Null,
624            true,
625        );
626        test(
627            &JsonNativeType::Array(Box::new(JsonNativeType::f64())),
628            &JsonNativeType::Array(Box::new(JsonNativeType::Null)),
629            true,
630        );
631        test(
632            &JsonNativeType::Array(Box::new(JsonNativeType::f64())),
633            &JsonNativeType::Array(Box::new(JsonNativeType::f64())),
634            true,
635        );
636        test(
637            &JsonNativeType::Array(Box::new(JsonNativeType::f64())),
638            &JsonNativeType::String,
639            false,
640        );
641        test(
642            &JsonNativeType::Array(Box::new(JsonNativeType::f64())),
643            &JsonNativeType::Object(JsonObjectType::new()),
644            false,
645        );
646
647        let simple_json_object = &JsonNativeType::Object(JsonObjectType::from([(
648            "foo".to_string(),
649            JsonNativeType::String,
650        )]));
651        test(simple_json_object, simple_json_object, true);
652        test(simple_json_object, &JsonNativeType::i64(), false);
653        test(
654            simple_json_object,
655            &JsonNativeType::Object(JsonObjectType::from([(
656                "bar".to_string(),
657                JsonNativeType::i64(),
658            )])),
659            false,
660        );
661
662        let complex_json_object = &JsonNativeType::Object(JsonObjectType::from([
663            (
664                "nested".to_string(),
665                JsonNativeType::Object(JsonObjectType::from([(
666                    "a".to_string(),
667                    JsonNativeType::Object(JsonObjectType::from([(
668                        "b".to_string(),
669                        JsonNativeType::Object(JsonObjectType::from([(
670                            "c".to_string(),
671                            JsonNativeType::String,
672                        )])),
673                    )])),
674                )])),
675            ),
676            ("bar".to_string(), JsonNativeType::i64()),
677        ]));
678        test(simple_json_object, &JsonNativeType::Null, true);
679        test(complex_json_object, &JsonNativeType::String, false);
680        test(complex_json_object, complex_json_object, true);
681        test(
682            complex_json_object,
683            &JsonNativeType::Object(JsonObjectType::from([(
684                "bar".to_string(),
685                JsonNativeType::i64(),
686            )])),
687            true,
688        );
689        test(
690            complex_json_object,
691            &JsonNativeType::Object(JsonObjectType::from([
692                (
693                    "nested".to_string(),
694                    JsonNativeType::Object(JsonObjectType::from([(
695                        "a".to_string(),
696                        JsonNativeType::Null,
697                    )])),
698                ),
699                ("bar".to_string(), JsonNativeType::i64()),
700            ])),
701            true,
702        );
703        test(
704            complex_json_object,
705            &JsonNativeType::Object(JsonObjectType::from([
706                (
707                    "nested".to_string(),
708                    JsonNativeType::Object(JsonObjectType::from([(
709                        "a".to_string(),
710                        JsonNativeType::String,
711                    )])),
712                ),
713                ("bar".to_string(), JsonNativeType::i64()),
714            ])),
715            false,
716        );
717        test(
718            complex_json_object,
719            &JsonNativeType::Object(JsonObjectType::from([
720                (
721                    "nested".to_string(),
722                    JsonNativeType::Object(JsonObjectType::from([(
723                        "a".to_string(),
724                        JsonNativeType::Object(JsonObjectType::from([(
725                            "b".to_string(),
726                            JsonNativeType::String,
727                        )])),
728                    )])),
729                ),
730                ("bar".to_string(), JsonNativeType::i64()),
731            ])),
732            false,
733        );
734        test(
735            complex_json_object,
736            &JsonNativeType::Object(JsonObjectType::from([
737                (
738                    "nested".to_string(),
739                    JsonNativeType::Object(JsonObjectType::from([(
740                        "a".to_string(),
741                        JsonNativeType::Object(JsonObjectType::from([(
742                            "b".to_string(),
743                            JsonNativeType::Object(JsonObjectType::from([(
744                                "c".to_string(),
745                                JsonNativeType::Null,
746                            )])),
747                        )])),
748                    )])),
749                ),
750                ("bar".to_string(), JsonNativeType::i64()),
751            ])),
752            true,
753        );
754        test(
755            complex_json_object,
756            &JsonNativeType::Object(JsonObjectType::from([
757                (
758                    "nested".to_string(),
759                    JsonNativeType::Object(JsonObjectType::from([(
760                        "a".to_string(),
761                        JsonNativeType::Object(JsonObjectType::from([(
762                            "b".to_string(),
763                            JsonNativeType::Object(JsonObjectType::from([(
764                                "c".to_string(),
765                                JsonNativeType::Bool,
766                            )])),
767                        )])),
768                    )])),
769                ),
770                ("bar".to_string(), JsonNativeType::i64()),
771            ])),
772            false,
773        );
774        test(
775            complex_json_object,
776            &JsonNativeType::Object(JsonObjectType::from([(
777                "nested".to_string(),
778                JsonNativeType::Object(JsonObjectType::from([(
779                    "a".to_string(),
780                    JsonNativeType::Object(JsonObjectType::from([(
781                        "b".to_string(),
782                        JsonNativeType::Object(JsonObjectType::from([(
783                            "c".to_string(),
784                            JsonNativeType::String,
785                        )])),
786                    )])),
787                )])),
788            )])),
789            true,
790        );
791    }
792
793    #[test]
794    fn test_merge_json_type() {
795        fn test(other: JsonNativeType, json_type: &mut JsonNativeType, expected: &str) {
796            json_type.merge(&other);
797            assert_eq!(json_type.to_string(), expected);
798        }
799
800        // Null should be absorbed by a concrete scalar type.
801        test(
802            JsonNativeType::Bool,
803            &mut JsonNativeType::Null,
804            r#""<Bool>""#,
805        );
806
807        // Merging a null value into an existing concrete type should keep the type unchanged.
808        test(
809            JsonNativeType::Null,
810            &mut JsonNativeType::Bool,
811            r#""<Bool>""#,
812        );
813
814        // Identical number categories should stay as Number.
815        test(
816            JsonNativeType::i64(),
817            &mut JsonNativeType::i64(),
818            r#""<Number>""#,
819        );
820
821        // Conflicting number categories should be lifted to Variant.
822        for (mut this, other) in [
823            (JsonNativeType::u64(), JsonNativeType::i64()),
824            (JsonNativeType::u64(), JsonNativeType::f64()),
825            (JsonNativeType::i64(), JsonNativeType::f64()),
826        ] {
827            test(other, &mut this, r#""<Variant>""#);
828        }
829
830        // Object merge should preserve existing fields and append missing fields.
831        test(
832            JsonNativeType::Object(JsonObjectType::from([(
833                "foo".to_string(),
834                JsonNativeType::String,
835            )])),
836            &mut JsonNativeType::Object(JsonObjectType::from([(
837                "bar".to_string(),
838                JsonNativeType::i64(),
839            )])),
840            r#"{"bar":"<Number>","foo":"<String>"}"#,
841        );
842
843        // Conflicting object field types should only lift that field to Variant.
844        test(
845            JsonNativeType::Object(JsonObjectType::from([(
846                "foo".to_string(),
847                JsonNativeType::i64(),
848            )])),
849            &mut JsonNativeType::Object(JsonObjectType::from([(
850                "foo".to_string(),
851                JsonNativeType::Bool,
852            )])),
853            r#"{"foo":"<Variant>"}"#,
854        );
855
856        // Nested objects should merge recursively.
857        test(
858            JsonNativeType::Object(JsonObjectType::from([(
859                "nested".to_string(),
860                JsonNativeType::Object(JsonObjectType::from([(
861                    "foo".to_string(),
862                    JsonNativeType::String,
863                )])),
864            )])),
865            &mut JsonNativeType::Object(JsonObjectType::from([(
866                "nested".to_string(),
867                JsonNativeType::Object(JsonObjectType::from([(
868                    "bar".to_string(),
869                    JsonNativeType::Bool,
870                )])),
871            )])),
872            r#"{"nested":{"bar":"<Bool>","foo":"<String>"}}"#,
873        );
874
875        // Arrays should merge their element types recursively.
876        test(
877            JsonNativeType::Array(Box::new(JsonNativeType::String)),
878            &mut JsonNativeType::Array(Box::new(JsonNativeType::u64())),
879            r#"["<Variant>"]"#,
880        );
881
882        // Root-level incompatible types should be lifted to Variant.
883        test(
884            JsonNativeType::Object(JsonObjectType::from([(
885                "foo".to_string(),
886                JsonNativeType::String,
887            )])),
888            &mut JsonNativeType::Bool,
889            r#""<Variant>""#,
890        );
891    }
892}