Skip to main content

reifydb_routine/function/time/
format.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::{constraint::bytes::MaxBytes, container::utf8::Utf8Container, r#type::Type};
6
7use crate::routine::{Function, FunctionKind, Routine, RoutineInfo, context::FunctionContext, error::RoutineError};
8
9pub struct TimeFormat {
10	info: RoutineInfo,
11}
12
13impl Default for TimeFormat {
14	fn default() -> Self {
15		Self::new()
16	}
17}
18
19impl TimeFormat {
20	pub fn new() -> Self {
21		Self {
22			info: RoutineInfo::new("time::format"),
23		}
24	}
25}
26
27fn format_time(hour: u32, minute: u32, second: u32, nanosecond: u32, fmt: &str) -> Result<String, String> {
28	let mut result = String::new();
29	let mut chars = fmt.chars().peekable();
30
31	while let Some(ch) = chars.next() {
32		if ch == '%' {
33			match chars.peek() {
34				Some('H') => {
35					chars.next();
36					result.push_str(&format!("{:02}", hour));
37				}
38				Some('M') => {
39					chars.next();
40					result.push_str(&format!("{:02}", minute));
41				}
42				Some('S') => {
43					chars.next();
44					result.push_str(&format!("{:02}", second));
45				}
46				Some('f') => {
47					chars.next();
48					result.push_str(&format!("{:09}", nanosecond));
49				}
50				Some('3') => {
51					chars.next();
52					if chars.peek() == Some(&'f') {
53						chars.next();
54						result.push_str(&format!("{:03}", nanosecond / 1_000_000));
55					} else {
56						return Err(
57							"invalid format specifier: '%3' (expected '%3f')".to_string()
58						);
59					}
60				}
61				Some('6') => {
62					chars.next();
63					if chars.peek() == Some(&'f') {
64						chars.next();
65						result.push_str(&format!("{:06}", nanosecond / 1_000));
66					} else {
67						return Err(
68							"invalid format specifier: '%6' (expected '%6f')".to_string()
69						);
70					}
71				}
72				Some('%') => {
73					chars.next();
74					result.push('%');
75				}
76				Some(c) => {
77					let c = *c;
78					return Err(format!("invalid format specifier: '%{}'", c));
79				}
80				None => return Err("unexpected end of format string after '%'".to_string()),
81			}
82		} else {
83			result.push(ch);
84		}
85	}
86
87	Ok(result)
88}
89
90impl<'a> Routine<FunctionContext<'a>> for TimeFormat {
91	fn info(&self) -> &RoutineInfo {
92		&self.info
93	}
94
95	fn return_type(&self, _input_types: &[Type]) -> Type {
96		Type::Utf8
97	}
98
99	fn execute(&self, ctx: &mut FunctionContext<'a>, args: &Columns) -> Result<Columns, RoutineError> {
100		if args.len() != 2 {
101			return Err(RoutineError::FunctionArityMismatch {
102				function: ctx.fragment.clone(),
103				expected: 2,
104				actual: args.len(),
105			});
106		}
107
108		let time_col = &args[0];
109		let fmt_col = &args[1];
110
111		let (time_data, time_bv) = time_col.unwrap_option();
112		let (fmt_data, _) = fmt_col.unwrap_option();
113
114		match (time_data, fmt_data) {
115			(
116				ColumnBuffer::Time(time_container),
117				ColumnBuffer::Utf8 {
118					container: fmt_container,
119					..
120				},
121			) => {
122				let row_count = time_data.len();
123				let mut result_data = Vec::with_capacity(row_count);
124
125				for i in 0..row_count {
126					match (time_container.get(i), fmt_container.is_defined(i)) {
127						(Some(t), true) => {
128							let fmt_str = fmt_container.get(i).unwrap();
129							match format_time(
130								t.hour(),
131								t.minute(),
132								t.second(),
133								t.nanosecond(),
134								fmt_str,
135							) {
136								Ok(formatted) => {
137									result_data.push(formatted);
138								}
139								Err(reason) => {
140									return Err(
141										RoutineError::FunctionExecutionFailed {
142											function: ctx.fragment.clone(),
143											reason,
144										},
145									);
146								}
147							}
148						}
149						_ => {
150							result_data.push(String::new());
151						}
152					}
153				}
154
155				let mut final_data = ColumnBuffer::Utf8 {
156					container: Utf8Container::new(result_data),
157					max_bytes: MaxBytes::MAX,
158				};
159				if let Some(bv) = time_bv {
160					final_data = ColumnBuffer::Option {
161						inner: Box::new(final_data),
162						bitvec: bv.clone(),
163					};
164				}
165				Ok(Columns::new(vec![ColumnWithName::new(ctx.fragment.clone(), final_data)]))
166			}
167			(ColumnBuffer::Time(_), other) => Err(RoutineError::FunctionInvalidArgumentType {
168				function: ctx.fragment.clone(),
169				argument_index: 1,
170				expected: vec![Type::Utf8],
171				actual: other.get_type(),
172			}),
173			(other, _) => Err(RoutineError::FunctionInvalidArgumentType {
174				function: ctx.fragment.clone(),
175				argument_index: 0,
176				expected: vec![Type::Time],
177				actual: other.get_type(),
178			}),
179		}
180	}
181}
182
183impl Function for TimeFormat {
184	fn kinds(&self) -> &[FunctionKind] {
185		&[FunctionKind::Scalar]
186	}
187}