Skip to main content

datatypes/json/
value.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::{Display, Formatter};
17use std::hash::{Hash, Hasher};
18use std::sync::{Arc, OnceLock};
19
20use num_traits::ToPrimitive;
21use ordered_float::OrderedFloat;
22use serde::{Deserialize, Serialize};
23use serde_json::Number;
24use snafu::{OptionExt, ensure};
25
26use crate::Result;
27use crate::data_type::ConcreteDataType;
28use crate::error::{AlignJsonValueSnafu, InvalidJsonSnafu, InvalidJsonbSnafu};
29use crate::types::json_type::{JsonNativeType, JsonNumberType, is_include};
30use crate::types::{StructField, StructType};
31use crate::value::{ListValue, StructValue, Value};
32
33pub type JsonObjectVariant = BTreeMap<String, JsonVariant>;
34
35/// Number in json, can be a positive integer, a negative integer, or a floating number.
36/// Each of which is represented as `u64`, `i64` and `f64`.
37///
38/// This follows how `serde_json` designs number.
39#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
40pub enum JsonNumber {
41    PosInt(u64),
42    NegInt(i64),
43    Float(OrderedFloat<f64>),
44}
45
46impl JsonNumber {
47    pub(crate) fn as_u64(&self) -> Option<u64> {
48        match self {
49            JsonNumber::PosInt(n) => Some(*n),
50            JsonNumber::NegInt(n) => (*n >= 0).then_some(*n as u64),
51            _ => None,
52        }
53    }
54
55    fn as_i64(&self) -> Option<i64> {
56        match self {
57            JsonNumber::PosInt(n) => (*n <= i64::MAX as u64).then_some(*n as i64),
58            JsonNumber::NegInt(n) => Some(*n),
59            _ => None,
60        }
61    }
62
63    fn as_f64(&self) -> f64 {
64        match self {
65            JsonNumber::PosInt(n) => *n as f64,
66            JsonNumber::NegInt(n) => *n as f64,
67            JsonNumber::Float(n) => n.0,
68        }
69    }
70
71    fn native_type(&self) -> JsonNativeType {
72        match self {
73            JsonNumber::PosInt(_) => JsonNativeType::u64(),
74            JsonNumber::NegInt(_) => JsonNativeType::i64(),
75            JsonNumber::Float(_) => JsonNativeType::f64(),
76        }
77    }
78}
79
80impl From<u64> for JsonNumber {
81    fn from(i: u64) -> Self {
82        Self::PosInt(i)
83    }
84}
85
86impl From<i64> for JsonNumber {
87    fn from(n: i64) -> Self {
88        Self::NegInt(n)
89    }
90}
91
92impl From<f64> for JsonNumber {
93    fn from(i: f64) -> Self {
94        Self::Float(i.into())
95    }
96}
97
98impl From<Number> for JsonNumber {
99    fn from(n: Number) -> Self {
100        if let Some(i) = n.as_i64() {
101            i.into()
102        } else if let Some(i) = n.as_u64() {
103            i.into()
104        } else {
105            n.as_f64().unwrap_or(f64::NAN).into()
106        }
107    }
108}
109
110impl Display for JsonNumber {
111    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
112        match self {
113            Self::PosInt(x) => write!(f, "{x}"),
114            Self::NegInt(x) => write!(f, "{x}"),
115            Self::Float(x) => write!(f, "{x}"),
116        }
117    }
118}
119
120/// Variants of json.
121#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
122pub enum JsonVariant {
123    #[default]
124    Null,
125    Bool(bool),
126    Number(JsonNumber),
127    String(String),
128    Array(Vec<JsonVariant>),
129    Object(JsonObjectVariant),
130    /// A special "variant" value of JSON, to represent a union result of conflict JSON type values.
131    Variant(Vec<u8>),
132}
133
134impl JsonVariant {
135    pub(crate) fn as_i64(&self) -> Option<i64> {
136        match self {
137            JsonVariant::Number(n) => n.as_i64(),
138            _ => None,
139        }
140    }
141
142    pub(crate) fn as_u64(&self) -> Option<u64> {
143        match self {
144            JsonVariant::Number(n) => n.as_u64(),
145            _ => None,
146        }
147    }
148
149    pub(crate) fn native_type(&self) -> JsonNativeType {
150        match self {
151            JsonVariant::Null => JsonNativeType::Null,
152            JsonVariant::Bool(_) => JsonNativeType::Bool,
153            JsonVariant::Number(n) => n.native_type(),
154            JsonVariant::String(_) => JsonNativeType::String,
155            JsonVariant::Array(array) => {
156                json_array_native_type(array.iter().map(JsonVariant::native_type))
157            }
158            JsonVariant::Object(object) => {
159                json_object_native_type(object.iter().map(|(k, v)| (k, v.native_type())))
160            }
161            JsonVariant::Variant(_) => JsonNativeType::Variant,
162        }
163    }
164
165    /// Returns whether this value recursively contains an empty object.
166    pub(crate) fn contains_empty_object(&self) -> bool {
167        match self {
168            JsonVariant::Array(array) => array.iter().any(JsonVariant::contains_empty_object),
169            JsonVariant::Object(object) => {
170                object.is_empty() || object.values().any(JsonVariant::contains_empty_object)
171            }
172            _ => false,
173        }
174    }
175
176    fn as_ref(&self) -> JsonVariantRef<'_> {
177        match self {
178            JsonVariant::Null => JsonVariantRef::Null,
179            JsonVariant::Bool(x) => (*x).into(),
180            JsonVariant::Number(x) => match x {
181                JsonNumber::PosInt(i) => (*i).into(),
182                JsonNumber::NegInt(i) => (*i).into(),
183                JsonNumber::Float(f) => (f.0).into(),
184            },
185            JsonVariant::String(x) => x.as_str().into(),
186            JsonVariant::Array(array) => {
187                JsonVariantRef::Array(array.iter().map(|x| x.as_ref()).collect())
188            }
189            JsonVariant::Object(object) => JsonVariantRef::Object(
190                object
191                    .iter()
192                    .map(|(k, v)| (k.as_str(), v.as_ref()))
193                    .collect(),
194            ),
195            JsonVariant::Variant(v) => JsonVariantRef::Variant(v),
196        }
197    }
198}
199
200impl From<()> for JsonVariant {
201    fn from(_: ()) -> Self {
202        Self::Null
203    }
204}
205
206impl From<bool> for JsonVariant {
207    fn from(v: bool) -> Self {
208        Self::Bool(v)
209    }
210}
211
212impl<T: Into<JsonNumber>> From<T> for JsonVariant {
213    fn from(v: T) -> Self {
214        Self::Number(v.into())
215    }
216}
217
218impl From<&str> for JsonVariant {
219    fn from(v: &str) -> Self {
220        Self::String(v.to_string())
221    }
222}
223
224impl From<String> for JsonVariant {
225    fn from(v: String) -> Self {
226        Self::String(v)
227    }
228}
229
230impl<const N: usize, T: Into<JsonVariant>> From<[T; N]> for JsonVariant {
231    fn from(vs: [T; N]) -> Self {
232        Self::Array(vs.into_iter().map(|x| x.into()).collect())
233    }
234}
235
236impl<K: Into<String>, V: Into<JsonVariant>, const N: usize> From<[(K, V); N]> for JsonVariant {
237    fn from(vs: [(K, V); N]) -> Self {
238        Self::Object(vs.into_iter().map(|(k, v)| (k.into(), v.into())).collect())
239    }
240}
241
242impl From<serde_json::Value> for JsonVariant {
243    fn from(v: serde_json::Value) -> Self {
244        fn helper(v: serde_json::Value) -> JsonVariant {
245            match v {
246                serde_json::Value::Null => JsonVariant::Null,
247                serde_json::Value::Bool(b) => b.into(),
248                serde_json::Value::Number(n) => n.into(),
249                serde_json::Value::String(s) => s.into(),
250                serde_json::Value::Array(array) => {
251                    JsonVariant::Array(array.into_iter().map(helper).collect())
252                }
253                serde_json::Value::Object(object) => {
254                    JsonVariant::Object(object.into_iter().map(|(k, v)| (k, helper(v))).collect())
255                }
256            }
257        }
258        helper(v)
259    }
260}
261
262impl From<BTreeMap<String, JsonVariant>> for JsonVariant {
263    fn from(v: BTreeMap<String, JsonVariant>) -> Self {
264        Self::Object(v)
265    }
266}
267
268impl Display for JsonVariant {
269    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
270        match self {
271            Self::Null => write!(f, "null"),
272            Self::Bool(x) => write!(f, "{x}"),
273            Self::Number(x) => write!(f, "{x}"),
274            Self::String(x) => write!(f, "{x}"),
275            Self::Array(array) => write!(
276                f,
277                "[{}]",
278                array
279                    .iter()
280                    .map(|x| x.to_string())
281                    .collect::<Vec<_>>()
282                    .join(", ")
283            ),
284            Self::Object(object) => {
285                write!(
286                    f,
287                    "{{ {} }}",
288                    object
289                        .iter()
290                        .map(|(k, v)| format!("{k}: {v}"))
291                        .collect::<Vec<_>>()
292                        .join(", ")
293                )
294            }
295            Self::Variant(x) => match decode_json_variant(x) {
296                Ok(v) => write!(f, "{v}"),
297                Err(_) => write!(f, "{x:?}"),
298            },
299        }
300    }
301}
302
303/// Represents any valid JSON value.
304#[derive(Debug, Eq, Serialize, Deserialize)]
305pub struct JsonValue {
306    #[serde(skip)]
307    json_type: OnceLock<Arc<JsonNativeType>>,
308    json_variant: JsonVariant,
309}
310
311impl JsonValue {
312    pub fn null() -> Self {
313        ().into()
314    }
315
316    pub(crate) fn new(json_variant: JsonVariant) -> Self {
317        Self {
318            json_type: OnceLock::new(),
319            json_variant,
320        }
321    }
322
323    pub(crate) fn data_type(&self) -> ConcreteDataType {
324        ConcreteDataType::json2(self.json_type().clone())
325    }
326
327    pub(crate) fn json_type(&self) -> &JsonNativeType {
328        self.json_type
329            .get_or_init(|| Arc::new(self.json_variant.native_type()))
330            .as_ref()
331    }
332
333    pub(crate) fn is_null(&self) -> bool {
334        matches!(self.json_variant, JsonVariant::Null)
335    }
336
337    /// Check if this JSON value is an empty object.
338    pub fn is_empty_object(&self) -> bool {
339        match &self.json_variant {
340            JsonVariant::Object(object) => object.is_empty(),
341            _ => false,
342        }
343    }
344
345    pub(crate) fn as_i64(&self) -> Option<i64> {
346        self.json_variant.as_i64()
347    }
348
349    pub(crate) fn as_u64(&self) -> Option<u64> {
350        self.json_variant.as_u64()
351    }
352
353    pub(crate) fn as_f64_lossy(&self) -> Option<f64> {
354        match self.json_variant {
355            JsonVariant::Number(n) => Some(match n {
356                JsonNumber::PosInt(i) => i as f64,
357                JsonNumber::NegInt(i) => i as f64,
358                JsonNumber::Float(f) => f.0,
359            }),
360            _ => None,
361        }
362    }
363
364    pub(crate) fn as_bool(&self) -> Option<bool> {
365        match self.json_variant {
366            JsonVariant::Bool(b) => Some(b),
367            _ => None,
368        }
369    }
370
371    pub fn as_ref(&self) -> JsonValueRef<'_> {
372        JsonValueRef {
373            json_type: OnceLock::new(),
374            json_variant: self.json_variant.as_ref(),
375        }
376    }
377
378    pub fn into_variant(self) -> JsonVariant {
379        self.json_variant
380    }
381
382    /// Borrows the JSON representation without constructing a tree of value references.
383    pub fn variant(&self) -> &JsonVariant {
384        &self.json_variant
385    }
386
387    pub(crate) fn into_value(self) -> Value {
388        fn helper(v: JsonVariant) -> Value {
389            match v {
390                JsonVariant::Null => Value::Null,
391                JsonVariant::Bool(x) => Value::Boolean(x),
392                JsonVariant::Number(x) => match x {
393                    JsonNumber::PosInt(i) => Value::UInt64(i),
394                    JsonNumber::NegInt(i) => Value::Int64(i),
395                    JsonNumber::Float(f) => Value::Float64(f),
396                },
397                JsonVariant::String(x) => Value::String(x.into()),
398                JsonVariant::Array(array) => {
399                    let values = array.into_iter().map(helper).collect::<Vec<_>>();
400                    debug_assert!(
401                        values
402                            .windows(2)
403                            .all(|w| w[0].data_type() == w[1].data_type())
404                    );
405                    let item_type = values
406                        .first()
407                        .map(|x| x.data_type())
408                        .unwrap_or_else(ConcreteDataType::null_datatype);
409                    Value::List(ListValue::new(values, Arc::new(item_type)))
410                }
411                JsonVariant::Object(object) => {
412                    let mut fields = Vec::with_capacity(object.len());
413                    let mut items = Vec::with_capacity(object.len());
414                    for (k, v) in object {
415                        let v = helper(v);
416                        fields.push(StructField::new(k, v.data_type(), true));
417                        items.push(v);
418                    }
419                    Value::Struct(StructValue::new(items, StructType::new(Arc::new(fields))))
420                }
421                JsonVariant::Variant(x) => Value::Binary(x.into()),
422            }
423        }
424        helper(self.json_variant)
425    }
426
427    /// Recursively aligns this JSON value to `expected` in place. This is to make JSON values fill
428    /// into a [StructArray], which requires a unified static datatype.
429    ///
430    /// Alignment follows these rules:
431    /// - `Null` aligns to any type, and any value aligns to `Null` as `Null`.
432    /// - Numbers are converted only within compatible number categories.
433    /// - Arrays align each element recursively to the expected item type.
434    /// - Objects require `expected` to have all fields from the current value.
435    /// - `Variant` preserves the original JSON payload as serialized bytes.
436    ///
437    /// Returns an error if the value cannot be aligned without losing existing object fields or
438    /// when a scalar type conversion is incompatible.
439    pub(crate) fn try_align(&mut self, expected: &JsonNativeType) -> Result<()> {
440        if is_include(expected, self.json_type()) && !self.json_variant.contains_empty_object() {
441            return Ok(());
442        }
443
444        fn helper(value: JsonVariant, expected: &JsonNativeType) -> Result<JsonVariant> {
445            Ok(match (value, expected) {
446                (JsonVariant::Null, _) | (_, JsonNativeType::Null) => JsonVariant::Null,
447                (JsonVariant::Bool(v), JsonNativeType::Bool) => JsonVariant::Bool(v),
448                (JsonVariant::Number(v), JsonNativeType::Number(n)) => {
449                    return match n {
450                        JsonNumberType::U64 => v
451                            .as_u64()
452                            .map(|x| JsonVariant::Number(JsonNumber::PosInt(x))),
453                        JsonNumberType::I64 => v
454                            .as_i64()
455                            .map(|x| JsonVariant::Number(JsonNumber::NegInt(x))),
456                        JsonNumberType::F64 => {
457                            Some(JsonVariant::Number(JsonNumber::Float(v.as_f64().into())))
458                        }
459                    }
460                    .with_context(|| AlignJsonValueSnafu {
461                        reason: format!("unable to align number ‘{}’ to type {}", v, expected),
462                    });
463                }
464                (JsonVariant::String(v), JsonNativeType::String) => JsonVariant::String(v),
465
466                (JsonVariant::Array(items), JsonNativeType::Array(expected)) => JsonVariant::Array(
467                    items
468                        .into_iter()
469                        .map(|item| helper(item, expected.as_ref()))
470                        .collect::<Result<_>>()?,
471                ),
472
473                (JsonVariant::Object(mut kvs), JsonNativeType::Object(expected)) => {
474                    ensure!(
475                        expected.keys().len() >= kvs.keys().len()
476                            && kvs.keys().all(|k| expected.contains_key(k)),
477                        AlignJsonValueSnafu {
478                            reason: format!(
479                                "aligned type '{}' should be superset of value '{}'",
480                                JsonNativeType::Object(expected.clone()),
481                                JsonVariant::from(kvs),
482                            )
483                        }
484                    );
485
486                    for (field, field_type) in expected {
487                        if let Some((k, v)) = kvs.remove_entry(field) {
488                            kvs.insert(k, helper(v, field_type)?);
489                        }
490                    }
491                    JsonVariant::Object(kvs)
492                }
493
494                (v, JsonNativeType::Variant) => JsonVariant::Variant(encode_json_variant(v)?),
495
496                (value, expected) => {
497                    return AlignJsonValueSnafu {
498                        reason: format!(
499                            "unable to align '{}' of type {} to type {}",
500                            value,
501                            value.native_type(),
502                            expected,
503                        ),
504                    }
505                    .fail();
506                }
507            })
508        }
509
510        let x = std::mem::take(&mut self.json_variant);
511
512        self.json_variant = helper(x, expected)?;
513        self.json_type = OnceLock::new();
514        Ok(())
515    }
516}
517
518impl<T: Into<JsonVariant>> From<T> for JsonValue {
519    fn from(v: T) -> Self {
520        Self {
521            json_type: OnceLock::new(),
522            json_variant: v.into(),
523        }
524    }
525}
526
527impl TryFrom<JsonValue> for serde_json::Value {
528    type Error = serde_json::Error;
529
530    fn try_from(v: JsonValue) -> serde_json::Result<Self> {
531        fn helper(v: JsonVariant) -> serde_json::Result<serde_json::Value> {
532            Ok(match v {
533                JsonVariant::Null => serde_json::Value::Null,
534                JsonVariant::Bool(x) => serde_json::Value::Bool(x),
535                JsonVariant::Number(x) => match x {
536                    JsonNumber::PosInt(i) => serde_json::Value::Number(i.into()),
537                    JsonNumber::NegInt(i) => serde_json::Value::Number(i.into()),
538                    JsonNumber::Float(f) => {
539                        if let Some(x) = Number::from_f64(f.0) {
540                            serde_json::Value::Number(x)
541                        } else {
542                            serde_json::Value::String("NaN".into())
543                        }
544                    }
545                },
546                JsonVariant::String(x) => serde_json::Value::String(x),
547                JsonVariant::Array(array) => serde_json::Value::Array(
548                    array
549                        .into_iter()
550                        .map(helper)
551                        .collect::<serde_json::Result<Vec<_>>>()?,
552                ),
553                JsonVariant::Object(object) => {
554                    let mut map = serde_json::Map::with_capacity(object.len());
555                    for (k, v) in object {
556                        map.insert(k, helper(v)?);
557                    }
558                    serde_json::Value::Object(map)
559                }
560                JsonVariant::Variant(x) => decode_json_variant(&x).map_err(|err| {
561                    serde_json::Error::io(std::io::Error::new(
562                        std::io::ErrorKind::InvalidData,
563                        err.to_string(),
564                    ))
565                })?,
566            })
567        }
568        helper(v.json_variant)
569    }
570}
571
572pub(crate) fn encode_json_variant(value: JsonVariant) -> Result<Vec<u8>> {
573    match value {
574        JsonVariant::Variant(bytes) => Ok(bytes),
575        value => jsonb::Value::try_from(value).map(|value| value.to_vec()),
576    }
577}
578
579pub(crate) fn decode_json_variant(
580    bytes: &[u8],
581) -> std::result::Result<serde_json::Value, jsonb::Error> {
582    jsonb::from_slice(bytes).map(Into::into)
583}
584
585pub(crate) fn encode_serde_json_as_jsonb(value: serde_json::Value) -> Vec<u8> {
586    jsonb::Value::from(value).to_vec()
587}
588
589impl TryFrom<JsonVariant> for jsonb::Value<'static> {
590    type Error = crate::Error;
591
592    fn try_from(value: JsonVariant) -> Result<Self> {
593        Ok(match value {
594            JsonVariant::Null => jsonb::Value::Null,
595            JsonVariant::Bool(value) => jsonb::Value::Bool(value),
596            JsonVariant::Number(value) => jsonb::Value::Number(value.try_into()?),
597            JsonVariant::String(value) => jsonb::Value::String(value.into()),
598            JsonVariant::Array(values) => jsonb::Value::Array(
599                values
600                    .into_iter()
601                    .map(jsonb::Value::try_from)
602                    .collect::<Result<_>>()?,
603            ),
604            JsonVariant::Object(values) => jsonb::Value::Object(
605                values
606                    .into_iter()
607                    .map(|(key, value)| jsonb::Value::try_from(value).map(|value| (key, value)))
608                    .collect::<Result<_>>()?,
609            ),
610            JsonVariant::Variant(value) => {
611                let value = decode_json_variant(&value)
612                    .map_err(|error| InvalidJsonbSnafu { error }.build())?;
613                jsonb::Value::from(value)
614            }
615        })
616    }
617}
618
619impl TryFrom<JsonNumber> for jsonb::Number {
620    type Error = crate::Error;
621
622    fn try_from(value: JsonNumber) -> Result<Self> {
623        Ok(match value {
624            JsonNumber::PosInt(value) => jsonb::Number::UInt64(value),
625            JsonNumber::NegInt(value) => jsonb::Number::Int64(value),
626            JsonNumber::Float(value) => {
627                ensure!(
628                    !value.0.is_nan(),
629                    InvalidJsonSnafu {
630                        value: "NaN is not a valid JSON number"
631                    }
632                );
633                jsonb::Number::Float64(value.0)
634            }
635        })
636    }
637}
638
639impl Clone for JsonValue {
640    fn clone(&self) -> Self {
641        let Self {
642            json_type: _,
643            json_variant,
644        } = self;
645        Self {
646            json_type: OnceLock::new(),
647            json_variant: json_variant.clone(),
648        }
649    }
650}
651
652impl PartialEq<JsonValue> for JsonValue {
653    fn eq(&self, other: &JsonValue) -> bool {
654        let Self {
655            json_type: _,
656            json_variant,
657        } = self;
658        json_variant.eq(&other.json_variant)
659    }
660}
661
662impl Hash for JsonValue {
663    fn hash<H: Hasher>(&self, state: &mut H) {
664        let Self {
665            json_type: _,
666            json_variant,
667        } = self;
668        json_variant.hash(state);
669    }
670}
671
672impl Display for JsonValue {
673    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
674        write!(f, "{}", self.json_variant)
675    }
676}
677
678/// References of variants of json.
679#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
680pub enum JsonVariantRef<'a> {
681    Null,
682    Bool(bool),
683    Number(JsonNumber),
684    String(&'a str),
685    Array(Vec<JsonVariantRef<'a>>),
686    Object(BTreeMap<&'a str, JsonVariantRef<'a>>),
687    Variant(&'a [u8]),
688}
689
690impl JsonVariantRef<'_> {
691    fn native_type(&self) -> JsonNativeType {
692        match self {
693            JsonVariantRef::Null => JsonNativeType::Null,
694            JsonVariantRef::Bool(_) => JsonNativeType::Bool,
695            JsonVariantRef::Number(n) => n.native_type(),
696            JsonVariantRef::String(_) => JsonNativeType::String,
697            JsonVariantRef::Array(array) => {
698                json_array_native_type(array.iter().map(JsonVariantRef::native_type))
699            }
700            JsonVariantRef::Object(object) => {
701                json_object_native_type(object.iter().map(|(k, v)| (*k, v.native_type())))
702            }
703            JsonVariantRef::Variant(_) => JsonNativeType::Variant,
704        }
705    }
706}
707
708fn json_array_native_type<I>(items: I) -> JsonNativeType
709where
710    I: IntoIterator<Item = JsonNativeType>,
711{
712    let mut iter = items.into_iter();
713    let mut item_type = match iter.next() {
714        Some(t) => t,
715        None => return JsonNativeType::Array(Box::new(JsonNativeType::Null)),
716    };
717
718    for x in iter {
719        if matches!(item_type, JsonNativeType::Variant) {
720            break;
721        }
722        item_type.merge(&x);
723    }
724    JsonNativeType::Array(Box::new(item_type))
725}
726
727fn json_object_native_type<I, K>(fields: I) -> JsonNativeType
728where
729    I: IntoIterator<Item = (K, JsonNativeType)>,
730    K: Into<String>,
731{
732    JsonNativeType::Object(fields.into_iter().map(|(k, v)| (k.into(), v)).collect())
733}
734
735impl From<()> for JsonVariantRef<'_> {
736    fn from(_: ()) -> Self {
737        Self::Null
738    }
739}
740
741impl From<bool> for JsonVariantRef<'_> {
742    fn from(v: bool) -> Self {
743        Self::Bool(v)
744    }
745}
746
747impl<T: Into<JsonNumber>> From<T> for JsonVariantRef<'_> {
748    fn from(v: T) -> Self {
749        Self::Number(v.into())
750    }
751}
752
753impl<'a> From<&'a str> for JsonVariantRef<'a> {
754    fn from(v: &'a str) -> Self {
755        Self::String(v)
756    }
757}
758
759impl<'a, const N: usize, T: Into<JsonVariantRef<'a>>> From<[T; N]> for JsonVariantRef<'a> {
760    fn from(vs: [T; N]) -> Self {
761        Self::Array(vs.into_iter().map(|x| x.into()).collect())
762    }
763}
764
765impl<'a, V: Into<JsonVariantRef<'a>>, const N: usize> From<[(&'a str, V); N]>
766    for JsonVariantRef<'a>
767{
768    fn from(vs: [(&'a str, V); N]) -> Self {
769        Self::Object(vs.into_iter().map(|(k, v)| (k, v.into())).collect())
770    }
771}
772
773impl<'a> From<Vec<JsonVariantRef<'a>>> for JsonVariantRef<'a> {
774    fn from(v: Vec<JsonVariantRef<'a>>) -> Self {
775        Self::Array(v)
776    }
777}
778
779impl<'a> From<BTreeMap<&'a str, JsonVariantRef<'a>>> for JsonVariantRef<'a> {
780    fn from(v: BTreeMap<&'a str, JsonVariantRef<'a>>) -> Self {
781        Self::Object(v)
782    }
783}
784
785impl From<&JsonVariantRef<'_>> for JsonVariant {
786    fn from(v: &JsonVariantRef) -> Self {
787        match v {
788            JsonVariantRef::Null => Self::Null,
789            JsonVariantRef::Bool(x) => Self::Bool(*x),
790            JsonVariantRef::Number(x) => Self::Number(*x),
791            JsonVariantRef::String(x) => Self::String(x.to_string()),
792            JsonVariantRef::Array(array) => Self::Array(array.iter().map(Into::into).collect()),
793            JsonVariantRef::Object(object) => Self::Object(
794                object
795                    .iter()
796                    .map(|(k, v)| (k.to_string(), v.into()))
797                    .collect(),
798            ),
799            JsonVariantRef::Variant(x) => Self::Variant(x.to_vec()),
800        }
801    }
802}
803
804impl<'a> From<&'a [u8]> for JsonVariantRef<'a> {
805    fn from(value: &'a [u8]) -> Self {
806        Self::Variant(value)
807    }
808}
809
810/// Reference to representation of any valid JSON value.
811#[derive(Debug, Serialize)]
812pub struct JsonValueRef<'a> {
813    #[serde(skip)]
814    json_type: OnceLock<Arc<JsonNativeType>>,
815    json_variant: JsonVariantRef<'a>,
816}
817
818impl<'a> JsonValueRef<'a> {
819    pub fn null() -> Self {
820        ().into()
821    }
822
823    /// Creates a JSON value reference with its precomputed native type.
824    /// The native type must describe `json_variant` exactly.
825    pub fn new_with_type(json_variant: JsonVariantRef<'a>, json_type: JsonNativeType) -> Self {
826        Self {
827            json_type: OnceLock::from(Arc::new(json_type)),
828            json_variant,
829        }
830    }
831
832    pub(crate) fn data_type(&self) -> ConcreteDataType {
833        ConcreteDataType::json2(self.json_type().as_ref().clone())
834    }
835
836    pub(crate) fn json_type(&self) -> Arc<JsonNativeType> {
837        self.json_type
838            .get_or_init(|| Arc::new(self.json_variant.native_type()))
839            .clone()
840    }
841
842    pub fn into_variant(self) -> JsonVariantRef<'a> {
843        self.json_variant
844    }
845
846    pub(crate) fn is_null(&self) -> bool {
847        matches!(self.json_variant, JsonVariantRef::Null)
848    }
849
850    pub fn is_object(&self) -> bool {
851        matches!(self.json_variant, JsonVariantRef::Object(_))
852    }
853
854    pub(crate) fn as_f32(&self) -> Option<f32> {
855        match self.json_variant {
856            JsonVariantRef::Number(JsonNumber::Float(f)) => f.to_f32(),
857            _ => None,
858        }
859    }
860
861    pub(crate) fn as_f64(&self) -> Option<f64> {
862        match self.json_variant {
863            JsonVariantRef::Number(JsonNumber::Float(f)) => Some(f.0),
864            _ => None,
865        }
866    }
867
868    pub(crate) fn data_size(&self) -> usize {
869        size_of_val(self)
870    }
871
872    pub(crate) fn variant(&self) -> &JsonVariantRef<'a> {
873        &self.json_variant
874    }
875}
876
877impl<'a, T: Into<JsonVariantRef<'a>>> From<T> for JsonValueRef<'a> {
878    fn from(v: T) -> Self {
879        Self {
880            json_type: OnceLock::new(),
881            json_variant: v.into(),
882        }
883    }
884}
885
886impl From<JsonValueRef<'_>> for JsonValue {
887    fn from(v: JsonValueRef<'_>) -> Self {
888        Self {
889            json_type: OnceLock::new(),
890            json_variant: JsonVariant::from(&v.json_variant),
891        }
892    }
893}
894
895impl PartialEq for JsonValueRef<'_> {
896    fn eq(&self, other: &Self) -> bool {
897        let Self {
898            json_type: _,
899            json_variant,
900        } = self;
901        json_variant == &other.json_variant
902    }
903}
904
905impl Eq for JsonValueRef<'_> {}
906
907impl Clone for JsonValueRef<'_> {
908    fn clone(&self) -> Self {
909        let Self {
910            json_type: _,
911            json_variant,
912        } = self;
913        Self {
914            json_type: OnceLock::new(),
915            json_variant: json_variant.clone(),
916        }
917    }
918}
919
920#[cfg(test)]
921mod tests {
922    use super::*;
923    use crate::types::json_type::JsonObjectType;
924
925    fn jsonb_bytes(json: &str) -> Vec<u8> {
926        let value: serde_json::Value = serde_json::from_str(json).unwrap();
927        encode_json_variant(value.into()).unwrap()
928    }
929
930    #[test]
931    fn test_align_json_value() -> Result<()> {
932        fn parse_json_value(json: &str) -> JsonValue {
933            let value: serde_json::Value = serde_json::from_str(json).unwrap();
934            value.into()
935        }
936
937        // Root type can be aligned to Null, and the cached json_type must be refreshed.
938        let mut value = JsonValue::from(true);
939        assert_eq!(value.json_type(), &JsonNativeType::Bool);
940        value.try_align(&JsonNativeType::Null)?;
941        assert_eq!(value, JsonValue::null());
942        assert_eq!(value.json_type(), &JsonNativeType::Null);
943
944        // Object alignment now requires the expected type to be a superset of the
945        // value fields, while still filling missing expected fields with null.
946        let expected = JsonNativeType::Object(JsonObjectType::from([
947            ("extra".to_string(), JsonNativeType::u64()),
948            (
949                "items".to_string(),
950                JsonNativeType::Array(Box::new(JsonNativeType::Object(JsonObjectType::from([
951                    ("id".to_string(), JsonNativeType::u64()),
952                    ("payload".to_string(), JsonNativeType::Variant),
953                    ("note".to_string(), JsonNativeType::String),
954                ])))),
955            ),
956            ("name".to_string(), JsonNativeType::String),
957        ]));
958        let mut value = parse_json_value(r#"{"items":[{"id":1,"payload":{"k":"v"}}],"extra":1}"#);
959        assert_ne!(value.json_type(), &expected);
960        value.try_align(&expected)?;
961        assert_eq!(
962            value,
963            JsonValue::from(JsonVariant::Object(BTreeMap::from([
964                ("extra".to_string(), JsonVariant::from(1_u64)),
965                (
966                    "items".to_string(),
967                    JsonVariant::Array(vec![JsonVariant::Object(BTreeMap::from([
968                        ("id".to_string(), JsonVariant::from(1_u64)),
969                        (
970                            "payload".to_string(),
971                            JsonVariant::Variant(jsonb_bytes(r#"{"k":"v"}"#)),
972                        ),
973                    ]))]),
974                ),
975            ])))
976        );
977
978        // Empty objects have an empty Object type and remain distinct from Null.
979        let expected = JsonNativeType::Object(JsonObjectType::from([(
980            "empty".to_string(),
981            JsonNativeType::Object(JsonObjectType::default()),
982        )]));
983        let mut value = parse_json_value(r#"{"empty":{}}"#);
984        assert_eq!(value.json_type(), &expected);
985        value.try_align(&expected)?;
986        assert_eq!(
987            value,
988            JsonValue::from(JsonVariant::Object(BTreeMap::from([(
989                "empty".to_string(),
990                JsonVariant::Object(BTreeMap::default()),
991            )])))
992        );
993
994        // Object alignment should fail if the expected type misses any field from the value.
995        let expected = JsonNativeType::Object(JsonObjectType::from([(
996            "items".to_string(),
997            JsonNativeType::Array(Box::new(JsonNativeType::Object(JsonObjectType::from([
998                ("id".to_string(), JsonNativeType::u64()),
999                ("payload".to_string(), JsonNativeType::Variant),
1000            ])))),
1001        )]));
1002        let mut value =
1003            parse_json_value(r#"{"items":[{"id":1,"payload":{"k":"v"},"extra":true}]}"#);
1004        let err = value.try_align(&expected).unwrap_err();
1005        assert_eq!(
1006            err.to_string(),
1007            r#"Failed to align JSON value, reason: aligned type '{"id":"<Number>","payload":"<Variant>"}' should be superset of value '{ extra: true, id: 1, payload: { k: v } }'"#
1008        );
1009
1010        // Root-level Variant alignment should preserve the original JSON payload.
1011        let mut value = parse_json_value(r#"{"foo":[1,true,null]}"#);
1012        value.try_align(&JsonNativeType::Variant)?;
1013        assert_eq!(
1014            value,
1015            JsonValue::from(JsonVariant::Variant(jsonb_bytes(
1016                r#"{"foo":[1,true,null]}"#
1017            )))
1018        );
1019
1020        // Incompatible scalar alignment should fail instead of coercing the value.
1021        let mut value = JsonValue::from("hello");
1022        let err = value.try_align(&JsonNativeType::Bool).unwrap_err();
1023        assert_eq!(
1024            err.to_string(),
1025            r#"Failed to align JSON value, reason: unable to align 'hello' of type "<String>" to type "<Bool>""#
1026        );
1027
1028        let mut value = JsonValue::from(f64::NAN);
1029        let err = value.try_align(&JsonNativeType::Variant).unwrap_err();
1030        assert_eq!(
1031            err.to_string(),
1032            "Invalid JSON: NaN is not a valid JSON number"
1033        );
1034
1035        Ok(())
1036    }
1037}