datatypes/types/
json_type.rs1use 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#[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
83pub 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
96pub 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
107pub 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}