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::{Column, columns::Columns, data::ColumnData};
5use reifydb_type::value::{Value, r#type::Type};
6
7use crate::function::{Function, FunctionCapability, FunctionContext, FunctionInfo, error::FunctionError};
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: FunctionInfo,
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: FunctionInfo::new("json::pretty"),
88		}
89	}
90}
91
92impl Function for JsonPretty {
93	fn info(&self) -> &FunctionInfo {
94		&self.info
95	}
96
97	fn capabilities(&self) -> &[FunctionCapability] {
98		&[FunctionCapability::Scalar]
99	}
100
101	fn return_type(&self, _input_types: &[Type]) -> Type {
102		Type::Utf8
103	}
104
105	fn execute(&self, ctx: &FunctionContext, args: &Columns) -> Result<Columns, FunctionError> {
106		if args.len() != 1 {
107			return Err(FunctionError::ArityMismatch {
108				function: ctx.fragment.clone(),
109				expected: 1,
110				actual: args.len(),
111			});
112		}
113
114		let column = &args[0];
115		let (data, bitvec) = column.data().unwrap_option();
116		let row_count = data.len();
117
118		let results: Vec<String> = (0..row_count).map(|row| to_json_pretty(&data.get_value(row), 0)).collect();
119
120		let result_data = ColumnData::utf8(results);
121		let final_data = match bitvec {
122			Some(bv) => ColumnData::Option {
123				inner: Box::new(result_data),
124				bitvec: bv.clone(),
125			},
126			None => result_data,
127		};
128
129		Ok(Columns::new(vec![Column::new(ctx.fragment.clone(), final_data)]))
130	}
131}