datatypes/types/
json_type.rs1use 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#[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 => Ok(jsonb::to_string(val)),
87 }
88}
89
90pub 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}