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::{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(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: FunctionInfo,
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: FunctionInfo::new("json::serialize"),
76		}
77	}
78}
79
80impl Function for JsonSerialize {
81	fn info(&self) -> &FunctionInfo {
82		&self.info
83	}
84
85	fn capabilities(&self) -> &[FunctionCapability] {
86		&[FunctionCapability::Scalar]
87	}
88
89	fn return_type(&self, _input_types: &[Type]) -> Type {
90		Type::Utf8
91	}
92
93	fn execute(&self, ctx: &FunctionContext, args: &Columns) -> Result<Columns, FunctionError> {
94		if args.len() != 1 {
95			return Err(FunctionError::ArityMismatch {
96				function: ctx.fragment.clone(),
97				expected: 1,
98				actual: args.len(),
99			});
100		}
101
102		let column = &args[0];
103		let (data, bitvec) = column.data().unwrap_option();
104		let row_count = data.len();
105
106		let results: Vec<String> = (0..row_count).map(|row| to_json(&data.get_value(row))).collect();
107
108		let result_data = ColumnData::utf8(results);
109		let final_data = match bitvec {
110			Some(bv) => ColumnData::Option {
111				inner: Box::new(result_data),
112				bitvec: bv.clone(),
113			},
114			None => result_data,
115		};
116
117		Ok(Columns::new(vec![Column::new(ctx.fragment.clone(), final_data)]))
118	}
119}