Skip to main content

reifydb_routine/function/json/
pretty.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2025 ReifyDB
3
4use reifydb_core::value::column::{ColumnWithName, buffer::ColumnBuffer, columns::Columns};
5use reifydb_type::value::{Value, r#type::Type};
6
7use crate::routine::{Function, FunctionKind, Routine, RoutineInfo, context::FunctionContext, error::RoutineError};
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	info: RoutineInfo,
76}
77
78impl Default for JsonPretty {
79	fn default() -> Self {
80		Self::new()
81	}
82}
83
84impl JsonPretty {
85	pub fn new() -> Self {
86		Self {
87			info: RoutineInfo::new("json::pretty"),
88		}
89	}
90}
91
92impl<'a> Routine<FunctionContext<'a>> for JsonPretty {
93	fn info(&self) -> &RoutineInfo {
94		&self.info
95	}
96
97	fn return_type(&self, _input_types: &[Type]) -> Type {
98		Type::Utf8
99	}
100
101	fn execute(&self, ctx: &mut FunctionContext<'a>, args: &Columns) -> Result<Columns, RoutineError> {
102		if args.len() != 1 {
103			return Err(RoutineError::FunctionArityMismatch {
104				function: ctx.fragment.clone(),
105				expected: 1,
106				actual: args.len(),
107			});
108		}
109
110		let column = &args[0];
111		let (data, bitvec) = column.unwrap_option();
112		let row_count = data.len();
113
114		let results: Vec<String> = (0..row_count).map(|row| to_json_pretty(&data.get_value(row), 0)).collect();
115
116		let result_data = ColumnBuffer::utf8(results);
117		let final_data = match bitvec {
118			Some(bv) => ColumnBuffer::Option {
119				inner: Box::new(result_data),
120				bitvec: bv.clone(),
121			},
122			None => result_data,
123		};
124
125		Ok(Columns::new(vec![ColumnWithName::new(ctx.fragment.clone(), final_data)]))
126	}
127}
128
129impl Function for JsonPretty {
130	fn kinds(&self) -> &[FunctionKind] {
131		&[FunctionKind::Scalar]
132	}
133}