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 arrow::datatypes::DataType as ArrowDataType;
16use common_base::bytes::Bytes;
17use serde::{Deserialize, Serialize};
18
19use crate::data_type::DataType;
20use crate::error::{InvalidJsonSnafu, Result};
21use crate::scalars::ScalarVectorBuilder;
22use crate::type_id::LogicalTypeId;
23use crate::value::Value;
24use crate::vectors::{BinaryVectorBuilder, MutableVector};
25
26pub const JSON_TYPE_NAME: &str = "Json";
27
28#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
29pub enum JsonFormat {
30    Jsonb,
31}
32
33impl Default for JsonFormat {
34    fn default() -> Self {
35        Self::Jsonb
36    }
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 => Ok(jsonb::to_string(val)),
87    }
88}
89
90/// Parses a string to a json type value
91pub fn parse_string_to_json_type_value(s: &str, format: &JsonFormat) -> Result<Vec<u8>> {
92    match format {
93        JsonFormat::Jsonb => jsonb::parse_value(s.as_bytes())
94            .map_err(|_| InvalidJsonSnafu { value: s }.build())
95            .map(|json| json.to_vec()),
96    }
97}