Skip to main content

datatypes/
json.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
15//! Data conversion between greptime's StructType and Json
16//!
17//! The idea of this module is to provide utilities to convert serde_json::Value to greptime's StructType and vice versa.
18//!
19//! The struct will carry all the fields of the Json object. We will not flatten any json object in this implementation.
20//!
21
22pub mod value;
23
24use std::collections::BTreeMap;
25use std::collections::btree_map::Entry;
26use std::sync::Arc;
27
28use serde::{Deserialize, Serialize};
29use serde_json::{Map, Value as Json};
30use snafu::ResultExt;
31
32use crate::data_type::ConcreteDataType;
33use crate::error::{self, InvalidJson2SettingsSnafu, Result, UnsupportedJsonTypeSnafu};
34use crate::json::value::{JsonValue, JsonVariant, encode_serde_json_as_jsonb};
35use crate::prelude::DataType as _;
36use crate::schema::{FulltextOptions, SkippingIndexOptions};
37use crate::types::json_type::{JsonNativeType, JsonObjectType};
38use crate::value::{ListValue, StructValue, Value};
39
40/// Maximum number of JSON container levels represented as nested Arrow types.
41pub const JSON2_MAX_STRUCTURED_DEPTH: usize = 50;
42/// Reserved physical field containing unexpanded JSON2 paths.
43pub const JSON2_REMAINDER_FIELD_NAME: &str = "!__remainder__!";
44/// Default maximum number of unhinted JSON leaf paths expanded into Arrow fields.
45pub const JSON2_DEFAULT_MAX_AUTO_EXPANDED_PATHS: u32 = 100;
46
47/// JSON2 settings stored in column schema metadata and represented through
48/// Arrow extension metadata.
49#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
50pub struct JsonSettings {
51    #[serde(default)]
52    type_hints: Vec<JsonTypeHint>,
53    /// Maximum number of unhinted JSON paths expanded into Arrow fields.
54    ///
55    /// `None` preserves the legacy unlimited layout.
56    #[serde(default, skip_serializing_if = "Option::is_none")]
57    max_auto_expanded_paths: Option<u32>,
58}
59
60#[derive(Deserialize)]
61struct JsonSettingsSerde {
62    #[serde(default)]
63    type_hints: Vec<JsonTypeHint>,
64    #[serde(default)]
65    max_auto_expanded_paths: Option<u32>,
66}
67
68impl<'de> Deserialize<'de> for JsonSettings {
69    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
70    where
71        D: serde::Deserializer<'de>,
72    {
73        let settings = JsonSettingsSerde::deserialize(deserializer)?;
74        Self::try_new(settings.type_hints, settings.max_auto_expanded_paths)
75            .map_err(serde::de::Error::custom)
76    }
77}
78
79/// Declares selected JSON2 subpaths as typed fields.
80///
81/// These hints let JSON2 encode frequently used subpaths in a typed layout, so
82/// queries over those subpaths can get behavior and performance closer to
83/// ordinary columns.
84#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
85pub struct JsonTypeHint {
86    /// JSON2 subpath for a typed field.
87    ///
88    /// Each item is one JSON object key. For example, `["user", "age"]`
89    /// represents `user.age`.
90    ///
91    /// Array traversal is not currently supported. For example, a hint cannot
92    /// describe `events[0].name` or fields shared by all items in `events[*]`.
93    pub path: Vec<String>,
94    #[serde(rename = "type")]
95    pub data_type: ConcreteDataType,
96    pub inverted_index: bool,
97    /// Optional Bloom Filter configuration for this path.
98    #[serde(default, skip_serializing_if = "Option::is_none")]
99    pub skipping_index: Option<SkippingIndexOptions>,
100    /// Optional fulltext configuration for a string path.
101    #[serde(default, skip_serializing_if = "Option::is_none")]
102    pub fulltext_index: Option<FulltextOptions>,
103}
104
105/// Specifies how encoding handles a value that does not match its JSON2 type hint.
106#[derive(Debug, Clone, Copy, PartialEq, Eq)]
107pub enum TypeHintMismatchPolicy {
108    /// Returns an error for a type hint mismatch.
109    Reject,
110    /// Coerces to the hint type, encoding unconvertible values as null.
111    CoerceOrNull,
112}
113
114/// Context for JSON encoding/decoding that tracks the current key path.
115#[derive(Clone, Debug)]
116pub struct JsonContext<'a> {
117    /// Current key path from the JSON2 root.
118    pub path: Vec<String>,
119    /// Settings for JSON encoding/decoding.
120    pub settings: &'a JsonSettings,
121}
122
123impl JsonSettings {
124    /// Creates default v2 settings for newly created JSON2 columns.
125    pub fn new_v2() -> Self {
126        Self {
127            type_hints: vec![],
128            max_auto_expanded_paths: Some(JSON2_DEFAULT_MAX_AUTO_EXPANDED_PATHS),
129        }
130    }
131
132    /// Creates and validates JSON2 settings.
133    pub fn try_new(
134        type_hints: Vec<JsonTypeHint>,
135        max_auto_expanded_paths: Option<u32>,
136    ) -> Result<Self> {
137        validate_type_hints(&type_hints)?;
138        Ok(Self {
139            type_hints,
140            max_auto_expanded_paths,
141        })
142    }
143
144    pub fn type_hints(&self) -> &[JsonTypeHint] {
145        &self.type_hints
146    }
147
148    pub fn max_auto_expanded_paths(&self) -> Option<u32> {
149        self.max_auto_expanded_paths
150    }
151
152    pub fn into_parts(self) -> (Vec<JsonTypeHint>, Option<u32>) {
153        (self.type_hints, self.max_auto_expanded_paths)
154    }
155
156    /// Returns whether the settings are equivalent, ignoring type hint order.
157    pub fn equivalent(&self, other: &Self) -> bool {
158        let Self {
159            type_hints,
160            max_auto_expanded_paths,
161        } = self;
162        let Self {
163            type_hints: other_hints,
164            max_auto_expanded_paths: other_max_auto_expanded_paths,
165        } = other;
166
167        if max_auto_expanded_paths != other_max_auto_expanded_paths
168            || type_hints.len() != other_hints.len()
169        {
170            return false;
171        }
172
173        let mut hints = type_hints.iter().collect::<Vec<_>>();
174        let mut other_hints = other_hints.iter().collect::<Vec<_>>();
175        hints.sort_unstable_by(|a, b| a.path.cmp(&b.path));
176        other_hints.sort_unstable_by(|a, b| a.path.cmp(&b.path));
177        hints == other_hints
178    }
179
180    /// Decode an encoded StructValue back into a serde_json::Value.
181    pub fn decode(&self, value: Value) -> Result<Json> {
182        let mut context = JsonContext {
183            path: Vec::new(),
184            settings: self,
185        };
186        decode_value_with_context(value, &mut context)
187    }
188
189    /// Encode a serde_json::Value into a Value::Json using current settings.
190    pub fn encode(&self, json: Json) -> Result<Value> {
191        self.encode_with_type_hint_mismatch_policy(json, TypeHintMismatchPolicy::Reject)
192    }
193
194    /// Encodes a serde_json::Value using the given type hint mismatch policy.
195    pub fn encode_with_type_hint_mismatch_policy(
196        &self,
197        json: Json,
198        policy: TypeHintMismatchPolicy,
199    ) -> Result<Value> {
200        if let Json::Object(object) = &json
201            && object.contains_key(JSON2_REMAINDER_FIELD_NAME)
202        {
203            return error::InvalidJsonSnafu {
204                value: format!(
205                    "root object cannot contain reserved field '{JSON2_REMAINDER_FIELD_NAME}'"
206                ),
207            }
208            .fail();
209        }
210        let mut context = JsonContext {
211            path: Vec::new(),
212            settings: self,
213        };
214        encode_json_with_context(json, &mut context, policy).map(|v| Value::Json(Box::new(v)))
215    }
216}
217
218fn validate_type_hints(type_hints: &[JsonTypeHint]) -> Result<()> {
219    if type_hints.is_empty() {
220        return Ok(());
221    }
222
223    let mut object = JsonObjectType::new();
224    for hint in type_hints {
225        if let Some(options) = &hint.fulltext_index {
226            if !hint.data_type.is_string() {
227                return InvalidJson2SettingsSnafu {
228                    reason: "JSON2 FULLTEXT index only supports string type hints",
229                }
230                .fail();
231            }
232            FulltextOptions::new(
233                options.enable,
234                options.analyzer.clone(),
235                options.case_sensitive,
236                options.backend.clone(),
237                options.granularity,
238                options.false_positive_rate(),
239            )?;
240        }
241        if let Some(options) = &hint.skipping_index {
242            SkippingIndexOptions::new(
243                options.granularity,
244                options.false_positive_rate(),
245                options.index_type.clone(),
246            )?;
247        }
248        if hint.path.len() > JSON2_MAX_STRUCTURED_DEPTH {
249            return InvalidJson2SettingsSnafu {
250                reason: format!(
251                    "JSON2 type hint path cannot exceed {JSON2_MAX_STRUCTURED_DEPTH} segments"
252                ),
253            }
254            .fail();
255        }
256        for part in &hint.path {
257            if part.is_empty() {
258                return InvalidJson2SettingsSnafu {
259                    reason: "JSON2 type hint path segments must not be empty",
260                }
261                .fail();
262            }
263            if part == JSON2_REMAINDER_FIELD_NAME {
264                return InvalidJson2SettingsSnafu {
265                    reason: format!(
266                        "JSON2 type hint path cannot contain reserved field '{JSON2_REMAINDER_FIELD_NAME}'"
267                    ),
268                }
269                .fail();
270            }
271        }
272        let data_type = match &hint.data_type {
273            ConcreteDataType::Boolean(_)
274            | ConcreteDataType::UInt64(_)
275            | ConcreteDataType::Int64(_)
276            | ConcreteDataType::Float64(_)
277            | ConcreteDataType::String(_) => (&hint.data_type).into(),
278            data_type => {
279                return InvalidJson2SettingsSnafu {
280                    reason: format!("unsupported JSON2 type hint data type: {data_type}"),
281                }
282                .fail();
283            }
284        };
285        validate_type_hint(&mut object, &hint.path, data_type)?;
286    }
287    Ok(())
288}
289
290fn validate_type_hint(
291    object: &mut JsonObjectType,
292    path: &[String],
293    data_type: JsonNativeType,
294) -> Result<()> {
295    let Some((name, path)) = path.split_first() else {
296        return InvalidJson2SettingsSnafu {
297            reason: "JSON2 type hint path must not be empty".to_string(),
298        }
299        .fail();
300    };
301    if path.is_empty() {
302        if object.insert(name.clone(), data_type).is_some() {
303            return InvalidJson2SettingsSnafu {
304                reason: format!("duplicate JSON2 type hint path '{name}'"),
305            }
306            .fail();
307        }
308        return Ok(());
309    }
310
311    let child = object
312        .entry(name.clone())
313        .or_insert_with(|| JsonNativeType::Object(JsonObjectType::new()));
314    let JsonNativeType::Object(child) = child else {
315        return InvalidJson2SettingsSnafu {
316            reason: format!("conflicting JSON2 type hint path at '{name}'"),
317        }
318        .fail();
319    };
320    validate_type_hint(child, path, data_type)
321}
322
323impl<'a> JsonContext<'a> {
324    fn type_hint(&self) -> Option<&'a JsonTypeHint> {
325        self.settings
326            .type_hints
327            .iter()
328            .find(|hint| hint.path == self.path)
329    }
330}
331
332fn with_key_context<T>(
333    context: &mut JsonContext,
334    key: &str,
335    f: impl FnOnce(&mut JsonContext) -> Result<T>,
336) -> Result<T> {
337    context.path.push(key.to_string());
338    let result = f(context);
339    context.path.pop();
340    result
341}
342
343/// Main encoding function with key path tracking
344fn encode_json_with_context(
345    json: Json,
346    context: &mut JsonContext,
347    policy: TypeHintMismatchPolicy,
348) -> Result<JsonValue> {
349    if context.path.is_empty() && !matches!(json, Json::Object(_)) {
350        return UnsupportedJsonTypeSnafu.fail();
351    }
352
353    match json {
354        Json::Object(json_object) => encode_json_object_with_context(json_object, context, policy),
355        Json::Array(json_array) => encode_json_array_with_context(json_array, context, policy),
356        _ => encode_json_value_with_context(json, context, policy),
357    }
358}
359
360fn encode_json_object_with_context<'a>(
361    json_object: Map<String, Json>,
362    context: &mut JsonContext<'a>,
363    policy: TypeHintMismatchPolicy,
364) -> Result<JsonValue> {
365    let mut object = BTreeMap::new();
366    for (key, value) in json_object {
367        let value = with_key_context(context, &key, |context| {
368            if let Some(hint) = context.type_hint() {
369                encode_json_value_with_hint(value, hint, context, policy)
370            } else {
371                encode_json_value_with_context(value, context, policy)
372            }
373        })?;
374
375        object.insert(key, value.into_variant());
376    }
377
378    fill_missing_type_hints(&mut object, context, policy)?;
379
380    Ok(JsonValue::new(JsonVariant::Object(object)))
381}
382
383fn fill_missing_type_hints(
384    object: &mut BTreeMap<String, JsonVariant>,
385    context: &mut JsonContext,
386    policy: TypeHintMismatchPolicy,
387) -> Result<()> {
388    for hint in &context.settings.type_hints {
389        if hint.path.len() > context.path.len() && hint.path.starts_with(&context.path) {
390            let depth = context.path.len();
391            let key = &hint.path[depth];
392            with_key_context(context, key, |context| {
393                insert_missing_type_hint(object, context, hint, depth, policy)
394            })?;
395        }
396    }
397    Ok(())
398}
399
400fn insert_missing_type_hint(
401    object: &mut BTreeMap<String, JsonVariant>,
402    field_context: &mut JsonContext,
403    hint: &JsonTypeHint,
404    depth: usize,
405    policy: TypeHintMismatchPolicy,
406) -> Result<()> {
407    let key = &hint.path[depth];
408    let is_leaf = depth + 1 == hint.path.len();
409
410    if is_leaf {
411        if !object.contains_key(key) {
412            object.insert(key.clone(), JsonValue::null().into_variant());
413        }
414        return Ok(());
415    }
416
417    match object.entry(key.clone()) {
418        Entry::Occupied(mut entry) => match entry.get_mut() {
419            JsonVariant::Object(child) => {
420                insert_missing_type_hint(child, field_context, hint, depth + 1, policy)
421            }
422            _ if policy == TypeHintMismatchPolicy::CoerceOrNull => {
423                entry.insert(JsonValue::null().into_variant());
424                Ok(())
425            }
426            _ => error::InvalidJsonSnafu {
427                value: format!(
428                    "JSON2 type hint path {} expects object at {}",
429                    hint.path.join("."),
430                    field_context.path.join(".")
431                ),
432            }
433            .fail(),
434        },
435        Entry::Vacant(entry) => {
436            let mut child = BTreeMap::new();
437            insert_missing_type_hint(&mut child, field_context, hint, depth + 1, policy)?;
438            entry.insert(JsonVariant::Object(child));
439            Ok(())
440        }
441    }
442}
443
444fn encode_json_value_with_hint(
445    json: Json,
446    hint: &JsonTypeHint,
447    context: &mut JsonContext,
448    policy: TypeHintMismatchPolicy,
449) -> Result<JsonValue> {
450    if json.is_null() {
451        return Ok(JsonValue::null());
452    }
453
454    let json = match (&hint.data_type, json) {
455        (ConcreteDataType::String(_), Json::String(value)) => {
456            return Ok(value.into());
457        }
458        (
459            ConcreteDataType::Int8(_)
460            | ConcreteDataType::Int16(_)
461            | ConcreteDataType::Int32(_)
462            | ConcreteDataType::Int64(_),
463            Json::Number(value),
464        ) => {
465            if let Some(value) = value.as_i64() {
466                return Ok(value.into());
467            }
468            Json::Number(value)
469        }
470        (
471            ConcreteDataType::UInt8(_)
472            | ConcreteDataType::UInt16(_)
473            | ConcreteDataType::UInt32(_)
474            | ConcreteDataType::UInt64(_),
475            Json::Number(value),
476        ) => {
477            if let Some(value) = value.as_u64() {
478                return Ok(value.into());
479            }
480            Json::Number(value)
481        }
482        (ConcreteDataType::Float32(_) | ConcreteDataType::Float64(_), Json::Number(value)) => {
483            if let Some(value) = value.as_f64() {
484                return Ok(value.into());
485            }
486            Json::Number(value)
487        }
488        (ConcreteDataType::Boolean(_), Json::Bool(value)) => {
489            return Ok(value.into());
490        }
491        (_, json) => json,
492    };
493
494    match policy {
495        TypeHintMismatchPolicy::Reject => error::InvalidJsonSnafu {
496            value: format!(
497                "JSON value at {} does not match JSON2 type hint {}",
498                context.path.join("."),
499                hint.data_type
500            ),
501        }
502        .fail(),
503        TypeHintMismatchPolicy::CoerceOrNull => {
504            let value = coerce_json_value_to_type(json, &hint.data_type);
505            let value = Json::try_from(value).map_err(|error| {
506                error::InvalidJsonSnafu {
507                    value: error.to_string(),
508                }
509                .build()
510            })?;
511            Ok(JsonValue::new(value.into()))
512        }
513    }
514}
515
516/// Coerces a JSON value using the same semantics as JSON2 query projection.
517/// Values that cannot be converted become null.
518pub(crate) fn coerce_json_value_to_type(value: Json, to_type: &ConcreteDataType) -> Value {
519    if value.is_null() {
520        return Value::Null;
521    }
522
523    if to_type.is_string() {
524        let value = match value {
525            Json::String(value) => value,
526            value => value.to_string(),
527        };
528        return Value::String(value.into());
529    }
530
531    if matches!(to_type, ConcreteDataType::Binary(_)) {
532        return Value::Binary(encode_serde_json_as_jsonb(value).into());
533    }
534
535    if let Some(struct_type) = to_type.as_struct() {
536        let Json::Object(mut object) = value else {
537            return Value::Null;
538        };
539        let values = struct_type
540            .fields()
541            .iter()
542            .map(|field| {
543                object
544                    .remove(field.name())
545                    .map(|value| coerce_json_value_to_type(value, field.data_type()))
546                    .unwrap_or(Value::Null)
547            })
548            .collect::<Vec<_>>();
549        return Value::Struct(StructValue::new(values, struct_type.clone()));
550    }
551
552    if let Some(list_type) = to_type.as_list() {
553        let Json::Array(values) = value else {
554            return Value::Null;
555        };
556        let item_type = list_type.item_type().clone();
557        let values = values
558            .into_iter()
559            .map(|value| coerce_json_value_to_type(value, &item_type))
560            .collect::<Vec<_>>();
561        return Value::List(ListValue::new(values, Arc::new(item_type)));
562    }
563
564    let value = match value {
565        Json::Bool(value) => Value::Boolean(value),
566        Json::Number(value) => {
567            if let Some(value) = value.as_i64() {
568                Value::Int64(value)
569            } else if let Some(value) = value.as_u64() {
570                Value::UInt64(value)
571            } else if let Some(value) = value.as_f64() {
572                Value::Float64(value.into())
573            } else {
574                Value::Null
575            }
576        }
577        Json::String(value) => Value::String(value.into()),
578        Json::Array(_) | Json::Object(_) | Json::Null => Value::Null,
579    };
580    to_type.try_cast(value).unwrap_or(Value::Null)
581}
582
583fn encode_json_array_with_context<'a>(
584    json_array: Vec<Json>,
585    context: &mut JsonContext<'a>,
586    policy: TypeHintMismatchPolicy,
587) -> Result<JsonValue> {
588    let json_array_len = json_array.len();
589    let mut items = Vec::with_capacity(json_array_len);
590
591    for (index, value) in json_array.into_iter().enumerate() {
592        let item_value = with_key_context(context, &index.to_string(), |context| {
593            encode_json_value_with_context(value, context, policy)
594        })?;
595        items.push(item_value);
596    }
597
598    // In specification, it's valid for a JSON array to have different types of items, for example,
599    // ["a string", 1]. However, in implementation, the `JsonValue` will be converted to Arrow list
600    // array, which requires all items have exactly the same type. So we merge out the maybe
601    // different item types to a unified type, and align all the item values to it.
602
603    let merged_item_type = if let Some((first, rests)) = items.split_first() {
604        let mut merged = first.json_type().clone();
605        for rest in rests.iter().map(|x| x.json_type()) {
606            if matches!(merged, JsonNativeType::Variant) {
607                break;
608            }
609            merged.merge(rest);
610        }
611        Some(merged)
612    } else {
613        None
614    };
615    if let Some(unified_item_type) = merged_item_type {
616        for item in &mut items {
617            item.try_align(&unified_item_type)?;
618        }
619    }
620    let items = items
621        .into_iter()
622        .map(|x| x.into_variant())
623        .collect::<Vec<_>>();
624    Ok(JsonValue::new(JsonVariant::Array(items)))
625}
626
627/// Helper function to encode a JSON value to a Value and determine its ConcreteDataType with context
628fn encode_json_value_with_context(
629    json: Json,
630    context: &mut JsonContext,
631    policy: TypeHintMismatchPolicy,
632) -> Result<JsonValue> {
633    if context.path.len() >= JSON2_MAX_STRUCTURED_DEPTH
634        && matches!(&json, Json::Object(_) | Json::Array(_))
635    {
636        return Ok(JsonValue::new(JsonVariant::Variant(
637            encode_serde_json_as_jsonb(json),
638        )));
639    }
640
641    match json {
642        Json::Null => Ok(JsonValue::null()),
643        Json::Bool(b) => Ok(b.into()),
644        Json::Number(n) => {
645            if let Some(i) = n.as_i64() {
646                Ok(i.into())
647            } else if let Some(u) = n.as_u64() {
648                if u <= i64::MAX as u64 {
649                    Ok((u as i64).into())
650                } else {
651                    Ok(u.into())
652                }
653            } else if let Some(f) = n.as_f64() {
654                Ok(f.into())
655            } else {
656                // Fallback to string representation
657                Ok(n.to_string().into())
658            }
659        }
660        Json::String(s) => Ok(s.into()),
661        Json::Array(arr) => encode_json_array_with_context(arr, context, policy),
662        Json::Object(obj) => encode_json_object_with_context(obj, context, policy),
663    }
664}
665
666/// Main decoding function with key path tracking
667fn decode_value_with_context(value: Value, context: &mut JsonContext) -> Result<Json> {
668    match value {
669        Value::Struct(struct_value) => decode_struct_with_context(struct_value, context),
670        Value::List(list_value) => decode_list_with_context(list_value, context),
671        _ => decode_primitive_value(value),
672    }
673}
674
675/// Decode a structured value to JSON object
676fn decode_struct_with_context<'a>(
677    struct_value: StructValue,
678    context: &mut JsonContext<'a>,
679) -> Result<Json> {
680    let mut json_object = Map::with_capacity(struct_value.len());
681
682    let (items, fields) = struct_value.into_parts();
683
684    for (field, field_value) in fields.fields().iter().zip(items) {
685        let json_value = with_key_context(context, field.name(), |context| {
686            decode_value_with_context(field_value, context)
687        })?;
688        json_object.insert(field.name().to_string(), json_value);
689    }
690
691    Ok(Json::Object(json_object))
692}
693
694/// Decode a list value to JSON array
695fn decode_list_with_context(list_value: ListValue, context: &mut JsonContext) -> Result<Json> {
696    let mut json_array = Vec::with_capacity(list_value.len());
697
698    let data_items = list_value.take_items();
699
700    for (index, item) in data_items.into_iter().enumerate() {
701        let json_value = with_key_context(context, &index.to_string(), |context| {
702            decode_value_with_context(item, context)
703        })?;
704        json_array.push(json_value);
705    }
706
707    Ok(Json::Array(json_array))
708}
709
710/// Decode primitive value to JSON
711fn decode_primitive_value(value: Value) -> Result<Json> {
712    match value {
713        Value::Null => Ok(Json::Null),
714        Value::Boolean(b) => Ok(Json::Bool(b)),
715        Value::UInt8(v) => Ok(Json::from(v)),
716        Value::UInt16(v) => Ok(Json::from(v)),
717        Value::UInt32(v) => Ok(Json::from(v)),
718        Value::UInt64(v) => Ok(Json::from(v)),
719        Value::Int8(v) => Ok(Json::from(v)),
720        Value::Int16(v) => Ok(Json::from(v)),
721        Value::Int32(v) => Ok(Json::from(v)),
722        Value::Int64(v) => Ok(Json::from(v)),
723        Value::Float32(v) => Ok(Json::from(v.0)),
724        Value::Float64(v) => Ok(Json::from(v.0)),
725        Value::String(s) => Ok(Json::String(s.as_utf8().to_string())),
726        Value::Binary(b) => serde_json::to_value(b).context(error::SerializeSnafu),
727        Value::Date(v) => Ok(Json::from(v.val())),
728        Value::Timestamp(v) => serde_json::to_value(v.value()).context(error::SerializeSnafu),
729        Value::Time(v) => serde_json::to_value(v.value()).context(error::SerializeSnafu),
730        Value::IntervalYearMonth(v) => {
731            serde_json::to_value(v.to_i32()).context(error::SerializeSnafu)
732        }
733        Value::IntervalDayTime(v) => {
734            serde_json::to_value(v.to_i64()).context(error::SerializeSnafu)
735        }
736        Value::IntervalMonthDayNano(v) => {
737            serde_json::to_value(v.to_i128()).context(error::SerializeSnafu)
738        }
739        Value::Duration(v) => serde_json::to_value(v.value()).context(error::SerializeSnafu),
740        Value::Decimal128(v) => serde_json::to_value(v.to_string()).context(error::SerializeSnafu),
741        Value::Struct(_) | Value::List(_) | Value::Json(_) => {
742            // These should be handled by the context-aware functions
743            Err(error::InvalidJsonSnafu {
744                value: "Structured values should be handled by context-aware decoding".to_string(),
745            }
746            .build())
747        }
748    }
749}
750
751#[cfg(test)]
752mod tests {
753    use std::sync::Arc;
754
755    use serde_json::json;
756
757    use super::*;
758    use crate::data_type::ConcreteDataType;
759    use crate::types::{ListType, StructField, StructType};
760
761    fn struct_field_value<'a>(struct_value: &'a StructValue, field_name: &str) -> &'a Value {
762        let index = struct_value
763            .struct_type()
764            .fields()
765            .iter()
766            .position(|field| field.name() == field_name)
767            .expect("field exists");
768        &struct_value.items()[index]
769    }
770
771    #[test]
772    fn test_fulltext_settings_roundtrip() {
773        let old =
774            r#"{"type_hints":[{"path":["message"],"type":{"String":{}},"inverted_index":false}]}"#;
775        let legacy: JsonSettings = serde_json::from_str(old).unwrap();
776        assert!(legacy.type_hints()[0].fulltext_index.is_none());
777        let mut hints = legacy.type_hints().to_vec();
778        hints[0].fulltext_index = Some(crate::schema::FulltextOptions {
779            enable: true,
780            ..Default::default()
781        });
782        let settings = JsonSettings::try_new(hints.clone(), Some(0)).unwrap();
783        assert_eq!(
784            settings,
785            serde_json::from_str::<JsonSettings>(&serde_json::to_string(&settings).unwrap())
786                .unwrap()
787        );
788        assert!(!settings.equivalent(&legacy));
789        hints[0].data_type = ConcreteDataType::int64_datatype();
790        assert!(JsonSettings::try_new(hints, Some(0)).is_err());
791    }
792
793    #[test]
794    fn test_skipping_index_settings_roundtrip() {
795        let old = r#"{"type_hints":[{"path":["service","name"],"type":{"String":{}},"inverted_index":true}]}"#;
796        let legacy: JsonSettings = serde_json::from_str(old).unwrap();
797        assert!(legacy.type_hints()[0].skipping_index.is_none());
798        let mut hints = legacy.type_hints().to_vec();
799        hints[0].skipping_index = Some(crate::schema::SkippingIndexOptions::default());
800        let settings = JsonSettings::try_new(hints.clone(), Some(0)).unwrap();
801        let json = serde_json::to_string(&settings).unwrap();
802        assert_eq!(
803            settings,
804            serde_json::from_str::<JsonSettings>(&json).unwrap()
805        );
806        assert!(!settings.equivalent(&legacy));
807        hints[0].skipping_index.as_mut().unwrap().granularity = 0;
808        assert!(JsonSettings::try_new(hints, Some(0)).is_err());
809    }
810
811    #[test]
812    fn test_json_settings_equivalent() -> Result<()> {
813        let hints = vec![
814            JsonTypeHint {
815                path: vec!["user".to_string(), "name".to_string()],
816                data_type: ConcreteDataType::string_datatype(),
817                inverted_index: false,
818                skipping_index: None,
819                fulltext_index: None,
820            },
821            JsonTypeHint {
822                path: vec!["count".to_string()],
823                data_type: ConcreteDataType::int64_datatype(),
824                inverted_index: false,
825                skipping_index: None,
826                fulltext_index: None,
827            },
828        ];
829        let settings = JsonSettings::try_new(hints.clone(), Some(10))?;
830        let mut reversed = hints.clone();
831        reversed.reverse();
832        let reordered = JsonSettings::try_new(reversed, Some(10))?;
833        assert_ne!(settings, reordered);
834        assert!(settings.equivalent(&reordered));
835        assert!(reordered.equivalent(&settings));
836        assert!(settings.equivalent(&settings));
837        assert_eq!(hints, settings.type_hints());
838        assert!(JsonSettings::default().equivalent(&JsonSettings::default()));
839
840        for limit in [None, Some(0), Some(11)] {
841            assert!(!settings.equivalent(&JsonSettings::try_new(hints.clone(), limit)?));
842        }
843        assert!(!settings.equivalent(&JsonSettings::try_new(vec![hints[0].clone()], Some(10))?));
844
845        let mut changed = hints.clone();
846        changed[0].path = vec!["user".to_string(), "id".to_string()];
847        assert!(!settings.equivalent(&JsonSettings::try_new(changed, Some(10))?));
848
849        let mut changed = hints.clone();
850        changed[0].data_type = ConcreteDataType::int64_datatype();
851        assert!(!settings.equivalent(&JsonSettings::try_new(changed, Some(10))?));
852
853        let mut changed = hints;
854        changed[0].inverted_index = true;
855        assert!(!settings.equivalent(&JsonSettings::try_new(changed, Some(10))?));
856        Ok(())
857    }
858
859    #[test]
860    fn test_json_settings_deserializes_legacy_type_hint_constraints()
861    -> std::result::Result<(), Box<dyn std::error::Error>> {
862        let json_str = r#"{
863            "type_hints": [
864                {
865                    "path": ["user", "age"],
866                    "type": {
867                        "Int64": {}
868                    },
869                    "nullable": false,
870                    "default_constraint": {
871                        "Value": {
872                            "Int64": 18
873                        }
874                    },
875                    "inverted_index": true
876                },
877                {
878                    "path": ["user", "name"],
879                    "type": {
880                        "String": {
881                            "size_type": "Utf8"
882                        }
883                    },
884                    "nullable": true,
885                    "inverted_index": false
886                }
887            ]
888        }"#;
889
890        let deserialized = serde_json::from_str::<JsonSettings>(json_str)?;
891
892        let expected = JsonSettings::try_new(
893            vec![
894                JsonTypeHint {
895                    path: vec!["user".to_string(), "age".to_string()],
896                    data_type: ConcreteDataType::int64_datatype(),
897                    inverted_index: true,
898                    skipping_index: None,
899                    fulltext_index: None,
900                },
901                JsonTypeHint {
902                    path: vec!["user".to_string(), "name".to_string()],
903                    data_type: ConcreteDataType::string_datatype(),
904                    inverted_index: false,
905                    skipping_index: None,
906                    fulltext_index: None,
907                },
908            ],
909            None,
910        )?;
911        assert_eq!(deserialized, expected);
912        Ok(())
913    }
914
915    #[test]
916    fn test_json_settings_ser_de() -> std::result::Result<(), Box<dyn std::error::Error>> {
917        let type_hints = vec![
918            JsonTypeHint {
919                path: vec!["user".to_string(), "age".to_string()],
920                data_type: ConcreteDataType::int64_datatype(),
921                inverted_index: true,
922                skipping_index: None,
923                fulltext_index: None,
924            },
925            JsonTypeHint {
926                path: vec!["user".to_string(), "name".to_string()],
927                data_type: ConcreteDataType::string_datatype(),
928                inverted_index: false,
929                skipping_index: None,
930                fulltext_index: None,
931            },
932        ];
933
934        for settings in [
935            JsonSettings {
936                type_hints: type_hints.clone(),
937                max_auto_expanded_paths: None,
938            },
939            JsonSettings {
940                type_hints,
941                max_auto_expanded_paths: Some(1),
942            },
943        ] {
944            let serialized = serde_json::to_string(&settings)?;
945            let deserialized = serde_json::from_str::<JsonSettings>(&serialized)?;
946            assert_eq!(settings, deserialized);
947        }
948        Ok(())
949    }
950
951    #[test]
952    fn test_json_settings_path_validation() {
953        for (path, expected_valid) in [
954            (vec![""], false),
955            (vec!["", "nested"], false),
956            (vec!["nested", ""], false),
957            (vec!["nested", "", "leaf"], false),
958            (vec!["nested", JSON2_REMAINDER_FIELD_NAME], false),
959            (vec!["nested", JSON2_REMAINDER_FIELD_NAME, "leaf"], false),
960            (vec!["nested", "leaf"], true),
961            (vec![], false),
962            (vec![JSON2_REMAINDER_FIELD_NAME], false),
963            (vec![JSON2_REMAINDER_FIELD_NAME, "leaf"], false),
964        ] {
965            for inverted_index in [false, true] {
966                let hint = JsonTypeHint {
967                    path: path.iter().map(|part| (*part).to_string()).collect(),
968                    data_type: ConcreteDataType::string_datatype(),
969                    inverted_index,
970                    skipping_index: None,
971                    fulltext_index: None,
972                };
973                let serialized = json!({"type_hints": [hint.clone()]});
974                assert_eq!(
975                    JsonSettings::try_new(vec![hint], None).is_ok(),
976                    expected_valid,
977                    "path: {path:?}, inverted_index: {inverted_index}"
978                );
979                assert_eq!(
980                    serde_json::from_value::<JsonSettings>(serialized).is_ok(),
981                    expected_valid,
982                    "path: {path:?}, inverted_index: {inverted_index}"
983                );
984            }
985        }
986    }
987
988    #[test]
989    fn test_json_settings_reject_invalid_type_hints() {
990        for type_hints in [
991            json!([{"path": [], "type": {"Int64": {}}, "nullable": true, "inverted_index": false}]),
992            json!([
993                {"path": ["a"], "type": {"Int64": {}}, "nullable": true, "inverted_index": false},
994                {"path": ["a", "b"], "type": {"Int64": {}}, "nullable": true, "inverted_index": false}
995            ]),
996            json!([{"path": [JSON2_REMAINDER_FIELD_NAME], "type": {"Int64": {}}, "nullable": true, "inverted_index": false}]),
997        ] {
998            let settings = json!({"type_hints": type_hints});
999            assert!(serde_json::from_value::<JsonSettings>(settings).is_err());
1000        }
1001
1002        let hint = |path, data_type| JsonTypeHint {
1003            path,
1004            data_type,
1005            inverted_index: false,
1006            skipping_index: None,
1007            fulltext_index: None,
1008        };
1009        assert!(
1010            JsonSettings::try_new(
1011                vec![hint(
1012                    vec!["nested".to_string(), JSON2_REMAINDER_FIELD_NAME.to_string()],
1013                    ConcreteDataType::string_datatype(),
1014                )],
1015                None,
1016            )
1017            .is_err()
1018        );
1019        assert!(
1020            JsonSettings::try_new(
1021                vec![hint(
1022                    vec!["nested".to_string(); JSON2_MAX_STRUCTURED_DEPTH + 1],
1023                    ConcreteDataType::string_datatype(),
1024                )],
1025                None,
1026            )
1027            .is_err()
1028        );
1029        assert!(
1030            JsonSettings::try_new(
1031                vec![hint(
1032                    vec!["date".to_string()],
1033                    ConcreteDataType::date_datatype(),
1034                )],
1035                None,
1036            )
1037            .is_err()
1038        );
1039    }
1040
1041    #[test]
1042    fn test_encode_root_non_object_json() {
1043        let settings = JsonSettings::default();
1044        let cases = [
1045            ("null", Json::Null),
1046            ("boolean", Json::Bool(true)),
1047            ("integer", Json::from(42)),
1048            ("float", Json::from(3.15)),
1049            ("string", Json::String("hello".to_string())),
1050            ("array", json!([1, 2, 3])),
1051            ("mixed array", json!([1, "hello", true, 3.15])),
1052            ("empty array", json!([])),
1053        ];
1054
1055        for (name, json) in cases {
1056            let err = settings.encode(json).unwrap_err();
1057            assert!(
1058                matches!(err, crate::error::Error::UnsupportedJsonType { .. }),
1059                "{name}: {err:?}"
1060            );
1061        }
1062    }
1063
1064    #[test]
1065    fn test_coerce_or_null_on_type_hint_mismatch() -> Result<()> {
1066        let settings = JsonSettings::try_new(
1067            vec![JsonTypeHint {
1068                path: vec!["kind".to_string()],
1069                data_type: ConcreteDataType::int64_datatype(),
1070                inverted_index: false,
1071                skipping_index: None,
1072                fulltext_index: None,
1073            }],
1074            None,
1075        )?;
1076
1077        let result = settings
1078            .encode_with_type_hint_mismatch_policy(
1079                json!({"kind": "invalid", "message": "kept"}),
1080                TypeHintMismatchPolicy::CoerceOrNull,
1081            )?
1082            .into_json_inner()
1083            .unwrap();
1084        let Value::Struct(root) = result else {
1085            panic!("Expected Struct value");
1086        };
1087        assert_eq!(struct_field_value(&root, "kind"), &Value::Null);
1088        assert_eq!(
1089            struct_field_value(&root, "message"),
1090            &Value::String("kept".into())
1091        );
1092        Ok(())
1093    }
1094
1095    #[test]
1096    fn test_coerce_or_null_converts_type_hint_values() -> Result<()> {
1097        let settings = JsonSettings::try_new(
1098            vec![
1099                JsonTypeHint {
1100                    path: vec!["to_string".to_string()],
1101                    data_type: ConcreteDataType::string_datatype(),
1102                    inverted_index: false,
1103                    skipping_index: None,
1104                    fulltext_index: None,
1105                },
1106                JsonTypeHint {
1107                    path: vec!["to_int".to_string()],
1108                    data_type: ConcreteDataType::int64_datatype(),
1109                    inverted_index: false,
1110                    skipping_index: None,
1111                    fulltext_index: None,
1112                },
1113            ],
1114            None,
1115        )?;
1116
1117        let result = settings
1118            .encode_with_type_hint_mismatch_policy(
1119                json!({"to_string": 123, "to_int": "456", "invalid": "value"}),
1120                TypeHintMismatchPolicy::CoerceOrNull,
1121            )?
1122            .into_json_inner()
1123            .unwrap();
1124        let Value::Struct(root) = result else {
1125            panic!("Expected Struct value");
1126        };
1127        assert_eq!(
1128            struct_field_value(&root, "to_string"),
1129            &Value::String("123".into())
1130        );
1131        assert_eq!(struct_field_value(&root, "to_int"), &Value::Int64(456));
1132        assert_eq!(
1133            struct_field_value(&root, "invalid"),
1134            &Value::String("value".into())
1135        );
1136        Ok(())
1137    }
1138
1139    #[test]
1140    fn test_coerce_or_null_on_nested_type_hint_structure_mismatch() -> Result<()> {
1141        let settings = JsonSettings::try_new(
1142            vec![JsonTypeHint {
1143                path: vec!["user".to_string(), "age".to_string()],
1144                data_type: ConcreteDataType::int64_datatype(),
1145                inverted_index: false,
1146                skipping_index: None,
1147                fulltext_index: None,
1148            }],
1149            None,
1150        )?;
1151
1152        let result = settings
1153            .encode_with_type_hint_mismatch_policy(
1154                json!({"user": "invalid", "message": "kept"}),
1155                TypeHintMismatchPolicy::CoerceOrNull,
1156            )?
1157            .into_json_inner()
1158            .unwrap();
1159        let Value::Struct(root) = result else {
1160            panic!("Expected Struct value");
1161        };
1162        assert_eq!(struct_field_value(&root, "user"), &Value::Null);
1163        assert_eq!(
1164            struct_field_value(&root, "message"),
1165            &Value::String("kept".into())
1166        );
1167        Ok(())
1168    }
1169
1170    #[test]
1171    fn test_encode_rejects_reserved_remainder_field() -> Result<()> {
1172        let settings = JsonSettings::default();
1173        let err = settings
1174            .encode(json!({"!__remainder__!": "user-value"}))
1175            .unwrap_err();
1176        assert!(
1177            err.to_string()
1178                .contains("root object cannot contain reserved field")
1179        );
1180
1181        settings.encode(json!({"nested": {"!__remainder__!": "user-value"}}))?;
1182        Ok(())
1183    }
1184
1185    #[test]
1186    fn test_encode_json_object() {
1187        let json = json!({
1188            "name": "John",
1189            "age": 30,
1190            "active": true
1191        });
1192
1193        let settings = JsonSettings::default();
1194        let result = settings.encode(json).unwrap().into_json_inner().unwrap();
1195        let Value::Struct(result) = result else {
1196            panic!("Expected Struct value");
1197        };
1198        assert_eq!(result.items().len(), 3);
1199
1200        let items = result.items();
1201        let struct_type = result.struct_type();
1202
1203        // Check that we have the expected fields
1204        let fields = struct_type.fields();
1205        let field_names: Vec<&str> = fields.iter().map(|f| f.name()).collect();
1206        assert!(field_names.contains(&"name"));
1207        assert!(field_names.contains(&"age"));
1208        assert!(field_names.contains(&"active"));
1209
1210        // Find and check each field
1211        for (i, field) in struct_type.fields().iter().enumerate() {
1212            match field.name() {
1213                "name" => {
1214                    assert_eq!(items[i], Value::String("John".into()));
1215                    assert_eq!(field.data_type(), &ConcreteDataType::string_datatype());
1216                }
1217                "age" => {
1218                    assert_eq!(items[i], Value::Int64(30));
1219                    assert_eq!(field.data_type(), &ConcreteDataType::int64_datatype());
1220                }
1221                "active" => {
1222                    assert_eq!(items[i], Value::Boolean(true));
1223                    assert_eq!(field.data_type(), &ConcreteDataType::boolean_datatype());
1224                }
1225                _ => panic!("Unexpected field: {}", field.name()),
1226            }
1227        }
1228    }
1229
1230    #[test]
1231    fn test_encode_json_nested_object() {
1232        let json = json!({
1233            "person": {
1234                "name": "Alice",
1235                "age": 25
1236            },
1237            "scores": [95, 87, 92]
1238        });
1239
1240        let settings = JsonSettings::default();
1241        let result = settings.encode(json).unwrap().into_json_inner().unwrap();
1242        let Value::Struct(result) = result else {
1243            panic!("Expected Struct value");
1244        };
1245        assert_eq!(result.items().len(), 2);
1246
1247        let items = result.items();
1248        let struct_type = result.struct_type();
1249
1250        // Check person field (nested struct)
1251        let person_index = struct_type
1252            .fields()
1253            .iter()
1254            .position(|f| f.name() == "person")
1255            .unwrap();
1256        if let Value::Struct(person_struct) = &items[person_index] {
1257            assert_eq!(person_struct.items().len(), 2);
1258            let fields = person_struct.struct_type().fields();
1259            let person_fields: Vec<&str> = fields.iter().map(|f| f.name()).collect();
1260            assert!(person_fields.contains(&"name"));
1261            assert!(person_fields.contains(&"age"));
1262        } else {
1263            panic!("Expected Struct value for person field");
1264        }
1265
1266        // Check scores field (list)
1267        let scores_index = struct_type
1268            .fields()
1269            .iter()
1270            .position(|f| f.name() == "scores")
1271            .unwrap();
1272        if let Value::List(scores_list) = &items[scores_index] {
1273            assert_eq!(scores_list.items().len(), 3);
1274            assert_eq!(scores_list.items()[0], Value::Int64(95));
1275            assert_eq!(scores_list.items()[1], Value::Int64(87));
1276            assert_eq!(scores_list.items()[2], Value::Int64(92));
1277        } else {
1278            panic!("Expected List value for scores field");
1279        }
1280    }
1281
1282    #[test]
1283    fn test_encode_json_structured() {
1284        let json = json!({
1285            "name": "Bob",
1286            "age": 35
1287        });
1288
1289        let settings = JsonSettings::default();
1290        let result = settings.encode(json).unwrap().into_json_inner().unwrap();
1291
1292        if let Value::Struct(struct_value) = result {
1293            assert_eq!(struct_value.items().len(), 2);
1294            let fields = struct_value.struct_type().fields();
1295            let field_names: Vec<&str> = fields.iter().map(|f| f.name()).collect();
1296            assert!(field_names.contains(&"name"));
1297            assert!(field_names.contains(&"age"));
1298        } else {
1299            panic!("Expected Struct value");
1300        }
1301    }
1302
1303    #[test]
1304    fn test_encode_json_respects_type_hint() -> Result<()> {
1305        let type_hints = vec![JsonTypeHint {
1306            path: vec!["age".to_string()],
1307            data_type: ConcreteDataType::int64_datatype(),
1308            inverted_index: false,
1309            skipping_index: None,
1310            fulltext_index: None,
1311        }];
1312        let settings = JsonSettings::try_new(type_hints, None)?;
1313
1314        let result = settings
1315            .encode(json!({
1316                "name": "Alice",
1317                "age": 42
1318            }))
1319            .unwrap()
1320            .into_json_inner()
1321            .unwrap();
1322
1323        let Value::Struct(struct_value) = result else {
1324            panic!("Expected Struct value");
1325        };
1326        assert_eq!(struct_field_value(&struct_value, "age"), &Value::Int64(42));
1327
1328        let err = settings
1329            .encode(json!({
1330                "age": "42"
1331            }))
1332            .unwrap_err();
1333        assert!(err.to_string().contains("does not match JSON2 type hint"));
1334        Ok(())
1335    }
1336
1337    #[test]
1338    fn test_encode_json_respects_unsigned_type_hint() -> Result<()> {
1339        let type_hints = vec![JsonTypeHint {
1340            path: vec!["count".to_string()],
1341            data_type: ConcreteDataType::uint64_datatype(),
1342            inverted_index: false,
1343            skipping_index: None,
1344            fulltext_index: None,
1345        }];
1346        let settings = JsonSettings::try_new(type_hints, None)?;
1347
1348        let result = settings
1349            .encode(json!({
1350                "count": u64::MAX
1351            }))
1352            .unwrap()
1353            .into_json_inner()
1354            .unwrap();
1355
1356        let Value::Struct(struct_value) = result else {
1357            panic!("Expected Struct value");
1358        };
1359        assert_eq!(
1360            struct_field_value(&struct_value, "count"),
1361            &Value::UInt64(u64::MAX)
1362        );
1363
1364        let err = settings
1365            .encode(json!({
1366                "count": -1
1367            }))
1368            .unwrap_err();
1369        assert!(err.to_string().contains("does not match JSON2 type hint"));
1370        Ok(())
1371    }
1372
1373    #[test]
1374    fn test_encode_json_fills_missing_type_hint_with_null() -> Result<()> {
1375        let type_hints = vec![JsonTypeHint {
1376            path: vec!["user".to_string(), "age".to_string()],
1377            data_type: ConcreteDataType::int64_datatype(),
1378            inverted_index: false,
1379            skipping_index: None,
1380            fulltext_index: None,
1381        }];
1382        let settings = JsonSettings::try_new(type_hints, None)?;
1383
1384        let result = settings
1385            .encode(json!({}))
1386            .unwrap()
1387            .into_json_inner()
1388            .unwrap();
1389
1390        let Value::Struct(root) = result else {
1391            panic!("Expected Struct value");
1392        };
1393        let Value::Struct(user) = struct_field_value(&root, "user") else {
1394            panic!("Expected user Struct value");
1395        };
1396        assert_eq!(struct_field_value(user, "age"), &Value::Null);
1397        Ok(())
1398    }
1399
1400    #[test]
1401    fn test_encode_json_fills_missing_nullable_type_hint_with_null() -> Result<()> {
1402        let type_hints = vec![JsonTypeHint {
1403            path: vec!["user".to_string(), "name".to_string()],
1404            data_type: ConcreteDataType::string_datatype(),
1405            inverted_index: false,
1406            skipping_index: None,
1407            fulltext_index: None,
1408        }];
1409        let settings = JsonSettings::try_new(type_hints, None)?;
1410
1411        let result = settings
1412            .encode(json!({ "user": {} }))
1413            .unwrap()
1414            .into_json_inner()
1415            .unwrap();
1416
1417        let Value::Struct(root) = result else {
1418            panic!("Expected Struct value");
1419        };
1420        let Value::Struct(user) = struct_field_value(&root, "user") else {
1421            panic!("Expected user Struct value");
1422        };
1423        assert_eq!(struct_field_value(user, "name"), &Value::Null);
1424        Ok(())
1425    }
1426
1427    #[test]
1428    fn test_encode_json_allows_missing_type_hint() -> Result<()> {
1429        let type_hints = vec![JsonTypeHint {
1430            path: vec!["user".to_string(), "age".to_string()],
1431            data_type: ConcreteDataType::int64_datatype(),
1432            inverted_index: false,
1433            skipping_index: None,
1434            fulltext_index: None,
1435        }];
1436        let settings = JsonSettings::try_new(type_hints, None)?;
1437
1438        settings.encode(json!({}))?;
1439        Ok(())
1440    }
1441
1442    #[test]
1443    fn test_encode_json_merges_missing_type_hint_prefix() -> Result<()> {
1444        let type_hints = vec![
1445            JsonTypeHint {
1446                path: vec!["user".to_string(), "age".to_string()],
1447                data_type: ConcreteDataType::int64_datatype(),
1448                inverted_index: false,
1449                skipping_index: None,
1450                fulltext_index: None,
1451            },
1452            JsonTypeHint {
1453                path: vec!["user".to_string(), "name".to_string()],
1454                data_type: ConcreteDataType::string_datatype(),
1455                inverted_index: false,
1456                skipping_index: None,
1457                fulltext_index: None,
1458            },
1459        ];
1460        let settings = JsonSettings::try_new(type_hints, None)?;
1461
1462        let result = settings.encode(json!({}))?.into_json_inner().unwrap();
1463
1464        let Value::Struct(root) = result else {
1465            panic!("Expected Struct value");
1466        };
1467        let Value::Struct(user) = struct_field_value(&root, "user") else {
1468            panic!("Expected user Struct value");
1469        };
1470        assert_eq!(struct_field_value(user, "age"), &Value::Null);
1471        assert_eq!(struct_field_value(user, "name"), &Value::Null);
1472        Ok(())
1473    }
1474
1475    #[test]
1476    fn test_json_settings_structured() {
1477        let json = json!({
1478            "name": "Eve",
1479            "score": 95
1480        });
1481
1482        let settings = JsonSettings::default();
1483        let result = settings.encode(json).unwrap().into_json_inner().unwrap();
1484
1485        if let Value::Struct(struct_value) = result {
1486            assert_eq!(struct_value.items().len(), 2);
1487        } else {
1488            panic!("Expected Struct value");
1489        }
1490    }
1491
1492    #[cfg(test)]
1493    mod decode_tests {
1494        use ordered_float::OrderedFloat;
1495        use serde_json::json;
1496
1497        use super::*;
1498
1499        #[test]
1500        fn test_decode_primitive_values() {
1501            let settings = JsonSettings::default();
1502
1503            // Test null
1504            let result = settings.decode(Value::Null).unwrap();
1505            assert_eq!(result, Json::Null);
1506
1507            // Test boolean
1508            let result = settings.decode(Value::Boolean(true)).unwrap();
1509            assert_eq!(result, Json::Bool(true));
1510
1511            // Test integer
1512            let result = settings.decode(Value::Int64(42)).unwrap();
1513            assert_eq!(result, Json::from(42));
1514
1515            // Test float
1516            let result = settings.decode(Value::Float64(OrderedFloat(3.16))).unwrap();
1517            assert_eq!(result, Json::from(3.16));
1518
1519            // Test string
1520            let result = settings.decode(Value::String("hello".into())).unwrap();
1521            assert_eq!(result, Json::String("hello".to_string()));
1522        }
1523
1524        #[test]
1525        fn test_decode_struct() {
1526            let settings = JsonSettings::default();
1527
1528            let struct_value = StructValue::new(
1529                vec![
1530                    Value::String("Alice".into()),
1531                    Value::Int64(25),
1532                    Value::Boolean(true),
1533                ],
1534                StructType::new(Arc::new(vec![
1535                    StructField::new(
1536                        "name".to_string(),
1537                        ConcreteDataType::string_datatype(),
1538                        true,
1539                    ),
1540                    StructField::new("age".to_string(), ConcreteDataType::int64_datatype(), true),
1541                    StructField::new(
1542                        "active".to_string(),
1543                        ConcreteDataType::boolean_datatype(),
1544                        true,
1545                    ),
1546                ])),
1547            );
1548
1549            let result = settings.decode(Value::Struct(struct_value)).unwrap();
1550            let expected = json!({
1551                "name": "Alice",
1552                "age": 25,
1553                "active": true
1554            });
1555            assert_eq!(result, expected);
1556        }
1557
1558        #[test]
1559        fn test_decode_list() {
1560            let settings = JsonSettings::default();
1561
1562            let list_value = ListValue::new(
1563                vec![Value::Int64(1), Value::Int64(2), Value::Int64(3)],
1564                Arc::new(ConcreteDataType::int64_datatype()),
1565            );
1566
1567            let result = settings.decode(Value::List(list_value)).unwrap();
1568            let expected = json!([1, 2, 3]);
1569            assert_eq!(result, expected);
1570        }
1571
1572        #[test]
1573        fn test_decode_nested_structure() {
1574            let settings = JsonSettings::default();
1575
1576            let inner_struct = StructValue::new(
1577                vec![Value::String("Alice".into()), Value::Int64(25)],
1578                StructType::new(Arc::new(vec![
1579                    StructField::new(
1580                        "name".to_string(),
1581                        ConcreteDataType::string_datatype(),
1582                        true,
1583                    ),
1584                    StructField::new("age".to_string(), ConcreteDataType::int64_datatype(), true),
1585                ])),
1586            );
1587
1588            let score_list_item_type = Arc::new(ConcreteDataType::int64_datatype());
1589            let outer_struct = StructValue::new(
1590                vec![
1591                    Value::Struct(inner_struct),
1592                    Value::List(ListValue::new(
1593                        vec![Value::Int64(95), Value::Int64(87)],
1594                        score_list_item_type.clone(),
1595                    )),
1596                ],
1597                StructType::new(Arc::new(vec![
1598                    StructField::new(
1599                        "user".to_string(),
1600                        ConcreteDataType::Struct(StructType::new(Arc::new(vec![
1601                            StructField::new(
1602                                "name".to_string(),
1603                                ConcreteDataType::string_datatype(),
1604                                true,
1605                            ),
1606                            StructField::new(
1607                                "age".to_string(),
1608                                ConcreteDataType::int64_datatype(),
1609                                true,
1610                            ),
1611                        ]))),
1612                        true,
1613                    ),
1614                    StructField::new(
1615                        "scores".to_string(),
1616                        ConcreteDataType::List(ListType::new(score_list_item_type.clone())),
1617                        true,
1618                    ),
1619                ])),
1620            );
1621
1622            let result = settings.decode(Value::Struct(outer_struct)).unwrap();
1623            let expected = json!({
1624                "user": {
1625                    "name": "Alice",
1626                    "age": 25
1627                },
1628                "scores": [95, 87]
1629            });
1630            assert_eq!(result, expected);
1631        }
1632
1633        #[test]
1634        fn test_decode_missing_fields() {
1635            let settings = JsonSettings::default();
1636
1637            // Struct with missing field (null value)
1638            let struct_value = StructValue::new(
1639                vec![
1640                    Value::String("Bob".into()),
1641                    Value::Null, // missing age field
1642                ],
1643                StructType::new(Arc::new(vec![
1644                    StructField::new(
1645                        "name".to_string(),
1646                        ConcreteDataType::string_datatype(),
1647                        true,
1648                    ),
1649                    StructField::new("age".to_string(), ConcreteDataType::int64_datatype(), true),
1650                ])),
1651            );
1652
1653            let result = settings.decode(Value::Struct(struct_value)).unwrap();
1654            let expected = json!({
1655                "name": "Bob",
1656                "age": null
1657            });
1658            assert_eq!(result, expected);
1659        }
1660    }
1661}