datatypes/types/
json_type.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::str::FromStr;
16
17use arrow::datatypes::DataType as ArrowDataType;
18use common_base::bytes::Bytes;
19use serde::{Deserialize, Serialize};
20use snafu::ResultExt;
21
22use crate::data_type::DataType;
23use crate::error::{DeserializeSnafu, InvalidJsonSnafu, InvalidJsonbSnafu, Result};
24use crate::scalars::ScalarVectorBuilder;
25use crate::type_id::LogicalTypeId;
26use crate::value::Value;
27use crate::vectors::{BinaryVectorBuilder, MutableVector};
28
29pub const JSON_TYPE_NAME: &str = "Json";
30
31#[derive(
32    Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize, Default,
33)]
34pub enum JsonFormat {
35    #[default]
36    Jsonb,
37}
38
39/// JsonType is a data type for JSON data. It is stored as binary data of jsonb format.
40/// It utilizes current binary value and vector implementation.
41#[derive(
42    Debug, Default, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize,
43)]
44pub struct JsonType {
45    pub format: JsonFormat,
46}
47
48impl JsonType {
49    pub fn new(format: JsonFormat) -> Self {
50        Self { format }
51    }
52}
53
54impl DataType for JsonType {
55    fn name(&self) -> String {
56        JSON_TYPE_NAME.to_string()
57    }
58
59    fn logical_type_id(&self) -> LogicalTypeId {
60        LogicalTypeId::Json
61    }
62
63    fn default_value(&self) -> Value {
64        Bytes::default().into()
65    }
66
67    fn as_arrow_type(&self) -> ArrowDataType {
68        ArrowDataType::Binary
69    }
70
71    fn create_mutable_vector(&self, capacity: usize) -> Box<dyn MutableVector> {
72        Box::new(BinaryVectorBuilder::with_capacity(capacity))
73    }
74
75    fn try_cast(&self, from: Value) -> Option<Value> {
76        match from {
77            Value::Binary(v) => Some(Value::Binary(v)),
78            _ => None,
79        }
80    }
81}
82
83/// Converts a json type value to string
84pub fn json_type_value_to_string(val: &[u8], format: &JsonFormat) -> Result<String> {
85    match format {
86        JsonFormat::Jsonb => match jsonb::from_slice(val) {
87            Ok(jsonb_value) => {
88                let serialized = jsonb_value.to_string();
89                Ok(serialized)
90            }
91            Err(e) => InvalidJsonbSnafu { error: e }.fail(),
92        },
93    }
94}
95
96/// Converts a json type value to serde_json::Value
97pub fn json_type_value_to_serde_json(val: &[u8], format: &JsonFormat) -> Result<serde_json::Value> {
98    match format {
99        JsonFormat::Jsonb => {
100            let json_string = json_type_value_to_string(val, format)?;
101            serde_json::Value::from_str(json_string.as_str())
102                .context(DeserializeSnafu { json: json_string })
103        }
104    }
105}
106
107/// Parses a string to a json type value
108pub fn parse_string_to_json_type_value(s: &str, format: &JsonFormat) -> Result<Vec<u8>> {
109    match format {
110        JsonFormat::Jsonb => jsonb::parse_value(s.as_bytes())
111            .map_err(|_| InvalidJsonSnafu { value: s }.build())
112            .map(|json| json.to_vec()),
113    }
114}