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