Skip to main content

reifydb_routine/function/json/
serialize.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(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(to_json).collect();
44			format!("[{}]", inner.join(", "))
45		}
46		Value::Tuple(items) => {
47			let inner: Vec<String> = items.iter().map(to_json).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	info: RoutineInfo,
64}
65
66impl Default for JsonSerialize {
67	fn default() -> Self {
68		Self::new()
69	}
70}
71
72impl JsonSerialize {
73	pub fn new() -> Self {
74		Self {
75			info: RoutineInfo::new("json::serialize"),
76		}
77	}
78}
79
80impl<'a> Routine<FunctionContext<'a>> for JsonSerialize {
81	fn info(&self) -> &RoutineInfo {
82		&self.info
83	}
84
85	fn return_type(&self, _input_types: &[Type]) -> Type {
86		Type::Utf8
87	}
88
89	fn execute(&self, ctx: &mut FunctionContext<'a>, args: &Columns) -> Result<Columns, RoutineError> {
90		if args.len() != 1 {
91			return Err(RoutineError::FunctionArityMismatch {
92				function: ctx.fragment.clone(),
93				expected: 1,
94				actual: args.len(),
95			});
96		}
97
98		let column = &args[0];
99		let (data, bitvec) = column.unwrap_option();
100		let row_count = data.len();
101
102		let results: Vec<String> = (0..row_count).map(|row| to_json(&data.get_value(row))).collect();
103
104		let result_data = ColumnBuffer::utf8(results);
105		let final_data = match bitvec {
106			Some(bv) => ColumnBuffer::Option {
107				inner: Box::new(result_data),
108				bitvec: bv.clone(),
109			},
110			None => result_data,
111		};
112
113		Ok(Columns::new(vec![ColumnWithName::new(ctx.fragment.clone(), final_data)]))
114	}
115}
116
117impl Function for JsonSerialize {
118	fn kinds(&self) -> &[FunctionKind] {
119		&[FunctionKind::Scalar]
120	}
121}