reifydb_function/json/
serialize.rs1use reifydb_core::value::column::data::ColumnData;
5use reifydb_type::value::{Value, r#type::Type};
6
7use crate::{ScalarFunction, ScalarFunctionContext, error::ScalarFunctionResult, propagate_options};
8
9fn to_json(value: &Value) -> String {
10 match value {
11 Value::None {
12 ..
13 } => "null".to_string(),
14 Value::Boolean(b) => b.to_string(),
15 Value::Float4(f) => f.to_string(),
16 Value::Float8(f) => f.to_string(),
17 Value::Int1(i) => i.to_string(),
18 Value::Int2(i) => i.to_string(),
19 Value::Int4(i) => i.to_string(),
20 Value::Int8(i) => i.to_string(),
21 Value::Int16(i) => i.to_string(),
22 Value::Uint1(u) => u.to_string(),
23 Value::Uint2(u) => u.to_string(),
24 Value::Uint4(u) => u.to_string(),
25 Value::Uint8(u) => u.to_string(),
26 Value::Uint16(u) => u.to_string(),
27 Value::Int(i) => i.to_string(),
28 Value::Uint(u) => u.to_string(),
29 Value::Decimal(d) => d.to_string(),
30 Value::Utf8(s) => format!("\"{}\"", s.replace('\\', "\\\\").replace('"', "\\\"")),
31 Value::Uuid4(u) => format!("\"{}\"", u),
32 Value::Uuid7(u) => format!("\"{}\"", u),
33 Value::IdentityId(id) => format!("\"{}\"", id),
34 Value::Date(d) => format!("\"{}\"", d),
35 Value::DateTime(dt) => format!("\"{}\"", dt),
36 Value::Time(t) => format!("\"{}\"", t),
37 Value::Duration(d) => format!("\"{}\"", d.to_iso_string()),
38 Value::Blob(b) => format!("\"{}\"", b),
39 Value::DictionaryId(id) => format!("\"{}\"", id),
40 Value::Type(t) => format!("\"{}\"", t),
41 Value::Any(v) => to_json(v),
42 Value::List(items) => {
43 let inner: Vec<String> = items.iter().map(|v| to_json(v)).collect();
44 format!("[{}]", inner.join(", "))
45 }
46 Value::Tuple(items) => {
47 let inner: Vec<String> = items.iter().map(|v| to_json(v)).collect();
48 format!("[{}]", inner.join(", "))
49 }
50 Value::Record(fields) => {
51 let inner: Vec<String> = fields
52 .iter()
53 .map(|(k, v)| {
54 format!("\"{}\": {}", k.replace('\\', "\\\\").replace('"', "\\\""), to_json(v))
55 })
56 .collect();
57 format!("{{{}}}", inner.join(", "))
58 }
59 }
60}
61
62pub struct JsonSerialize;
63
64impl JsonSerialize {
65 pub fn new() -> Self {
66 Self
67 }
68}
69
70impl ScalarFunction for JsonSerialize {
71 fn scalar(&self, ctx: ScalarFunctionContext) -> ScalarFunctionResult<ColumnData> {
72 if let Some(result) = propagate_options(self, &ctx) {
73 return result;
74 }
75
76 let columns = ctx.columns;
77 let row_count = ctx.row_count;
78
79 let col = columns.get(0).unwrap();
80 let results: Vec<String> = (0..row_count).map(|row| to_json(&col.data().get_value(row))).collect();
81
82 Ok(ColumnData::utf8(results))
83 }
84
85 fn return_type(&self, _input_types: &[Type]) -> Type {
86 Type::Utf8
87 }
88}